project QadFinancials > class BCInvoice > method ApiStdMaintainTTInitialDefaulting

Description

This method is called when creating an invoice through an API right before the processing of the input.
This method can be used to default field values to the incoming dataset prior to the acctual processing.

Standard-defaulting in this method:

• Default Company_ID with the current company you are logged on to
• Default CInvoiceType with INVOICE
• Default CInvoiceCIText with CInvoiceReference.
• Default CInvoicePostingDate with CInvoiceDate (and vice-versa so one of them is mandatory).
• Default CInvoiceTaxPointDate with CInvoicePostingDate
• Default CInvoicePostingYear and CInvoicePostingPeriod based upon CInvoicePostingDate
• Default all ShipTo-, VatCurrency- and OwnVat-related fields on the invoice based upon the business-relation of the current company
• Default Invoice-status with the default invoice-status of the supplier
• Default following fields based upon the invoice-status: CInvoiceAllocationStatus, tcReasonAllocationStatus, CInvoiceIsInvoiceApproved, CInvoiceIsLockPayment, CInvoiceIsLogisticMatching and CInvoiceIsInitialStatus
• Default following fields based upon the invoice-type and the associated default profiles of the supplier; ControlGLCode, DivisionCode, CostCentreCode and ProjectCode
• Default CInvoiceSiteCode and CInvoiceDayBookSetCode based upon the supplier-defaults
• Default Daybook based upon CInvoiceSiteCode and CInvoiceDayBookSetCode and the daybooks defined in the application
• Default NormalPaymentConditionCode with the defaults of the supplier
• Default CInvoiceDueDate and CInvoiceDiscountDueDate based upon a non-staged NormalPaymentConditionCode and CInvoiceDate
• Default complete CInvoiceBank and CInvoiceBankPayCode in case no CInvoiceBank was specified
• Default CInvoiceVat.tcDomainCode with the domain of the current company
• Default CInvoiceVat.tcVatInOut with INPUT
• Default CInvoiceVat.CInvoiceVatSequence with 1
• Default following fields based upon the VatCode and the Domain related to the Company: CInvoiceVatIsUpdAllow, CInvoiceVatIsAbsRet, CInvoiceVatIsAccrRcpUs, CInvoiceVatIsRevCharge and CInvoiceVatIsSuspDel
• Replace unknown-values with an empty-string for these fields in CInvoiceVat: TxuTaxUsage, TxenvTaxEnv and TxclTaxCls
• Default the Taxable flag on the invoice-level based on the same flag on the CInvoiceVat-records
• Default following fields with their normal default-value in case they have the unknown-value: CInvoiceIsExternal, CInvoiceIsTaxConfirmed, CInvoiceIsTaxExcluded, CInvoiceCreationDate, CInvoiceIsERS, CInvoiceIsDiscTaxAtInv, CInvoiceIsDiscTaxAtPaym, CInvoiceIsVatDelay, CInvoiceNonDiscAmtTC, CInvoiceNonDiscAmtCC, CInvoiceNonDiscAmtLC, CInvoiceHoldAmountTC, CInvoiceOriginalCreditLC, CInvoiceOriginalCreditTC, CInvoiceOriginalDebitLC, CInvoiceOriginalDebitTC, CInvoiceVatBaseCreditLC, CInvoiceVatBaseCreditTC, CInvoiceVatBaseDebitLC, CInvoiceVatBaseDebitTC, CInvoiceVatCreditLC, CInvoiceVatCreditTC, CInvoiceVatDebitLC, CInvoiceVatDebitTC, CInvoiceBalanceDebitLC, CInvoiceBalanceCreditLC, CInvoiceBalanceDebitTC, CInvoiceBalanceCreditTC, CInvoiceBalanceLC, CInvoiceBalanceTC and CInvoiceBalanceCC


Parameters


oiReturnStatusoutputintegerReturn status of the method.


Internal usage


QadFinancials
method BCInvoice.ApiStdMaintainTTV01


