CREATE PROC [dbo].[SupplyChainHIX_InsertUnsuccessfulInvoice]
    @StartShamsiDate VARCHAR(10),
    @EndShamsiDate VARCHAR(10)
AS
DECLARE @StartDate DATE = dbo.ShamsiToMiladi(@StartShamsiDate),
        @EndDate DATE = dbo.ShamsiToMiladi(@EndShamsiDate);
INSERT INTO SupplyChainHIXInvoice
(
    InvoiceId,
    Status,
    InsertDate
)
SELECT SupplyChainHIXInvoice.InvoiceId,
       0,
       GETDATE()
FROM dbo.SupplyChainHIXInvoice
WHERE Id IN (
                SELECT cshix.Id
                FROM [dbo].[SupplyChainHIXInvoice] cshix
                WHERE cshix.Id IN (
                                      SELECT MAX(hix.Id) Id
                                      FROM dbo.SupplyChainHIXInvoice hix
                                      WHERE CAST(cshix.InsertDate AS DATE)
                                            BETWEEN @StartDate AND @EndDate
                                            AND cshix.Status IN ( 3,  2)
                                      GROUP BY hix.InvoiceId
                                  )
            );
