CREATE PROCEDURE [dbo].[PostMoveDeleteTransaction] @ATransactionNumberStr VARCHAR(8000), @AUserIdNumber INT, @AMovedFolioNumber INT, 
@AHotelCustomerNumber INT, @AReductionPrice Money, @AReductionPcs INT, @ASplitCount INT, @ACashDesk1 INT = -1 AS
/*
  Created by Kent Johansen december 2008
  Notes: 
    If @AMovedFolioNumber > 0 then it's handled as a move to that folio otherwise it is a delete.
    If @AMovedFolioNumber <= 0 then is's handled as a reduction on same folio (Without move)
    
  Changes:
    MLJ 20230926: Changed default for @ACashDesk1 to -1. Fixed error message in case of transactions. 
    KJ 20230915: Bug: Fix for "Reduction by pieces result in wrong amount" Case #CR235714
    KJ 20230707: Bug: Fix for "Reduction by pieces on daymeeting result in wrong amout"
    KJ 20230524: Bug: Fix for "Reduction by pieces on daymeeting result in wrong amout"
    KJ 20221027: Case #223604 + #224848. Bug: Fix for "Wrong price when reduction(move by pcs)".
    KJ 20220926: Bug: Fix for "Wrong price when reduction(move by pcs)". Case #CR223604
    KJ 20220728: Avavilability on Transactions
    NB20210812 Calculate price remained after reductions 4 use in split 
    KJ 20210809: Relation missing for delete without move
    KJ 20210804: Added to exception text + added isnull before insert into TransactionTransactionXtab
    KJ 20210715: Ext: Added TransactionTransactionXtab relation for reduction and split. Type defined in EconomyTL -> TransactionRelationType
    KJ 20210105: Reverted changes from 20200422 as it results in wrong postings when package value is greater than price. Package is not posted for reduction due to that change.
                 Only set PWLN to null if it is reduction without move   
                 Case #CR203546
    KJ 20200422: Bug: Fix for "Wrong PWLN for reduction on product postings". Case #CR185595
    KJ 20200106: Ext: If deleted transaction is precharged and date is in the future, then delete should be done on same date
    KJ 20181015: Ext: Add raise error if trying to delete/move a printed transaction
    KJ 20180924: Ext: Added try catch to break out of sp if any exception/error happens
    KJ 20180312: Ext: TransactionTransactionXtab
    NB 20161013: Bug: Split roundings fixed
    KJ 20160229: Bug: Fix for "Error delete of transactions" Case #CR099492
    KJ 20131113: Bug: Fix for "Reduction (without move) results in a clean delete".
    NB 20131015: bug in split part as 0,01 restence fixed by calculating rest of split on last split and using that value instead of devision
    KJ 20130409: Bug: Fix for "Reduction by delete after reduction by move results in duplicate GTN" Bug #82
    KJ 20130327: Bug: Fix for "Reduction by delete after reduction by move results in duplicate GTN" Bug #82
    KJ/NB 20121220: Bug: Fix for "Reduction on pieces gives wrong amount and GTN".
    KJ 20121210: FirstGlobalTransactionNumber missing for reduction/split handling. case #CR050667
    NB 20121002: Ext: Added Reduction and Split support
    New params description:
    -ReductionPrice or ReductionSplitPcs used for Reduction either by Price (Result= Price - ReductionPrice) or by Pcs (Result = Pcs - ReductionPcs)
    -SplitCount is used for splitting  (Pcs = 1 and Result = Price/SplitCount
     
    KJ 20100708: Bug: Fix for "Wrong userid on TransactionDeleteNote"
    KJ 20100422: Bug: Fix for "Not able to move transactions"
    KJ 20100421: Bug: Fix for "Delete with more than one pieces wrong"
    KJ 20091207: Ext: Added CashDesk
    KJ 20090223: Bug: CURSOR should be LOCAL
    KJ 20090114: Bug: Fix for "not able to delete payments"
    KJ 20081212: Changed to use TransactionNumber instead of GlobalTransactionNumber
    KJ 20081211: Removed Department as input param. Use the existing from original department 
*/

SET NOCOUNT ON