program code (program9/bcinvoice.p)

        
    /* ============================================================================================================= */
    /* Add an include in here so we can easily trace the methods that do direct db-access (or via dynamic querying)  */
    /* As in this method a lot of different tables are accessed we do not specify the complete list here in the call */
    /* ============================================================================================================= */
    <I-51 {READDIRECTDBACCESS
         &READTABLENAMES = "Plenty of Finacials and Operational tables"}>
    
    /* ============================================================================== */
    /* Notes:                                                                         */
    /*  0. The defaulting that applies to both the Invoice and the assicoated Posting */
    /*     should be written in BCInvoiceJournalEntry as in there we have both data   */
    /*     available.                                                                 */
    /*     A sample is the JournalCode: that one is on the Invoice and on the Posting */
    /*  1. No records are available at the moment this method is entered              */
    /*  2. The records that need to be extended are the tApi-tables (eg tApiCInvoice) */
    /*  3. Exception handling is done via progress itself (on error undo throw)       */
    /*  4. Database is accessed directly and variables are defined manually to:       */
    /*        A. Come to a proper performance                                         */
    /*        B. Ease downgradability                                                 */
    /*        C. Ease installations on released products: This complete peice of code */
    /*           can be copied into the 'before' hook of the parent-method of this    */
    /*           method by using the customization-technology that we have in the Fin */
    /*  Addition: Note that only Financial-tables can be accessed directly - for      */ 
    /*            Operational tables we will have to use dynamic queries!             */ 
    /* ============================================================================== */
    
    
    /* We are naming these manual defined varaiable with an X to avoid interactions with the normaly defined method-data-items */
    define variable viXCreditorSharedSetID        as  integer no-undo. 
    define variable viXGLSharedSetID              as  integer no-undo. 
    define variable viXDivisionSharedSetID        as  integer no-undo. 
    define variable viXCostCentreSharedSetID      as  integer no-undo. 
    define variable viXProjectSharedSetID         as  integer no-undo.  
    define variable viXJournalSharedSetID         as  integer no-undo.
    define variable viXGLProfileID                as  integer no-undo.
    define variable viXDivisionProfileID          as  integer no-undo.
    define variable viXCostCentreProfileID        as  integer no-undo.
    define variable viXProjectProfileID           as  integer no-undo.    
    define variable viXGLIsDivisionAccount        as  logical no-undo.
    define variable viXGLIsCostCentreAccount      as  logical no-undo.
    define variable viXGLIsProjectAccount         as  logical no-undo.    
    define variable vcXDomainCode                 as  character no-undo.
    define variable vcXPaymentConditionPeriodType as  character no-undo.
    define variable vtXPaymentConditionBaseDate   as  date no-undo.
    define variable viXPaymentConditionDaysMonths as  integer no-undo.
    define variable viXPaymentConditionSupplDays  as  integer no-undo.
    define variable viXPaymentConditionBaseDays   as  integer no-undo.
    define variable viXPaymentConditionDueDays    as  integer no-undo.
    define variable viXPaymentConditionDayMthDisc as  integer no-undo.
    define variable viXPaymentConditionSupDayDisc as  integer no-undo.
    define variable vcXPaymentConditionpDiscType  as  character no-undo.
    define variable vtXPaymentConditionStartDate  as  date no-undo.
    define variable viXBankNumberID               as  integer no-undo.
    define variable viXbXBankNumberID             as  integer no-undo.
    define variable viXBankPayFormatID            as  integer no-undo.
    define buffer   bXBankNumber                  for BankNumber.
    define buffer   bXCurrency                    for Currency.    
    define variable vhXBufferPocCtrl              as  handle no-undo.
    define variable vhXQueryPocCtrl               as  handle no-undo.
    define variable vhXBufferDybsMstr             as  handle no-undo.
    define variable vhXQueryDybsMstr              as  handle no-undo.
    define variable vhXBufferVdMstr               as  handle no-undo.
    define variable vhXQueryVdMstr                as  handle no-undo.
    define variable vhXBufferTx2Mstr              as  handle no-undo.
    define variable vhXQueryTx2Mstr               as  handle no-undo.
    define variable vhXBufferPoMstr               as  handle no-undo.
    define variable vhXQueryPoMstr                as  handle no-undo.
    define variable vhXBufferAdMstr               as  handle no-undo.
    define variable vhXQueryAdMstr                as  handle no-undo.
    define variable vtXCInvoiceStageDueDate       as  date no-undo.
    define variable vtXCInvoiceStageDiscDate      as  date no-undo.
    define variable vdXCInvoiceOriginalTC         as  decimal no-undo.
    define variable vlXNoRecord                   as logical no-undo.
    define variable vlXNoDueDates                 as logical no-undo.
    define buffer   bXPaymentCondition            for PaymentCondition.

    /* Initialise the handles for queries and buffers */
    CREATE BUFFER vhXBufferPocCtrl          FOR TABLE "poc_ctrl".
    CREATE QUERY vhXQueryPocCtrl.
    vhXQueryPocCtrl:Set-Buffers(vhXBufferPocCtrl).
    CREATE BUFFER vhXBufferDybsMstr         FOR TABLE "dybs_mstr".
    CREATE QUERY vhXQueryDybsMstr.
    vhXQueryDybsMstr:Set-Buffers(vhXBufferDybsMstr).
    CREATE BUFFER vhXBufferVdMstr           FOR TABLE "vd_mstr".
    CREATE QUERY vhXQueryVdMstr.
    vhXQueryVdMstr:Set-Buffers(vhXBufferVdMstr).    
    CREATE BUFFER vhXBufferTx2Mstr          FOR TABLE "tx2_mstr".
    CREATE QUERY vhXQueryTx2Mstr.
    vhXQueryTx2Mstr:Set-Buffers(vhXBufferTx2Mstr).
    CREATE BUFFER vhXBufferPoMstr           FOR TABLE "po_mstr".
    CREATE QUERY vhXQueryPoMstr.
    vhXQueryPoMstr:Set-Buffers(vhXBufferPoMstr).
    CREATE BUFFER vhXBufferAdMstr           FOR TABLE "ad_mstr".
    CREATE QUERY vhXQueryAdMstr.
    vhXQueryAdMstr:Set-Buffers(vhXBufferAdMstr).
    
    
    /* ====================================================== */
    /* Go through all invoices as only new-mode is supported  */
    /* ====================================================== */
    for each tApiCInvoice on error undo, throw :
        
        /* ================================================================================================= */
        /* Avoid unkown-values as this is not allowed although some interfaces (like QXtend) do pass in this */
        /* ================================================================================================= */
        assign tApiCInvoice.CInvoiceIsExternal        = no    when tApiCInvoice.CInvoiceIsExternal        = ?
               tApiCInvoice.CInvoiceIsTaxConfirmed    = yes   when tApiCInvoice.CInvoiceIsTaxConfirmed    = ?
               tApiCInvoice.CInvoiceIsTaxExcluded     = no    when tApiCInvoice.CInvoiceIsTaxExcluded     = ?
               tApiCInvoice.CInvoiceCreationDate      = today when tApiCInvoice.CInvoiceCreationDate      = ?
               tApiCInvoice.CInvoiceIsERS             = no    when tApiCInvoice.CInvoiceIsERS             = ?
               tApiCInvoice.CInvoiceIsDiscTaxAtInv    = no    when tApiCInvoice.CInvoiceIsDiscTaxAtInv    = ?
               tApiCInvoice.CInvoiceIsDiscTaxAtPaym   = no    when tApiCInvoice.CInvoiceIsDiscTaxAtPaym   = ?
               tApiCInvoice.CInvoiceIsVatDelay        = no    when tApiCInvoice.CInvoiceIsVatDelay        = ?
               tApiCInvoice.CInvoiceNonDiscAmtTC      = 0     when tApiCInvoice.CInvoiceNonDiscAmtTC      = ?
               tApiCInvoice.CInvoiceNonDiscAmtCC      = 0     when tApiCInvoice.CInvoiceNonDiscAmtCC      = ?
               tApiCInvoice.CInvoiceNonDiscAmtLC      = 0     when tApiCInvoice.CInvoiceNonDiscAmtLC      = ?
               tApiCInvoice.CInvoiceHoldAmountTC      = 0     when tApiCInvoice.CInvoiceHoldAmountTC      = ?
               tApiCInvoice.CInvoiceOriginalCreditLC  = 0     when tApiCInvoice.CInvoiceOriginalCreditLC  = ?
               tApiCInvoice.CInvoiceOriginalCreditTC  = 0     when tApiCInvoice.CInvoiceOriginalCreditTC  = ?
               tApiCInvoice.CInvoiceOriginalDebitLC   = 0     when tApiCInvoice.CInvoiceOriginalDebitLC   = ?
               tApiCInvoice.CInvoiceOriginalDebitTC   = 0     when tApiCInvoice.CInvoiceOriginalDebitTC   = ?
               tApiCInvoice.CInvoiceVatBaseCreditLC   = 0     when tApiCInvoice.CInvoiceVatBaseCreditLC   = ?
               tApiCInvoice.CInvoiceVatBaseCreditTC   = 0     when tApiCInvoice.CInvoiceVatBaseCreditTC   = ?
               tApiCInvoice.CInvoiceVatBaseDebitLC    = 0     when tApiCInvoice.CInvoiceVatBaseDebitLC    = ?
               tApiCInvoice.CInvoiceVatBaseDebitTC    = 0     when tApiCInvoice.CInvoiceVatBaseDebitTC    = ?
               tApiCInvoice.CInvoiceVatCreditLC       = 0     when tApiCInvoice.CInvoiceVatCreditLC       = ?
               tApiCInvoice.CInvoiceVatCreditTC       = 0     when tApiCInvoice.CInvoiceVatCreditTC       = ?
               tApiCInvoice.CInvoiceVatDebitLC        = 0     when tApiCInvoice.CInvoiceVatDebitLC        = ?
               tApiCInvoice.CInvoiceVatDebitTC        = 0     when tApiCInvoice.CInvoiceVatDebitTC        = ?
               tApiCInvoice.CInvoiceBalanceDebitLC    = 0     when tApiCInvoice.CInvoiceBalanceDebitLC    = ?
               tApiCInvoice.CInvoiceBalanceCreditLC   = 0     when tApiCInvoice.CInvoiceBalanceCreditLC   = ?
               tApiCInvoice.CInvoiceBalanceDebitTC    = 0     when tApiCInvoice.CInvoiceBalanceDebitTC    = ?
               tApiCInvoice.CInvoiceBalanceCreditTC   = 0     when tApiCInvoice.CInvoiceBalanceCreditTC   = ?
               tApiCInvoice.CInvoiceBalanceLC         = 0     when tApiCInvoice.CInvoiceBalanceLC         = ?
               tApiCInvoice.CInvoiceBalanceTC         = 0     when tApiCInvoice.CInvoiceBalanceTC         = ?
               tApiCInvoice.CInvoiceBalanceCC         = 0     when tApiCInvoice.CInvoiceBalanceCC         = ?.
        
        /* ================================================ */
        /* Fill in tApiCInvoice.tc_Rowid when not specified */
        /* Fill in default Company_ID when not specified    */
        /* Fill in default InvoiceType when not specified   */
        /* Fill CIText with Reference when not specified    */
        /* ================================================ */
        if tApiCInvoice.tc_Rowid = "":U or 
           tApiCInvoice.tc_Rowid = ?
        then assign tApiCInvoice.tc_Rowid = string(rowid(tApiCInvoice)).
        if tApiCInvoice.Company_ID = ? or
           tApiCInvoice.Company_ID = 0
        then assign tApiCInvoice.Company_ID = viCompanyID.
        if tApiCInvoice.CInvoiceType = ? or 
           tApiCInvoice.CInvoiceType = "":U
        then assign tApiCInvoice.CInvoiceType = {&INVOICETYPE-INVOICE}. /* INVOICE */ 
        if tApiCInvoice.CInvoiceCIText = "":U or 
           tApiCInvoice.CInvoiceCIText = ?
        then assign tApiCInvoice.CInvoiceCIText = tApiCInvoice.CInvoiceReference.
        if tApiCInvoice.CInvoiceDescription = "":U or 
           tApiCInvoice.CInvoiceDescription = ?
        then assign tApiCInvoice.CInvoiceDescription = substring(tApiCInvoice.CInvoiceReference + " ":U + tApiCInvoice.tcCreditorCode,1,40,'Character':U).
        
        /* =================================== */
        /* Get the DomainCode and SharedSetIDs */
        /* =================================== */
        For each Company where 
                 Company.Company_ID = tApiCInvoice.Company_ID
                 no-lock ,
            first Domains of Company no-lock,
            each CompanySharedSet of Company no-lock
            on error undo, throw :
            Assign vcXDomainCode = Domains.DomainCode.
            For each SharedSet of CompanySharedSet where 
                     SharedSet.SharedSetTypeCode = {&SHAREDSETTYPE-CREDITOR} /* CREDITOR */
                     no-lock 
                     on error undo, throw :
                assign viXCreditorSharedSetID = SharedSet.SharedSet_ID.
            end. /* For each SharedSet of CompanySharedSet where */
            For each SharedSet of CompanySharedSet where 
                     SharedSet.SharedSetTypeCode = {&SHAREDSETTYPE-GL} /* GL */
                     no-lock 
                     on error undo, throw :
                assign viXGLSharedSetID = SharedSet.SharedSet_ID.
            end. /* For each SharedSet of CompanySharedSet where */
            For each SharedSet of CompanySharedSet where 
                     SharedSet.SharedSetTypeCode = {&SHAREDSETTYPE-DIVISION} /* DIVISION */
                     no-lock 
                     on error undo, throw :
                assign viXDivisionSharedSetID = SharedSet.SharedSet_ID.
            end. /* For each SharedSet of CompanySharedSet where */
            For each SharedSet of CompanySharedSet where 
                     SharedSet.SharedSetTypeCode = {&SHAREDSETTYPE-PROJECT} /* PROJECT */
                     no-lock 
                     on error undo, throw :
                assign viXProjectSharedSetID = SharedSet.SharedSet_ID.
            end. /* For each SharedSet of CompanySharedSet where */
            For each SharedSet of CompanySharedSet where 
                     SharedSet.SharedSetTypeCode = {&SHAREDSETTYPE-COSTCENTRE} /* COSTCENTRE */
                     no-lock 
                     on error undo, throw :
                assign viXCostCentreSharedSetID = SharedSet.SharedSet_ID.
            end. /* For each SharedSet of CompanySharedSet where */
            For each SharedSet of CompanySharedSet where 
                     SharedSet.SharedSetTypeCode = {&SHAREDSETTYPE-JOURNAL} /* JOURNAL */
                     no-lock 
                     on error undo, throw :
                assign viXJournalSharedSetID = SharedSet.SharedSet_ID.
            end. /* For each SharedSet of CompanySharedSet where */
        end. /* For each Company where */                 
        if viXCreditorSharedSetID = 0 or 
           viXCreditorSharedSetID = ? 
        then Return. /* If this missing then further defaulting makes no sense */

        /* ============================================================= */
        /* PostingDate-InvoiceDate-TaxPointDate + AccountingYearPeriod   */
        /* ============================================================= */
        if tApiCInvoice.CInvoicePostingDate  = ? and 
           tApiCInvoice.CInvoiceDate         = ?
        then assign tApiCInvoice.CInvoicePostingDate = today.
        if tApiCInvoice.CInvoicePostingDate  = ? and 
           tApiCInvoice.CInvoiceDate        <> ? 
        then assign tApiCInvoice.CInvoicePostingDate = tApiCInvoice.CInvoiceDate.
        if tApiCInvoice.CInvoiceDate         = ? and 
           tApiCInvoice.CInvoicePostingDate <> ? 
        then assign tApiCInvoice.CInvoiceDate = tApiCInvoice.CInvoicePostingDate. 
        if tApiCInvoice.CInvoiceTaxPointDate = ? and 
           tApiCInvoice.CInvoicePostingDate <> ? 
        then assign tApiCInvoice.CInvoiceTaxPointDate = tApiCInvoice.CInvoicePostingDate. 
        if tApiCInvoice.CInvoicePostingDate <> ? and 
           (tApiCInvoice.CInvoicePostingYear = 0 or 
            tApiCInvoice.CInvoicePostingYear = ?) and 
           (tApiCInvoice.CInvoicePostingPeriod = 0 or 
            tApiCInvoice.CInvoicePostingPeriod = ?)
        then do :
            Release Period no-error.
            Find Period where 
                 Period.Company_ID                 = tApiCInvoice.Company_ID          and 
                 Period.PeriodStartDate           <= tApiCInvoice.CInvoicePostingDate and 
                 Period.PeriodEndDate             >= tApiCInvoice.CInvoicePostingDate and 
                 Period.PeriodTypeCode             = {&PERIODTYPECODE-NORMAL}         and /* NORM */
                 Period.PeriodIsPostingGLAllowed   = true                             and
                 Period.PeriodIsPostingPurchAllow  = true 
                 no-lock no-error.
            if not available Period 
            then Find Period where 
                      Period.Company_ID                 = tApiCInvoice.Company_ID          and 
                      Period.PeriodStartDate           <= tApiCInvoice.CInvoicePostingDate and 
                      Period.PeriodEndDate             >= tApiCInvoice.CInvoicePostingDate and 
                      Period.PeriodIsPostingGLAllowed   = true                             and
                      Period.PeriodIsPostingPurchAllow  = true 
                      no-lock no-error.
            if available Period
            then assign tApiCInvoice.CInvoicePostingYear   = Period.PeriodYear
                        tApiCInvoice.CInvoicePostingPeriod = Period.PeriodPeriod.
        end. /* if tApiCInvoice.CInvoicePostingDate <> ? and */

        /* ================================================================ */
        /* Find the Creditor record                                         */
        /* Fill in Creditor_ID as we need that to default the bank-data etc */
        /* ================================================================ */
        Release Creditor no-error.
        if tApiCInvoice.Creditor_ID = ? or 
           tApiCInvoice.Creditor_ID = 0 
        then do:
            if tApiCInvoice.tcCreditorCode <> "":U and 
               tApiCInvoice.tcCreditorCode <> ?
            then do :
                find Creditor where 
                     Creditor.SharedSet_ID = viXCreditorSharedSetID and 
                     Creditor.CreditorCode = tApiCInvoice.tcCreditorCode
                     no-lock no-error.
                if available Creditor
                then assign tApiCInvoice.Creditor_ID = Creditor.Creditor_ID.
            end. /* if tApiCInvoice.tcCreditorCode <> "":U and  */
        end. /* if (tApiCInvoice.Creditor_ID = ? or  */
        else find Creditor where 
                  Creditor.Creditor_ID = tApiCInvoice.Creditor_ID
                  no-lock no-error.
        if not available Creditor
        then Return. /* If this missing then further defaulting makes no sense */
        
        /* ============================================================================================================= */
        /* If the PO on tApiCInvoice is empty and there are tCInvoicePO-records then fille the PO on the invoice with it */
        /* ============================================================================================================= */
        if tApiCInvoice.CInvoicePoNbr = "":U or 
           tApiCInvoice.CInvoicePoNbr = ?
        then do :
            Find first tApiCInvoicePO where 
                       tApiCInvoicePO.tc_ParentRowid  = tApiCInvoice.tc_Rowid and 
                       tApiCInvoicePO.CInvoicePOPoNbr <> "":U                 and 
                       tApiCInvoicePO.CInvoicePOPoNbr <> ?
                       no-error.
            if available tApiCInvoicePO 
            then do :
                assign tApiCInvoice.CInvoicePoNbr = tApiCInvoicePO.CInvoicePOPoNbr.
                if tApiCInvoice.CInvoicePoDomain = "":U or 
                   tApiCInvoice.CInvoicePoDomain = ?
                then assign tApiCInvoice.CInvoicePoDomain = vcXDomainCode.
                if tApiCInvoicePO.CInvoicePOPoDomain = "":U or 
                   tApiCInvoicePO.CInvoicePOPoDomain = ?
                then assign tCInvoicePO.CInvoicePOPoDomain = vcXDomainCode.
            end. /* if available tApiCInvoicePO */
        end. /* if (tApiCInvoice.CInvoicePoDomain = "":U or  */
        
        /* ============================================================================================================== */
        /* Fill in the ShipTo-fields (and the associated BusRel) when not specified                                       */
        /* If the PO on invoice-level is filled then ShipTo is taken from the PO and else from the company of the invoice */ 
        /* Note that although we here default the correct ShipTo, the ShipTo on the final invoice will not be the one we  */
        /* state here because by default, method CreateCinvoices that is called from ApiStdMaintainTTWithIntPost is       */
        /* overwriting the ShoTo. So to make sure the final invoice has got the ShoTo that is specified here, we also     */
        /* need changes in method ApiStdMaintainTTWithIntPost after CreateCInvoices is called                             */
        /* ============================================================================================================== */
        if (tApiCInvoice.tcShipToAddressStreet1 = "":U or 
            tApiCInvoice.tcShipToAddressStreet1 = ?) and 
           (tApiCInvoice.tcShipToBusinessRelationCode = "":U or 
            tApiCInvoice.tcShipToBusinessRelationCode = ?)
        then do :
            if tApiCInvoice.CInvoicePoNbr    <> "":U and
               tApiCInvoice.CInvoicePoNbr    <> ?    and
               tApiCInvoice.CInvoicePoDomain <> "":U and 
               tApiCInvoice.CInvoicePoDomain <> ?
            then do :
                /* Get the PO of the invoice */
                vhXQueryPoMstr:Query-Prepare("for each po_mstr where " + 
                                                      "po_mstr.po_domain = '" + tApiCInvoice.CInvoicePoDomain + "' and " + 
                                                      "po_mstr.po_nbr = '" + tApiCInvoice.CInvoicePoNbr + "' and " + 
                                                      "po_mstr.po_ship <> '' and " + 
                                                      "po_mstr.po_ship <> ? " ).
                vhXQueryPoMstr:Query-Open.
                vhXQueryPoMstr:Get-First(no-lock).
                if valid-handle(vhXBufferPoMstr) and 
                   vhXBufferPoMstr:available 
                then do :
                    /* Get the ShipTo-Address of the PO */
                    vhXQueryAdMstr:Query-Prepare("for each ad_mstr where " + 
                                                          "ad_mstr.ad_domain = '" + vhXBufferPoMstr::po_domain + "' and " + 
                                                          "ad_mstr.ad_addr = '" + vhXBufferPoMstr::po_ship + "' and " + 
                                                          "ad_mstr.ad_address_id <> 0 and " + 
                                                          "ad_mstr.ad_address_id <> ? " ).
                    vhXQueryAdMstr:Query-Open.
                    vhXQueryAdMstr:Get-First(no-lock).
                    if valid-handle(vhXBufferAdMstr) and 
                       vhXBufferAdMstr:available
                    then do :
                        /* Get all Address-details */
                        For first Address where 
                                  Address.Address_ID = vhXBufferAdMstr::ad_address_id no-lock,
                            first BusinessRelation of Address no-lock,
                            first AddressType of Address no-lock,
                            first Country of Address
                                  no-lock on error undo, throw :
                            /* Assign the ShipTo-related fields */
                            assign tApiCInvoice.tcShipToBusinessRelationCode = BusinessRelation.BusinessRelationCode
                                   tApiCInvoice.tcShipToCountryCode          = Country.CountryCode
                                   tApiCInvoice.tcOwnVatNumberCountryCode    = Country.CountryCode    
                                   tApiCInvoice.tlShipToCountryIsEUCountry   = Country.CountryIsEUCountry  
                                   tApiCInvoice.tcShipToAddressTypeCode      = AddressType.AddressTypeCode
                                   tApiCInvoice.CInvoiceOwnVatNumber         = Address.AddressTaxIDState
                                   tApiCInvoice.tcShipToAddressStreet1       = Address.AddressStreet1
                                   tApiCInvoice.tcShipToAddressStreet2       = Address.AddressStreet2
                                   tApiCInvoice.tcShipToAddressStreet3       = Address.AddressStreet3
                                   tApiCInvoice.tcShipToAddressZip           = Address.AddressZip
                                   tApiCInvoice.tcShipToAddressCity          = Address.AddressCity
                                   tApiCInvoice.tlShipToAddressIsTaxInCity   = Address.AddressIsTaxInCity
                                   tApiCInvoice.tcShipToTaxZone              = Address.TxzTaxZone
                                   tApiCInvoice.tiShipToAddressID            = Address.Address_ID
                                   tApiCInvoice.ShipToAddress_ID             = Address.Address_ID.
                            /* Read some optional tables and assign the field */
                            Find State of Address no-lock no-error.
                            if available State 
                            then assign tApiCInvoice.tcShipToAddressState = State.StateCode.
                            Find bXCurrency of Country no-lock no-error.
                            if available bXCurrency 
                            then assign tApiCInvoice.tcVatCurrencyCode = bXCurrency.CurrencyCode
                                        tApiCInvoice.VatCurrency_ID    = bXCurrency.Currency_ID.
                        end. /* For first Address where */
                    end. /* if valid-handle(vhXBufferAdMstr) and  */
                end. /* if valid-handle(vhXBufferPoMstr) and  */            
            end. /* if tApiCInvoice.CInvoicePoNbr    <> "":U and */
        end. /* if (tApiCInvoice.tcShipToAddressStreet1 = "":U or */   
        if (tApiCInvoice.tcShipToAddressStreet1 = "":U or 
            tApiCInvoice.tcShipToAddressStreet1 = ?) and 
           (tApiCInvoice.tcShipToBusinessRelationCode = "":U or 
            tApiCInvoice.tcShipToBusinessRelationCode = ?)
        then do :
            /* Read the BusRel of the company of the invoice */
            For first CompanyProperty where  
                      CompanyProperty.Company_Id = tApiCInvoice.Company_ID
                      no-lock,
                first BusinessRelation where
                      BusinessRelation.BusinessRelation_ID = CompanyProperty.BusinessRelation_ID 
                      no-lock,
                each  Address of BusinessRelation 
                      no-lock,
                first AddressType of Address where 
                      AddressType.AddressTypeCode = {&ADDRESSTYPECODESYSTEM-HEADOFFICE} /* HEADOFFICE */
                      no-lock,
                first Country of Address
                      no-lock on error undo, throw :
                /* Assign the ShipTo-related fields */
                assign tApiCInvoice.tcShipToBusinessRelationCode = BusinessRelation.BusinessRelationCode
                       tApiCInvoice.tcShipToCountryCode          = Country.CountryCode
                       tApiCInvoice.tcOwnVatNumberCountryCode    = Country.CountryCode    
                       tApiCInvoice.tlShipToCountryIsEUCountry   = Country.CountryIsEUCountry  
                       tApiCInvoice.tcShipToAddressTypeCode      = AddressType.AddressTypeCode
                       tApiCInvoice.CInvoiceOwnVatNumber         = Address.AddressTaxIDState
                       tApiCInvoice.tcShipToAddressStreet1       = Address.AddressStreet1
                       tApiCInvoice.tcShipToAddressStreet2       = Address.AddressStreet2
                       tApiCInvoice.tcShipToAddressStreet3       = Address.AddressStreet3
                       tApiCInvoice.tcShipToAddressZip           = Address.AddressZip
                       tApiCInvoice.tcShipToAddressCity          = Address.AddressCity
                       tApiCInvoice.tlShipToAddressIsTaxInCity   = Address.AddressIsTaxInCity
                       tApiCInvoice.tcShipToTaxZone              = Address.TxzTaxZone
                       tApiCInvoice.tiShipToAddressID            = Address.Address_ID
                       tApiCInvoice.ShipToAddress_ID             = Address.Address_ID.
                /* Read some optional tables and assign the field */
                Find State of Address no-lock no-error.
                if available State 
                then assign tApiCInvoice.tcShipToAddressState = State.StateCode.
                Find bXCurrency of Country no-lock no-error.
                if available bXCurrency 
                then assign tApiCInvoice.tcVatCurrencyCode = bXCurrency.CurrencyCode
                            tApiCInvoice.VatCurrency_ID    = bXCurrency.Currency_ID.
            end. /* For first CompanyProperty where   */
        end. /* if (tApiCInvoice.tcShipToAddressStreet1 = "":U or */
         
        /* =============================================================== */
        /* Fill in the Reason when not speified                            */
        /* Fill all Reason/InvoiceStatus-related fields when not specified */ 
        /* =============================================================== */
        Release Reason no-error.
        if tApiCInvoice.tcReasonCode = "":U or 
           tApiCInvoice.tcReasonCode = ?
        then do :
            Find Reason where 
                 Reason.Reason_ID = Creditor.Reason_ID
                 no-lock no-error.
            if available Reason 
            then assign tApiCInvoice.tcReasonCode = Reason.ReasonCode
                        tApiCInvoice.Reason_ID    = Reason.Reason_ID.
        end. /* if tApiCInvoice.tcReasonCode = "":U or */
        if tApiCInvoice.tcReasonCode <> "":U and 
           tApiCInvoice.tcReasonCode <> ?    and 
           (tApiCInvoice.tcReasonAllocationStatus = "":U or 
            tApiCInvoice.tcReasonAllocationStatus = ?)
        then do :
            Find Reason where 
                 Reason.ReasonCode = tApiCInvoice.tcReasonCode
                 no-lock no-error.
            if available Reason 
            then assign tApiCInvoice.tcReasonAllocationStatus   = Reason.ReasonAllocationStatus
                        tApiCInvoice.CInvoiceAllocationStatus   = Reason.ReasonAllocationStatus
                        tApiCInvoice.CInvoiceIsInvoiceApproved  = Reason.ReasonIsInvoiceApproved
                        tApiCInvoice.CInvoiceIsLockPayment      = Reason.ReasonIsLockPayment
                        tApiCInvoice.CInvoiceIsLogisticMatching = Reason.ReasonIsLogisticMatching
                        tApiCInvoice.CInvoiceIsInitialStatus    = Reason.ReasonIsInitialStatus.
        end. /* if tApiCInvoice.tcReasonCode <> "":U and  */
        
        /* ====================================================================================================================== */
        /* Fill in the Control-GL, Div, CC and Prj-info on the Invoice when not filled                                            */
        /* If the Control-GL is enabled for Div/Prj/CC:                                                                           */
        /*   1st: Take the Div/Prj/CC from the input if it is provided                                                            */
        /*   2nd: If the Div is not yet filled then take the Div from the Creditor-definition (no Creditor-defaults for Prj/CC)   */
        /*   3rd: If the Div/Prj/CC is not yet filled then take the Div/Prj/CC from the Control-GL-definition                     */
        /* ====================================================================================================================== */
        assign viXProjectProfileID      = 0
               viXCostCentreProfileID   = 0
               viXDivisionProfileID     = 0
               viXGLIsDivisionAccount   = false 
               viXGLIsCostCentreAccount = false
               viXGLIsProjectAccount    = false.
        if tApiCInvoice.tcControlGLCode = "":U or 
           tApiCInvoice.tcControlGLCode = ?
        then do :
            assign viXGLProfileID = if tApiCInvoice.CInvoiceType= {&INVOICETYPE-PREPAYMENT} /* PREPAYMENT */
                                    then Creditor.PrePayControlGLProfile_ID
                                    else if tApiCInvoice.CInvoiceType= {&INVOICETYPE-INVOICE}           or /* INVOICE */
                                            tApiCInvoice.CInvoiceType= {&INVOICETYPE-INVOICECORRECTION}    /* INVOICECORRECTION */
                                         then Creditor.InvControlGLProfile_ID
                                         else Creditor.CnControlGLProfile_ID. 
            for first ProfileLink  where 
                      ProfileLink.Profile_ID = viXGLProfileID and 
                      ProfileLink.SharedSet_ID = viXGLSharedSetID
                      no-lock,
                first GL where 
                      GL.GL_ID = ProfileLink.ProfileLinkObject_ID 
                      no-lock
                      on error undo, throw:
                assign tApiCInvoice.tcControlGLCode = GL.GLCode
                       tApiCInvoice.ControlGL_ID    = GL.GL_ID
                       viXGLIsDivisionAccount       = GL.GLIsDivisionAccount
                       viXGLIsCostCentreAccount     = GL.GLIsCostCentreAccount
                       viXGLIsProjectAccount        = GL.GLIsProjectAccount.
                if GL.GLIsDivisionAccount = true
                then assign viXDivisionProfileID = GL.DivisionProfile_ID.
                if GL.GLIsCostCentreAccount = true
                then assign viXCostCentreProfileID = GL.CostCentreProfile_ID.
                if GL.GLIsProjectAccount = true
                then assign viXProjectProfileID = GL.ProjectProfile_ID.
            end. /* for first ProfileLink  where */
        end. /* if tApiCInvoice.tcControlGLCode = "":U or */
        else do :
            Find GL where 
                 GL.SharedSet_ID = viXGLSharedSetID and 
                 GL.GLCode       = tApiCInvoice.tcControlGLCode
                 no-lock no-error.
            if available GL
            then do :     
                assign tApiCInvoice.ControlGL_ID = GL.GL_ID.
                if GL.GLIsDivisionAccount = true
                then assign viXDivisionProfileID = GL.DivisionProfile_ID.
                if GL.GLIsCostCentreAccount = true
                then assign viXCostCentreProfileID = GL.CostCentreProfile_ID.
                if GL.GLIsProjectAccount = true
                then assign viXProjectProfileID = GL.ProjectProfile_ID.
                assign viXGLIsDivisionAccount       = GL.GLIsDivisionAccount
                       viXGLIsCostCentreAccount     = GL.GLIsCostCentreAccount
                       viXGLIsProjectAccount        = GL.GLIsProjectAccount.
            end. /* if available GL */
        end. /* Not if tApiCInvoice.tcControlGLCode = "":U or */
        /* Default the division when the ControlGL supports divisions */      
        if viXGLIsDivisionAccount = true and 
           viXDivisionProfileID <> 0 and 
           viXDivisionProfileID <> ?
        then do :
            if (tApiCInvoice.tcDivisionCode = "":U or
                tApiCInvoice.tcDivisionCode = ?) and 
               Creditor.DivisionProfile_ID <> 0 and 
               Creditor.DivisionProfile_ID <> ?
            then for first ProfileLink  where 
                           ProfileLink.Profile_ID   = Creditor.DivisionProfile_ID and 
                           ProfileLink.SharedSet_ID = viXDivisionSharedSetID
                           no-lock,
                     first Division where 
                           Division.Division_ID = ProfileLink.ProfileLinkObject_ID 
                           no-lock
                           on error undo, throw:
                    assign tApiCInvoice.tcDivisionCode = Division.DivisionCode
                           tApiCInvoice.Division_ID    = Division.Division_ID.                    
                 end. /* or first Profile where */
            if tApiCInvoice.tcDivisionCode = "":U or
               tApiCInvoice.tcDivisionCode = ?
            then for first ProfileLink  where 
                           ProfileLink.Profile_ID   = viXDivisionProfileID and 
                           ProfileLink.SharedSet_ID = viXDivisionSharedSetID
                           no-lock,
                     first Division where 
                           Division.Division_ID = ProfileLink.ProfileLinkObject_ID 
                           no-lock
                           on error undo, throw:
                    assign tApiCInvoice.tcDivisionCode = Division.DivisionCode
                           tApiCInvoice.Division_ID    = Division.Division_ID.                    
                 end. /* or first Profile where */
        end. /* if viXDivisionProfileID <> 0 and */
        /* Default the cost-centre when the ControlGL supports cost-centress */
        if viXGLIsCostCentreAccount and 
           viXCostCentreProfileID <> 0 and 
           viXCostCentreProfileID <> ? and 
           (tApiCInvoice.tcCostCentreCode = "":U or 
            tApiCInvoice.tcCostCentreCode = ?)
        then do :
            for first ProfileLink  where 
                      ProfileLink.Profile_ID = viXCostCentreProfileID and 
                      ProfileLink.SharedSet_ID = viXCostCentreSharedSetID
                      no-lock,
                first CostCentre where 
                      CostCentre.CostCentre_ID = ProfileLink.ProfileLinkObject_ID 
                      no-lock
                      on error undo, throw:
                assign tApiCInvoice.tcCostCentreCode = CostCentre.CostCentreCode
                       tApiCInvoice.CostCentre_ID    = CostCentre.CostCentre_ID.                    
            end. /* or first Profile where */
        end. /* if viXCostCentreProfileID <> 0 and */
        /* Default the project when the ControlGL supports projects */
        if viXGLIsProjectAccount and 
           viXProjectProfileID <> 0 and 
           viXProjectProfileID <> ? and 
           (tApiCInvoice.tcProjectCode = "":U or 
            tApiCInvoice.tcProjectCode = ?)
        then do :
            for first ProfileLink  where 
                      ProfileLink.Profile_ID = viXProjectProfileID and 
                      ProfileLink.SharedSet_ID = viXProjectSharedSetID
                      no-lock,
                first qaddb.Project where 
                      qaddb.Project.Project_ID = ProfileLink.ProfileLinkObject_ID 
                      no-lock
                      on error undo, throw:
                assign tApiCInvoice.tcProjectCode = qaddb.Project.ProjectCode
                       tApiCInvoice.Project_ID    = qaddb.Project.Project_ID.                    
            end. /* or first Profile where */
        end. /* if viXProjectProfileID <> 0 and */        
        
        /* =========================================================================================== */
        /* Fill in the Journal-related fields based on the InvoiceType/Creditor when not specified     */
        /* =========================================================================================== */
        /* Normalise input to restict the conditions later on in this program */
        if tApiCInvoice.CInvoiceDayBookSetCode = ? then assign tApiCInvoice.CInvoiceDayBookSetCode = "":U.
        if tApiCInvoice.CInvoiceSiteCode = ? then assign tApiCInvoice.CInvoiceSiteCode = "":U.
        if tApiCInvoice.tcJournalCode = ? then assign tApiCInvoice.tcJournalCode = "":U.
        if tApiCInvoice.Journal_ID = ? then assign tApiCInvoice.Journal_ID = 0.
        /* Get the default DaybookSet and Site of the Creditor */
        if tApiCInvoice.CInvoiceSiteCode        = "":U or 
           tApiCInvoice.CInvoiceDayBookSetCode  = "":U
        then do :
            vhXQueryVdMstr:Query-Prepare("for each vd_mstr where vd_mstr.vd_domain = '" + vcXDomainCode + "' and " + 
                                          "vd_mstr.vd_addr = '" + Creditor.CreditorCode + "'").
            vhXQueryVdMstr:Query-Open.
            vhXQueryVdMstr:Get-First(no-lock).
            if valid-handle(vhXBufferVdMstr) and 
               vhXBufferVdMstr:available 
            then do :
                if tApiCInvoice.CInvoiceSiteCode = "":U 
                then assign tApiCInvoice.CInvoiceSiteCode = vhXBufferVdMstr::vd_site.
                if tApiCInvoice.CInvoiceDayBookSetCode = "":U 
                then assign tApiCInvoice.CInvoiceDayBookSetCode = vhXBufferVdMstr::vd_daybookset.
            end. /* if valid-handle(vhXBufferVdMstr) and  */
        end. /* if tApiCInvoice.CInvoiceSiteCode = "":U or */
        /* Check if DaybookSetBySite is turned on and optionally fill DaybookSet and Site */
        vhXQueryPocCtrl:Query-Prepare("for each poc_ctrl where poc_ctrl.poc_domain = '" + vcXDomainCode + "'").
        vhXQueryPocCtrl:Query-Open.
        vhXQueryPocCtrl:Get-First(no-lock).
        if valid-handle(vhXBufferPocCtrl) and  
           vhXBufferPocCtrl:available     and 
           vhXBufferPocCtrl::poc_dybkset_by_site = true 
        then do :
            if tApiCInvoice.CInvoiceSiteCode       <> "":U and 
               tApiCInvoice.CInvoiceDayBookSetCode  = "":U
            then vhXQueryDybsMstr:Query-Prepare("for each dybs_mstr where " + 
                                                "dybs_mstr.dybs_domain = '" + vcXDomainCode + "' and " + 
                                                "dybs_mstr.dybs_type = '2' and " + 
                                                "dybs_mstr.dybs_site = '" + tApiCInvoice.CInvoiceSiteCode + "'").
            else if tApiCInvoice.CInvoiceSiteCode        = "":U and 
                    tApiCInvoice.CInvoiceDayBookSetCode <> "":U
                 then vhXQueryDybsMstr:Query-Prepare("for each dybs_mstr where " + 
                                                     "dybs_mstr.dybs_domain = '" + vcXDomainCode + "' and " + 
                                                     "dybs_mstr.dybs_type = '2' and " + 
                                                     "dybs_mstr.dybs_code = '" + tApiCInvoice.CInvoiceDayBookSetCode + "'").
                 else if tApiCInvoice.CInvoiceSiteCode       <> "":U and 
                         tApiCInvoice.CInvoiceDayBookSetCode <> "":U
                      then vhXQueryDybsMstr:Query-Prepare("for each dybs_mstr where " + 
                                                          "dybs_mstr.dybs_domain = '" + vcXDomainCode + "' and " + 
                                                          "dybs_mstr.dybs_type = '2' and " + 
                                                          "dybs_mstr.dybs_site = '" + tApiCInvoice.CInvoiceSiteCode + "' and " + 
                                                          "dybs_mstr.dybs_code = '" + tApiCInvoice.CInvoiceDayBookSetCode + "'").
                      else vhXQueryDybsMstr:Query-Prepare("for each dybs_mstr where " + 
                                                          "dybs_mstr.dybs_domain = '" + vcXDomainCode + "' and " + 
                                                          "dybs_mstr.dybs_type = '2' ").
            vhXQueryDybsMstr:Query-Open.
            vhXQueryDybsMstr:Get-First(no-lock).            
        end. /* if valid-handle(vhXBufferPocCtrl) and */
        else do :
            assign tApiCInvoice.CInvoiceSiteCode = "":U.
            if tApiCInvoice.CInvoiceDayBookSetCode = "":U
            then vhXQueryDybsMstr:Query-Prepare("for each dybs_mstr where " + 
                                                "dybs_mstr.dybs_domain = '" + vcXDomainCode + "' and " + 
                                                "dybs_mstr.dybs_type = '2'").
            else vhXQueryDybsMstr:Query-Prepare("for each dybs_mstr where " + 
                                                "dybs_mstr.dybs_domain = '" + vcXDomainCode + "' and " + 
                                                "dybs_mstr.dybs_type = '2' and " + 
                                                "dybs_mstr.dybs_code = '" + tApiCInvoice.CInvoiceDayBookSetCode + "'").
            vhXQueryDybsMstr:Query-Open.
            vhXQueryDybsMstr:Get-First(no-lock).
        end. /* Not if valid-handle(vhXBufferPocCtrl) and */
        if valid-handle(vhXBufferDybsMstr) and 
           vhXBufferDybsMstr:available 
        then do :
            assign tApiCInvoice.CInvoiceSiteCode       = vhXBufferDybsMstr::dybs_site
                   tApiCInvoice.CInvoiceDayBookSetCode = vhXBufferDybsMstr::dybs_code.
            if tApiCInvoice.tcJournalCode = "":U 
            then if tApiCInvoice.CInvoiceType = {&INVOICETYPE-CREDITNOTE} /* CREDITNOTE */
                 then assign tApiCInvoice.tcJournalCode = vhXBufferDybsMstr::dybs_credit_dybk.
                 else if tApiCInvoice.CInvoiceType = {&INVOICETYPE-CREDITNOTECORRECTION}  /* CREDITNOTECORRECTION */
                      then assign tApiCInvoice.tcJournalCode = vhXBufferDybsMstr::dybs_neg_crcn_dybk.
                      else if tApiCInvoice.CInvoiceType = {&INVOICETYPE-INVOICECORRECTION} /* INVOICECORRECTION */
                           then assign tApiCInvoice.tcJournalCode = vhXBufferDybsMstr::dybs_neg_criv_dybk.
                           else assign tApiCInvoice.tcJournalCode = vhXBufferDybsMstr::dybs_invoices_dybk.
        end. /* if valid-handle(vhXBufferDybsMstr) and */
        /* If Journal is still empty then use the first Journal with the correct properties */
        if tApiCInvoice.tcJournalCode = "":U
        then 
            for each  Journal where 
                      Journal.SharedSet_ID    = viXJournalSharedSetID       and 
                      Journal.JournalIsActive = true                        and 
                      Journal.JournalControl  = {&JOURNALCONTROL-FINANCIAL} and  /* FINANCIAL */ 
                      Journal.JournalTypeCode = (if tApiCInvoice.CInvoiceType = {&INVOICETYPE-CREDITNOTE} /* CREDITNOTE */
                                                 then {&JOURNALTYPE-CREDITORCREDITNOTE}
                                                 else if tApiCInvoice.CInvoiceType = {&INVOICETYPE-INVOICECORRECTION} /* INVOICECORRECTION */
                                                      then {&JOURNALTYPE-CREDITORINVOICECORRECT}
                                                      else if tApiCInvoice.CInvoiceType = {&INVOICETYPE-CREDITNOTECORRECTION} /* CREDITNOTECORRECTION */
                                                           then {&JOURNALTYPE-CREDITORCREDITNOTECORRECT}
                                                           else {&JOURNALTYPE-CREDITORINVOICE}) /* meaning {&INVOICETYPE-INVOICE} or {&INVOICETYPE-FINANCECHARGE} */
                      no-lock,
                each  JournalType of Journal where 
                      JournalType.JournalTypeIsCorrection = (if tApiCInvoice.CInvoiceType = {&INVOICETYPE-INVOICECORRECTION} or /* INVOICECORRECTION */
                                                                tApiCInvoice.CInvoiceType = {&INVOICETYPE-CREDITNOTECORRECTION} /* CREDITNOTECORRECTION */
                                                             then true
                                                             else false) 
                      no-lock,
                each  Layer of Journal where
                      Layer.LayerTypeCode = {&LAYERTYPECODE-OFFICIAL} /* OFFICIAL */
                      no-lock 
                      on error undo, throw:
                assign tApiCInvoice.tcJournalCode = Journal.JournalCode.
                Leave. 
            end. /* for first Profile where */

        /* ================================================= */
        /* Fill in the Payment Condition when not filled yet */
        /* ================================================= */
        Release PaymentCondition.
        if (tApiCInvoice.tcNormalPaymentConditionCode = "":U or
            tApiCInvoice.tcNormalPaymentConditionCode = ?) and 
           Creditor.NormalPaymentCondition_ID <> 0 and 
           Creditor.NormalPaymentCondition_ID <> ?
        then do :
            find first PaymentCondition where 
                 PaymentCondition.PaymentCondition_ID  = Creditor.NormalPaymentCondition_ID
                 no-lock no-error.
            if available PaymentCondition
            then assign tApiCInvoice.tcNormalPaymentConditionCode = PaymentCondition.PaymentConditionCode
                        tApiCInvoice.tcNormalPaymentConditionType = PaymentCondition.PaymentConditionPaymentTyp
                        tApiCInvoice.NormalPaymentCondition_ID    = PaymentCondition.PaymentCondition_ID.
        end. /* if (tApiCInvoice.tcNormalPaymentConditionCode = "":U or */
        else if (tApiCInvoice.tcNormalPaymentConditionCode <> "":U and
                 tApiCInvoice.tcNormalPaymentConditionCode <> ?) 
        then do:
            /*This condition is required so that tApiCInvoice.tcNormalPaymentConditionType has value to check whether it is of type staged or normal*/ 
            find first PaymentCondition where 
                       PaymentCondition.PaymentConditionCode  = tApiCInvoice.tcNormalPaymentConditionCode
                 no-lock no-error.
            if available PaymentCondition
            then assign tApiCInvoice.tcNormalPaymentConditionType = PaymentCondition.PaymentConditionPaymentTyp
                        tApiCInvoice.NormalPaymentCondition_ID    = PaymentCondition.PaymentCondition_ID.         
        end. /*else if (tApiCInvoice.tcNormalPaymentConditionCode <> "":U and*/
                
        /* ============================================================ */
        /* Fill in the Due-Date and Disc-Due-Date - only for non-staged */
        /* ============================================================ */
        if (tApiCInvoice.CInvoiceDueDate          = ? or 
            tApiCInvoice.CInvoiceDiscountDueDate = ?)        and 
           tApiCInvoice.CInvoiceDate                 <> ?    and 
           tApiCInvoice.tcNormalPaymentConditionCode <> "":U and 
           tApiCInvoice.tcNormalPaymentConditionCode <> ?
        then PAYMENTDATESBLOCK: do :
            If not available PaymentCondition 
            then Find PaymentCondition where 
                      PaymentCondition.PaymentConditionCode = tApiCInvoice.tcNormalPaymentConditionCode
                      no-lock no-error.
            if available PaymentCondition and 
               PaymentCondition.PaymentConditionPaymentTyp = {&PAYMENTCONDITIONPAYMENTTYPE-NORMAL} /* NORMAL */
            then do :
                assign vcXPaymentConditionPeriodType = PaymentCondition.PaymentConditionPeriodType  
                       vtXPaymentConditionBaseDate   = PaymentCondition.PaymentConditionBaseDate
                       viXPaymentConditionDaysMonths = PaymentCondition.PaymentConditionDaysMonths
                       viXPaymentConditionSupplDays  = PaymentCondition.PaymentConditionSupplDays
                       viXPaymentConditionBaseDays   = PaymentCondition.PaymentConditionBaseDays
                       viXPaymentConditionDueDays    = PaymentCondition.PaymentConditionDueDays
                       viXPaymentConditionDayMthDisc = PaymentCondition.PaymentConditionDayMthDisc
                       viXPaymentConditionSupDayDisc = PaymentCondition.PaymentConditionSupDayDisc
                       vcXPaymentConditionpDiscType  = PaymentCondition.PaymentConditionPdDiscType.                   
               /* === Set Due Date ==== */
               assign vtXPaymentConditionStartDate = tApiCInvoice.CInvoiceDate.
               if vtXPaymentConditionBaseDate <> ?
               then do:
                   if tApiCInvoice.CInvoiceDate < vtXPaymentConditionBaseDate
                   then assign vtXPaymentConditionStartDate = vtXPaymentConditionBaseDate.
               end. /* if vtXPaymentConditionBaseDate <> ? */
               if vtXPaymentConditionStartDate = ? then Leave PAYMENTDATESBLOCK.                   
               if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS}  /* MONTHS */
               then assign vtXPaymentConditionStartDate                  = date((viXPaymentConditionDaysMonths + month(vtXPaymentConditionStartDate)) modulo 12 + 1,
                                                                1,
                                                                int(year(vtXPaymentConditionStartDate) + (viXPaymentConditionDaysMonths + month(vtXPaymentConditionStartDate) - (viXPaymentConditionDaysMonths + month(vtXPaymentConditionStartDate)) modulo 12) / 12))
                           vtXPaymentConditionStartDate                  = vtXPaymentConditionStartDate - 1
                           tApiCInvoice.CInvoiceDueDate = vtXPaymentConditionStartDate + viXPaymentConditionSupplDays + viXPaymentConditionBaseDays.
               else if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT}  /* FORTNIGHT */
                    then do:
                       if day(vtXPaymentConditionStartDate) <= 15
                       then assign vtXPaymentConditionStartDate = date(month(vtXPaymentConditionStartDate), 15, year(vtXPaymentConditionStartDate)).
                       else assign vtXPaymentConditionStartDate = date((month(vtXPaymentConditionStartDate) modulo 12) + 1, 1, year(vtXPaymentConditionStartDate) + if month(vtXPaymentConditionStartDate) = 12 then 1 else 0)
                                   vtXPaymentConditionStartDate = vtXPaymentConditionStartDate - 1.
                       assign tApiCInvoice.CInvoiceDueDate = vtXPaymentConditionStartDate + (viXPaymentConditionDaysMonths * 14) + viXPaymentConditionBaseDays.
                    end. /* if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT}  /* FORTNIGHT */ */
                    else if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-WEEK}  /* WEEK */
                         then assign vtXPaymentConditionStartDate                  = vtXPaymentConditionStartDate + 7 - weekday(vtXPaymentConditionStartDate)
                                     tApiCInvoice.CInvoiceDueDate = vtXPaymentConditionStartDate + viXPaymentConditionDaysMonths * 7 + viXPaymentConditionBaseDays.
                           else assign tApiCInvoice.CInvoiceDueDate = vtXPaymentConditionStartDate + viXPaymentConditionDaysMonths + viXPaymentConditionBaseDays.
               if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS}    or  /* MONTHS */
                  vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} or  /* FORTNIGHT */
                  vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-WEEK}          /* WEEK */
               then do while (tApiCInvoice.CInvoiceDueDate - tApiCInvoice.CInvoiceDate) < viXPaymentConditionDueDays:
                   if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS} /* MONTHS */
                   then assign tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate - viXPaymentConditionSupplDays - viXPaymentConditionBaseDays + 1
                               tApiCInvoice.CInvoiceDueDate = date(month(tApiCInvoice.CInvoiceDueDate) modulo 12 + 1,
                                                                    1,
                                                                    int(year(tApiCInvoice.CInvoiceDueDate) + (1 + month(tApiCInvoice.CInvoiceDueDate) - (1 + month(tApiCInvoice.CInvoiceDueDate)) modulo 12) / 12))
                               tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate  - 1
                               tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate + viXPaymentConditionSupplDays + viXPaymentConditionBaseDays.
                   else if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} /* FORTNIGHT */
                        then do:
                           assign tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate - viXPaymentConditionDaysMonths - viXPaymentConditionBaseDays.
                           if day(tApiCInvoice.CInvoiceDueDate) = 15
                           then assign tApiCInvoice.CInvoiceDueDate = date(month(tApiCInvoice.CInvoiceDueDate) modulo 12 + 1,
                                                                            1, 
                                                                            year(tApiCInvoice.CInvoiceDueDate) + if month(tApiCInvoice.CInvoiceDueDate) = 12 then 1 else 0)
                                       tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate - 1.
                           else assign tApiCInvoice.CInvoiceDueDate = date(month(tApiCInvoice.CInvoiceDueDate) modulo 12 + 1,
                                                                            15,
                                                                            year(tApiCInvoice.CInvoiceDueDate) + if month(tApiCInvoice.CInvoiceDueDate) = 12 then 1 else 0).
                           assign tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate + viXPaymentConditionDaysMonths + viXPaymentConditionBaseDays.
                        end. /* if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} */
                        else assign tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDueDate + 7.
               end. /* then do while (tApiCInvoice.CInvoiceDueDate - tApiCInvoice.CInvoiceDate) < viXPaymentConditionDueDays */
               else if tApiCInvoice.CInvoiceDueDate - tApiCInvoice.CInvoiceDate < viXPaymentConditionDueDays
                    then assign tApiCInvoice.CInvoiceDueDate = tApiCInvoice.CInvoiceDate + viXPaymentConditionDueDays.
               /* === Set Discount Due Date === */
               assign vtXPaymentConditionStartDate = if vtXPaymentConditionBaseDate = ?
                                    then tApiCInvoice.CInvoiceDate
                                    else vtXPaymentConditionBaseDate.
               if vtXPaymentConditionStartDate = ? then Leave PAYMENTDATESBLOCK.
               if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS} /* MONTHS */
               then assign vtXPaymentConditionStartDate    = date((viXPaymentConditionDayMthDisc + month(vtXPaymentConditionStartDate)) modulo 12 + 1,  
                                                   1,
                                                   int(year(vtXPaymentConditionStartDate) + (viXPaymentConditionDayMthDisc + month(vtXPaymentConditionStartDate) - (viXPaymentConditionDayMthDisc + month(vtXPaymentConditionStartDate)) modulo 12) / 12))
                           vtXPaymentConditionStartDate    = vtXPaymentConditionStartDate - 1
                           tApiCInvoice.CInvoiceDiscountDueDate = vtXPaymentConditionStartDate + viXPaymentConditionSupDayDisc + viXPaymentConditionBaseDays.
               else if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} /* FORTNIGHT */
                    then do:
                       if day(vtXPaymentConditionStartDate) <= 15
                       then assign vtXPaymentConditionStartDate = date(month(vtXPaymentConditionStartDate), 15, year(vtXPaymentConditionStartDate)).
                       else assign vtXPaymentConditionStartDate = date((month(vtXPaymentConditionStartDate) modulo 12) + 1,
                                                      1,
                                                      year(vtXPaymentConditionStartDate) + if month(vtXPaymentConditionStartDate) = 12 then 1 else 0)
                                   vtXPaymentConditionStartDate = vtXPaymentConditionStartDate - 1.
                       assign tApiCInvoice.CInvoiceDiscountDueDate = vtXPaymentConditionStartDate + (viXPaymentConditionDayMthDisc  * 14) + viXPaymentConditionBaseDays.
                    end. /* if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} */
                    else if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-WEEK} /* WEEK */
                         then assign vtXPaymentConditionStartDate    = vtXPaymentConditionStartDate + 7 - weekday(vtXPaymentConditionStartDate)
                                     tApiCInvoice.CInvoiceDiscountDueDate = vtXPaymentConditionStartDate + (viXPaymentConditionDayMthDisc  * 7) + viXPaymentConditionBaseDays.
                         else assign tApiCInvoice.CInvoiceDiscountDueDate = vtXPaymentConditionStartDate + viXPaymentConditionDayMthDisc + viXPaymentConditionBaseDays.               
            end. /* if available PaymentCondition */
        end. /* if (tApiCInvoice.CInvoiceDueDate  = ? or   + PAYMENTDATESBLOCK  */
        
        if not can-find(first tApiCInvoiceStage where 
                              tApiCInvoiceStage.tc_ParentRowid = tApiCInvoice.tc_Rowid
        no-lock)
        then assign vlXNoRecord   = true
                    vlXNoDueDates = true.
        else do:
            assign vlXNoRecord = false.
            for each tApiCInvoiceStage where
                     tApiCInvoiceStage.tc_ParentRowid = tApiCInvoice.tc_Rowid
            no-lock:
                if tApiCInvoiceStage.CInvoiceStageDueDate  = ? or
                   tApiCInvoiceStage.CInvoiceStageDiscDate = ?    
                then do: 
                    assign vlXNoDueDates = true.
                    leave.
                end. /*if tApiCInvoiceStage.CInvoiceStageDueDate  = ? or*/
                else assign vlXNoDueDates = false.
            end. /*for each tApiCInvoiceStage where*/
        end. /*else do:*/
        
        /* ============================================================ */
        /* Fill in the Due-Date and Disc-Due-Date - only for staged */
        /* ============================================================ */
        if  vlXNoDueDates                               = true                                  and
            tApiCInvoice.CInvoiceDate                   <> ?                                    and 
            tApiCInvoice.tcNormalPaymentConditionType   = {&PAYMENTCONDITIONPAYMENTTYPE-STAGED} 
        then PAYMENTSTAGEDDATESBLOCK: do: 
        
            find first PaymentCondition where 
                 PaymentCondition.PaymentCondition_ID = tApiCInvoice.NormalPaymentCondition_ID
            no-lock no-error.
            for each PaymentConditionStaged of PaymentCondition 
            no-lock,
            each bXPaymentCondition where 
                 bXPaymentCondition.PaymentCondition_ID = PaymentConditionstaged.StagedPaymentCondition_ID
            no-lock :

                assign vcXPaymentConditionPeriodType = bXPaymentCondition.PaymentConditionPeriodType
                       vtXPaymentConditionBaseDate   = bXPaymentCondition.PaymentConditionBaseDate
                       viXPaymentConditionDaysMonths = bXPaymentCondition.PaymentConditionDaysMonths
                       viXPaymentConditionSupplDays  = bXPaymentCondition.PaymentConditionSupplDays
                       viXPaymentConditionBaseDays   = bXPaymentCondition.PaymentConditionBaseDays
                       viXPaymentConditionDueDays    = bXPaymentCondition.PaymentConditionDueDays
                       viXPaymentConditionDayMthDisc = bXPaymentCondition.PaymentConditionDayMthDisc
                       viXPaymentConditionSupDayDisc = bXPaymentCondition.PaymentConditionSupDayDisc
                       vcXPaymentConditionpDiscType  = bXPaymentCondition.PaymentConditionPdDiscType.
            
                /* === Set Due Date ==== */
                assign vtXPaymentConditionStartDate = tApiCInvoice.CInvoiceDate.
                if vtXPaymentConditionBaseDate <> ?
                then do:
                    if tApiCInvoice.CInvoiceDate < vtXPaymentConditionBaseDate
                    then assign vtXPaymentConditionStartDate = vtXPaymentConditionBaseDate.
                end. /* if vtXPaymentConditionBaseDate <> ? */
             
                if vtXPaymentConditionStartDate = ? then Leave PAYMENTSTAGEDDATESBLOCK.
                if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS}  /* MONTHS */
                then assign vtXPaymentConditionStartDate           = date((viXPaymentConditionDaysMonths + month(vtXPaymentConditionStartDate)) modulo 12 + 1,
                                                                     1,
                                                                     int(year(vtXPaymentConditionStartDate) + (viXPaymentConditionDaysMonths + month(vtXPaymentConditionStartDate) - (viXPaymentConditionDaysMonths + month(vtXPaymentConditionStartDate)) modulo 12) / 12))
                            vtXPaymentConditionStartDate           = vtXPaymentConditionStartDate - 1
                            vtXCInvoiceStageDueDate                = vtXPaymentConditionStartDate + viXPaymentConditionSupplDays + viXPaymentConditionBaseDays.
                else if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT}  /* FORTNIGHT */
                then do:
                    if day(vtXPaymentConditionStartDate) <= 15
                    then assign vtXPaymentConditionStartDate = date(month(vtXPaymentConditionStartDate), 15, year(vtXPaymentConditionStartDate)).
                    else assign vtXPaymentConditionStartDate = date((month(vtXPaymentConditionStartDate) modulo 12) + 1, 1, year(vtXPaymentConditionStartDate) + if month(vtXPaymentConditionStartDate) = 12 then 1 else 0)
                                vtXPaymentConditionStartDate = vtXPaymentConditionStartDate - 1.
                
                    assign vtXCInvoiceStageDueDate = vtXPaymentConditionStartDate + (viXPaymentConditionDaysMonths * 14) + viXPaymentConditionBaseDays.
                end. /* if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT}  /* FORTNIGHT */ */
            
                else if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-WEEK}  /* WEEK */
                then assign vtXPaymentConditionStartDate  = vtXPaymentConditionStartDate + 7 - weekday(vtXPaymentConditionStartDate)
                            vtXCInvoiceStageDueDate       = vtXPaymentConditionStartDate + viXPaymentConditionDaysMonths * 7 + viXPaymentConditionBaseDays.
                else assign vtXCInvoiceStageDueDate = vtXPaymentConditionStartDate + viXPaymentConditionDaysMonths + viXPaymentConditionBaseDays.
              
                if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS}    or  /* MONTHS */
                   vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} or  /* FORTNIGHT */
                   vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-WEEK}          /* WEEK */
                then do while (vtXCInvoiceStageDueDate - tApiCInvoice.CInvoiceDate) < viXPaymentConditionDueDays:
                    if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS} /* MONTHS */
                    then assign vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate - viXPaymentConditionSupplDays - viXPaymentConditionBaseDays + 1
                                vtXCInvoiceStageDueDate = date(month(vtXCInvoiceStageDueDate) modulo 12 + 1,
                                                          1,
                                                          int(year(vtXCInvoiceStageDueDate) + (1 + month(vtXCInvoiceStageDueDate) - (1 + month(vtXCInvoiceStageDueDate)) modulo 12) / 12))
                                vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate  - 1
                                vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate + viXPaymentConditionSupplDays + viXPaymentConditionBaseDays.
                    else if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} /* FORTNIGHT */
                    then do:
                        assign vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate - viXPaymentConditionDaysMonths - viXPaymentConditionBaseDays.
                        if day(vtXCInvoiceStageDueDate) = 15
                        then assign vtXCInvoiceStageDueDate = date(month(vtXCInvoiceStageDueDate) modulo 12 + 1,
                                                              1, 
                                                              year(vtXCInvoiceStageDueDate) + if month(vtXCInvoiceStageDueDate) = 12 then 1 else 0)
                                    vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate - 1.
                        else assign vtXCInvoiceStageDueDate = date(month(vtXCInvoiceStageDueDate) modulo 12 + 1,
                                                              15,
                                                              year(vtXCInvoiceStageDueDate) + if month(vtXCInvoiceStageDueDate) = 12 then 1 else 0).
                     
                        assign vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate + viXPaymentConditionDaysMonths + viXPaymentConditionBaseDays.
                    end. /* if vcXPaymentConditionPeriodType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} */
                    else assign vtXCInvoiceStageDueDate = vtXCInvoiceStageDueDate + 7.
            
                end. /* then do while (vtXCInvoiceStageDueDate - tApiCInvoice.CInvoiceDate) < viXPaymentConditionDueDays */
                else if vtXCInvoiceStageDueDate - tApiCInvoice.CInvoiceDate < viXPaymentConditionDueDays
                then assign vtXCInvoiceStageDueDate = tApiCInvoice.CInvoiceDate + viXPaymentConditionDueDays.
                    
                /* === Set Discount Due Date === */
                assign vtXPaymentConditionStartDate = if vtXPaymentConditionBaseDate = ?
                                                      then tApiCInvoice.CInvoiceDate
                                                      else vtXPaymentConditionBaseDate.
                if vtXPaymentConditionStartDate = ? then Leave PAYMENTSTAGEDDATESBLOCK.
                if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-MONTHS} /* MONTHS */
                then assign vtXPaymentConditionStartDate    = date((viXPaymentConditionDayMthDisc + month(vtXPaymentConditionStartDate)) modulo 12 + 1,  
                                                              1,
                                                              int(year(vtXPaymentConditionStartDate) + (viXPaymentConditionDayMthDisc + month(vtXPaymentConditionStartDate) - (viXPaymentConditionDayMthDisc + month(vtXPaymentConditionStartDate)) modulo 12) / 12))
                            vtXPaymentConditionStartDate    = vtXPaymentConditionStartDate - 1
                            vtXCInvoiceStageDiscDate = vtXPaymentConditionStartDate + viXPaymentConditionSupDayDisc + viXPaymentConditionBaseDays.
                else if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} /* FORTNIGHT */
                then do:
                    if day(vtXPaymentConditionStartDate) <= 15
                    then assign vtXPaymentConditionStartDate = date(month(vtXPaymentConditionStartDate), 15, year(vtXPaymentConditionStartDate)).
                    else assign vtXPaymentConditionStartDate = date((month(vtXPaymentConditionStartDate) modulo 12) + 1,
                                                               1,
                                                               year(vtXPaymentConditionStartDate) + if month(vtXPaymentConditionStartDate) = 12 then 1 else 0)
                                vtXPaymentConditionStartDate = vtXPaymentConditionStartDate - 1.
                    assign vtXCInvoiceStageDiscDate = vtXPaymentConditionStartDate + (viXPaymentConditionDayMthDisc  * 14) + viXPaymentConditionBaseDays.
                end. /* if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-FORTNIGHT} */
             
                else if vcXPaymentConditionpDiscType = {&PAYMENTCONDITIONPERIODTYPE-WEEK} /* WEEK */
                then assign vtXPaymentConditionStartDate    = vtXPaymentConditionStartDate + 7 - weekday(vtXPaymentConditionStartDate)
                            vtXCInvoiceStageDiscDate = vtXPaymentConditionStartDate + (viXPaymentConditionDayMthDisc  * 7) + viXPaymentConditionBaseDays.
                else assign vtXCInvoiceStageDiscDate = vtXPaymentConditionStartDate + viXPaymentConditionDayMthDisc + viXPaymentConditionBaseDays.

                /* ======================================================================== */
                /* Create tApiCInvoiceStage records if not available else assign the Dates  */   
                /* ======================================================================== */
                assign vdXCInvoiceOriginalTC = if tApiCInvoice.CInvoiceType <> {&INVOICETYPE-INVOICE} and 
                                                  tApiCInvoice.CInvoiceType <> {&INVOICETYPE-INVOICECORRECTION}
                                               then tApiCInvoice.CInvoiceOriginalDebitTC
                                               else tApiCInvoice.CInvoiceOriginalCreditTC.
                if vlXNoRecord
                then do:
                
                    create tApiCInvoiceStage.
                    assign tApiCInvoiceStage.CInvoiceStage_ID             = 0
                           tApiCINvoiceStage.CInvoiceStageDueDate         = vtXCInvoiceStageDueDate
                           tApiCInvoiceStage.CInvoice_ID                  = if tApiCInvoice.CInvoice_ID = ?
                                                                            then 0
                                                                            else tApiCInvoice.CInvoice_ID 
                           tApiCInvoiceStage.CInvoiceStageAmountTC        = <M-24 RoundAmount
                                                                               (input  vdXCInvoiceOriginalTC * PaymentConditionStaged.PaymentConditionStagedPerc / 100 (idUnroundedAmount), 
                                                                                input  ? (iiCurrencyID), 
                                                                                input  vcCompanyLC (icCurrencyCode)) in BCInvoice>
                           tApiCInvoiceStage.tc_rowid                     = string(rowid(PaymentConditionStaged))
                           tApiCInvoiceStage.tc_ParentRowid               = tApiCInvoice.tc_Rowid
                           tApiCInvoiceStage.CInvoiceStagePercent         = PaymentConditionStaged.PaymentConditionStagedPerc
                           tApiCInvoiceStage.PaymentConditionStaged_ID    = PaymentConditionStaged.PaymentConditionStaged_ID
                           tApiCInvoiceStage.tcPaymentConditionCode       = bXPaymentCondition.PaymentConditionCode
                           tApiCInvoiceStage.tcPaymentConditionDescript   = bXPaymentCondition.PaymentConditionDescript
                           tApiCInvoiceStage.tdPaymentConditionPercentage = bXPaymentCondition.PaymentConditionPercentage
                           tApiCInvoiceStage.CInvoiceStageDiscPerc        = bXPaymentCondition.PaymentConditionPercentage
                           tApiCInvoiceStage.CInvoiceStageDiscDate        = vtXCInvoiceStageDiscDate.
                
                end. /*if vlXNoRecord*/
                else do:
                    find first tApiCInvoiceStage where
                             tApiCInvoiceStage.tc_ParentRowid         = tApiCInvoice.tc_Rowid and
                             tApiCInvoiceStage.tcPaymentConditionCode = bXPaymentCondition.PaymentConditionCode
                    no-lock no-error.
                    
                    if available tApiCInvoiceStage
                    then
                       assign tApiCInvoiceStage.CInvoiceStageDueDate         = vtXCInvoiceStageDueDate
                              tApiCInvoiceStage.CInvoiceStageDiscDate        = vtXCInvoiceStageDiscDate
                              tApiCInvoiceStage.tcPaymentConditionCode       = bXPaymentCondition.PaymentConditionCode
                              tApiCInvoiceStage.tcPaymentConditionDescript   = bXPaymentCondition.PaymentConditionDescript
                              tApiCInvoiceStage.tdPaymentConditionPercentage = bXPaymentCondition.PaymentConditionPercentage
                              tApiCInvoiceStage.CInvoiceStageDiscPerc        = bXPaymentCondition.PaymentConditionPercentage.
                    
                end. /*else then do:*/
            end. /*for each PaymentConditionStaged where*/
            
        end. /*then PAYMENTSTAGEDDATESBLOCK do:*/
        
        for each tApiCInvoiceStage where
                 tApiCInvoiceStage.tc_ParentRowid = tApiCInvoice.tc_Rowid
        break by tApiCInvoiceStage.CInvoiceStageDueDate descending:
            assign tApiCInvoice.CInvoiceDueDate         = tApiCInvoiceStage.CInvoiceStageDueDate
                   tApiCInvoice.CInvoiceDiscountDueDate = tApiCInvoiceStage.CInvoiceStageDiscDate.
        end. /*for each tApiCInvoiceStage where*/
        
        /* ===================================================== */
        /* Fill in the default bank information if not specified */
        /* ===================================================== */
        if tApiCInvoice.Creditor_ID <> 0 and 
           tApiCInvoice.Creditor_ID <> ? and 
           not can-find (first tApiCInvoiceBank where 
                               tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid)
        then do :
            /* Read the best applicable banknumber that is related to this Creditor: including Default and CompanyID */
            if not can-find (first tApiCInvoiceBank where 
                                   tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid)
            then do :
                for each  BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and
                          BankNumber.BankNumberIsDefault = true                     and
                          BankNumber.BankNumberIsActive  = true
                          no-lock,        
                    each BankPayFormat where 
                         BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                         no-lock,
                    each bXBankNumber where 
                         bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID 
                         no-lock,
                    each CompanySharedSet where
                         CompanySharedSet.CompanySharedSet_ID = bXBankNumber.CompanySharedSet_ID and 
                         CompanySharedSet.Company_ID          = tApiCInvoice.Company_ID
                         no-lock 
                         on error undo, throw :
                    create tApiCInvoiceBank.
                    assign tApiCInvoiceBank.tc_ParentRowid         = tApiCInvoice.tc_Rowid
                           tApiCInvoiceBank.tiParentObject_ID      = tApiCInvoice.Creditor_ID
                           tApiCInvoiceBank.BankNumber_ID          = BankNumber.BankNumber_ID
                           tApiCInvoiceBank.tcBankNumber           = BankNumber.BankNumberFormatted
                           tApiCInvoiceBank.tcBankNumberExtension  = BankNumber.BankNumberExtension
                           tApiCInvoiceBank.tcBankNumberValidation = BankNumber.BankNumberValidation
                           tApiCInvoiceBank.tcBankNumberSwiftCode  = BankNumber.BankNumberSwiftCode
                           tApiCInvoiceBank.tiBankPayFormat_ID     = BankNumber.BankPayFormat_ID
                           tApiCInvoiceBank.CInvoiceBankToPayTC    = /* Assign the value to pay equal to the amount of the invoice */
                                                                     if tApiCInvoice.CInvoiceOriginalCreditTC <> 0 and
                                                                        tApiCInvoice.CInvoiceOriginalCreditTC <> ?
                                                                     then tApiCInvoice.CInvoiceOriginalCreditTC
                                                                     else tApiCInvoice.CInvoiceOriginalDebitTC
                           tApiCInvoiceBank.tc_Rowid               =  string(rowid(BankNumber)). 
                    Leave. 
                end. /* for each BankNumber where */
            end. /* if not can-find (first tApiCInvoiceBank where  */
            /* Read the second best applicable banknumber that is related to this Creditor: including CompanyID without Default */
            if not can-find (first tApiCInvoiceBank where 
                                   tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid)
            then do :
                for each BankNumber where
                         BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and
                         BankNumber.BankNumberIsActive  = true
                         no-lock,        
                    each BankPayFormat where 
                         BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                         no-lock,
                    each bXBankNumber where 
                         bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID 
                         no-lock,
                    each CompanySharedSet where
                         CompanySharedSet.CompanySharedSet_ID = bXBankNumber.CompanySharedSet_ID and 
                         CompanySharedSet.Company_ID          = tApiCInvoice.Company_ID
                         no-lock
                         on error undo, throw :
                    create tApiCInvoiceBank.
                    assign tApiCInvoiceBank.tc_ParentRowid         = tApiCInvoice.tc_Rowid
                           tApiCInvoiceBank.tiParentObject_ID      = tApiCInvoice.Creditor_ID
                           tApiCInvoiceBank.BankNumber_ID          = BankNumber.BankNumber_ID
                           tApiCInvoiceBank.tcBankNumber           = BankNumber.BankNumberFormatted
                           tApiCInvoiceBank.tcBankNumberExtension  = BankNumber.BankNumberExtension
                           tApiCInvoiceBank.tcBankNumberValidation = BankNumber.BankNumberValidation
                           tApiCInvoiceBank.tcBankNumberSwiftCode  = BankNumber.BankNumberSwiftCode
                           tApiCInvoiceBank.tiBankPayFormat_ID     = BankNumber.BankPayFormat_ID
                           tApiCInvoiceBank.CInvoiceBankToPayTC    = /* Assign the value to pay equal to the amount of the invoice */
                                                                     if tApiCInvoice.CInvoiceOriginalCreditTC <> 0 and
                                                                        tApiCInvoice.CInvoiceOriginalCreditTC <> ?
                                                                     then tApiCInvoice.CInvoiceOriginalCreditTC
                                                                     else tApiCInvoice.CInvoiceOriginalDebitTC
                           tApiCInvoiceBank.tc_Rowid               = string(rowid(BankNumber)).  
                    Leave.
                end. /* for first BankNumber where */
            end. /* if not can-find (first tApiCInvoiceBank where  */
            /* Read the third best applicable banknumber that is related to this Creditor: including Default without CompanyID */
            if not can-find (first tApiCInvoiceBank where 
                                   tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid)
            then do :
                for first BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumberIsDefault = true
                          no-lock
                          on error undo, throw :
                    create tApiCInvoiceBank.
                    assign tApiCInvoiceBank.tc_ParentRowid         = tApiCInvoice.tc_Rowid
                           tApiCInvoiceBank.tiParentObject_ID      = tApiCInvoice.Creditor_ID
                           tApiCInvoiceBank.BankNumber_ID          = BankNumber.BankNumber_ID
                           tApiCInvoiceBank.tcBankNumber           = BankNumber.BankNumberFormatted
                           tApiCInvoiceBank.tcBankNumberExtension  = BankNumber.BankNumberExtension
                           tApiCInvoiceBank.tcBankNumberValidation = BankNumber.BankNumberValidation
                           tApiCInvoiceBank.tcBankNumberSwiftCode  = BankNumber.BankNumberSwiftCode
                           tApiCInvoiceBank.tiBankPayFormat_ID     = BankNumber.BankPayFormat_ID
                           tApiCInvoiceBank.CInvoiceBankToPayTC    = /* Assign the value to pay equal to the amount of the invoice */
                                                                     if tApiCInvoice.CInvoiceOriginalCreditTC <> 0 and
                                                                        tApiCInvoice.CInvoiceOriginalCreditTC <> ?
                                                                     then tApiCInvoice.CInvoiceOriginalCreditTC
                                                                     else tApiCInvoice.CInvoiceOriginalDebitTC
                           tApiCInvoiceBank.tc_Rowid               = string(rowid(BankNumber)).  
                end. /* for first BankNumber where */
            end. /* if not can-find (first tApiCInvoiceBank where  */
            /* ================================================================================================================ */
            /* In case we have created a BankNumber by now, we will also create the underlying BankNumberPayCode-records for it */
            /* ================================================================================================================ */
            Find first tApiCInvoiceBank where 
                       tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid and 
                       tApiCInvoiceBank.BankNumber_ID <> 0                     and 
                       tApiCInvoiceBank.BankNumber_ID <> ?
                       no-lock no-error.
            if available tApiCInvoiceBank
            then do :
                for each BankNumberPayCode where 
                         BankNumberPayCode.BankNumber_ID = tApiCInvoiceBank.BankNumber_ID
                         no-lock
                         on error undo, throw :
                    create tApiCInvoiceBankPayCode.
                    assign tApiCInvoiceBankPayCode.tc_ParentRowid           = tApiCInvoiceBank.tc_Rowid
                           tApiCInvoiceBankPayCode.tc_Rowid                 = string(rowid(BankNumberPayCode))
                           tApiCInvoiceBankPayCode.PayFormatGroup_ID        = BankNumberPayCode.PayFormatGroup_ID
                           tApiCInvoiceBankPayCode.PayFormatCode_ID         = BankNumberPayCode.PayFormatCode_ID
                           tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = BankNumberPayCode.BankNumberPayCodeValue.
                    if BankNumberPayCode.PayFormatGroup_ID <> 0 and 
                       BankNumberPayCode.PayFormatGroup_ID <> ? 
                    then do :
                        find PayFormatGroup where 
                             PayFormatGroup.PayFormatGroup_ID = BankNumberPayCode.PayFormatGroup_ID
                             no-lock no-error.
                        if available PayFormatGroup 
                        then assign tApiCInvoiceBankPayCode.tcPayFormatGroupCode = PayFormatGroup.PayFormatGroupCode.
                    end. /* if BankNumberPayCode.PayFormatGroup_ID <> 0 and */
                    if tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = "":U or 
                       tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = ? 
                    then do :
                        find PayFormatCode of BankNumberPayCode
                             no-lock no-error.
                        if available PayFormatCode
                        then do:
                            assign tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = PayFormatCode.PayFormatCode.
                            if tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = ? or
                               tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = "":U
                            then do :  
                                find PayFormatGroup of BankNumberPayCode where
                                     PayFormatGroup.PayFormatGroupDataType = 'LOGICAL':U
                                     no-lock no-error.
                                if available PayFormatGroup
                                then assign tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = "false":U.
                            end. /* if tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = ? or */
                        end. /* if available PayFormatCode */
                    end. /* if tApiCInvoiceBankPayCode.CInvoiceBankPayCodeValue = "":U or */
                end. /* for each BankNumberPayCode where  */
            end. /* if available tApiCInvoiceBank */
        end. /* if tApiCInvoice.Creditor_ID <> 0 and */
        
        /* ======================================================================================================== */
        /* Fill tApiCInvoiceBank.BankNumber_ID: For those tApiCInvoiceBank record where BankNumber_ID is not filled */ 
        /* then we will try to assign it with the banknumber that best matches the filled properties                */
        /* ======================================================================================================== */
        /* This is the logical sequence for finding the correct BankNumber-record in the db:                        */
        /*  Case  Act  OwnBnkNbr  BnkNbr  Cy	Def                                                                 */
        /*    1   Y	    Y/N	  Y	  Y     Y                                                                  */
        /*    2   Y	    Y/N	  Y	  Y	 N                                                                  */
        /*    3   Y	    Y/N	  Y	  N	 Y                                                                  */
        /*    4   Y	    Y/N	  Y	  N	 N                                                                  */
        /*    5   Y	    Y/N	  N	  Y	 Y                                                                  */
        /*    6   Y	    Y/N	  N	  Y	 N                                                                  */
        /*    7   Y	    Y/N	  N	  N	 Y                                                                  */
        /*    8   Y	    Y/N	  N	  N	 N                                                                  */
        /*    9   Y	     N		  N	  N	 Y                                                                  */
        /*    10  Y	     N		  N	  N	 N                                                                  */
        /* ======================================================================================================== */
        /* While we assign tApiCInvoiceBank.BankNumber_ID here and we thus have a BankNumber-record available, we   */
        /* will also assign tApiCInvoiceBank.tiBankPayFormat_ID and optionally tApiCInvoiceBank.tcPayFormatTypeCode */
        /* as well in case we have a BankPayFormat record available next to the BankNumber reocrd.                  */
        /* ======================================================================================================== */
        if tApiCInvoice.Creditor_ID <> 0 and 
           tApiCInvoice.Creditor_ID <> ? 
        then for each tApiCInvoiceBank where 
                      tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid: 
            
            /* Strip-off some formatting characters that are not stored in the db */
            assign tApiCInvoiceBank.tcBankNumber = replace(tApiCInvoiceBank.tcBankNumber, " ":U, "":U)
                   tApiCInvoiceBank.tcBankNumber = replace(tApiCInvoiceBank.tcBankNumber, ".":U, "":U)
                   tApiCInvoiceBank.tcBankNumber = replace(tApiCInvoiceBank.tcBankNumber, "/":U, "":U)
                   tApiCInvoiceBank.tcBankNumber = replace(tApiCInvoiceBank.tcBankNumber, "-":U, "":U).
            
            /* Skip record in case the BankNumber_ID is already filled */
            if tApiCInvoiceBank.BankNumber_ID <> 0 and 
               tApiCInvoiceBank.BankNumber_ID <> ? 
            then next.
            
            /* Try to find the correct BankNumber - first reset the IDs of the found records */
            Assign viXBankNumberID    = 0
                   viXBankPayFormatID = 0
                   viXbXBankNumberID  = 0.
            /*    1  First try finding with Active, tcOwnBankNumber, BankNbr, Company, Default */
            for each BankNumber where
                     BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                     BankNumber.BankNumberIsActive  = true                     and 
                     BankNumber.BankNumberIsDefault = true                     and
                     BankNumber.BankNumber          = tApiCInvoiceBank.tcBankNumber 
                     no-lock,        
                each BankPayFormat where 
                     BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                     no-lock,
                each bXBankNumber where 
                     bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                     bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                      tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                   then tApiCInvoiceBank.tcOwnBankNumber
                                                   else bXBankNumber.BankNumber) 
                     no-lock,
                each CompanySharedSet where
                     CompanySharedSet.CompanySharedSet_ID = bXBankNumber.CompanySharedSet_ID and 
                     CompanySharedSet.Company_ID          = tApiCInvoice.Company_ID
                     no-lock 
                     on error undo, throw :
                assign viXBankNumberID    = BankNumber.BankNumber_ID
                       viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                       viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                Leave.
            end. /* for each BankNumber */
            /*    2  Second try finding with Active, tcOwnBankNumber, BankNbr, Company */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumber          = tApiCInvoiceBank.tcBankNumber 
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock,
                     each CompanySharedSet where
                          CompanySharedSet.CompanySharedSet_ID = bXBankNumber.CompanySharedSet_ID and 
                          CompanySharedSet.Company_ID          = tApiCInvoice.Company_ID
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.                          
                 end. /* for each BankNumber */
            /*    3  Third try finding with Active, tcOwnBankNumber, BankNbr, Default */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumberIsDefault = true                     and
                          BankNumber.BankNumber          = tApiCInvoiceBank.tcBankNumber 
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    4  Fourth try finding with Active, tcOwnBankNumber, BankNbr */ 
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumber          = tApiCInvoiceBank.tcBankNumber 
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    5  Fifth try finding with Active, tcOwnBankNumber, Company, Default  */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumberIsDefault = true  
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock,
                     each CompanySharedSet where
                          CompanySharedSet.CompanySharedSet_ID = bXBankNumber.CompanySharedSet_ID and 
                          CompanySharedSet.Company_ID          = tApiCInvoice.Company_ID
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    6  Sixth try finding with Active, tcOwnBankNumber, Company  */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true   
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock,
                     each CompanySharedSet where
                          CompanySharedSet.CompanySharedSet_ID = bXBankNumber.CompanySharedSet_ID and 
                          CompanySharedSet.Company_ID          = tApiCInvoice.Company_ID
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    7  Seventh try finding with Active, tcOwnBankNumber, Default  */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumberIsDefault = true  
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    8  Eighth try finding with Active, tcOwnBankNumber  */ 
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true  
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID and 
                          bXBankNumber.BankNumber    = (if tApiCInvoiceBank.tcOwnBankNumber <> "":U and 
                                                           tApiCInvoiceBank.tcOwnBankNumber <> ?
                                                        then tApiCInvoiceBank.tcOwnBankNumber
                                                        else bXBankNumber.BankNumber) 
                          no-lock 
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    9  Nineth try finding with Active, Default  */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true                     and 
                          BankNumber.BankNumberIsDefault = true  
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID
                          no-lock
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            /*    10 Tenth try finding with Active */
            if viXBankNumberID = 0
            then for each BankNumber where
                          BankNumber.ParentObject_ID     = tApiCInvoice.Creditor_ID and 
                          BankNumber.BankNumberIsActive  = true  
                          no-lock,        
                     each BankPayFormat where 
                          BankPayFormat.BankPayFormat_ID = BankNumber.BankPayFormat_ID 
                          no-lock,
                     each bXBankNumber where 
                          bXBankNumber.BankNumber_ID = BankPayFormat.BankNumber_ID
                          no-lock
                          on error undo, throw :
                    assign viXBankNumberID    = BankNumber.BankNumber_ID
                           viXBankPayFormatID = BankPayFormat.BankPayFormat_ID
                           viXbXBankNumberID  = bXBankNumber.BankNumber_ID.
                    Leave.
                 end. /* for each BankNumber */
            
            /* Fill tApiCInvoiceBank.BankNumber_ID and its 'updatable-related key-business-fields' */
            if viXBankNumberID <> 0 and 
               viXBankNumberID <> ?
            then do :
                Find BankNumber where 
                     BankNumber.BankNumber_ID = viXBankNumberID 
                     no-lock no-error.
                if available BankNumber 
                then assign tApiCInvoiceBank.BankNumber_ID         = BankNumber.BankNumber_ID
                            tApiCInvoiceBank.tiBankPayFormat_ID    = BankNumber.BankPayFormat_ID
                            tApiCInvoiceBank.tiParentObject_ID     = BankNumber.ParentObject_ID
                            tApiCInvoiceBank.tcBankNumber          = BankNumber.BankNumber
                            tApiCInvoiceBank.tcBankNumberExtension = BankNumber.BankNumberExtension.
                Find BankPayFormat where 
                     BankPayFormat.BankPayFormat_ID = viXBankPayFormatID 
                     no-lock no-error.
                if available BankPayFormat
                then assign tApiCInvoiceBank.tcPayFormatTypeCode = BankPayFormat.PayFormatTypeCode.                
                Find BankNumber where 
                     BankNumber.BankNumber_ID = viXbXBankNumberID
                     no-lock no-error.
                if available BankNumber 
                then assign tApiCInvoiceBank.tcOwnBankNumber = BankNumber.BankNumber.                
            end. /* if viXBankNumberID <> 0 and  */
            
        end. /* if tApiCInvoice.Creditor_ID <> 0 and tApiCInvoice.Creditor_ID <> ? then for each tApiCInvoiceBank where */ 
        
        /* ==================================================================================================================== */
        /* If there is only a single tApiCInvoiceBank and its amount is empty then default the amount on it from the invoice    */
        /* ==================================================================================================================== */
        Find tApiCInvoiceBank where 
             tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid 
             no-lock no-error. /* do not use the last or first option as we only want the record to be available in case there is only one for the invoice */
        if available tApiCInvoiceBank and 
           (tApiCInvoiceBank.CInvoiceBankToPayTC = 0 or
            tApiCInvoiceBank.CInvoiceBankToPayTC = ?)
        then if tApiCInvoice.CInvoiceOriginalCreditTC <> 0 and 
                tApiCInvoice.CInvoiceOriginalCreditTC <> ?
             then assign tApiCInvoiceBank.CInvoiceBankToPayTC = tApiCInvoice.CInvoiceOriginalCreditTC.
             else if tApiCInvoice.CInvoiceOriginalDebitTC <> 0 and 
                     tApiCInvoice.CInvoiceOriginalDebitTC <> ?
                  then assign tApiCInvoiceBank.CInvoiceBankToPayTC = tApiCInvoice.CInvoiceOriginalDebitTC.
        
        /* ==================================================================================================================== */
        /* Apply some additional defaulting on the redundant fields of tApiCInvoiceBank and the tApiCInvoiceBankPayCode records */
        /* ==================================================================================================================== */
        for each tApiCInvoiceBank where 
                 tApiCInvoiceBank.tc_ParentRowid = tApiCInvoice.tc_Rowid :   
            /* Fill tApiCInvoiceBank.tiBankPayFormat_ID */
            if tApiCInvoiceBank.BankNumber_ID <> 0 and 
               tApiCInvoiceBank.BankNumber_ID <> ? and 
               (tApiCInvoiceBank.tiBankPayFormat_ID = 0 or 
                tApiCInvoiceBank.tiBankPayFormat_ID = ?)
            then do :
                find BankNumber where 
                     BankNumber.BankNumber_ID = tApiCInvoiceBank.BankNumber_ID
                     no-lock no-error.
                if available BankNumber
                then assign tApiCInvoiceBank.tiBankPayFormat_ID = BankNumber.BankPayFormat_ID.
            end. /* if tApiCInvoiceBank.BankNumber_ID <> 0 and  */
            /* Fill tApiCInvoiceBank.tcPayFormatTypeCode */
            if tApiCInvoiceBank.tiBankPayFormat_ID <> 0 and 
               tApiCInvoiceBank.tiBankPayFormat_ID <> ? and 
               (tApiCInvoiceBank.tcPayFormatTypeCode = "":U or 
                tApiCInvoiceBank.tcPayFormatTypeCode = ?)
            then do :
                find BankPayFormat where 
                     BankPayFormat.BankPayFormat_ID = tApiCInvoiceBank.tiBankPayFormat_ID
                     no-lock no-error.
                if available BankPayFormat
                then assign tApiCInvoiceBank.tcPayFormatTypeCode = BankPayFormat.PayFormatTypeCode.
            end. /* if tApiCInvoiceBank.tiBankPayFormat_ID <> 0 and  */
            /* Go through the underlying tApiCInvoiceBankPayCode */
            for each tApiCInvoiceBankPayCode where 
                     tApiCInvoiceBankPayCode.tc_ParentRowid = tApiCInvoiceBank.tc_Rowid :
                /* Fill tApiCInvoiceBankPayCode.tcPayFormatGroupCode */
                if tApiCInvoiceBankPayCode.PayFormatGroup_ID <> 0 and 
                   tApiCInvoiceBankPayCode.PayFormatGroup_ID <> ? and 
                   (tApiCInvoiceBankPayCode.tcPayFormatGroupCode = "":U or 
                    tApiCInvoiceBankPayCode.tcPayFormatGroupCode = ?)
                then do :
                    find PayFormatGroup where 
                         PayFormatGroup.PayFormatGroup_ID = tApiCInvoiceBankPayCode.PayFormatGroup_ID
                         no-lock no-error.
                    if available PayFormatGroup 
                    then assign tApiCInvoiceBankPayCode.tcPayFormatGroupCode = PayFormatGroup.PayFormatGroupCode.
                end. /* if BankNumberPayCode.PayFormatGroup_ID <> 0 and */
            end. /* for each tApiCInvoiceBankPayCode where */
        end. /* for each tApiCInvoiceBank where */
        
        /* ====================================================================== */
        /* Fill in defaults in tApiCInvoiceVat records that are in the input      */
        /* ====================================================================== */
        for each tApiCInvoiceVat where 
                 tApiCInvoiceVat.tc_ParentRowid = tApiCInvoice.tc_rowid
                 on error undo, throw :
            /* Replace empty fields with default fixed values */
            if tApiCInvoiceVat.tcDomainCode = "":U or 
               tApiCInvoiceVat.tcDomainCode = ?
            then assign tApiCInvoiceVat.tcDomainCode = vcXDomainCode.
            if tApiCInvoiceVat.tcVatInOut = "":U or 
               tApiCInvoiceVat.tcVatInOut = ?
            then assign tApiCInvoiceVat.tcVatInOut =  {&VATINOUT-INPUT}. /* INPUT */               
            if tApiCInvoiceVat.CInvoiceVatSequence = 0 or 
               tApiCInvoiceVat.CInvoiceVatSequence = ?
            then assign tApiCInvoiceVat.CInvoiceVatSequence = 1.
            /* Replace unknown values with data from the tax-definitions */
            if tApiCInvoiceVat.tcVatCode <> "":U and 
               tApiCInvoiceVat.tcVatCode <> ?
            then do :
                vhXQueryTx2Mstr:Query-Prepare("for each tx2_mstr where tx2_mstr.tx2_domain = '" + vcXDomainCode + "' and " + 
                                              "tx2_mstr.tx2_tax_code = '" + tApiCInvoiceVat.tcVatCode + "'").
                vhXQueryTx2Mstr:Query-Open.
                vhXQueryTx2Mstr:Get-First(no-lock).
                if valid-handle(vhXBufferTx2Mstr) and 
                   vhXBufferTx2Mstr:available 
                then do :
                    if tApiCInvoiceVat.CInvoiceVatIsUpdAllow = ?
                    then assign tApiCInvoiceVat.CInvoiceVatIsUpdAllow = vhXBufferTx2Mstr::tx2_update_tax. .
                    if tApiCInvoiceVat.CInvoiceVatIsAbsRet = ?
                    then assign tApiCInvoiceVat.CInvoiceVatIsAbsRet = vhXBufferTx2Mstr::tx2_apr_use.
                    if tApiCInvoiceVat.CInvoiceVatIsAccrRcpUs = ?  
                    then assign tApiCInvoiceVat.CInvoiceVatIsAccrRcpUs = vhXBufferTx2Mstr::tx2_rcpt_tax_point or vhXBufferTx2Mstr::tx2_usage_tax_point.
                    if tApiCInvoiceVat.CInvoiceVatIsRevCharge = ?
                    then assign tApiCInvoiceVat.CInvoiceVatIsRevCharge = vhXBufferTx2Mstr::tx2_reverse_charge.
                    if tApiCInvoiceVat.CInvoiceVatIsSuspDel = ?
                    then assign tApiCInvoiceVat.CInvoiceVatIsSuspDel = vhXBufferTx2Mstr::tx2_stx_dltx_use.
                end. /* if valid-handle(vhXBufferTx2Mstr) */
            end. /* if tApiCInvoiceVat.tcVatCode <> "":U and  */
            /* Avoid unknown values */
            if tApiCInvoiceVat.TxuTaxUsage = ?
            then assign tApiCInvoiceVat.TxuTaxUsage = "":U.
            if tApiCInvoiceVat.TxenvTaxEnv = ?
            then assign tApiCInvoiceVat.TxenvTaxEnv = "":U.
            if tApiCInvoiceVat.TxclTaxCls = ?
            then assign tApiCInvoiceVat.TxclTaxCls = "":U.
            /* Set the Taxable flag on the invoice-level based on the Vat-records     */
            if ((tApiCInvoiceVat.CInvoiceVatVatDebitTC  <> 0 and 
                 tApiCInvoiceVat.CInvoiceVatVatDebitTC  <> ?) or  
                (tApiCInvoiceVat.CInvoiceVatVatCreditTC <> 0 and 
                 tApiCInvoiceVat.CInvoiceVatVatCreditTC <> ?)) and 
               (tApiCInvoice.CInvoiceIsTaxable = ? or 
                tApiCInvoice.CInvoiceIsTaxable = false)
            then assign tApiCInvoice.CInvoiceIsTaxable = true.            
        end. /* for each tApiCInvoiceVat where */
        
    end. /* for each tApiCInvoice where */             
    
    
    /* close queries and delete buffer handle objects  */         
    FINALLY:  
          
        if valid-handle(vhXQueryPocCtrl)
        then do:
            vhXQueryPocCtrl:QUERY-CLOSE().
            delete object vhXQueryPocCtrl.
        end. /* if valid-handle */
        if valid-handle(vhXBufferPocCtrl) 
        then delete object vhXBufferPocCtrl.
        
        if valid-handle(vhXQueryDybsMstr)
        then do:
            vhXQueryDybsMstr:QUERY-CLOSE().
            delete object vhXQueryDybsMstr.
        end. /* if valid-handle */
        if valid-handle(vhXBufferDybsMstr) 
        then delete object vhXBufferDybsMstr.
        
        if valid-handle(vhXQueryVdMstr)
        then do:
            vhXQueryVdMstr:QUERY-CLOSE().
            delete object vhXQueryVdMstr.
        end. /* if valid-handle */
        if valid-handle(vhXBufferVdMstr) 
        then delete object vhXBufferVdMstr.
        
        if valid-handle(vhXQueryTx2Mstr)
        then do:
            vhXQueryTx2Mstr:QUERY-CLOSE().
            delete object vhXQueryTx2Mstr.
        end. /* if valid-handle */
        if valid-handle(vhXBufferTx2Mstr) 
        then delete object vhXBufferTx2Mstr.
        
        if valid-handle(vhXQueryPoMstr)
        then do:
            vhXQueryPoMstr:QUERY-CLOSE().
            delete object vhXQueryPoMstr.
        end. /* if valid-handle */
        if valid-handle(vhXBufferPoMstr) 
        then delete object vhXBufferPoMstr.
        
        if valid-handle(vhXQueryAdMstr)
        then do:
            vhXQueryAdMstr:QUERY-CLOSE().
            delete object vhXQueryAdMstr.
        end. /* if valid-handle */
        if valid-handle(vhXBufferAdMstr) 
        then delete object vhXBufferAdMstr.
                
    END FINALLY.