CREATE PROCEDURE [dbo].[BO_AddTraderFeedbacks]
	@knokId			bigint,
	@userId			bigint,
	@feedbackType	smallint,
	@comment VARCHAR(100),
	@clear int null,
	@educational int null,
	@comprehensive int null,
	@knokBenefit int null

AS
DECLARE		@TranStarted		BIT,
			@ERROR				SMALLINT,
			@RC					INT,
			@ErrorMessage		VARCHAR(100),
			@OngoingFeedback float,
			@userReviewPerTrader float,
			@clearall float,
			@educationalall float,
			@comprehensiveall float,
			@knokBenefitall float,
			@countall int
	
BEGIN TRY  
	SET @TranStarted = 0 
	SET @RC	 = 0 

	BEGIN TRANSACTION
	SET @TranStarted = 1
	

	Insert TraderFeedbacks 
	(UserId, KnokId, FeedbackType,Comment,
	[Clear],[Educational ]
      ,[Comprehensive ]
      ,[KnokBenefit]
	  ) 
	  VALUES
	  
	  (@userId, @knokId,
	  @feedbackType,
	  @comment,@clear,
	  @educational,
	  @comprehensive,
	  @knokBenefit
	    ) -- failure on errors

	IF( @TranStarted = 1 )    
	COMMIT TRANSACTION 
	
	BEGIN TRANSACTION
	SET @TranStarted = 1
	--SET @countall = (Select DISTINCT COUNT([Clear]) FROM [dbo].[TraderFeedbacks] WHERE  KnokId = @knokId GROUP BY UserId)

	
		
	
			
			 SET @userReviewPerTrader =
			 (SELECT sum(val) / count(UserId) FROM (
SELECT t.UserId, 
case when count(t.UserId) = 1
then iif(sum(v1) = 0, sum(v), sum(v1)) else sum(v)*0.25
 + sum(v1)*0.75 
 end as val --,
FROM 
 (
 SELECT
 fb1.UserId, (sum(isnull(fb1.[Clear], 0))* 0.33 + sum(isnull(fb1.[Educational ], 0)) * 0.33 
 + sum(isnull(fb1.[Comprehensive ], 0)) * 0.34) v, 0 v1
 FROM [dbo].[TraderFeedbacks] fb1 WHERE fb1.FeedbackType =0 AND fb1.KnokId = @knokId 
 GROUP BY fb1.UserId
 union all
 SELECT
  fb2.UserId, 0 v, sum(isnull(fb2.[KnokBenefit], 0)) v1
 FROM [dbo].[TraderFeedbacks] fb2 WHERE fb2.FeedbackType =1 AND fb2.KnokId = @knokId
 GROUP BY fb2.UserId) t
GROUP BY t.UserId
) t1)
	

	Update Signals 
	
	  SET
	  UserReview = @userReviewPerTrader Where  KnokId = @knokId
	

	IF( @TranStarted = 1 )    
	COMMIT TRANSACTION  
END TRY 
BEGIN CATCH  
	IF( @TranStarted = 1 )    
	ROLLBACK TRANSACTION  
	
	EXEC USP_LogError            
	EXEC USP_RethrowError                       
   
	IF @RC = 0
		SET @RC = 1   ---- Unexpected Error	   
		                     
	RETURN @RC                        
END CATCH
