Table of Contents

WARNING: This is not kids stuff. Use of this feature requires expertise in SQL Server and in the Cyrious database structure. It is very possible to irreversibly damage your Cyrious Control database if you make a mistake. Always develop your tests using a separate database on a separate machine. If you are interested in using SQL Bridge but are not a SQL guru, please contact a sales or consulting at Cyrious.
Note: This feature requires Control 5.75 or higher.

Overview

The stored procedure can be used to add a payment to an existing order in Control

One (and only one) of the following values are required:

One (and only one) of the following values are required:

The following value is also required:

The following values may be supplied, but will use the default value is not supplied:

  
* @LockRecords          - Set this to 0 to nor lock the records
* @RefreshRecords       - Set this to 0 to not refresh the order and/or customer (as appropriate)
  1. - If you want to post part of the payment to credit, you must supply BOTH of these values and they must add to the Payment Amount

– The following optional OUTPUT parameters can be used to obtain the new IDs.

– They can also be supplied, in which case SQL Bridge will not be used to obtain them.

Notes:

The stored procedure requires SQLBridge in order to obtain IDs for the inserted records. SQL Bridge is a collection of SQL Server stored prodedures and functions and external modules that can be called to safely insert or update data into the Control database and notify the CHAPI service that data has been updated. The CHAPI service is a controller program that will then notify the SSLIP and all copies of Control about the changes.

Example Usage

Post a Payment on an Order

code_formatsql

exec dbo.csp_ImportPayment

      @OrderNumber = 1977,
      @PaymentAmount = 238.15,
      @PaymentMethod = 'Check',
      @DisplayNumber = 'Check #1234'

;

code

Post a Payment with an Overpayment

code_formatsql

exec dbo.csp_ImportPayment

	  @OrderNumber = 1971
	, @PaymentAmount = 300.00
	, @PaymentMethod = 'Visa'
	, @DisplayNumber = 'Visa *****4520'
	, @EmployeeID = 10005
	, @Notes = 'Payment with Overpayment'
	, @PaymentToOrder = 200.00
	, @PaymentToCredit = 100.00

;

code

Post a Refund of an Amount from Previous Order Payments

Note: This is not voiding the earlier payment(s). This issues a refund.

code_formatsql

exec dbo.csp_ImportPayment

	  @OrderNumber = 1971
	, @PaymentAmount = -175.00
	, @PaymentMethod = 'Visa'
	, @DisplayNumber = 'Visa *****4520'
	, @EmployeeID = 10005
	, @Notes = 'Refund From Previous Order Payments'

;

code

Apply a Customer Credit to an Order

Note: Always use @PaymentMethodID = 16 for system credit transfers!

code_formatsql

exec dbo.csp_ImportPayment

	  @OrderNumber = 1971
	, @PaymentAmount = 0.00
	, @PaymentMethodID = 16 -- System Transfer Account
	, @DisplayNumber = 'Credit Applied to Order'
	, @EmployeeID = 10005
	, @Notes = 'Apply Credit to Order'
	, @PaymentToOrder  = 500
	, @PaymentToCredit = -500

;

code

Move the Payment Balance from an Order to the Customer Credit

Note: Always use @PaymentMethodID = 16 for system credit transfers!

code_formatsql

exec dbo.csp_ImportPayment

	  @OrderNumber = 1971
	, @PaymentAmount = 0.00
	, @PaymentMethodID = 16 -- System Transfer Account
	, @DisplayNumber = 'Payments Transferred to Credit'
	, @EmployeeID = 10005
	, @Notes = 'Transfer Order Payment to Credit'
	, @PaymentToOrder  = 175.00
	, @PaymentToCredit = -175.00

;

code

Post a Payment Only to Customer Credit

