﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__setInvoicePaymentStatus_auto]
	
AS
BEGIN
	SET NOCOUNT ON;

	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__setInvoicePaymentStatus_auto' ,'', '');


    with ic as (
		
		SELECT 
			bt.[taID]
			, i.[InvoiceId]
			, [InvID] = i.[Id]
			, bt.[amount] 
			, [auto] = CAST(CASE WHEN bs.[assigned_invoice_id] = i.[Id] THEN 0 WHEN bs.[auto_invoice_id] = i.[Id] THEN 1 ELSE NULL END as bit)
		FROM [dbo].[fds__bankingtransactions] as bt 
			JOIN [dbo].[fds__bankingtransactions_settings] as bs  ON bt.[taID] = bs.[taID]
			JOIN [dbo].[fds__invoices] as i on (bs.[assigned_invoice_id] = i.[Id] OR bs.[auto_invoice_id] = i.[Id]) and i.[IsFinal] = 1
			
	), ic2 as (
		SELECT [taID]	= ic.[taID]
			, [amount]			= SUM(ISNULL(ic.[amount], 0.0))
			, ic.[invoiceid]
			, ic.[InvID]
			, ic.[auto]
		from ic
		WHERE ic.[invoiceid] is not null
		GROUP BY ic.[taID], ic.[invoiceid], ic.[InvID], ic.[auto]
	)
--select * from ic2
	UPDATE i
		SET i.IsPayed = CASE WHEN ic.[amount] between (i.InvoiceBalance - 0.01) and (i.InvoiceBalance + 0.01) THEN 1 else 0 END
			, I.[PaymentStatus] = CASE WHEN ic.[amount] between (i.InvoiceBalance - 0.01) and (i.InvoiceBalance + 0.01) THEN 'a' 
									WHEN ic.[amount] < i.InvoiceBalance THEN 'p' 
									ELSE NULL END
	FROM [dbo].[fds__invoices] as i
		JOIN ic2 as ic on i.[InvoiceId] = ic.[invoiceid]
	WHERE i.ispayed = 0;




END