
--Exec PROC_PARTNER_RECONCILIATION @user='admin' ,@controlNo='80121788012' ,@pAgent='601349'

alter PROC PROC_PARTNER_RECONCILIATION
(
	@user			VARCHAR(100)
	,@controlNo		VARCHAR(100)	= null
	,@pSuperAgent	VARCHAR(20)		= null
	,@flag			VARCHAR(20)		= NULL
	,@PaidDate		VARCHAR(10)		= null

)
AS
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN

IF @flag = 'partnerList-recon'  ----## API PARTNER LIST FOR CHECKING DIRECT reconciliation
BEGIN
	SELECT agentId AS [VALUE],agentName AS [TEXT] 
	FROM agentMaster(NOLOCK) 
	WHERE parentId = 0 AND agentType='2902'
	AND isActive = 'Y' AND  AGENTID IN( 590851,601353)
	RETURN
END

IF @pSuperAgent=590851 --====KASIKORNBANK PUBLIC CO. LTD.===
	BEGIN	
		IF EXISTS	(SELECT 'X' FROM remittran(NOLOCK) WHERE controlNo= dbo.fnaencryptstring(@controlNo) 
			AND payStatus = 'Post' AND tranStatus='Payment' AND pSuperAgent  = @pSuperAgent
					)
			BEGIN
				UPDATE remitTran SET 
				payStatus		= 'Paid', 
				tranStatus		= 'Paid', 
				paidBy			= 'system', 
				paidDate		= @PaidDate,
				paidDateLocal	= @PaidDate
				WHERE controlno = dbo.FNAEncryptString(@controlNo)
				AND payStatus = 'Post'
				AND tranStatus='Payment'  
				AND pSuperAgent  = @pSuperAgent

				EXEC proc_errorHandler 0, 'Update status sucessfully.', @controlNo
				RETURN
			END
		ELSE
		BEGIN
			EXEC proc_errorHandler 1, 'No Record found.', @controlNo
			RETURN
		END
	END
IF @pSuperAgent=601353 ----====Lyhour---====-------
	BEGIN	
		IF EXISTS	(SELECT 'X' FROM remittran(NOLOCK) WHERE contno= @controlNo
			AND payStatus = 'Post' AND tranStatus='Payment' AND pSuperAgent  = @pSuperAgent)
			BEGIN
				UPDATE remitTran SET 
				payStatus		= 'Paid', 
				tranStatus		= 'Paid', 
				paidBy			= 'system', 
				paidDate		= ISNULL(@PaidDate,approvedDate),
				paidDateLocal	= ISNULL(@PaidDate,approvedDate)
				WHERE ContNo    = @controlNo
				AND payStatus   = 'Post' 
				AND tranStatus  ='Payment'  
				AND pSuperAgent  = @pSuperAgent
				EXEC proc_errorHandler 0, 'Update status sucessfully.', @controlNo
				RETURN
			END
		ELSE
			BEGIN
				EXEC proc_errorHandler 1, 'No Record found.', @controlNo
				RETURN
			END
	 END
END