Note: This demonstrates the routine, but this is not the best way to accomplish this task since you still need an order to specify the company (though the order isn't used). It is better to use the csp_ImportPaymentToCredit function.

code_formatsql

exec dbo.csp_ImportPayment

	  @OrderNumber = 1971
	, @PaymentAmount = -175.00
	, @PaymentMethod = 'Check'
	, @DisplayNumber = 'Check #1234'
	, @Notes = 'Payment straight to Credit'
	, @PaymentToOrder = 0.00
	, @PaymentToCredit = -175.00

;

code

Stored Procedure

The SQL to create the imported payment stored procedure follows. This must be run to create the stored procedure before it can be used.

code_formatsql

– Author: Cyrious Software

– Create date: August-2016

– Description: This stored procedure imports a payment record into Control.

– Returns: 1 for Success. Error Message on Failure.

CREATE PROCEDURE csp_ImportPayment

  1. - You must supply 1 (and only 1) of the following
  @THID               INT = NULL OUTPUT
  , @OrderNumber      INT = NULL OUTPUT
  1. - You must supply 1 (and only 1) of the following
  , @PaymentMethod    VARCHAR(50)    = NULL   -- the AccountName from PaymentAccount table (e.g., Visa, Check)
  , @PaymentMethodID  INT            = NULL   -- the ID from PaymentAccount table (e.g., Visa, Check)
  1. - You must supply this Required Fields
  , @PaymentAmount    DECIMAL(18,4)           -- must be an amount less than the order balance due
  1. - You may or may not supply these Optional Fields
  , @EmployeeID           INT      = 10       -- must be an ID from the Employee table.  House Account (10) if not specified
  , @PaymentDT            DATETIME = NULL     -- Effective DateTime of Payment.  Uses current DateTime is omitted.
  , @PaymentDivisionID    INT      = NULL     -- must be an ID from the Division View
  , @ContactID            INT      = NULL     -- The contact the payment is for.  Defaults to the order's primary contact
  , @Notes                VARCHAR(255) = NULL -- The notes for the journal 
  , @DisplayNumber        VARCHAR(32)  = NULL -- The payment tracking display number
  1. - If you want to post part of the payment to credit, you must supply BOTH of these values and they must add to the Payment Amount
  , @PaymentToOrder        DECIMAL(18,4) = NULL    -- The amount of the payment to apply to the order.  Leave blank to apply the full payment to the otder.
  , @PaymentToCredit       DECIMAL(18,4) = NULL    -- The amount of the payment to apply to the customer credit.  Leave blank for zero.
  1. - Optional Configuration Values
  , @LockRecords          BIT      = 1        -- Set this to 0 to nor lock the records
  , @RefreshRecords         BIT      = 1        -- Set this to 0 to not refresh the order
  1. - Some OUTPUT Parameters in case the caller wants any of these value back. Pass this value in to NOT use SQL Bridge to look up the records
  , @MasterPaymentID      INT    = NULL  OUTPUT  -- The ID of the Master Payment Record
  , @DetailPaymentID      INT    = NULL  OUTPUT  -- The ID of the Detail Order Payment Record
  , @DetailCreditID       INT    = NULL  OUTPUT  -- The ID of the Detail Credit Record
  , @LedgerID             INT    = NULL  OUTPUT  -- The first ID of the Ledger Records.  You need 2 if only payment to order; 4 if customesr credit also 
  , @OrderGLGroupID       INT    = NULL  OUTPUT  -- The ID of the GL Group Record
  , @CreditGLGroupID      INT    = NULL  OUTPUT  -- The ID of the GL Group Record

AS

BEGIN

  SET NOCOUNT ON;
  1. - ———————————————————–
  1. - Initial Variable Declarations
  1. - ———————————————————–
  DECLARE @OrderStatusID  INT;
  DECLARE @AccountID      INT;
  DECLARE @DivisionID     INT;
  DECLARE @OrderSeqNo     INT;
  DECLARE @GLPaymentAccountID INT;       -- must be an ID from GLAccount where GLClassificationType = 1007
  DECLARE @NewSeqNo       INT;
  DECLARE @CompanyName    VARCHAR(64);
  DECLARE @BalanceDue     DECIMAL(18,4);
  DECLARE @CurrentPayments DECIMAL(18,4);
  DECLARE @GLAccountOffset INT;
  DECLARE @CloseOrder     BIT;
  DECLARE @UnCloseOrder   BIT;
  DECLARE @OrderLocked    BIT            = 0;
  DECLARE @CompanyLocked  BIT            = 0;
  DECLARE @PaymentGLClassificationType    INT; 
  DECLARE @PaymentGLClassificationName    INT; 
  DECLARE @LedgerIDCount  TINYINT;
  DECLARE @LedgerIDOffset TINYINT         = 0;
  DECLARE @StartGLGroupID INT;
  DECLARE @EndGLGroupID   INT;
  1. - Define some error variables in case we need them
  DECLARE @DT              SMALLDATETIME  = GetDate();
  DECLARE @ComputerName    VARCHAR(25)    = @@ServerName;
  DECLARE @NewLine         CHAR(2)        = CHAR(10)+CHAR(13);
  DECLARE @ProcName	     VARCHAR(50)    = OBJECT_NAME(@@PROCID);
  DECLARE @ErrorMessage    VARCHAR(2048)  = '';
  DECLARE @ErrorNumber     INT            = 99;
  DECLARE @ErrorSeverity   INT            = 15;
  DECLARE @ErrorState      INT            = 0;
  DECLARE @ErrorLine       INT            = 0;
  DECLARE @ErrorProcedure  VARCHAR(200)   = @ProcName;
  1. - ———————————————————–
  1. - Fill in initial data
  1. - ———————————————————–
  IF (@PaymentDT IS NULL) SET @PaymentDT = @DT;
  IF ((@THID IS NOT NULL) AND (@OrderNumber IS NOT NULL))  SET @ErrorMessage = @ErrorMessage + 'Only one of the parameters THID and OrderNumber may be supplied.; ';
  IF (@PaymentToOrder IS NULL)
  BEGIN
      IF (@PaymentToCredit IS NOT NULL)
          SET @ErrorMessage = @ErrorMessage + 'You must specify the @PaymentToCredit when the @PaymentToOrder if provided; ' 
      SET @PaymentToOrder = @PaymentAmount;
      SET @PaymentToCredit = 0.0;
  END
  ELSE
  BEGIN
      IF (@PaymentToCredit IS NULL)
          SET @ErrorMessage = @ErrorMessage + 'You must specify the @PaymentToOrder when the @PaymentToCredit if provided; ' 
      IF ((@PaymentToOrder + @PaymentToCredit) != @PaymentAmount)
          SET @ErrorMessage = @ErrorMessage + 'The @PaymentToCredit plus @PaymentToOrder must equal the @PaymentTotal; ';
  END; 
  SELECT @THID = ID
      , @OrderNumber = OrderNumber
      , @AccountID = AccountID
      , @OrderStatusID = StatusID
      , @DivisionID = DivisionID
      , @PaymentDivisionID = coalesce(@PaymentDivisionID, DivisionID)
      , @ContactID = coalesce(@ContactID, ContactID)
      , @OrderSeqNo = coalesce(SeqID,0)
      , @NewSeqNo   = coalesce(SeqID,0) + 1
      , @BalanceDue = BalanceDue
	, @CurrentPayments = PaymentTotal
      , @CompanyName = (SELECT CompanyName FROM Account WHERE ID = AccountID)
      , @GLAccountOffset = (CASE WHEN StatusID IN (1,2) THEN 24 ELSE 14 END)  -- If in WIP or Built, GL Offset is Customer Deposits (24), Otherwise A/Rs (14) 
      , @CloseOrder = (CASE WHEN (@OrderStatusID = 3) AND (@BalanceDue = @PaymentToOrder) AND (COALESCE(ManuallyReopened,0) = 0) THEN 1 ELSE 0 END)
      , @UnCloseOrder = (CASE WHEN (@OrderStatusID = 4) AND (@PaymentToOrder < 0) THEN 1 else 0 END)
  FROM TransHeader
  WHERE (ID = @THID) or (OrderNumber = @OrderNumber AND TransactionType in (1,6));
  SELECT @PaymentGLClassificationType = GLClassificationType
      , @PaymentGLClassificationName = GLClassTypeName
  FROM GLAccount WHERE ID = @GLPaymentAccountID;
  1. - ———————————————————–
  1. - Validate the Input
  1. - ———————————————————–
  IF (@PaymentMethodID IS NOT NULL) 
  BEGIN
      IF (@PaymentMethod IS NOT NULL)  
          SET @ErrorMessage = @ErrorMessage + 'Only one of the parameters PaymentMethodID and PaymentMethodName may be supplied.; ';
  END
  ELSE 
      SET @PaymentMethodID = (SELECT ID FROM PaymentAccount WHERE AccountName = @PaymentMethod AND ClassTypeID = 8002);
  SET @GLPaymentAccountID = (Select BankAccountID from PaymentAccount where ID = @PaymentMethodID);
  IF (@PaymentToOrder > @BalanceDue)  SET @ErrorMessage = @ErrorMessage + 'Payment Amount Greater than Balance Due; ';
  IF ((@PaymentToOrder < 0) AND (-@PaymentToOrder > @CurrentPayments) )  SET @ErrorMessage = @ErrorMessage + 'Can''t Refund More than the Current Payment Balance; ';
  IF (@OrderStatusID not in (1,2,3) AND (@PaymentToOrder > 0) ) 
      SET @ErrorMessage = @ErrorMessage + 'Payment Can Only be Applied to Order in WIP, Built, or Sale; ';
  IF (@GLPaymentAccountID IS NULL)   SET @ErrorMessage = @ErrorMessage + 'Invalid Payment Method or no GL Account Associated with it; ';
  1. - ———————————————————–
  1. - Lock the Order
  1. - ———————————————————–
  IF ((@LockRecords = 1) AND (@ErrorMessage = ''))
  BEGIN
      BEGIN TRY
          IF (@PaymentToOrder  0.0)
          BEGIN  
              EXEC dbo.csf_chapi_lock @THID, 10000;
              SET @OrderLocked = 1;
          END;
          IF (@PaymentToCredit  0)
          BEGIN
              EXEC dbo.csf_chapi_lock @AccountID, 2000;
              SET @CompanyLocked = 1;
          END;
      END TRY
      BEGIN CATCH
          IF (@OrderLocked = 1)
          BEGIN
              EXEC dbo.csf_chapi_unlock @THID, 10000;
              SET @OrderLocked = 0;
          END;
          SET @ErrorMessage = 'Unable to lock Order ID '+CONVERT(VARCHAR(16), @THID);
  1. - Assign variables to error-handling functions that
  1. - capture information for RAISERROR.
          SELECT 
              @ErrorNumber = ERROR_NUMBER(),
              @ErrorSeverity = ERROR_SEVERITY(),
              @ErrorState = ERROR_STATE(),
              @ErrorLine = ERROR_LINE(),
              @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');
      END CATCH;
  END;   
  IF (@ErrorMessage != '')
  BEGIN
  1. - Build the message string that will contain original
  1. - error information.
      SET @ErrorMessage = 'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: '+ @ErrorMessage;
  1. - Raise an error: msg_str parameter of RAISERROR will contain
  1. - the original error information.
      RAISERROR 
          (
          @ErrorMessage, 
          @ErrorSeverity, 
          1,               
          @ErrorNumber,    -- parameter: original error number.
          @ErrorSeverity,  -- parameter: original error severity.
          @ErrorState,     -- parameter: original error state.
          @ErrorProcedure, -- parameter: original error procedure name.
          @ErrorLine       -- parameter: original error line number.
          );  
          RETURN; 
  END;    
  1. - ———————————————————–
  1. - Step 3, Request New IDs if needed
  1. - ———————————————————–
  SET @LedgerIDCount = ((CASE WHEN @PaymentToOrder != 0.0 THEN 2 ELSE 0 END) + (CASE WHEN @PaymentToCredit != 0.0 THEN 2 ELSE 0 END))
  IF (@MasterPaymentID IS NULL) SET @MasterPaymentID = (SELECT dbo.csf_chapi_nextid(20000, 1));
  IF (@LedgerID        IS NULL) SET @LedgerID        = (SELECT dbo.csf_chapi_nextid(8900, @LedgerIDCount));
  IF (@PaymentToOrder  != 0.0)
  BEGIN
      IF (@DetailPaymentID IS NULL)  SET @DetailPaymentID     = (SELECT dbo.csf_chapi_nextid(20001, 1));
      IF (@OrderGLGroupID  IS NULL)  SET @OrderGLGroupID      = (SELECT dbo.csf_chapi_nextnumber('GLGroupID', 1));
  END;
  IF (@PaymentToCredit != 0.0)
  BEGIN
      IF (@DetailCreditID  IS NULL)   SET @DetailCreditID     = (SELECT dbo.csf_chapi_nextid(20002, 1));
      IF (@CreditGLGroupID IS NULL)   SET @CreditGLGroupID    = (SELECT dbo.csf_chapi_nextnumber('GLGroupID', 1));
  END; 
  SET @StartGLGroupID = ( SELECT MIN(ID) FROM (VALUES (@OrderGLGroupID),(@CreditGLGroupID)) AS AllIDs(ID) );
  SET @EndGLGroupID   = ( SELECT MAX(ID) FROM (VALUES (@OrderGLGroupID),(@CreditGLGroupID)) AS AllIDs(ID) );
  1. - ———————————————————–
  1. - Step 4, Insert the new Records (in a transaction) and update the Order Total
  1. - ———————————————————–
  BEGIN TRANSACTION
  BEGIN TRY
  1. - ———————————————————–
  1. - Insert MASTER Payment Records
  1. - ———————————————————–
  1. - Insert Master Record into Journal
          INSERT INTO [Journal] ([ID], [StoreID], [ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EmployeeID],[JournalActivityType] ,[JournalActivityText] ,[Description] ,[Notes] ,[StartDateTime] ,[EndDateTime] ,[TotalTime] ,[ScheduledDateTime]  ,[CompletedByID] ,[CompletedDateTime] ,[IsSummary] ,[IsDetail] ,[SummaryID] ,[SummaryClassTypeID] ,[SummaryAmount] ,[DetailAmount]
          ,[StartGLGroupID]  ,[EndGLGroupID]  ,[AccountID] ,[AccountClassTypeID]  ,[ContactID]  ,[ContactClassTypeID]  ,[TransactionID] ,[TransactionClassTypeID]  ,[IsVoided]  ,[VoidedDateTime]  ,[VoidedEntryID] ,[VoidedEntryClassTypeID]  ,[VoidedReason]  ,[QueryStartDateTime]
          ,[QueryEndDateTime]  ,[ReminderDateTime]  ,[ReminderPrompt]  ,[PartID]  ,[ActivityType]  ,[ActivityTypeText]  ,[IsBillable]   ,[BillableDateTime]  ,[UseActualTime]  ,[BillingNotes]  ,[BillingType]  ,[TotalBilledTime]  ,[RecurringActivityID]  ,[LinkID]  ,[LinkStoreID]
          ,[LinkClassTypeID] ,[SpecialCode] ,[DivisionID] ,[HasCalendarLinks] ,[TipRecipientID] ,[PartClassTypeID] ,[RecurringClassTypeID] ,[StationID] ,[StationClassTypeID] ,[CurrentState] ,[StageID] ,[StageClassTypeID]) 
          VALUES
          ( @MasterPaymentID     -- (
          , -1     -- ,
          , 20000     -- ,
          , @ProcName     -- ,
          , @ComputerName     -- ,
          , @DT    -- ,
          , 0    -- ,
          , 0    -- ,
          , 1    -- ,
          , @EmployeeID  -- 
          , 2  -- 
          , 'Payment'  -- 
          , LEFT( (CASE WHEN @PaymentAmount > 0 
                          THEN 'Master Payment for '
                          ELSE 'Master Refund for '
                      END)+convert(varchar(12), @OrderNumber)+' - '+@CompanyName, 50) -- 
          , @Notes  -- 
          , @PaymentDT  -- 
          , @PaymentDT  -- 
          , NULL  -- 
          , NULL  -- 
          , @EmployeeID  -- 
          , @PaymentDT  -- 
          , 1  -- 
          , 0  -- 
          , NULL  -- 
          , NULL  -- 
          , @PaymentAmount  -- 
          , 0  -- 
          , @StartGLGroupID  -- 
          , @EndGLGroupID  -- 
          , @AccountID  -- 
          , 2000  -- 
          , @ContactID  -- 
          , 3000  -- 
          , NULL  -- 
          , NULL  -- 
          , 0  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , @PaymentDT  -- 
          , @PaymentDT  -- 
          , NULL  -- 
          , 0  -- 
          , NULL  -- 
          , 0  -- 
          , NULL  -- 
          , 0  -- 
          , NULL  -- 
          , 0  -- 
          , NULL  -- 
          , 0  -- 
          , 0  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , @DivisionID  -- 
          , 0  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- 
          , NULL  -- )
          );
  1. - Insert Master Record into Payment Table
          INSERT INTO [Payment] 
          ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[NameOnCard] ,[TrackingNumber] ,[PaymentAccountID] ,[PaymentAccountClassTypeID] ,[ExpirationDate] ,[VCode] ,[IsCCNumEncrypt] ,[DisplayNumber] ,[IsVCodeEncrypted] ,[Undeposited] ,[DepositGLGroupID] ,[DepositJournalID] ,[PaymentDate] ,[BankAccountID] ,[BankAccountClasstypeID] ,[TenderType] ,[PayrollID] ,[PayrollClassTypeID] ,[PaycheckID] ,[BankReference] ,[BankCode] ,[BranchCode] ,[CIN] ,[State] ,[CCAccount]
          ,[CCCSTransactionGuid] ,[CCCSCustomerGuid] ,[IsActualCheck])
          VALUES 
          ( @MasterPaymentID     -- (
          , -1     -- ,
          , 20000     -- ,
          , @ProcName     -- ,
          , @ComputerName     -- ,
          , @DT    -- ,
          , 0    -- ,
          , 0    -- ,
          , 1    -- ,
          , ''     -- ,
          , NULL     -- ,
          , @PaymentMethodID     -- ,
          , 8002     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , 0     -- ,
          , @DisplayNumber     -- ,
          , NULL     -- ,
          , 0        -- ,
          , NULL     -- ,
          , NULL     -- ,
          , @PaymentDT     -- ,
          , @GLPaymentAccountID     -- ,
          , 8001     -- ,
          , 2     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , NULL     -- ,
          , 0     -- ,)
          );
  1. - ———————————————————–
  1. - Handle ORDER part of Payment
  1. - ———————————————————–
          IF (@PaymentToOrder  0.0)
          BEGIN
  1. - Insert ORDER Detail Record into Journal
              INSERT INTO [Journal] ([ID], [StoreID], [ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EmployeeID],[JournalActivityType] ,[JournalActivityText] ,[Description] ,[Notes] ,[StartDateTime] ,[EndDateTime] ,[TotalTime] ,[ScheduledDateTime]  ,[CompletedByID] ,[CompletedDateTime] ,[IsSummary] ,[IsDetail] ,[SummaryID] ,[SummaryClassTypeID] ,[SummaryAmount] ,[DetailAmount]
              ,[StartGLGroupID]  ,[EndGLGroupID]  ,[AccountID] ,[AccountClassTypeID]  ,[ContactID]  ,[ContactClassTypeID]  ,[TransactionID] ,[TransactionClassTypeID]  ,[IsVoided]  ,[VoidedDateTime]  ,[VoidedEntryID] ,[VoidedEntryClassTypeID]  ,[VoidedReason]  ,[QueryStartDateTime]
              ,[QueryEndDateTime]  ,[ReminderDateTime]  ,[ReminderPrompt]  ,[PartID]  ,[ActivityType]  ,[ActivityTypeText]  ,[IsBillable]   ,[BillableDateTime]  ,[UseActualTime]  ,[BillingNotes]  ,[BillingType]  ,[TotalBilledTime]  ,[RecurringActivityID]  ,[LinkID]  ,[LinkStoreID]
              ,[LinkClassTypeID] ,[SpecialCode] ,[DivisionID] ,[HasCalendarLinks] ,[TipRecipientID] ,[PartClassTypeID] ,[RecurringClassTypeID] ,[StationID] ,[StationClassTypeID] ,[CurrentState] ,[StageID] ,[StageClassTypeID]) 
              VALUES 
              ( @DetailPaymentID     -- (
              , -1     -- ,
              , 20001     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              ,  0    -- ,
              ,  0    -- ,
              ,  1    -- ,
              , @EmployeeID  -- 
              , 2  -- 
              , 'Payment'  -- 
              , LEFT( (CASE WHEN @PaymentToOrder > 0 
                            THEN 'Order Payment for #'
                            ELSE 'Refund Payment for #'
                       END)+convert(varchar(12), @OrderNumber)+' - '+@CompanyName, 50) -- 
              , @Notes  -- 
              , @PaymentDT  -- 
              , @PaymentDT  -- 
              , NULL  -- 
              , NULL  -- 
              , @EmployeeID  -- 
              , @PaymentDT  -- 
              , 0  -- 
              , 1  -- 
              , @MasterPaymentID  -- 
              , 20000  -- 
              , 0  -- 
              , @PaymentToOrder  -- 
              , @OrderGLGroupID  -- 
              , @OrderGLGroupID  -- 
              , @AccountID  -- 
              , 2000  -- 
              , @ContactID  -- 
              , 3000  -- 
              , @THID  -- 
              , 10000  -- 
              , 0  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , @PaymentDT  -- 
              , @PaymentDT  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , 0  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , @DivisionID  -- 
              , 0  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- )
              );
  1. - Insert Detail Record into Payment Table
              INSERT INTO [Payment] 
              ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[NameOnCard] ,[TrackingNumber] ,[PaymentAccountID] ,[PaymentAccountClassTypeID] ,[ExpirationDate] ,[VCode] ,[IsCCNumEncrypt] ,[DisplayNumber] ,[IsVCodeEncrypted] ,[Undeposited] ,[DepositGLGroupID] ,[DepositJournalID] ,[PaymentDate] ,[BankAccountID] ,[BankAccountClasstypeID] ,[TenderType] ,[PayrollID] ,[PayrollClassTypeID] ,[PaycheckID] ,[BankReference] ,[BankCode] ,[BranchCode] ,[CIN] ,[State] ,[CCAccount]
              ,[CCCSTransactionGuid] ,[CCCSCustomerGuid] ,[IsActualCheck])
              VALUES 
              ( @DetailPaymentID     -- (
              , -1     -- ,
              , 20001     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              , 0    -- ,
              , 0    -- ,
              , 1    -- ,
              , ''     -- ,
              , NULL     -- ,
              , @PaymentMethodID     -- ,
              , 8002     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , 0     -- ,
              , @DisplayNumber     -- ,
              , NULL     -- ,
              , 0        -- ,
              , NULL     -- ,
              , NULL     -- ,
              , @PaymentDT     -- ,
              , @GLPaymentAccountID     -- ,
              , 8001     -- ,
              , 2     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , 0     -- ,)
              );
  1. - Create GL Entries for Payment Account
              INSERT INTO [Ledger] 
              ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EntryDateTime] ,[Amount] ,[Classification] ,[IsTaxable] ,[GroupID] ,[GLAccountID] ,[GLAccountClassTypeID] ,[AccountID] ,[AccountClassTypeID] ,[TransactionID] ,[TransactionClassTypeID] ,[TransDetailID] ,[TransDetailClassTypeID] ,[GoodsItemID] ,[GoodsItemClassTypeID] ,[Description] ,[DivisionID] ,[Notes] ,[IsModified] ,[IsUser] ,[TaxClassID] ,[Quantity] ,[PartID] ,[PartClassTypeID] ,[JournalID] ,[JournalClassTypeID] ,[Reconciled] ,[ReconciliationDateTime] ,[ReconciliationID] ,[ReconciliationClassTypeID] ,[ProcessedDivisionID] ,[GLClassificationType] ,[GLClassTypeName] ,[TransPartID] ,[TransPartClassTypeID] ,[StationID] ,[PayrollID] ,[PayrollClassTypeID] ,[DepositJournalID] ,[EntryType] ,[EmployeeID] ,[OffBalanceSheet] ,[WarehouseID] ,[InventoryID])
              VALUES
              ( @LedgerID+@LedgerIDOffset   -- 
              , -1     -- ,
              , 8900     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              , 0    -- ,
              , 0    -- ,
              , 1    -- ,
              , @PaymentDT   -- 
              , @PaymentToOrder   -- 
              , @PaymentMethodID   -- 
              , 0   -- 
              , @OrderGLGroupID   -- 
              , @GLPaymentAccountID   -- 
              , 8001   -- 
              , @AccountID   -- 
              , 2000   -- 
              , @THID   -- 
              , 10000   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , (CASE WHEN @PaymentToOrder > 0 THEN 'Order Payment' ELSE 'Refund Payment' END)   -- 
              , @DivisionID   -- 
              , @Notes   -- 
              , 0   -- 
              , 0   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , @DetailPaymentID   -- 
              , 20001   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , @DivisionID   -- 
              , @PaymentGLClassificationType -- 
              , @PaymentGLClassificationName -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , 3   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              )
              SET @LedgerIDOffset = @LedgerIDOffset + 1;
  1. - Create GL Entry #2 for Offset to Order Payments
              INSERT INTO [Ledger] 
              ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EntryDateTime] ,[Amount] ,[Classification] ,[IsTaxable] ,[GroupID] ,[GLAccountID] ,[GLAccountClassTypeID] ,[AccountID] ,[AccountClassTypeID] ,[TransactionID] ,[TransactionClassTypeID] ,[TransDetailID] ,[TransDetailClassTypeID] ,[GoodsItemID] ,[GoodsItemClassTypeID] ,[Description] ,[DivisionID] ,[Notes] ,[IsModified] ,[IsUser] ,[TaxClassID] ,[Quantity] ,[PartID] ,[PartClassTypeID] ,[JournalID] ,[JournalClassTypeID] ,[Reconciled] ,[ReconciliationDateTime] ,[ReconciliationID] ,[ReconciliationClassTypeID] ,[ProcessedDivisionID] ,[GLClassificationType] ,[GLClassTypeName] ,[TransPartID] ,[TransPartClassTypeID] ,[StationID] ,[PayrollID] ,[PayrollClassTypeID] ,[DepositJournalID] ,[EntryType] ,[EmployeeID] ,[OffBalanceSheet] ,[WarehouseID] ,[InventoryID])
              VALUES
              ( @LedgerID+@LedgerIDOffset   -- 
              , -1     -- ,
              , 8900     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              , 0    -- ,
              , 0    -- ,
              , 1    -- ,
              , @PaymentDT   -- 
              , -@PaymentToOrder   -- 
              , 0   -- 
              , 0   -- 
              , @OrderGLGroupID   -- 
              , @GLAccountOffset  -- 
              , 8001   -- 
              , @AccountID   -- 
              , 2000   -- 
              , @THID   -- 
              , 10000   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , (CASE WHEN @PaymentToOrder > 0 THEN 'Order Payment' ELSE 'Refund Payment' END)   -- 
              , @DivisionID   -- 
              , @Notes   -- 
              , 0   -- 
              , 0   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , @DetailPaymentID   -- 
              , 20001   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , @DivisionID   -- 
              , (CASE WHEN @GLAccountOffset = 24 THEN 2002 ELSE 1002 END) -- 
              , (CASE WHEN @GLAccountOffset = 24 THEN 'Current Asset' ELSE 'Current Liability' END)   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , 3   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              );
              SET @LedgerIDOffset = @LedgerIDOffset + 1;
  1. - ———————————————————–
  1. - Update Order with new Balance and check if the Order should be closed
  1. - ———————————————————–
              UPDATE TransHeader
              SET     SeqID                = @NewSeqNo
                      , ModifiedDate       = @DT
                      , ModifiedByComputer = @ComputerName
                      , ModifiedByUser     = @ProcName
                      , PaymentTotal  = (PaymentTotal + @PaymentToOrder)
                      , BalanceDue    = (BalanceDue - @PaymentToOrder)
                      , StatusID      = (case when @closeOrder   = 1 then 4 
                                              when @UncLoseOrder = 1 then 3
                                              else StatusID  -- keep the same
                                         end)
                      , ClosedDate    = (case when @closeOrder   = 1 then @PaymentDT 
                                              when @UncLoseOrder = 1 then NULL
                                              else ClosedDate -- keep the same
                                         end)
                      , StatusText    = (case when @closeOrder = 1 then 'Closed' else StatusText end)
              WHERE ID = @THID;
          END;
  1. - ———————————————————–
  1. - Handle CREDIT part of Payment
  1. - ———————————————————–
          IF (@PaymentToCredit  0.0)
          BEGIN /* A region */
  1. - Insert CREDIT Detail Record into Journal
              INSERT INTO [Journal] ([ID], [StoreID], [ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EmployeeID],[JournalActivityType] ,[JournalActivityText] ,[Description] ,[Notes] ,[StartDateTime] ,[EndDateTime] ,[TotalTime] ,[ScheduledDateTime]  ,[CompletedByID] ,[CompletedDateTime] ,[IsSummary] ,[IsDetail] ,[SummaryID] ,[SummaryClassTypeID] ,[SummaryAmount] ,[DetailAmount]
              ,[StartGLGroupID]  ,[EndGLGroupID]  ,[AccountID] ,[AccountClassTypeID]  ,[ContactID]  ,[ContactClassTypeID]  ,[TransactionID] ,[TransactionClassTypeID]  ,[IsVoided]  ,[VoidedDateTime]  ,[VoidedEntryID] ,[VoidedEntryClassTypeID]  ,[VoidedReason]  ,[QueryStartDateTime]
              ,[QueryEndDateTime]  ,[ReminderDateTime]  ,[ReminderPrompt]  ,[PartID]  ,[ActivityType]  ,[ActivityTypeText]  ,[IsBillable]   ,[BillableDateTime]  ,[UseActualTime]  ,[BillingNotes]  ,[BillingType]  ,[TotalBilledTime]  ,[RecurringActivityID]  ,[LinkID]  ,[LinkStoreID]
              ,[LinkClassTypeID] ,[SpecialCode] ,[DivisionID] ,[HasCalendarLinks] ,[TipRecipientID] ,[PartClassTypeID] ,[RecurringClassTypeID] ,[StationID] ,[StationClassTypeID] ,[CurrentState] ,[StageID] ,[StageClassTypeID]) 
              VALUES 
              ( @DetailCreditID     -- (
              , -1     -- ,
              , 20002     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              ,  0    -- ,
              ,  0    -- ,
              ,  1    -- ,
              , @EmployeeID  -- 
              , 2  -- 
              , 'Payment'  -- 
              , LEFT( (CASE WHEN @PaymentToCredit > 0 
                            THEN 'OverPayment for '
                            ELSE 'Refund Credit for '
                       END)+@CompanyName, 50) -- 
              , @Notes  -- 
              , @PaymentDT  -- 
              , @PaymentDT  -- 
              , NULL  -- 
              , NULL  -- 
              , @EmployeeID  -- 
              , @PaymentDT  -- 
              , 0  -- 
              , 1  -- 
              , @MasterPaymentID  -- 
              , 20000  -- 
              , 0  -- 
              , @PaymentToCredit  -- 
              , @CreditGLGroupID  -- 
              , @CreditGLGroupID  -- 
              , @AccountID  -- 
              , 2000  -- 
              , @ContactID  -- 
              , 3000  -- 
              , NULL  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , @PaymentDT  -- 
              , @PaymentDT  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , NULL  -- 
              , 0  -- 
              , 0  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , @DivisionID  -- 
              , 0  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- 
              , NULL  -- )
              );
  1. - Insert CREDIT Detail Record into Payment Table
              INSERT INTO [Payment] 
              ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[NameOnCard] ,[TrackingNumber] ,[PaymentAccountID] ,[PaymentAccountClassTypeID] ,[ExpirationDate] ,[VCode] ,[IsCCNumEncrypt] ,[DisplayNumber] ,[IsVCodeEncrypted] ,[Undeposited] ,[DepositGLGroupID] ,[DepositJournalID] ,[PaymentDate] ,[BankAccountID] ,[BankAccountClasstypeID] ,[TenderType] ,[PayrollID] ,[PayrollClassTypeID] ,[PaycheckID] ,[BankReference] ,[BankCode] ,[BranchCode] ,[CIN] ,[State] ,[CCAccount]
              ,[CCCSTransactionGuid] ,[CCCSCustomerGuid] ,[IsActualCheck])
              VALUES 
              ( @DetailCreditID     -- (
              , -1     -- ,
              , 20002     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              , 0    -- ,
              , 0    -- ,
              , 1    -- ,
              , ''     -- ,
              , NULL     -- ,
              , @PaymentMethodID     -- ,
              , 8002     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , 0     -- ,
              , @DisplayNumber     -- ,
              , NULL     -- ,
              , 0        -- ,
              , NULL     -- ,
              , NULL     -- ,
              , @PaymentDT     -- ,
              , @GLPaymentAccountID     -- ,
              , 8001     -- ,
              , 2     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , NULL     -- ,
              , 0     -- ,)
              );
  1. - Create GL Entries for Customer Credit
              INSERT INTO [Ledger] 
              ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EntryDateTime] ,[Amount] ,[Classification] ,[IsTaxable] ,[GroupID] ,[GLAccountID] ,[GLAccountClassTypeID] ,[AccountID] ,[AccountClassTypeID] ,[TransactionID] ,[TransactionClassTypeID] ,[TransDetailID] ,[TransDetailClassTypeID] ,[GoodsItemID] ,[GoodsItemClassTypeID] ,[Description] ,[DivisionID] ,[Notes] ,[IsModified] ,[IsUser] ,[TaxClassID] ,[Quantity] ,[PartID] ,[PartClassTypeID] ,[JournalID] ,[JournalClassTypeID] ,[Reconciled] ,[ReconciliationDateTime] ,[ReconciliationID] ,[ReconciliationClassTypeID] ,[ProcessedDivisionID] ,[GLClassificationType] ,[GLClassTypeName] ,[TransPartID] ,[TransPartClassTypeID] ,[StationID] ,[PayrollID] ,[PayrollClassTypeID] ,[DepositJournalID] ,[EntryType] ,[EmployeeID] ,[OffBalanceSheet] ,[WarehouseID] ,[InventoryID])
              VALUES
              ( @LedgerID+@LedgerIDOffset   -- 
              , -1     -- ,
              , 8900     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              , 0    -- ,
              , 0    -- ,
              , 1    -- ,
              , @PaymentDT   -- 
              , @PaymentToCredit   -- 
              , @PaymentMethodID   -- 
              , 0   -- 
              , @CreditGLGroupID   -- 
              , @GLPaymentAccountID   -- 
              , 8001   -- 
              , @AccountID   -- 
              , 2000   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , LEFT( (CASE WHEN @PaymentToCredit > 0 THEN 'Overpayment for ' ELSE 'Refund Payment for' END)+@CompanyName, 50)   -- 
              , @DivisionID   -- 
              , @Notes   -- 
              , 0   -- 
              , 0   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , @DetailCreditID   -- 
              , 20002   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , @DivisionID   -- 
              , @PaymentGLClassificationType -- 
              , @PaymentGLClassificationName -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , 3   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              )
              SET @LedgerIDOffset = @LedgerIDOffset + 1;
  1. - Create GL Entry #2 for Offset to Credits
              INSERT INTO [Ledger] 
              ([ID] ,[StoreID] ,[ClassTypeID] ,[ModifiedByUser] ,[ModifiedByComputer] ,[ModifiedDate] ,[SeqID] ,[IsSystem] ,[IsActive] ,[EntryDateTime] ,[Amount] ,[Classification] ,[IsTaxable] ,[GroupID] ,[GLAccountID] ,[GLAccountClassTypeID] ,[AccountID] ,[AccountClassTypeID] ,[TransactionID] ,[TransactionClassTypeID] ,[TransDetailID] ,[TransDetailClassTypeID] ,[GoodsItemID] ,[GoodsItemClassTypeID] ,[Description] ,[DivisionID] ,[Notes] ,[IsModified] ,[IsUser] ,[TaxClassID] ,[Quantity] ,[PartID] ,[PartClassTypeID] ,[JournalID] ,[JournalClassTypeID] ,[Reconciled] ,[ReconciliationDateTime] ,[ReconciliationID] ,[ReconciliationClassTypeID] ,[ProcessedDivisionID] ,[GLClassificationType] ,[GLClassTypeName] ,[TransPartID] ,[TransPartClassTypeID] ,[StationID] ,[PayrollID] ,[PayrollClassTypeID] ,[DepositJournalID] ,[EntryType] ,[EmployeeID] ,[OffBalanceSheet] ,[WarehouseID] ,[InventoryID])
              VALUES
              ( @LedgerID+@LedgerIDOffset   -- 
              , -1     -- ,
              , 8900     -- ,
              , @ProcName     -- ,
              , @ComputerName     -- ,
              , @DT    -- ,
              , 0    -- ,
              , 0    -- ,
              , 1    -- ,
              , @PaymentDT   -- 
              , -@PaymentToCredit   -- 
              , 0   -- 
              , 0   -- 
              , @CreditGLGroupID   -- 
              , 23  -- 
              , 8001   -- 
              , @AccountID   -- 
              , 2000   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , LEFT( (CASE WHEN @PaymentToCredit > 0 THEN 'Overpayment for ' ELSE 'Refund Payment for' END)+@CompanyName, 50)   -- 
              , @DivisionID   -- 
              , @Notes   -- 
              , 0   -- 
              , 0   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , @DetailCreditID   -- 
              , 20002   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , @DivisionID   -- 
              , 2002 -- 
              , 'Current Liability'   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , NULL   -- 
              , 3   -- 
              , NULL   -- 
              , 0   -- 
              , NULL   -- 
              , NULL   -- 
              );
              SET @LedgerIDOffset = @LedgerIDOffset + 1;
  1. - ———————————————————–
  1. - Update Customer Record with new credit Balance
  1. - ———————————————————–
              UPDATE Account
              SET     SeqID                = @NewSeqNo
                      , ModifiedDate       = @DT
                      , ModifiedByComputer = @ComputerName
                      , ModifiedByUser     = @ProcName
                      , CreditBalance  = (CreditBalance + @PaymentToCredit)
              WHERE ID = @AccountID;
          END;
  1. - ———————————————————–
  1. - Now commit the Transaction
  1. - ———————————————————–
          COMMIT TRANSACTION
      END TRY
  1. - ———————————————————–
  1. - Handle any Errors
  1. - ———————————————————–
      BEGIN CATCH
          ROLLBACK TRANSACTION;
          IF (@OrderLocked = 1) 
              EXEC dbo.csf_chapi_unlock @THID, 10000;
          IF (@CompanyLocked = 1)
              EXEC dbo.csf_chapi_unlock @AccountID, 2000;
          SELECT @ErrorMessage = ERROR_MESSAGE(),
              @ErrorNumber = ERROR_NUMBER(),
              @ErrorSeverity = ERROR_SEVERITY(),
              @ErrorState = ERROR_STATE(),
              @ErrorLine = ERROR_LINE(),
              @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');
  1. - Use RAISERROR inside the CATCH block to return
  1. - error information about the original error that
  1. - caused execution to jump to the CATCH block.
          RAISERROR 
              (
              @ErrorMessage, 
              @ErrorSeverity, 
              1,               
              @ErrorNumber,    -- parameter: original error number.
              @ErrorSeverity,  -- parameter: original error severity.
              @ErrorState,     -- parameter: original error state.
              @ErrorProcedure, -- parameter: original error procedure name.
              @ErrorLine       -- parameter: original error line number.
              );  
          RETURN; 
      END CATCH;
  1. - ———————————————————–
  1. - Step 5, Release the Locks and Refresh
  1. - ———————————————————–
  IF (@OrderLocked = 1) 
      EXEC dbo.csf_chapi_unlock @THID, 10000;
  IF (@CompanyLocked = 1)
      EXEC dbo.csf_chapi_unlock @AccountID, 2000;
  IF (@RefreshRecords = 1)
  BEGIN
      IF (@PaymentToOrder  0.0)
          EXEC dbo.csf_chapi_refresh @THID, 10000, @NewSeqNo;
      IF (@PaymentToCredit  0.0)
          EXEC dbo.csf_chapi_refresh @AccountID, 2000, @NewSeqNo;
  END;
  SELECT convert(bit, 1) as RESULT;  -- True = Success

END;

code

Source

Contributor: Cyrious Software

Date: 8/2016

Version: Control 5.7+

See Also