DECLARE @DebugLevel TINYINT
SET @DebugLevel = 0

BEGIN TRY
  DECLARE @TransactionNumber INT
  DECLARE @GlobalTransactionNumber INT
  DECLARE @SplitGTN INT
  DECLARE @FolioNumber INT
  DECLARE @TextOverwrite VARCHAR(150)
  DECLARE @Pieces INT
  DECLARE @PriceOverwrite FLOAT
  DECLARE @PriceRestCalc FLOAT
  DECLARE @WareNumber INT
  DECLARE @ProductWareLinkNumber INT
  DECLARE @Correction BIT
  DECLARE @Note VARCHAR(10)
  DECLARE @DummyTransNrShowOnBill INT
  DECLARE @FK_DepartmentNumber INT
  DECLARE @Payment INT
  DECLARE @PcsSign INT
  DECLARE @ReductionPcs INT
  DECLARE @ReductionPrice MONEY
  DECLARE @SplitCount INT
  DECLARE @FirstGlobalTransactionNumber INT
  DECLARE @InvoiceBillNumber INT
  DECLARE @s VARCHAR(500)
  DECLARE @PostDateTime DATETIME
  DECLARE @TransactionDateStamp DATETIME
  DECLARE @TransactionDateStampStr CHAR(8)
  DECLARE @CurrentDateStr CHAR(8)
  DECLARE @MoveGTN INT
  DECLARE @LTranRelationType INT
  DECLARE @TrnRelation INT
  DECLARE @LFromDate DATETIME
  DECLARE @LToDate DATETIME
  DECLARE @DoAddTransactionPeriod BIT
  DECLARE @WGPayment INT

  SET @LTranRelationType = 0
  SET @PostDateTime = NULL
  SELECT @CurrentDateStr = SYSTEMDATE FROM System WITH (NOLOCK)

  IF ISNULL(@AMovedFolioNumber, 0) <= 0
    SET @AMovedFolioNumber = 0

  SET @ReductionPcs = ABS(@AReductionPcs)
  SET @SplitCount = ABS(@ASplitCount)
  SET @ReductionPrice = ABS(@AReductionPrice)

  SET @DoAddTransactionPeriod = 0

  DECLARE db_cur CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
    SELECT TransactionNumber, GlobalTransactionNumber, T.FolioNumber, TextOverwrite, Pieces, 
    CASE WHEN TV.SplitCount > 0 AND @ASplitCount > 0 THEN TV.Total ELSE PriceOverwrite END,
    T.WareNumber, ProductWareLinkNumber, T.Note, FK_DepartmentNumber, T.Payment, DateStamp,
    (
      SELECT TOP 1 FKInvoice 
      FROM InvoiceTransactionXTab WITH (NOLOCK)
      INNER JOIN Invoice WITH (NOLOCK) ON Invoice.PkInvoice = InvoiceTransactionXTab.FkInvoice
        AND Invoice.CancelDate IS NULL
        AND Invoice.ReceiptType <> 0
      WHERE InvoiceTransactionXTab.FkTransaction = T.TransactionNumber
    ), WareGroups.Payment AS WGPayment
    FROM Transactions T WITH (NOLOCK)
    LEFT JOIN TTransactionGoView TV WITH (NOLOCK) ON TV.FolioNumber = T.FolioNumber AND TV.MGTN = T.OriginalGlobalTransactionNumber
    LEFT OUTER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = T.WareNumber
    LEFT OUTER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
    WHERE T.TransactionNumber IN (SELECT DISTINCT Number FROM iter_intlist_to_table_No_Dummy(@ATransactionNumberStr))
    AND T.ShowOnBillFlag = 1
    AND T.MovedDeleted = 0
  OPEN db_cur

  FETCH NEXT FROM db_cur INTO @TransactionNumber, @GlobalTransactionNumber, @FolioNumber, @TextOverwrite, @Pieces, @PriceOverwrite, @WareNumber, @ProductWareLinkNumber, @Note, @FK_DepartmentNumber, @Payment, @TransactionDateStamp, @InvoiceBillNumber, @WGPayment
  WHILE @@FETCH_STATUS = 0
  BEGIN
    IF @DebugLevel > 0
	  BEGIN
      PRINT '@PriceOverwrite = ' + CONVERT(NVARCHAR, ISNULL(@PriceOverwrite, 0))
      PRINT '@ReductionPrice = ' + CONVERT(NVARCHAR, ISNULL(@ReductionPrice, 0))
      PRINT '@ReductionPcs = ' + CONVERT(NVARCHAR, ISNULL(@ReductionPcs, 0))
      PRINT '@Pieces = ' + CONVERT(NVARCHAR, ISNULL(@Pieces, 0))
      PRINT '@SplitCount = ' + CONVERT(NVARCHAR, ISNULL(@SplitCount, 0))
      PRINT '@AMovedFolioNumber = ' + CONVERT(NVARCHAR, ISNULL(@AMovedFolioNumber, 0))	  
    END

    IF @DebugLevel > 1
	  BEGIN
      PRINT '@FolioNumber = ' + CONVERT(NVARCHAR, ISNULL(@FolioNumber, 0))
      PRINT '@InvoiceBillNumber = ' + CONVERT(NVARCHAR, ISNULL(@InvoiceBillNumber, 0))
    END

    SET @TrnRelation = @TransactionNumber

    --Reduction and Split part  
    IF (@ReductionPrice > 0 and @ReductionPrice <> ABS(@PriceOverwrite)) or 
      (@ReductionPcs > 0 and @ReductionPcs <> ABS(@Pieces)) or 
      (@SplitCount > 0)
    BEGIN
      IF @DebugLevel > 0
        PRINT 'Reduction and split'

      SET @SplitGTN = @GlobalTransactionNumber

      IF @SplitCount > 0
        SET @LTranRelationType = 5
      ELSE IF @ReductionPcs > 0 and @ReductionPcs <> ABS(@Pieces)
        SET @LTranRelationType = 3
      ELSE IF @ReductionPrice > 0 and @ReductionPrice <> ABS(@PriceOverwrite)
        SET @LTranRelationType = 4

      IF ISNULL(@AMovedFolioNumber, 0) = 0
      BEGIN
        -- Part delete on same folio as original
        EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @GlobalTransactionNumber OUTPUT
        SET @TransactionNumber = 0
      END
      ELSE
      BEGIN
        EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @FirstGlobalTransactionNumber OUTPUT
        SET @GlobalTransactionNumber = 0
      END  

      SET @Correction = 0
      IF @Pieces > 0 
        SET @PcsSign = 1
      ELSE IF @Pieces < 0
        SET @PcsSign = -1

      IF @SplitCount > 0 
      BEGIN
        IF @ReductionPcs > 0 
          SET @PriceOverwrite = @PriceOverwrite*@ReductionPcs/@SplitCount
        ELSE
          SET @PriceOverwrite = @PriceOverwrite/@SplitCount
        
        SELECT @PriceRestCalc = SUM(TV.Total) 
        FROM dbo.TTransactionSplitView TV WITH (NOLOCK) 
        WHERE FolioNumber = @FolioNumber 
        AND MGTN = @SplitGTN

        IF ABS(@PriceRestCalc - @PriceOverwrite) <= 0.02 and ABS(@PriceRestCalc - @PriceOverwrite) >= 0 
          SET @PriceOverwrite = @PriceRestCalc
        SET @Pieces = -1*@PcsSign
      END
      ELSE IF @ReductionPrice > 0
      BEGIN
        SET @PriceOverwrite = @ReductionPrice
        SET @Pieces = -1*@PcsSign
        IF @AMovedFolioNumber <= 0
          SET @ProductWareLinkNumber = NULL
      END
      ELSE IF @ReductionPcs > 0
      BEGIN
        IF ISNULL(@AMovedFolioNumber, 0) = 0
          SET @PriceOverwrite = (@PriceOverwrite/@Pieces)
        ELSE
        BEGIN
          IF @WGPayment = 3
            SET @PriceOverwrite = (@PriceOverwrite/@Pieces)*@ReductionPcs
          ELSE
            SET @PriceOverwrite = (@PriceOverwrite/@Pieces)
        END
        SET @Pieces = @ReductionPcs*-1*@PcsSign
        IF @AMovedFolioNumber <= 0
          SET @ProductWareLinkNumber = NULL
        SET @DoAddTransactionPeriod = 1
      END
    END 
    --Move and Delete part
    ELSE IF @AMovedFolioNumber > 0
    BEGIN
      -- Move
      IF @DebugLevel = 1
        PRINT 'MOVE'
      SET @Pieces = 0
      SET @PriceOverwrite = 0
      SET @Correction = 0
      EXEC GetNextNumber 'GLOBALTRANSACTIONIDENTITY', 1, @FirstGlobalTransactionNumber OUTPUT
      SET @MoveGTN = @GlobalTransactionNumber --Why getting an new GTN when the current GTN is reused?
      SET @GlobalTransactionNumber = 0   
      
      IF ISNULL(@InvoiceBillNumber, 0) > 0
      BEGIN
        SET @s = 'Error in storedprocedure <<PostMoveDeleteTransaction>>: Deleting transactions that has been printed is not allowed. Invoice:' + CAST(@InvoiceBillNumber AS VARCHAR)
        RAISERROR(@s, 15, 1)
      END         
	  END
    ELSE
    BEGIN
      --Delete
      IF @DebugLevel = 1
        PRINT 'DELETE'

      SET @DoAddTransactionPeriod = 1
      SET @Pieces = @Pieces*-1
      SET @Correction = 1
      SET @GlobaltransactionNumber = 0
      IF (NOT (@Pieces = 1 OR @Pieces = -1)) AND @Pieces <> 0
        SET @PriceOverwrite = (@PriceOverwrite/@Pieces) * -1

      IF ISNULL(@InvoiceBillNumber, 0) > 0
      BEGIN
        SET @s = 'Error in storedprocedure <<PostMoveDeleteTransaction>>: Deleting transactions that has been printed is not allowed. Invoice:' + CAST(@InvoiceBillNumber AS VARCHAR)
        RAISERROR(@s, 15, 1)
      END 
      
      IF (CONVERT(CHAR(8), @TransactionDateStamp, 112) > @CurrentDateStr)
      BEGIN
        SET @TransactionDateStampStr = CONVERT(CHAR(8), @TransactionDateStamp, 112)
        EXEC SystemDateTime @TransactionDateStampStr, @PostDateTime OUTPUT
      END
      ELSE
        SET @PostDateTime = NULL
    END

    IF @DebugLevel > 0
    BEGIN
      PRINT '*****************************'
      PRINT '@PriceOverwrite = ' + CONVERT(NVARCHAR, ISNULL(@PriceOverwrite, 0))
      PRINT '@PriceRestCalc = ' + CONVERT(NVARCHAR, ISNULL(@PriceRestCalc, 0))	  
    END
    IF @DebugLevel > 1
    BEGIN
      PRINT '@AUserIDNumber'
      PRINT @AUserIDNumber
      PRINT '@FolioNumber'
      PRINT @FolioNumber
      PRINT '@TextOverwrite'
      PRINT @TextOverwrite
      PRINT '@Pieces'
      PRINT @Pieces
      PRINT '@PriceOverwrite'
      PRINT @PriceOverwrite
      PRINT '@AMovedFolioNumber'
      PRINT @AMovedFolioNumber
      PRINT '@FK_DepartmentNumber'
      PRINT @FK_DepartmentNumber
      PRINT '@WareNumber'
      PRINT @WareNumber
      PRINT '@TransactionNumber'
      PRINT @TransactionNumber
      PRINT '@Correction'
      PRINT @Correction
      PRINT '@Note'
      PRINT @Note
      PRINT '@AHotelCustomerNumber'
      PRINT @AHotelCustomerNumber
      PRINT '@ProductWareLinkNumber'
      PRINT @ProductWareLinkNumber
      PRINT '@FirstGlobalTransactionNumber'
      PRINT @FirstGlobalTransactionNumber
    END

    EXEC Postering @PostDateTime, 0, 1, 0, 0, 0, @AUserIDNumber, @FolioNumber, 
    0, 0, 0, 0, @TextOverwrite, @Pieces, @PriceOverwrite, 0, 
    0, 0, 0, @AMovedFolioNumber, @FK_DepartmentNumber, @WareNumber, @Payment, @GlobaltransactionNumber, 
    @TransactionNumber, @Correction, @Note, @DummyTransNrShowOnBill OUTPUT, @AHotelCustomerNumber, @ProductWareLinkNumber, 0, 
    0, NULL, 0, @FirstGlobalTransactionNumber, 0, 0, 
    @FirstGlobalTransactionNumber, @ACashDesk = @ACashDesk1, @ATranRelationType = @LTranRelationType

    UPDATE TransactionDeleteNote SET FK_TransactionNumber = @DummyTransNrShowOnBill WHERE FK_TransactionNumber = @TransactionNumber

    IF ISNULL(@LTranRelationType, 0) > 0 AND ISNULL(@TrnRelation, 0) > 0 AND ISNULL(@DummyTransNrShowOnBill, 0) > 0
      INSERT INTO TransactionTransactionXtab (FK_TransactionNumber1, FK_TransactionNumber2, RelationType) VALUES (@TrnRelation, @DummyTransNrShowOnBill, @LTranRelationType)
    ELSE
      EXEC PostTranTranXtab @TransactionNumber, @DummyTransNrShowOnBill

    -- Save for availability by Transactions
    IF @DoAddTransactionPeriod = 1
    BEGIN
      IF @DebugLevel > 1
      BEGIN
        PRINT '@DoAddTransactionPeriod'
        PRINT @DoAddTransactionPeriod
        PRINT '@TransactionNumber'
        PRINT @TransactionNumber
        PRINT '@TrnRelation'
        PRINT @TrnRelation
      END

      SELECT @LFromDate = FromDateTime, @LToDate = ToDateTime FROM TransactionPeriod WITH (NOLOCK) WHERE FK_TransactionNumber = @TrnRelation
      IF ISNULL(@LFromDate, 0) > 0 AND ISNULL(@LToDate, 0) > 0
        INSERT INTO TransactionPeriod (FK_TransactionNumber, FromDateTime, ToDateTime) VALUES (@DummyTransNrShowOnBill, @LFromDate, @LToDate)
    END

    --nb20200623 Move Terminal based CC support   
    IF EXISTS (SELECT COUNT(*) FROM IntCreditCardsOnReservations (NOLOCK) WHERE PicassoTransactionId = @MoveGTN)
    BEGIN
      DECLARE @Reference INT, @Guest INT, @Folio INT, @HRI NVARCHAR(50)
      SELECT @Folio = FolioNumber, @Reference = ReferenceNumber, @Guest = GuestNumber 
      FROM Folios (NOLOCK) 
      WHERE FolioNumber = @AMovedFolioNumber
      IF ISNULL(@Reference, 0) = 0
        SET @HRI = 'F'+CONVERT(NVARCHAR, @Folio)
      ELSE 
        SET @HRI = CONVERT(NVARCHAR, @Reference) + '/' + CONVERT(NVARCHAR, @Guest)  
      UPDATE IntCreditCardsOnReservations SET HotReservationIdentifier = @HRI WHERE PicassoTransactionId = @MoveGTN
    END

    FETCH NEXT FROM db_cur INTO @TransactionNumber, @GlobalTransactionNumber, @FolioNumber, @TextOverwrite, @Pieces, @PriceOverwrite, @WareNumber, @ProductWareLinkNumber, @Note, @FK_DepartmentNumber, @Payment, @TransactionDateStamp, @InvoiceBillNumber, @WGPayment
  END
END TRY
BEGIN CATCH
  DECLARE @ErrorMessage NVARCHAR(MAX)=ERROR_MESSAGE(), @ErrorLine INT=ERROR_LINE(),@ErrorSeverity INT=ERROR_SEVERITY(), @ErrorState INT=ERROR_STATE()

  RAISERROR ('%s. Line %d. TRN %d. TRNOnBill %d', 
	  @ErrorSeverity, 
	  @ErrorState,
	  @ErrorMessage,
	  @ErrorLine,
	  @TransactionNumber,
	  @DummyTransNrShowOnBill
  )
END CATCH

CLOSE db_cur
DEALLOCATE db_cur