Sales invoice report

 /// <summary>

/// Event handler class for adding document based on document types to print management.

/// </summary>

public class GOPPrintMgmtDocTypeEventHandler

{

    /// <summary>

    /// To add custom invoice report document in print management for sales order invoice.

    /// </summary>

    /// <param name = "_docType"> <c>PrintMgmtDocumentType</c> </param>

    /// <param name = "_result"> <c>EventHandlerResult</c> </param>

    [SubscribesTo(classStr(PrintMgmtDocType), delegateStr(PrintMgmtDocType, getDefaultReportFormatDelegate))]

    public static void PrintMgmtDocType_getDefaultReportFormatDelegate(PrintMgmtDocumentType _docType, EventHandlerResult _result)

    {

        #ISOCountryRegionCodes


        switch (_docType)

        {

            case PrintMgmtDocumentType::SalesOrderInvoice:

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA]))

                {

                    _result.result(ssrsReportStr(GOPSalesTaxInvoice, Proforma_SA));

                    _result.result(ssrsReportStr(GOPSalesTaxInvoice, TaxInvoice_SA));

                  

                }

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU,#isoNZ]))

                {

                    _result.result(ssrsReportStr(GOPSalesInvoice, ReportANZ));

                }


                if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIL]))

                {

                    _result.result(ssrsReportStr(GOPILSalesInvoice, TaxInvoices_IL));

                }

                if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE]))

                {

                    _result.result(ssrsReportStr(GOPSalesTaxInvoiceSAGulf, SalesTaxInvoice_SAGulf));

                }

                break;

            /* if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE]))

                {

                    _result.result(ssrsReportStr(GOPSalesTaxInvoice, TaxInvoice_UAE));

                    break;

                }*/

            case PrintMgmtDocumentType::SalesOrderConfirmation:

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA,#isoAE,#isoIL]))

                {

                    _result.result(ssrsReportStr(GOPSalesConfirm, Report));

                }

                Break;


            case PrintMgmtDocumentType::PurchaseOrderRequisition:

                _result.result(ssrsReportStr(GOPPOConfirmation, Report));

                break;

            case PrintMgmtDocumentType::SalesOrderPackingSlip:

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU,#isoNZ]))

                {

                    _result.result(ssrsReportStr(GOPSalesPackingSlip, ReportANZ));

                }

                else

                {

                    _result.result(ssrsReportStr(GOPDefaultPackingSlip, Report));

                }

                break;

            case PrintMgmtDocumentType::SalesFreeTextInvoice:

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE]))

                {

                    _result.result(ssrsReportStr(GOPFreeTextInvoice, Report));

                }

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoNZ]))

                {

                    _result.result(ssrsReportStr(GOPFreeTextInvoice, Report1));

                }

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU]))

                {

                    _result.result(ssrsReportStr(GOPFreeTextInvoice, Report1));

                }

                break;

            case PrintMgmtDocumentType::CustAccountStatement:

                if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU,#isoNZ]))

                {

                    _result.result(ssrsReportStr(GOPCustAccountStatementExt, ReportANZ));

                    //_result.result(ssrsReportStr(GOPCustAccountStatementExt, GOPReport));

                }

                break;

            case PrintMgmtDocumentType::TMSCommercialInvoice:

                if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU,#isoNZ]))

                {

                    _result.result(ssrsReportStr(GOPTMSCommercialInvoice, Report));

                }

                break;

            case PrintMgmtDocumentType::InventPickList:

                _result.result(ssrsReportStr(GOPWMSPickingList_OrderPick, Report));

                break;

        }

    }


    [PostHandlerFor(classStr(PrintMgmtPrintSettingDetail), methodStr(PrintMgmtPrintSettingDetail, parmReportFormatName))]

    public static void PrintMgmtPrintSettingDetail_Post_parmReportFormatName(XppPrePostArgs args)

    {

        PrintMgmtPrintSettingDetail PrintMgmtPrintSettingDetail = args.getThis();

        str reportName = args.getArg('_reportFormatName');

        if(reportName == 'ILFreeTextInvoice.Report' || reportName == 'ILFreeTextInvoice.ReportIL')

        {

            reportName = 'GOPFreeTextInvoice.Report';

            PrintMgmtPrintSettingDetail.parmReportFormatName(reportName);

 

            PrintMgmtSettings printMgmtSettings ;

            PrintMgmtReportFormat   PrintMgmtReportFormat;

            PrintMgmtIdentificationText PrintMgmtIdentificationText;

 

            select printMgmtSettings

                join PrintMgmtReportFormat

                    where printMgmtSettings.ReportFormat == PrintMgmtReportFormat.RecId

                    && PrintMgmtReportFormat.DocumentType == PrintMgmtDocumentType::SalesFreeTextInvoice

                    && PrintMgmtReportFormat.Name == reportName;

 

            select PrintMgmtIdentificationText

                where PrintMgmtIdentificationText.ParentId == printMgmtSettings.RecId;

 

            PrintMgmtPrintSettingDetail.parmIdentificationText(PrintMgmtIdentificationText.IdentificationText);

        }


        #ISOCountryRegionCodes

        if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIL])

           && (reportName == 'SalesInvoice.Report' || reportName == 'ILSalesInvoice.Report' || reportName == 'GOPSalesTaxInvoice.TaxInvoice_IL'))

        {

            reportName = 'GOPILSalesInvoice.TaxInvoices_IL';

            PrintMgmtPrintSettingDetail.parmReportFormatName(reportName);

 

            PrintMgmtSettings printMgmtSettings ;

            PrintMgmtReportFormat   PrintMgmtReportFormat;

            PrintMgmtIdentificationText PrintMgmtIdentificationText;

 

            select printMgmtSettings

                join PrintMgmtReportFormat

                    where printMgmtSettings.ReportFormat == PrintMgmtReportFormat.RecId

                    && PrintMgmtReportFormat.DocumentType == PrintMgmtDocumentType::SalesFreeTextInvoice

                    && PrintMgmtReportFormat.Name == reportName;

 

            select PrintMgmtIdentificationText

                where PrintMgmtIdentificationText.ParentId == printMgmtSettings.RecId;

 

            PrintMgmtPrintSettingDetail.parmIdentificationText(PrintMgmtIdentificationText.IdentificationText);

        }


        //#ISOCountryRegionCodes

        if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE])

           && (reportName == 'SalesInvoice.Report' ))

        {

            reportName = 'GOPSalesTaxInvoiceSAGulf.SalesTaxInvoice_SAGulf';

            PrintMgmtPrintSettingDetail.parmReportFormatName(reportName);

 

            PrintMgmtSettings printMgmtSettings ;

            PrintMgmtReportFormat   PrintMgmtReportFormat;

            PrintMgmtIdentificationText PrintMgmtIdentificationText;

 

            select printMgmtSettings

                join PrintMgmtReportFormat

                    where printMgmtSettings.ReportFormat == PrintMgmtReportFormat.RecId

                    && PrintMgmtReportFormat.DocumentType == PrintMgmtDocumentType::SalesFreeTextInvoice

                    && PrintMgmtReportFormat.Name == reportName;

 

            select PrintMgmtIdentificationText

                where PrintMgmtIdentificationText.ParentId == printMgmtSettings.RecId;

 

            PrintMgmtPrintSettingDetail.parmIdentificationText(PrintMgmtIdentificationText.IdentificationText);

        }

    }


}


/// <summary>

/// This Class is the extension of PrintMgmtReportFormatPopulator Class

/// </summary>

[ExtensionOf(classStr(PrintMgmtReportFormatPopulator))]

final class PrintMgmtReportFormatPopulator_Class_GOP_Extension

{

    #PrintMgmtSetup


    // Macro for defining country region codes

    #ISOCountryRegionCodes


    /// <summary>

    /// COC of addDocuments method.

    /// </summary>

    protected void addDocuments()

    {

        // Add sales invoice report formats

        this.AddGOPSalesTaxInvoiceReportDesigns();

        this.AddGOPPurchaseOrderConfirmation();

        // Add  sales free text invoice

        this.AddGOPSalesFreeTextInvoice();

        next addDocuments();

    }


    /// <summary>

    /// Method to popuate Sales invoice report formats in PrintMgmtReportFormat table.

    /// </summary>

    void AddGOPSalesTaxInvoiceReportDesigns()

    {

        this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPSalesTaxInvoice, TaxInvoice_SA), ssrsReportStr(GOPSalesTaxInvoice, TaxInvoice_SA), #isoSA);

        this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPSalesTaxInvoice, Proforma_SA), ssrsReportStr(GOPSalesTaxInvoice, Proforma_SA), #isoSA);

        this.addOther(PrintMgmtDocumentType::SalesOrderConfirmation, ssrsReportStr(GOPSalesConfirm, Report), ssrsReportStr(GOPSalesConfirm, Report), #isoSA);

        this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPSalesInvoice, ReportANZ), ssrsReportStr(GOPSalesInvoice, ReportANZ), #isoAU);

        this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPSalesInvoice, ReportANZ), ssrsReportStr(GOPSalesInvoice, ReportANZ), #isoNZ);

        this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPILSalesInvoice, TaxInvoices_IL), ssrsReportStr(GOPILSalesInvoice, TaxInvoices_IL), #isoIL);

        this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPSalesTaxInvoiceSAGulf, SalesTaxInvoice_SAGulf), ssrsReportStr(GOPSalesTaxInvoiceSAGulf, SalesTaxInvoice_SAGulf), #isoAE);


        //this.addOther(PrintMgmtDocumentType::SalesOrderInvoice, ssrsReportStr(GOPSalesTaxInvoice, TaxInvoice_UAE), ssrsReportStr(GOPSalesTaxInvoice, TaxInvoice_UAE), #isoAE);

    }


    /// <summary>

    /// Method to polulate Purchase order confirmation report format in PrintMgmtReportFormat table.

    /// </summary>

    void AddGOPPurchaseOrderConfirmation()

    {

        this.addOther(PrintMgmtDocumentType::PurchaseOrderRequisition, ssrsReportStr(GOPPOConfirmation, Report), ssrsReportStr(GOPPOConfirmation, Report), #NoCountryRegionId);

    }


    /// <summary>

    /// Method to populate packing slip report in PrintMgmtReportFormat table

    /// </summary>

    void AddGOPDefaultPackingSlip()

    {

        this.addOther(PrintMgmtDocumentType::SalesOrderPackingSlip, ssrsReportStr(GOPDefaultPackingSlip, Report), ssrsReportStr(GOPDefaultPackingSlip, Report), #NoCountryRegionId);

        this.addOther(PrintMgmtDocumentType::SalesOrderPackingSlip, ssrsReportStr(GOPSalesPackingSlip, ReportANZ), ssrsReportStr(GOPSalesPackingSlip, ReportANZ), #NoCountryRegionId);

    }


    /// <summary>

    /// Method to polulate Sales freeText Invoice report format in PrintMgmtReportFormat table.

    /// </summary>

    void AddGOPSalesFreeTextInvoice()

    {

        this.addOther(PrintMgmtDocumentType::SalesFreeTextInvoice, ssrsReportStr(GOPFreeTextInvoice, Report), ssrsReportStr(GOPFreeTextInvoice, Report), #isoAE);

        this.addOther(PrintMgmtDocumentType::SalesFreeTextInvoice, ssrsReportStr(GOPFreeTextInvoice, Report), ssrsReportStr(GOPFreeTextInvoice, Report), #isoNZ);

        this.addOther(PrintMgmtDocumentType::SalesFreeTextInvoice, ssrsReportStr(GOPFreeTextInvoice, Report), ssrsReportStr(GOPFreeTextInvoice, Report), #isoAU);

        this.addOther(PrintMgmtDocumentType::SalesFreeTextInvoice, ssrsReportStr(GOPFreeTextInvoice, Report), ssrsReportStr(GOPFreeTextInvoice, Report), #isoIL);


    }


}


/// <summary>

/// <c>SalesInvoiceDP</c> class extension

/// </summary>

[ExtensionOf(classStr(SalesInvoiceDP))]

final class SalesInvoiceDP_Class_GOP_Extension

{

    #ISOCountryRegionCodes


    private String255 Verbiage32, Verbiage32Ar, Verbiage33, Verbiage33Ar, Verbiage35, Verbiage35Ar;

    private CustVendCorrectedInvoiceId custVendCorrectedInvoiceId;

    private InvoiceDate custVendCorrectedInvoiceDate;

    private boolean allowToCreateOrigInvoiceDetailsLineForCreditNote;

    //public GOPSalesInvoiceSummaryTmp GOPSalesInvoiceSummaryTmp;


    /// <summary>

    /// COC of processReport method for deleting buffer so that the report always gets the latest data.

    /// </summary>

    public void processReport()

    {

        SalesInvoiceHeaderFooterTmp localSalesInvoiceHeaderFooterTmp;

        SalesInvoiceTmp localSalesInvoiceTmp;


        SalesInvoiceContract contractLoc = this.parmDataContract() as SalesInvoiceContract;


        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA]) 

            || (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIL]) && CustInvoiceJour::findRecId(contractLoc.parmRecordId()))

            || SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE]))

        {

            delete_from localSalesInvoiceHeaderFooterTmp;

            delete_from localSalesInvoiceTmp; 

        }


        next processReport();

    }


    /// <summary>

    /// COC on populateSalesInvoiceHeaderFooterTmp method to populate the custom fields.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_companyInfo"> <c>CompanyInfo</c> table </param>

    protected void populateSalesInvoiceHeaderFooterTmpSA(CustInvoiceJour _custInvoiceJour, CompanyInfo _companyInfo)

    {

        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA]))

        {

            salesInvoiceHeaderFooterTmp.GOPCompanyAddressInArabic = DirParty::primaryPostalAddress(_companyInfo.RecId).GOPAddressInArabic;


            BankAccountTable bankAccountTableSAR, bankAccountTableNotSAR;


            select firstonly bankAccountTableSAR

                where bankAccountTableSAR.GOPBankForTaxInvoice == NoYes::Yes

                && bankAccountTableSAR.CurrencyCode == Ledger::accountingCurrency(CompanyInfo::current()); // Selects bank accounts with SAR currency.


            select firstonly bankAccountTableNotSAR

                where bankAccountTableNotSAR.GOPBankForTaxInvoice == NoYes::Yes

                && bankAccountTableNotSAR.AccountID != bankAccountTableSAR.AccountID

                && bankAccountTableNotSAR.Name == bankAccountTableSAR.Name; // Selects bank account in same bank as above with other currency.


            SalesTable salesTable = _custInvoiceJour.salesTable();


            salesInvoiceHeaderFooterTmp.GOPShipTerm = salesTable.DlvTerm;

            salesInvoiceHeaderFooterTmp.GOPRouting = salesTable.DlvMode;

            salesInvoiceHeaderFooterTmp.GOPLCRemarks = salesTable.GOPLCRemarks;


            salesInvoiceHeaderFooterTmp.GOPNameInArabic = _companyInfo.GOPNameInArabic;


            salesInvoiceHeaderFooterTmp.GOPBankName = bankAccountTableSAR.Name;

            salesInvoiceHeaderFooterTmp.GOPBankNameInArabic = bankAccountTableSAR.GOPBankNameInArabic;

            salesInvoiceHeaderFooterTmp.GOPAccountNum = bankAccountTableSAR.AccountNum;

            salesInvoiceHeaderFooterTmp.GOPIBANNum = bankAccountTableSAR.IBAN;

            salesInvoiceHeaderFooterTmp.GOPSwiftCode = bankAccountTableSAR.SWIFTNo;

            salesInvoiceHeaderFooterTmp.GOPIBANNumNotSAR = bankAccountTableNotSAR.IBAN;


            LogisticsPostalAddress bankLogisticsPostalAddress = LogisticsPostalAddress::findByLocation(bankAccountTableSAR.Location); // Selects bank address.


            salesInvoiceHeaderFooterTmp.GOPBankAddress = bankLogisticsPostalAddress.Address;

            salesInvoiceHeaderFooterTmp.GOPBankAddressInArabic = bankLogisticsPostalAddress.GOPAddressInArabic;

            salesInvoiceHeaderFooterTmp.GOPEnteredDate = _custInvoiceJour.CreatedDateTime;

            salesInvoiceHeaderFooterTmp.GOPCustomerID = salesTable.CustAccount;


            DirPartyTable dirPartyTable = DirPartyTable::findRec(_custInvoiceJour.custTable_InvoiceAccount().Party);


            LogisticsPostalAddress billToLogisticsPostalAddress = LogisticsPostalAddress::findByLocation(dirPartyTable.PrimaryAddressLocation); // Customer billing address.


            LogisticsLocation logisticsLocation;


            select firstonly RecId from logisticsLocation

                where logisticsLocation.ParentLocation == billToLogisticsPostalAddress.Location;


            TaxRegistration taxRegistration;


            select firstonly RegistrationNumber from taxRegistration

                where taxRegistration.DirPartyLocation == DirPartyLocation::findByPartyLocation(dirPartyTable.RecId, LogisticsLocation::find(billToLogisticsPostalAddress.Location).RecId).RecId;


            salesInvoiceHeaderFooterTmp.GOPBillToAddressName = LogisticsLocation::find(billToLogisticsPostalAddress.Location).Description;

            salesInvoiceHeaderFooterTmp.GOPBillToAddress = billToLogisticsPostalAddress.Address;

            salesInvoiceHeaderFooterTmp.GOPCustomerVATNum = taxRegistration.RegistrationNumber;

            salesInvoiceHeaderFooterTmp.GOPBillToAddrISOcode = LogisticsAddressCountryRegion::find(billToLogisticsPostalAddress.CountryRegionId).ISOcode;

            salesInvoiceHeaderFooterTmp.GOPBillToAddressInArabic = billToLogisticsPostalAddress.GOPAddressInArabic;

            salesInvoiceHeaderFooterTmp.GOPBillToPhone = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Phone).Locator;

            salesInvoiceHeaderFooterTmp.GOPBillToFax = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Fax).Locator;

            salesInvoiceHeaderFooterTmp.GOPBillToEmail = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Email).Locator;

            salesInvoiceHeaderFooterTmp.GOPReceivedDate = salesTable.GOPReceivedDate;

            salesInvoiceHeaderFooterTmp.GOPShippingMarks = salesTable.GOPShippingMarks;

            salesInvoiceHeaderFooterTmp.GOPShippingMarksInArabic = salesTable.GOPShippingMarksInArabic;

            salesInvoiceHeaderFooterTmp.GOPCustomerRef = salesTable.CustomerRef;

            salesInvoiceHeaderFooterTmp.GOPLetterOfCreditNum = salesTable.GOPLetterOfCreditNum;

            salesInvoiceHeaderFooterTmp.GOPPaymTerm = PaymTerm::find(_custInvoiceJour.custTable_OrderAccount().PaymTermId).Description;


            DirPartyTable dirPartyTableAddnSellerId = DirPartyTable::findByName(salesInvoiceHeaderFooterTmp.CompanyName);


            TaxRegistration taxRegAddnSellerId;


            select firstonly RegistrationNumber from taxRegAddnSellerId

                where taxRegAddnSellerId.Description == "@GOP:CommercialRegistration"

                && taxRegAddnSellerId.DirPartyLocation == DirPartyLocation::findByPartyLocation(dirPartyTableAddnSellerId.RecId,

                                                                                                   dirPartyTableAddnSellerId.PrimaryAddressLocation).RecId;


            salesInvoiceHeaderFooterTmp.GOPAdditionalSellerId = taxRegAddnSellerId.RegistrationNumber;


            InventTrans inventTrans;

            InventTransOrigin inventTransOrigin;

            CustPackingSlipJour custPackingSlipJour;

            CustInvoiceTrans custInvoiceTrans;


            select firstonly InvoiceId, InventTransId from custInvoiceTrans

                where custInvoiceTrans.InvoiceId == _custInvoiceJour.InvoiceId;


            select firstonly DeliveryDate from custPackingSlipJour

                exists join inventTrans

                    where inventTrans.PackingSlipId == custPackingSlipJour.PackingSlipId

                            && inventTrans.InvoiceId == custInvoiceTrans.InvoiceId

                exists join inventTransOrigin

                    where inventTransOrigin.RecId == inventTrans.inventTransOrigin

                            && inventTransOrigin.InventTransId == custInvoiceTrans.InventTransId;



            if (salesInvoiceHeaderFooterTmp.InvoiceDate != custPackingSlipJour.DeliveryDate)

            {

                salesInvoiceHeaderFooterTmp.GOPPickDeliveryDate = custPackingSlipJour.DeliveryDate;

            }


            CustConfirmJour custConfirmJour;


            select firstonly ConfirmDocNum from custConfirmJour order by RecId desc

            where custConfirmJour.SalesId == salesTable.SalesId;


            salesInvoiceHeaderFooterTmp.GOPVersion = custConfirmJour.ConfirmDocNum;


            CustInvoiceJour custInvoiceJour;


            while select custInvoiceJour

            where custInvoiceJour.SalesId == salesTable.SalesId

                && custInvoiceJour.InvoiceId != _custInvoiceJour.InvoiceId

            {

                if (!salesInvoiceHeaderFooterTmp.GOPBackOrderRef)

                {

                    salesInvoiceHeaderFooterTmp.GOPBackOrderRef = custInvoiceJour.InvoiceId;

                }

                else

                {

                    salesInvoiceHeaderFooterTmp.GOPBackOrderRef = salesInvoiceHeaderFooterTmp.GOPBackOrderRef + "@GOP:CommaSpace" + custInvoiceJour.InvoiceId;

                }

            }

        }

    }


    /// <summary>

    /// COC of populateSalesInvoiceTmp method to populate the custom fields and add custom logic.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_custInvoiceTrans"> <c>CustInvoiceTrans</c> table </param>

    /// <param name = "_taxSpec"> <c>TaxSpec</c> table </param>

    /// <param name = "_custPaymSchedLine"> <c>CustPaymSchedLine</c> table </param>

    /// <param name = "_prepaymentCustTrans"> <c>CustTrans</c> table </param>

    /// <param name = "_prepaymentTaxTrans"> <c>TaxTrans</c> table </param>

    protected void populateSalesInvoiceTmpSA(CustInvoiceJour _custInvoiceJour,

        CustInvoiceTrans _custInvoiceTrans,

        TaxSpec _taxSpec,

        CustPaymSchedLine _custPaymSchedLine,

        CustTrans _prepaymentCustTrans,

        TaxTrans _prepaymentTaxTrans)

    {

        TaxTrans taxTrans;


        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA]))

        {

            salesInvoiceTmp.CurrencyCode = _custInvoiceJour.CurrencyCode;

            salesInvoiceTmp.InventLocationId = _custInvoiceJour.inventLocationId;

            

            SalesLine salesLine = _custInvoiceTrans.salesLine();


            LogisticsPostalAddress shipToLogisticsPostalAddress = LogisticsPostalAddress::findRecId(salesLine.DeliveryPostalAddress);


            LogisticsLocation logisticsLocation;


            select firstonly RecId from logisticsLocation

                where logisticsLocation.ParentLocation == shipToLogisticsPostalAddress.Location;


            salesInvoiceTmp.GOPShipToAddressName = LogisticsLocation::find(shipToLogisticsPostalAddress.Location).Description;

            salesInvoiceTmp.GOPShipToAddress = shipToLogisticsPostalAddress.Address;

            salesInvoiceTmp.GOPShipToAddrISOcode = LogisticsAddressCountryRegion::find(shipToLogisticsPostalAddress.CountryRegionId).ISOcode;

            salesInvoiceTmp.GOPShipToAddressInArabic = shipToLogisticsPostalAddress.GOPAddressInArabic;

            salesInvoiceTmp.GOPShipToPhone = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Phone).Locator;

            salesInvoiceTmp.GOPShipToFax = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Fax).Locator;

            salesInvoiceTmp.GOPShipToEmail = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Email).Locator;


            InventTrans inventTrans;

            InventTransOrigin inventTransOrigin;

            CustPackingSlipJour custPackingSlipJour;

            CustPackingSlipTrans custPackingSlipTrans;

            CustInvoicePackingSlipQuantityMatch custInvoicePackingSlipQuantityMatch;


            select firstonly InventQuantity from custInvoicePackingSlipQuantityMatch

                where custInvoicePackingSlipQuantityMatch.InvoiceSourceDocumentLine == _custInvoiceTrans.SourceDocumentLine;


            salesInvoiceTmp.GOPOrderedQty = salesLine.SalesQty;

            salesInvoiceTmp.GOPShippedQty = custInvoicePackingSlipQuantityMatch.InventQuantity;

            salesInvoiceTmp.GOPBalanceQty = salesLine.SalesQty - custInvoicePackingSlipQuantityMatch.InventQuantity;


            salesInvoiceTmp.GOPOriginOfGoods = InventTable::find(salesLine.ItemId).GOPOriginOfGoods;


            select firstonly taxTrans where taxTrans.InventTransId == _custInvoiceTrans.InventTransId;


            salesInvoiceTmp.TaxValue = taxTrans.TaxValue;


            if (!salesInvoiceTmp.TaxValue)

            {

                TmpTaxWorkTrans tmpTaxWorkTrans = SalesInvoiceDP::CalcTaxPercentAndValue(_custInvoiceJour.salesTable());


                select firstonly tmpTaxWorkTrans

                    where tmpTaxWorkTrans.SourceRecId == salesLine.RecId

                    && tmpTaxWorkTrans.SourceTableId == tableNum(SalesLine); // For getting sales tax percent and sales tax amount.


                salesInvoiceTmp.TaxValue = tmpTaxWorkTrans.showTaxValue();

            }


            salesInvoiceTmp.TaxAmount = abs((salesInvoiceTmp.TaxValue/100) * salesInvoiceTmp.LineAmount);

            salesInvoiceTmp.GOPPostedBy = _custInvoiceTrans.CreatedBy;


            InventTable inventTable = _custInvoiceTrans.inventTable();


            salesInvoiceTmp.GOPProductNameInArabic = EcoResProduct::find(inventTable.Product).productName("@GOP:ArSa");

            salesInvoiceTmp.GOPProductNameInEng = EcoResProduct::find(inventTable.Product).productName("@GOP:EnUS");


            salesInvoiceTmp.GOPOriginOfGoodsInArabic = inventTable.GOPOriginOfGoodsInArabic;

            salesInvoiceTmp.GOPPerCode = inventTable.GOPSellPerCode;

            salesInvoiceTmp.GOPHSC = inventTable.GOPHSC;

            salesInvoiceTmp.SalesPrice = CurrencyExchangeHelper::amount(_custInvoiceTrans.SalesPrice * cachedExchRate);

            salesInvoiceTmp.LineAmount = _custInvoiceTrans.LineAmountMST;


            if (_custInvoiceTrans.DiscPercent && !_custInvoiceTrans.DiscAmount)

            {

                salesInvoiceTmp.GOPDiscPercent = _custInvoiceTrans.DiscPercent;

                salesInvoiceTmp.GOPDiscAmount = (_custInvoiceTrans.DiscPercent*salesInvoiceTmp.SalesPrice*salesInvoiceTmp.GOPShippedQty)/100;

            }


            if (_custInvoiceTrans.DiscAmount  && !_custInvoiceTrans.DiscPercent)

            {

                salesInvoiceTmp.GOPDiscAmount = _custInvoiceTrans.DiscAmount*salesInvoiceTmp.GOPShippedQty;

                salesInvoiceTmp.GOPDiscPercent = (_custInvoiceTrans.DiscAmount/salesInvoiceTmp.SalesPrice)*100;

            }


            if (salesLine.TaxGroup == "@GOP:ForeignTaxCode")

            {

                if (salesLine.TaxItemGroup == "@GOP:ServiceZeroTacGroup" && inventTable.GOPIsMedicalGood == NoYes::No) //Services

                {

                    Verbiage33 = "@GOP:verbiage33";

                    Verbiage33Ar = "@GOP:Verbiage33Ar";

                }


                if (salesLine.TaxItemGroup == "@GOP:GoodsZeroTaxGroup" && (inventTable.GOPIsMedicalGood == NoYes::No || inventTable.GOPIsMedicalGood == NoYes::Yes)) //Goods

                {

                    Verbiage32 = "@GOP:Verbiage32";

                    Verbiage32Ar = "@GOP:Verbiage32Ar";

                }

            }


            if (salesLine.TaxGroup == "@GOP:DomesticTaxCode")

            {

                if (salesLine.TaxItemGroup == "@GOP:GoodsZeroTaxGroup" && inventTable.GOPIsMedicalGood == NoYes::Yes) //Medical Goods

                {

                    Verbiage35 = "@GOP:Verbiage35";

                    Verbiage35Ar = "@GOP:Verbiage35Ar";

                }

            }


            salesInvoiceTmp.GOPVerbiage32 = Verbiage32;

            salesInvoiceTmp.GOPVerbiage32Ar = Verbiage32Ar;

            salesInvoiceTmp.GOPVerbiage33 = Verbiage33;

            salesInvoiceTmp.GOPVerbiage33Ar = Verbiage33Ar;

            salesInvoiceTmp.GOPVerbiage35 = Verbiage35;

            salesInvoiceTmp.GOPVerbiage35Ar = Verbiage35Ar;

            salesInvoiceTmp.GOPNetUnitAmount = salesLine.LineAmount/salesLine.QtyOrdered;


            //Added as part of AD-FDD-04 Customer and Item X reference

            salesInvoiceTmp.SalesUnitTxt = salesLine.GOPCustomerOrderUOM;

            salesInvoiceTmp.Qty = salesLine.GOPCustomerOrderQty;

            //end

        }


        


    }


    /// <summary>

    /// Helper method to load and get <c>TmpTaxWorkTrans</c> table.

    /// </summary>

    /// <param name = "_salesTable"> <c>SalesTable</c> </param>

    /// <returns> Loaded <c>TmpTaxWorkTrans</c> table </returns>

    public static TmpTaxWorkTrans CalcTaxPercentAndValue(SalesTable _salesTable)

    {

        TmpTaxWorkTrans tmpTaxWorkTrans;


        SalesTotals salesTotals = SalesTotals::construct(_salesTable);

 

        salesTotals.calc();

 

        // Load tmpTaxWorkTrans

        tmpTaxWorkTrans.setTmpData(salesTotals.tax().tmpTaxWorkTrans());


        return tmpTaxWorkTrans;

    }


    /// <summary>

    /// COC on populateSalesInvoiceHeaderFooterTmp method to populate the custom fields.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_companyInfo"> <c>CompanyInfo</c> table </param>

    protected void populateSalesInvoiceHeaderFooterTmp(CustInvoiceJour _custInvoiceJour, CompanyInfo _companyInfo)

    {

        next populateSalesInvoiceHeaderFooterTmp(_custInvoiceJour, _companyInfo);

        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA]) )

        {

            this.populateSalesInvoiceHeaderFooterTmpSA(_custInvoiceJour, _companyInfo);

        }

        else if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIL]))

        {

            this.populateSalesInvoiceHeaderFooterTmpISL(_custInvoiceJour, _companyInfo);

        }

        else if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU,#isoNZ,#isoUS]))

        {

            this.populateSalesInvoiceHeaderFooterTmpANZ(_custInvoiceJour, _companyInfo);

        }

        else if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE]))

        {

            this.populateSalesInvoiceHeaderFooterTmpAE(_custInvoiceJour, _companyInfo);

        }

    }


    /// <summary>

    /// COC on populateSalesInvoiceHeaderFooterTmp method to populate the custom fields fro Isreal.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_companyInfo"> <c>CompanyInfo</c> table </param>

    private void populateSalesInvoiceHeaderFooterTmpISL(CustInvoiceJour _custInvoiceJour, CompanyInfo _companyInfo)

    {

        BankAccountTable    bankAccountTableLoc, bankAccountTableEURUSD;

        UserInfo            UserInfo;


        SalesTable salesTable = _custInvoiceJour.salesTable();


        salesInvoiceHeaderFooterTmp.GOPShipTerm = salesTable.DlvTerm;

        salesInvoiceHeaderFooterTmp.GOPSalesOrderDate = salesTable.createDate();

        salesInvoiceHeaderFooterTmp.GOPRemarksISL = salesTable.GOPRemarksISL;

        salesInvoiceHeaderFooterTmp.GOPInvoiceId = _custInvoiceJour.InvoiceId;

        //int ILVatInvoiceIdLen = strLen(_custInvoiceJour.ILVatInvoiceId);

        //str GOPVatInvoiceId = subStr(_custInvoiceJour.ILVatInvoiceId, ILVatInvoiceIdLen, -9);

        salesInvoiceHeaderFooterTmp.GOPVatInvoiceId =  _custInvoiceJour.ILVatInvoiceId;


        select firstonly Id, name from UserInfo

                where UserInfo.id == salesTable.CreatedBy;

        salesInvoiceHeaderFooterTmp.GOPCustServiceRepresentative = UserInfo.name;


        bankAccountTableLoc.clear();

        select firstonly AccountNum, IBAN, SWIFTNo, Name, Location from bankAccountTableLoc

            where bankAccountTableLoc.GOPBankForTaxInvoice == NoYes::Yes

            && bankAccountTableLoc.CurrencyCode == Ledger::accountingCurrency(CompanyInfo::current());

        salesInvoiceHeaderFooterTmp.GOPAccountNumISL = bankAccountTableLoc.AccountNum;

        salesInvoiceHeaderFooterTmp.GOPIBANNumISL = bankAccountTableLoc.IBAN;

        salesInvoiceHeaderFooterTmp.GOPSwiftCodeISL = bankAccountTableLoc.SWIFTNo;

        salesInvoiceHeaderFooterTmp.GOPBankName = bankAccountTableLoc.Name;

        LogisticsPostalAddress bankLogisticsPostalAddress = LogisticsPostalAddress::findByLocation(bankAccountTableLoc.Location); // Selects bank address.


        salesInvoiceHeaderFooterTmp.GOPBankAddress = bankLogisticsPostalAddress.Address;


        bankAccountTableEURUSD.clear();

        select firstonly AccountNum, IBAN from bankAccountTableEURUSD

            where bankAccountTableEURUSD.GOPBankForTaxInvoice == NoYes::Yes

            && bankAccountTableEURUSD.CurrencyCode == '@SYS57303'; //Currency:Europe

        salesInvoiceHeaderFooterTmp.GOPAccountNumEUR = bankAccountTableEURUSD.AccountNum;

        salesInvoiceHeaderFooterTmp.GOPIBANNumEUR = bankAccountTableEURUSD.IBAN;


        bankAccountTableEURUSD.clear();

        select firstonly AccountNum, IBAN from bankAccountTableEURUSD

            where bankAccountTableEURUSD.GOPBankForTaxInvoice == NoYes::Yes

            && bankAccountTableEURUSD.CurrencyCode == '@CurrencyExchange:UnitedStatesCurrency'; //Currency:USD

        salesInvoiceHeaderFooterTmp.GOPAccountNumUSD = bankAccountTableEURUSD.AccountNum;

        salesInvoiceHeaderFooterTmp.GOPIBANNumUSD = bankAccountTableEURUSD.IBAN;

        salesInvoiceHeaderFooterTmp.GOPCustomerID = salesTable.CustAccount;


        DirPartyTable dirPartyTable = DirPartyTable::findRec(_custInvoiceJour.custTable_InvoiceAccount().Party);


        LogisticsPostalAddress billToLogisticsPostalAddress = LogisticsPostalAddress::findByLocation(dirPartyTable.PrimaryAddressLocation); // Customer billing address.


        salesInvoiceHeaderFooterTmp.GOPBillToAddressName = LogisticsLocation::find(billToLogisticsPostalAddress.Location).Description;

        salesInvoiceHeaderFooterTmp.GOPBillToAddress = billToLogisticsPostalAddress.Address;

        salesInvoiceHeaderFooterTmp.GOPCustomerRef = salesTable.CustomerRef;

        salesInvoiceHeaderFooterTmp.GOPPaymTerm = PaymTerm::find(_custInvoiceJour.custTable_OrderAccount().PaymTermId).Description;


        InventTrans inventTrans;

        InventTransOrigin inventTransOrigin;

        CustPackingSlipJour custPackingSlipJour;

        CustInvoiceTrans custInvoiceTrans;


        if (_custInvoiceJour.isProforma())

        {

            while select DeliveryDate, PackingSlipId from custPackingSlipJour

                where custPackingSlipJour.SalesId == _custInvoiceJour.SalesId

            {

                this.setPackingSlipIdAndDate(custPackingSlipJour);

            }

        }

        else

        {

            while select DeliveryDate,PackingSlipId from custPackingSlipJour

                //order DeliveryDate asc

                exists join inventTrans

                    where inventTrans.PackingSlipId == custPackingSlipJour.PackingSlipId

                exists join InvoiceId, InventTransId from custInvoiceTrans

                    where inventTrans.InvoiceId == custInvoiceTrans.InvoiceId

                exists join inventTransOrigin

                    where inventTransOrigin.RecId == inventTrans.inventTransOrigin

                        && inventTransOrigin.InventTransId == custInvoiceTrans.InventTransId

                && custInvoiceTrans.InvoiceId == _custInvoiceJour.InvoiceId

            {

                this.setPackingSlipIdAndDate(custPackingSlipJour);

            }

        }


        CustInvoiceJour custInvoiceJour;


        while select custInvoiceJour

        where custInvoiceJour.SalesId == salesTable.SalesId

            && custInvoiceJour.InvoiceId != _custInvoiceJour.InvoiceId

        {

            if (!salesInvoiceHeaderFooterTmp.GOPBackOrderRef)

            {

                salesInvoiceHeaderFooterTmp.GOPBackOrderRef = custInvoiceJour.InvoiceId;

            }

            else

            {

                salesInvoiceHeaderFooterTmp.GOPBackOrderRef = salesInvoiceHeaderFooterTmp.GOPBackOrderRef + "@GOP:CommaSpace" + custInvoiceJour.InvoiceId;

            }

        }


        if (_custInvoiceJour.isProforma())

        {

            salesInvoiceHeaderFooterTmp.GOPIsProformaInt = 1;

        }

        else

        {

            salesInvoiceHeaderFooterTmp.GOPIsProformaInt = 0;

        }


        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIL]) && _custInvoiceJour.isProforma())

        {

            GOPProformaInvoiceNum GOPProformaInvoiceNum;


            select firstonly forupdate GOPProformaInvoiceNum;


            if (GOPProformaInvoiceNum)

            {

                GOPProformaInvoiceNum.ProformaNum = GOPProformaInvoiceNum.ProFormaNum + 1;

                GOPProformaInvoiceNum.ProformaNumberSeq = "@GOP:PFIN" + int2Str(GOPProformaInvoiceNum.ProformaNum);


                if (GOPProformaInvoiceNum.validateWrite())

                {

                    ttsbegin;

                    GOPProformaInvoiceNum.update();

                    ttscommit;

                }

            }

            else

            {

                GOPProformaInvoiceNum.ProFormaNum =  1;

                GOPProformaInvoiceNum.ProformaNumberSeq = "@GOP:PFIN" + int2Str(GOPProformaInvoiceNum.ProformaNum);


                if (GOPProformaInvoiceNum.validateWrite())

                {

                    GOPProformaInvoiceNum.insert();

                }

            }


            salesInvoiceHeaderFooterTmp.GOPProFormaNum = GOPProformaInvoiceNum.ProformaNumberSeq;

        }

    }


    private void populateSalesInvoiceHeaderFooterTmpANZ(CustInvoiceJour _custInvoiceJour, CompanyInfo _companyInfo)

    {

        CustPackingSlipJour packingSlipJour;

        InventTrans         inventTrans;


        salesInvoiceHeaderFooterTmp.GOPCarrierCode = TMSSalesTable::find(_custInvoiceJour.SalesId).CarrierCode;

 

        SalesTable salesTable2 = _custInvoiceJour.salesTable();

        salesInvoiceHeaderFooterTmp.GOPBillToAddress = LogisticsPostalAddress::findRecId(salesTable2.GOPBillToAddress).Address;

        salesInvoiceHeaderFooterTmp.GOPBillToAddressName = salesTable2.GOPBillToAddrName;

 

        salesInvoiceHeaderFooterTmp.GOPShipToAddress = LogisticsPostalAddress::findRecId(salesTable2.DeliveryPostalAddress).Address;

        salesInvoiceHeaderFooterTmp.GOPShipToAddressName = salesTable2.DeliveryName;

        salesInvoiceHeaderFooterTmp.CompanyPhone = CompanyInfo::findDataArea(curExt()).phone();

        salesInvoiceHeaderFooterTmp.GOPEnteredDate = PaymTerm::find(_custInvoiceJour.Payment).due(_custInvoiceJour.InvoiceDate);


        //Notes

        //salesInvoiceHeaderFooterTmp.HeaderNotes = salesTable2.GOPSpecialInstructionCustomer;

        select * from inventTrans

            where inventTrans.InvoiceId == _custInvoiceJour.InvoiceId

                join packingSlipJour where packingSlipJour.PackingSlipId == inventTrans.PackingSlipId;


        salesInvoiceHeaderFooterTmp.GOPExternalItmIdDesc = packingSlipJour.GOPConNoteNumber;

        salesInvoiceHeaderFooterTmp.GOPSpecialInstructionCustomer = salesTable2.GOPSpecialInstructionCustomer;

        

        //For NZ

        if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoNZ]))

        {

            salesInvoiceHeaderFooterTmp.CompanyTeleFax = CustParameters::findByCompany(curExt()).GOPOrderEnquiriesTelephone;

        }

        else

        {

            smmBusRelSalesDistrictGroup salesDisct;

            select firstonly salesDisct

                where salesDisct.SalesDistrictId == CustTable::find(salesTable2.CustAccount).SalesDistrictId;

 

            salesInvoiceHeaderFooterTmp.CompanyTeleFax = salesDisct.GOPOrderEnquiriesTelephone;

 

        }

    }


    /// <summary>

    /// COC of populateSalesInvoiceTmp method to populate the custom fields and add custom logic.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_custInvoiceTrans"> <c>CustInvoiceTrans</c> table </param>

    /// <param name = "_taxSpec"> <c>TaxSpec</c> table </param>

    /// <param name = "_custPaymSchedLine"> <c>CustPaymSchedLine</c> table </param>

    /// <param name = "_prepaymentCustTrans"> <c>CustTrans</c> table </param>

    /// <param name = "_prepaymentTaxTrans"> <c>TaxTrans</c> table </param>

    protected void populateSalesInvoiceTmp(CustInvoiceJour _custInvoiceJour,

        CustInvoiceTrans _custInvoiceTrans,

        TaxSpec _taxSpec,

        CustPaymSchedLine _custPaymSchedLine,

        CustTrans _prepaymentCustTrans,

        TaxTrans _prepaymentTaxTrans)

    {

        next populateSalesInvoiceTmp(_custInvoiceJour, _custInvoiceTrans, _taxSpec, _custPaymSchedLine, _prepaymentCustTrans, _prepaymentTaxTrans);

        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoSA]) )

        {

            this.populateSalesInvoiceTmpSA(_custInvoiceJour, _custInvoiceTrans, _taxSpec, _custPaymSchedLine, _prepaymentCustTrans, _prepaymentTaxTrans);

        }

        else if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIL]))

        {

            this.populateSalesInvoiceTmpISL(_custInvoiceJour, _custInvoiceTrans, _taxSpec, _custPaymSchedLine, _prepaymentCustTrans, _prepaymentTaxTrans);

        }

        else if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAU,#isoNZ,#isoUS]))

        {

            this.populateSalesInvoiceTmpAU(_custInvoiceJour, _custInvoiceTrans, _taxSpec, _custPaymSchedLine, _prepaymentCustTrans, _prepaymentTaxTrans);

        }

        else if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoAE]) )

        {

            this.populateSalesInvoiceTmpAE(_custInvoiceJour, _custInvoiceTrans, _taxSpec, _custPaymSchedLine, _prepaymentCustTrans, _prepaymentTaxTrans);

        }

    }


    /// <summary>

    /// COC of populateSalesInvoiceTmp method to populate the custom fields and add custom logic for iseral.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_custInvoiceTrans"> <c>CustInvoiceTrans</c> table </param>

    /// <param name = "_taxSpec"> <c>TaxSpec</c> table </param>

    /// <param name = "_custPaymSchedLine"> <c>CustPaymSchedLine</c> table </param>

    /// <param name = "_prepaymentCustTrans"> <c>CustTrans</c> table </param>

    /// <param name = "_prepaymentTaxTrans"> <c>TaxTrans</c> table </param>

    protected void populateSalesInvoiceTmpISL(CustInvoiceJour _custInvoiceJour,

        CustInvoiceTrans _custInvoiceTrans,

        TaxSpec _taxSpec,

        CustPaymSchedLine _custPaymSchedLine,

        CustTrans _prepaymentCustTrans,

        TaxTrans _prepaymentTaxTrans)

    {

        SalesLine   OrigSalesLineSalesID;

        CustInvoiceTrans custInvoiceTransLoc;

        CustVendExternalItem custVendExternalItem;

        SalesLine salesLine = _custInvoiceTrans.salesLine();

        salesInvoiceTmp.GOPShowTaxValue = this.getSalesHeadershowTaxValue(_custInvoiceJour, salesLine.RecId);        

        select ExternalItemId from custVendExternalItem

            where custVendExternalItem.ItemId     == salesLine.ItemId

                && custVendExternalItem.ModuleType          == ModuleInventPurchSalesVendCustGroup::Cust

                && custVendExternalItem.CustVendRelation    == salesLine.CustAccount;

        if (custVendExternalItem)

        {

            salesInvoiceTmp.GOPItemDescription = salesLine.itemName() + ' - ' + custVendExternalItem.ExternalItemId;

        }

        else

        {

            salesInvoiceTmp.GOPItemDescription = salesLine.itemName();

        }

        salesInvoiceTmp.GOPSalesUnit = salesLine.SalesUnit;

        salesInvoiceTmp.CurrencyCode = _custInvoiceTrans.CurrencyCode;

        salesInvoiceTmp.ExchRate = cachedExchRate;

        salesInvoiceTmp.GOPPerCode = _custInvoiceTrans.inventTable().GOPSellPerCode;


        if (_custInvoiceJour.isProforma())

        {

            salesInvoiceTmp.GOPPackSlipOrderedQty = salesInvoiceTmp.Qty;

            salesInvoiceTmp.GOPShippedQty = 0;

            salesInvoiceTmp.GOPPackSlipRemain = 0;

        }

        else

        {

            this.getPackingSlipTransFrmInvoice(_custInvoiceTrans);

        }


        if (SalesLine.InventTransIdReturn)

        {

            select firstOnly InvoiceId from custInvoiceTransLoc 

                exists join OrigSalesLineSalesID

                    where OrigSalesLineSalesID.InventTransId == custInvoiceTransLoc.InventTransId

                        && OrigSalesLineSalesID.InventTransId == SalesLine.InventTransIdReturn

                        && OrigSalesLineSalesID.ItemId == SalesLine.ItemId;


            salesInvoiceTmp.GOPInventTransIdReturn = custInvoiceTransLoc.InvoiceId;

        }


        LogisticsPostalAddress shipToLogisticsPostalAddress = LogisticsPostalAddress::findRecId(salesLine.DeliveryPostalAddress);


        salesInvoiceTmp.GOPShipToAddressName = LogisticsLocation::find(shipToLogisticsPostalAddress.Location).Description;

        salesInvoiceTmp.GOPShipToAddress = shipToLogisticsPostalAddress.Address;

        salesInvoiceTmp.DueDate = _custInvoiceJour.DueDate;

    }


    protected void populateSalesInvoiceTmpAU(CustInvoiceJour _custInvoiceJour,

        CustInvoiceTrans _custInvoiceTrans,

        TaxSpec _taxSpec,

        CustPaymSchedLine _custPaymSchedLine,

        CustTrans _prepaymentCustTrans,

        TaxTrans _prepaymentTaxTrans)

    {

        TaxTrans taxTrans;

       

        SalesLine salesLine2 = _custInvoiceTrans.salesLine();


        HMIMItemMaterial    hmIMItemMaterial;

        GOPCustomerItemXReference  customerItemXReference;


        select firstonly hmIMItemMaterial

        where hmIMItemMaterial.ItemId == _custInvoiceTrans.ItemId;

        salesInvoiceTmp.GOPClassCode = hmIMItemMaterial.ClassCode;


        salesInvoiceTmp.GOPOrderedQty = _custInvoiceTrans.salesLine().QtyOrdered;

        salesInvoiceTmp.GOPShippedQty = _custInvoiceTrans.qty;

        salesInvoiceTmp.GOPCustomerOrderUOM = salesLine2.SalesUnit;

        salesInvoiceTmp.GOPCustAccount = salesLine2.CustAccount;

        salesInvoiceTmp.GOPSalesPrice = _custInvoiceTrans.SalesPrice;


        if (salesLine2.GOPCustomerPartNumber)

        {

            select firstonly customerItemXReference

                where customerItemXReference.CustomerID == salesLine2.CustAccount

                && customerItemXReference.CustomerPartNumber == salesLine2.GOPCustomerPartNumber

                && customerItemXReference.CustomerOrderUOM == salesLine2.GOPCustomerOrderUOM;


            if(customerItemXReference)

            {

                if (customerItemXReference.CustomerConversionFactor)

                {

                    salesInvoiceTmp.GOPOrderedQty = salesLine2.QtyOrdered / customerItemXReference.CustomerConversionFactor;

                    salesInvoiceTmp.GOPShippedQty =  _custInvoiceTrans.qty / customerItemXReference.CustomerConversionFactor;

                    salesInvoiceTmp.GOPSalesPrice = _custInvoiceTrans.lineAmountInclTax() / (salesLine2.deliveredInTotal() / customerItemXReference.CustomerConversionFactor);

                    salesInvoiceTmp.GOPCustomerOrderUOM = customerItemXReference.CustomerOrderUOM;

                }

                else if (customerItemXReference.BaseConversionFactor)

                {

                    salesInvoiceTmp.GOPOrderedQty = salesLine2.QtyOrdered * customerItemXReference.BaseConversionFactor;

                    salesInvoiceTmp.GOPShippedQty =  _custInvoiceTrans.qty * customerItemXReference.BaseConversionFactor;

                    salesInvoiceTmp.GOPSalesPrice = _custInvoiceTrans.lineAmountInclTax() / (salesLine2.deliveredInTotal() * customerItemXReference.BaseConversionFactor);

                    salesInvoiceTmp.GOPCustomerOrderUOM = customerItemXReference.BaseUOM;

                }

                salesInvoiceTmp.GOPExternalItmIdDesc = customerItemXReference.CustomerPartNumber;

            }

        }

        else if (salesLine2.GOPGTINNumber || salesLine2.GOPCatalogueNumber)

        {

            select firstonly customerItemXReference

                    where (customerItemXReference.GTINNumber == salesLine2.GOPGTINNumber

                    || customerItemXReference.CatalogueNumber == salesLine2.GOPCatalogueNumber);


            if(customerItemXReference)

            {

                if (customerItemXReference.CustomerConversionFactor)

                {

                    salesInvoiceTmp.GOPOrderedQty = salesLine2.QtyOrdered / customerItemXReference.CustomerConversionFactor;

                    salesInvoiceTmp.GOPShippedQty =  _custInvoiceTrans.qty / customerItemXReference.CustomerConversionFactor;

                    salesInvoiceTmp.GOPSalesPrice = _custInvoiceTrans.lineAmountInclTax() / (salesLine2.deliveredInTotal() / customerItemXReference.CustomerConversionFactor);

                    salesInvoiceTmp.GOPCustomerOrderUOM = customerItemXReference.CustomerOrderUOM;

                }

                else if (customerItemXReference.BaseConversionFactor)

                {

                    salesInvoiceTmp.GOPOrderedQty = salesLine2.QtyOrdered * customerItemXReference.BaseConversionFactor;

                    salesInvoiceTmp.GOPShippedQty =  _custInvoiceTrans.qty * customerItemXReference.BaseConversionFactor;

                    salesInvoiceTmp.GOPSalesPrice = _custInvoiceTrans.lineAmountInclTax() / (salesLine2.deliveredInTotal() * customerItemXReference.BaseConversionFactor);

                    salesInvoiceTmp.GOPCustomerOrderUOM = customerItemXReference.BaseUOM;

                }

               

            }

        }


        select firstonly

            taxTrans where taxTrans.InventTransId == _custInvoiceTrans.InventTransId;


        salesInvoiceTmp.TaxValue = taxTrans.TaxValue;

        if(Sign(_custInvoiceTrans.lineAmountInclTax() == -1))

        {

            salesInvoiceTmp.TaxAmount = - taxTrans.TaxAmount;

        }

        else

        {

            salesInvoiceTmp.TaxAmount = taxTrans.TaxAmount;

        }


        if (!salesInvoiceTmp.TaxValue)

        {

            TmpTaxWorkTrans tmpTaxWorkTrans = SalesInvoiceDP::CalcTaxPercentAndValue(_custInvoiceJour.salesTable());


            select firstonly tmpTaxWorkTrans

                where tmpTaxWorkTrans.SourceRecId == salesLine2.RecId

                && tmpTaxWorkTrans.SourceTableId == tableNum(SalesLine); // For getting sales tax percent and sales tax amount.


            salesInvoiceTmp.TaxValue = tmpTaxWorkTrans.showTaxValue();

            if(Sign(_custInvoiceTrans.lineAmountInclTax() == -1))

            {

                salesInvoiceTmp.TaxAmount = - tmpTaxWorkTrans.TaxAmount;

            }

            else

            {

                salesInvoiceTmp.TaxAmount = tmpTaxWorkTrans.TaxAmount;

            }

        }

    }


    public TaxValue getSalesHeadershowTaxValue(custInvoiceJour _custInvoiceJour, RefRecId _salesLineRecId)

    {

        TmpTaxWorkTrans             tmpTaxWorkTrans;

        TaxValue                    TaxValue = 0.00;

        

        tmpTaxWorkTrans = SalesInvoiceDP::CalcTaxPercentAndValue(_custInvoiceJour.salesTable());


        select firstonly tmpTaxWorkTrans

                    where tmpTaxWorkTrans.SourceRecId == _salesLineRecId

                    && tmpTaxWorkTrans.SourceTableId == tableNum(SalesLine); // For getting sales tax percent and sales tax amount.


         TaxValue = tmpTaxWorkTrans.showTaxValue();

         return TaxValue;

    }


    /// <summary>

    /// This method populates packingslip ID and date.

    /// </summary>

    /// <param name = "_custPackingSlipJour"> <c>CustPackingSlipJour</c> </param>

    private void setPackingSlipIdAndDate(CustPackingSlipJour _custPackingSlipJour)

    {

        if (!salesInvoiceHeaderFooterTmp.GOPPackingSlipId && salesInvoiceHeaderFooterTmp.GOPPickDeliveryDate == dateNull())

        {

            salesInvoiceHeaderFooterTmp.GOPPackingSlipId = _custPackingSlipJour.PackingSlipId;

            salesInvoiceHeaderFooterTmp.GOPPickDeliveryDates = date2Str(_custPackingSlipJour.DeliveryDate,123,

                                                                                DateDay::Digits2,

                                                                                DateSeparator::Slash, // separator1

                                                                                DateMonth::Digits2,

                                                                                DateSeparator::Slash, // separator2

                                                                                DateYear::Digits4);

        }

        else

        {

            salesInvoiceHeaderFooterTmp.GOPPackingSlipId +="@GOP:CommaSpace" +_custPackingSlipJour.PackingSlipId;

            salesInvoiceHeaderFooterTmp.GOPPickDeliveryDates +="@GOP:CommaSpace" +date2Str(_custPackingSlipJour.DeliveryDate,123,

                                                                                                    DateDay::Digits2,

                                                                                                    DateSeparator::Slash, // separator1

                                                                                                    DateMonth::Digits2,

                                                                                                    DateSeparator::Slash, // separator2

                                                                                                    DateYear::Digits4);

        }

    }


    /// <summary>

    /// COC on populateSalesInvoiceHeaderFooterTmp method to populate the custom fields.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_companyInfo"> <c>CompanyInfo</c> table </param>

    protected void populateSalesInvoiceHeaderFooterTmpAE(CustInvoiceJour _custInvoiceJour, CompanyInfo _companyInfo)

    {

        BankAccountTable bankAccountTableLoc, bankAccountTableEURUSD;

        UserInfo UserInfo;

        DirPartyTable dirPartyTable;

        TaxRegistration taxRegistration;

        LogisticsPostalAddress billToLogisticsPostalAddress;

        LogisticsLocation logisticsLocation;


        SalesTable salesTable = _custInvoiceJour.salesTable();


        salesInvoiceHeaderFooterTmp.GOPShipTerm = salesTable.DlvTerm;

        salesInvoiceHeaderFooterTmp.GOPSalesOrderDate = salesTable.createDate();

        salesInvoiceHeaderFooterTmp.GOPRemarksISL = salesTable.GOPRemarksISL;

        salesInvoiceHeaderFooterTmp.GOPCurrencyCode = salesTable.CurrencyCode;

        salesInvoiceHeaderFooterTmp.GOPInventLocationId = salesTable.InventLocationId;

        salesInvoiceHeaderFooterTmp.GOPRouting = salesTable.DlvMode;

        salesInvoiceHeaderFooterTmp.GOPNameInArabic = _companyInfo.GOPNameInArabic;

        salesInvoiceHeaderFooterTmp.CompanyPhone = CompanyInfo::findDataArea(curExt()).phone();

        salesInvoiceHeaderFooterTmp.GOPInvoiceId = _custInvoiceJour.InvoiceId;

        salesInvoiceHeaderFooterTmp.GOPReceivedDate = salesTable.GOPReceivedDate;

        salesInvoiceHeaderFooterTmp.GOPShippingMarks = salesTable.GOPShippingMarks;

        salesInvoiceHeaderFooterTmp.GOPLetterOfCreditNum = salesTable.GOPLetterOfCreditNum;


        select firstonly Id, name from UserInfo

            where UserInfo.id == salesTable.CreatedBy;

        salesInvoiceHeaderFooterTmp.GOPCustServiceRepresentative = UserInfo.name;


        bankAccountTableLoc.clear();

        select firstonly AccountNum, IBAN, SWIFTNo, Name, Location from bankAccountTableLoc

            where bankAccountTableLoc.GOPBankForTaxInvoice == NoYes::Yes

            && bankAccountTableLoc.CurrencyCode == Ledger::accountingCurrency(CompanyInfo::current());

        salesInvoiceHeaderFooterTmp.GOPAccountNum = bankAccountTableLoc.AccountNum;

        salesInvoiceHeaderFooterTmp.GOPIBANNum = bankAccountTableLoc.IBAN;

        salesInvoiceHeaderFooterTmp.GOPSwiftCode = bankAccountTableLoc.SWIFTNo;

        salesInvoiceHeaderFooterTmp.GOPBankName = bankAccountTableLoc.Name;


        LogisticsPostalAddress bankLogisticsPostalAddress = LogisticsPostalAddress::findByLocation(bankAccountTableLoc.Location); // Selects bank address.

        salesInvoiceHeaderFooterTmp.GOPBankAddress = bankLogisticsPostalAddress.Address;


        bankAccountTableEURUSD.clear();

        select firstonly AccountNum, IBAN from bankAccountTableEURUSD

            where bankAccountTableEURUSD.GOPBankForTaxInvoice == NoYes::Yes

            && bankAccountTableEURUSD.CurrencyCode == '@SYS57303'; //Currency:Europe

        salesInvoiceHeaderFooterTmp.GOPAccountNumEUR = bankAccountTableEURUSD.AccountNum;

        salesInvoiceHeaderFooterTmp.GOPIBANNumEUR = bankAccountTableEURUSD.IBAN;


        bankAccountTableEURUSD.clear();

        select firstonly AccountNum, IBAN from bankAccountTableEURUSD

            where bankAccountTableEURUSD.GOPBankForTaxInvoice == NoYes::Yes

            && bankAccountTableEURUSD.CurrencyCode == '@CurrencyExchange:UnitedStatesCurrency'; //Currency:USD

        salesInvoiceHeaderFooterTmp.GOPAccountNumUSD = bankAccountTableEURUSD.AccountNum;

        salesInvoiceHeaderFooterTmp.GOPIBANNumUSD = bankAccountTableEURUSD.IBAN;

        salesInvoiceHeaderFooterTmp.GOPCustomerID = salesTable.CustAccount;


        dirPartyTable = DirPartyTable::findRec(_custInvoiceJour.custTable_InvoiceAccount().Party);


        billToLogisticsPostalAddress = LogisticsPostalAddress::findByLocation(dirPartyTable.PrimaryAddressLocation); // Customer billing address.


        select firstonly RecId from logisticsLocation

                where logisticsLocation.ParentLocation == billToLogisticsPostalAddress.Location;


        select firstonly RegistrationNumber from taxRegistration

                where taxRegistration.DirPartyLocation == DirPartyLocation::findByPartyLocation(dirPartyTable.RecId, LogisticsLocation::find(billToLogisticsPostalAddress.Location).RecId).RecId;


        salesInvoiceHeaderFooterTmp.GOPCustomerVATNum = taxRegistration.RegistrationNumber;

        salesInvoiceHeaderFooterTmp.GOPBillToAddressName = LogisticsLocation::find(billToLogisticsPostalAddress.Location).Description;

        salesInvoiceHeaderFooterTmp.GOPBillToAddress = billToLogisticsPostalAddress.Address;

        salesInvoiceHeaderFooterTmp.GOPCustomerRef = salesTable.CustomerRef;

        salesInvoiceHeaderFooterTmp.GOPPaymTerm = PaymTerm::find(_custInvoiceJour.custTable_OrderAccount().PaymTermId).Description;

        salesInvoiceHeaderFooterTmp.GOPBillToPhone = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Phone).Locator;


        InventTrans inventTrans;

        InventTransOrigin inventTransOrigin;

        CustPackingSlipJour custPackingSlipJour;

        CustInvoiceTrans custInvoiceTrans;


        while select DeliveryDate,PackingSlipId from custPackingSlipJour

            //order DeliveryDate asc

            exists join inventTrans

                where inventTrans.PackingSlipId == custPackingSlipJour.PackingSlipId

            exists join InvoiceId, InventTransId from custInvoiceTrans

                where inventTrans.InvoiceId == custInvoiceTrans.InvoiceId

            exists join inventTransOrigin

                where inventTransOrigin.RecId == inventTrans.inventTransOrigin

                    && inventTransOrigin.InventTransId == custInvoiceTrans.InventTransId

            && custInvoiceTrans.InvoiceId == _custInvoiceJour.InvoiceId

        {

            if (!salesInvoiceHeaderFooterTmp.GOPPackingSlipId && salesInvoiceHeaderFooterTmp.GOPPickDeliveryDate == dateNull())

            {

                salesInvoiceHeaderFooterTmp.GOPPackingSlipId = custPackingSlipJour.PackingSlipId;

                salesInvoiceHeaderFooterTmp.GOPPickDeliveryDates = date2Str(custPackingSlipJour.DeliveryDate,213,

                                                                            DateDay::Digits2,

                                                                            DateSeparator::Slash, // separator1

                                                                            DateMonth::Digits2,

                                                                            DateSeparator::Slash, // separator2

                                                                            DateYear::Digits4);

            }

            else

            {

                salesInvoiceHeaderFooterTmp.GOPPackingSlipId +="@GOP:CommaSpace" +custPackingSlipJour.PackingSlipId;

                salesInvoiceHeaderFooterTmp.GOPPickDeliveryDates +="@GOP:CommaSpace" +date2Str(custPackingSlipJour.DeliveryDate,213,

                                                                                                DateDay::Digits2,

                                                                                                DateSeparator::Slash, // separator1

                                                                                                DateMonth::Digits2,

                                                                                                DateSeparator::Slash, // separator2

                                                                                                DateYear::Digits4);

            }

        }


        CustInvoiceJour custInvoiceJour;


        while select custInvoiceJour

        where custInvoiceJour.SalesId == salesTable.SalesId

            && custInvoiceJour.InvoiceId != _custInvoiceJour.InvoiceId

        {

            if (!salesInvoiceHeaderFooterTmp.GOPBackOrderRef)

            {

                salesInvoiceHeaderFooterTmp.GOPBackOrderRef = custInvoiceJour.InvoiceId;

            }

            else

            {

                salesInvoiceHeaderFooterTmp.GOPBackOrderRef = salesInvoiceHeaderFooterTmp.GOPBackOrderRef + "@GOP:CommaSpace" + custInvoiceJour.InvoiceId;

            }

        }


        if (_custInvoiceJour.isProforma())

        {

            salesInvoiceHeaderFooterTmp.GOPIsProformaInt = 1;

        }

        else

        {

            salesInvoiceHeaderFooterTmp.GOPIsProformaInt = 0;

        }


        if (_custInvoiceJour.isProforma())

        {

            GOPProformaInvoiceNum_AE GOPProformaInvoiceNum;


            select firstonly forupdate GOPProformaInvoiceNum;


            if (GOPProformaInvoiceNum)

            {

                GOPProformaInvoiceNum.ProformaNum = GOPProformaInvoiceNum.ProFormaNum + 1;

                GOPProformaInvoiceNum.ProformaNumberSeq = "@GOP:PFIN" + int2Str(GOPProformaInvoiceNum.ProformaNum);


                if (GOPProformaInvoiceNum.validateWrite())

                {

                    ttsbegin;

                    GOPProformaInvoiceNum.update();

                    ttscommit;

                }

            }

            else

            {

                GOPProformaInvoiceNum.ProFormaNum =  1;

                GOPProformaInvoiceNum.ProformaNumberSeq = "@GOP:PFIN" + int2Str(GOPProformaInvoiceNum.ProformaNum);


                if (GOPProformaInvoiceNum.validateWrite())

                {

                    GOPProformaInvoiceNum.insert();

                }

            }


            salesInvoiceHeaderFooterTmp.GOPProFormaNum = GOPProformaInvoiceNum.ProformaNumberSeq;

        }


        SalesParmTable salesParmTabe;


        select firstonly GOPProformaInvConfirm, TransDate from salesParmTabe order by RecId desc

            where salesParmTabe.SalesId == salesTable.SalesId;


        if (salesParmTabe.GOPProformaInvConfirm)

        {

            salesInvoiceHeaderFooterTmp.GOPProformaInvConfirmInt = 1;

        }

        else

        {

            salesInvoiceHeaderFooterTmp.GOPProformaInvConfirmInt = 0;

        }


        salesInvoiceHeaderFooterTmp.GOPProformaDate = salesParmTabe.Transdate;

    }


    /// <summary>

    /// COC of populateSalesInvoiceTmp method to populate the custom fields and add custom logic.

    /// </summary>

    /// <param name = "_custInvoiceJour"> <c>CustInvoiceJour</c> table </param>

    /// <param name = "_custInvoiceTrans"> <c>CustInvoiceTrans</c> table </param>

    /// <param name = "_taxSpec"> <c>TaxSpec</c> table </param>

    /// <param name = "_custPaymSchedLine"> <c>CustPaymSchedLine</c> table </param>

    /// <param name = "_prepaymentCustTrans"> <c>CustTrans</c> table </param>

    /// <param name = "_prepaymentTaxTrans"> <c>TaxTrans</c> table </param>

    protected void populateSalesInvoiceTmpAE(CustInvoiceJour _custInvoiceJour,

                                                CustInvoiceTrans _custInvoiceTrans,

                                                TaxSpec _taxSpec,

                                                CustPaymSchedLine _custPaymSchedLine,

                                                CustTrans _prepaymentCustTrans,

                                                TaxTrans _prepaymentTaxTrans)

    {


        salesInvoiceTmp salesInvoiceTmpLoc;


        allowToCreateOrigInvoiceDetailsLineForCreditNote = 0;

        custVendCorrectedInvoiceId = "";

        custVendCorrectedInvoiceDate = dateNull();

        this.populateSalesInvoiceTmpAEOrigDetails(_custInvoiceJour,

                                                    _custInvoiceTrans,

                                                    _taxSpec,

                                                    _custPaymSchedLine,

                                                    _prepaymentCustTrans,

                                                    _prepaymentTaxTrans);

        this.creditInvoicingHeaderLoc(_custInvoiceJour);

        if (allowToCreateOrigInvoiceDetailsLineForCreditNote)

        {

            this.populateSalesInvoiceCreditNoteAndOriginalInvId(_custInvoiceJour,

                                                            _custInvoiceTrans);

            


        }


        ////Added as part of AD-FDD-04 Customer and Item X reference

        //salesInvoiceTmp.SalesUnitTxt = salesLine.GOPCustomerOrderUOM;

        //salesInvoiceTmp.Qty = salesLine.GOPCustomerOrderQty;

        //end

    }


    protected void populateSalesInvoiceCreditNoteAndOriginalInvId(CustInvoiceJour _custInvoiceJour,

                                                                                CustInvoiceTrans _custInvoiceTrans)

    {

        TaxTrans taxTrans;

        InventTable inventTable;

        salesInvoiceTmp salesInvoiceTmpLoc;

        LogisticsLocation logisticsLocation;

        LogisticsPostalAddress shipToLogisticsPostalAddress;

        CustInvoiceJour custInvoiceJourLoc;

        CustInvoiceTrans custInvoiceTransLoc;

           

        SalesLine salesLine = _custInvoiceTrans.salesLine();

        TradeInventTransId origInventTransIdReturn = salesLine.InventTransIdReturn;

            

        select * from custInvoiceJourLoc

            where custInvoiceJourLoc.InvoiceId == custVendCorrectedInvoiceId

                && custInvoiceJourLoc.InvoiceDate == custVendCorrectedInvoiceDate;


        select * from custInvoiceTransLoc

            where custInvoiceTransLoc.InvoiceId == custVendCorrectedInvoiceId

                && custInvoiceTransLoc.InvoiceDate == custVendCorrectedInvoiceDate

                && custInvoiceTransLoc.InventTransId == origInventTransIdReturn;

        salesLine.clear();

        salesLine = custInvoiceTransLoc.salesLine();


        salesInvoiceTmpLoc.LineAmount = 0.00;

        salesInvoiceTmpLoc.GOPCreateOrigInvoiceForCreditNote = NoYes::Yes;

        

        salesInvoiceTmpLoc.ItemId = salesLine.ItemId;

        salesInvoiceTmpLoc.GOPSalesUnit = salesLine.SalesUnit;

        salesInvoiceTmpLoc.GOPItemDescription = salesLine.itemName();


        this.getPackingSlipTransFrmInvoice(custInvoiceTransLoc);

        salesInvoiceTmp.GOPOrderedQty = salesLine.SalesQty;


        salesInvoiceTmpLoc.GOPOriginOfGoods = InventTable::find(salesLine.ItemId).GOPOriginOfGoods;


        //salesInvoiceTmp.TaxAmount = abs((salesInvoiceTmp.TaxValue/100) * salesInvoiceTmp.LineAmount);

        inventTable = custInvoiceTransLoc.inventTable();

        salesInvoiceTmpLoc.GOPPerCode = inventTable.GOPSellPerCode;

        salesInvoiceTmpLoc.GOPHSC = inventTable.GOPHSC;

        salesInvoiceTmpLoc.SalesPrice = custInvoiceTransLoc.SalesPrice; //CurrencyExchangeHelper::amount(custInvoiceTransLoc.SalesPrice * cachedExchRate); Todo


        if (custInvoiceTransLoc.DiscPercent && !custInvoiceTransLoc.DiscAmount)

        {

            salesInvoiceTmpLoc.GOPDiscPercent = custInvoiceTransLoc.DiscPercent;

            salesInvoiceTmpLoc.GOPDiscAmount = (custInvoiceTransLoc.DiscPercent*salesInvoiceTmpLoc.SalesPrice*salesInvoiceTmpLoc.GOPShippedQty)/100;

        }


        if (custInvoiceTransLoc.DiscAmount  && !custInvoiceTransLoc.DiscPercent)

        {

            salesInvoiceTmpLoc.GOPDiscAmount = custInvoiceTransLoc.DiscAmount*salesInvoiceTmpLoc.GOPShippedQty;

            salesInvoiceTmpLoc.GOPDiscPercent = (custInvoiceTransLoc.DiscAmount/salesInvoiceTmpLoc.SalesPrice)*100;

        }

        salesInvoiceTmpLoc.ExchRate = salesInvoiceTmp.ExchRate;

        if (salesLine.LinePercent && !salesLine.LineDisc)

        {

            salesInvoiceTmp.GOPDiscPercent = salesLine.LinePercent;

            salesInvoiceTmp.GOPDiscAmount = (salesLine.LinePercent*salesInvoiceTmp.SalesPrice*salesInvoiceTmp.GOPShippedQty)/100;

        }


        if (salesLine.LineDisc  && !salesLine.LinePercent)

        {

            salesInvoiceTmp.GOPDiscAmount = salesLine.LineDisc*salesInvoiceTmp.GOPShippedQty;

            salesInvoiceTmp.GOPDiscPercent = (salesLine.LineDisc/salesInvoiceTmp.SalesPrice)*100;

        }

        

        this.getBatchDetails(custInvoiceTransLoc.InventDimId, custInvoiceTransLoc.ItemId);

        this.getVatFromInvoiceLine(salesLine.TaxGroup, salesLine.TaxItemGroup,salesLine.CurrencyCode, _custInvoiceTrans.LineAmount);


        salesInvoiceTmpLoc.insert();

    }


    protected void creditInvoicingHeaderLoc(CustInvoiceJour _custInvoiceJour)

    {

        CustInvoiceJour localCustInvoiceJour;

        CustInvoiceTable localCustInvoiceTable;

        CustVendCorrectedInvoiceId correctedInvoiceId;

        

        CustVendCreditInvoicingJour custVendCreditInvoicingJour = CustVendCreditInvoicingJour::findInvoiceId(_custInvoiceJour.TableId, _custInvoiceJour.RecId);


        if (custVendCreditInvoicingJour)

        {

            if (_custInvoiceJour.isProforma())

            {

                // When printing a proforma Free Text Invoice ID, the custInvoiceJour.InvoiceId is a concatenation of # and the custInvoiceJour.RecId

                // see FreeTextInvoiceController.invoiceId2RecID()

                select firstOnly RecId from localCustInvoiceTable

                    where localCustInvoiceTable.RecId == str2int64(subStr(_custInvoiceJour.InvoiceId, 2, strLen(_custInvoiceJour.InvoiceId)));

            }


            if (localCustInvoiceTable)

            {

                CustVendCreditInvoicingTable custVendCreditInvoicingTable = custVendCreditInvoicingTable::find(localCustInvoiceTable.TableId, localCustInvoiceTable.RecId);

                custVendCorrectedInvoiceId = CustVendCreditInvoicingTable.CustVendCorrectedInvoiceId;

                custVendCorrectedInvoiceDate = CustVendCreditInvoicingTable.CustVendCorrectedInvoiceDate;

                allowToCreateOrigInvoiceDetailsLineForCreditNote = 1;

                

            }

            else

            {

                custVendCorrectedInvoiceId = custVendCreditInvoicingJour.CustVendCorrectedInvoiceId;

                custVendCorrectedInvoiceDate = custVendCreditInvoicingJour.CustVendCorrectedInvoiceDate;

                allowToCreateOrigInvoiceDetailsLineForCreditNote = 1;

            }

        }

    }


    public void populateSalesInvoiceTmpAEOrigDetails(CustInvoiceJour _custInvoiceJour,

                                                CustInvoiceTrans _custInvoiceTrans,

                                                TaxSpec _taxSpec,

                                                CustPaymSchedLine _custPaymSchedLine,

                                                CustTrans _prepaymentCustTrans,

                                                TaxTrans _prepaymentTaxTrans)

    {

        TaxTrans taxTrans;

        InventTable inventTable;

        LogisticsLocation logisticsLocation;

        LogisticsPostalAddress shipToLogisticsPostalAddress;


        

        SalesLine salesLine = _custInvoiceTrans.salesLine();

        salesInvoiceTmp.ItemId = salesLine.ItemId;

        salesInvoiceTmp.GOPSalesUnit = salesLine.SalesUnit;

        salesInvoiceTmp.GOPItemDescription = salesLine.itemName();


        this.getPackingSlipTransFrmInvoice(_custInvoiceTrans);


        salesInvoiceTmp.GOPOriginOfGoods = InventTable::find(salesLine.ItemId).GOPOriginOfGoods;


        inventTable = _custInvoiceTrans.inventTable();

        salesInvoiceTmp.GOPPerCode = inventTable.GOPSellPerCode;

        salesInvoiceTmp.GOPHSC = inventTable.GOPHSC;

        salesInvoiceTmp.SalesPrice = _custInvoiceTrans.SalesPrice; //CurrencyExchangeHelper::amount(_custInvoiceTrans.SalesPrice * cachedExchRate); ToDo


        if (salesLine.LinePercent && !salesLine.LineDisc)

        {

            salesInvoiceTmp.GOPDiscPercent = salesLine.LinePercent;


            if (_custInvoiceJour.isProforma())

            {

                salesInvoiceTmp.GOPDiscAmount = (salesLine.LinePercent*salesInvoiceTmp.SalesPrice*salesInvoiceTmp.GOPOrderedQty)/100;

            }

            else

            {

                salesInvoiceTmp.GOPDiscAmount = (salesLine.LinePercent*salesInvoiceTmp.SalesPrice*salesInvoiceTmp.GOPShippedQty)/100;

            }

        }


        if (salesLine.LineDisc  && !salesLine.LinePercent)

        {

            if (_custInvoiceJour.isProforma())

            {

                salesInvoiceTmp.GOPDiscAmount = salesLine.LineDisc*salesInvoiceTmp.GOPOrderedQty;

            }

            else

            {

                salesInvoiceTmp.GOPDiscAmount = salesLine.LineDisc*salesInvoiceTmp.GOPShippedQty;

            }


            salesInvoiceTmp.GOPDiscPercent = (salesLine.LineDisc/salesInvoiceTmp.SalesPrice)*100;

        }


        salesInvoiceTmp.LineAmount = _custInvoiceTrans.LineAmountMST;

        shipToLogisticsPostalAddress = LogisticsPostalAddress::findRecId(salesLine.DeliveryPostalAddress);

            

        select firstonly RecId from logisticsLocation

            where logisticsLocation.ParentLocation == shipToLogisticsPostalAddress.Location;


        salesInvoiceTmp.GOPShipToAddressName = LogisticsLocation::find(shipToLogisticsPostalAddress.Location).Description;

        salesInvoiceTmp.GOPShipToAddress = shipToLogisticsPostalAddress.Address;

        salesInvoiceTmp.GOPShipToPhone = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Phone).Locator;

        salesInvoiceTmp.GOPShipToFax = LogisticsElectronicAddress::findByLocationAndType(logisticsLocation.RecId, LogisticsElectronicAddressMethodType::Fax).Locator;


        if (_custInvoiceJour.isProforma())

        {

            salesInvoiceTmp.GOPOrderedQty = salesInvoiceTmp.Qty;

            salesInvoiceTmp.GOPShippedQty = 0;

            salesInvoiceTmp.GOPPackSlipRemain = 0;


            InventBatch inventBatch = InventBatch::find(InventDim::find(salesLine.InventDimId).inventBatchId, salesLine.ItemId);


            salesInvoiceTmp.GOPInventBatchId = inventBatch.inventBatchId;

            salesInvoiceTmp.GOPProdDate = inventBatch.prodDate;

            salesInvoiceTmp.GOPExpDate = inventBatch.expDate;


            salesInvoiceTmp.TaxAmount = Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(),

                                                           salesLine.CurrencyCode, salesLine.LineAmount, TaxModuleType::Sales);

            salesInvoiceTmp.TaxValue = (salesInvoiceTmp.TaxAmount*100)/salesInvoiceTmp.LineAmount;

        }

        else

        {

            this.getBatchDetails(_custInvoiceTrans.InventDimId, _custInvoiceTrans.ItemId);

            this.getVatFromInvoiceLine(salesLine.TaxGroup, salesLine.TaxItemGroup,salesLine.CurrencyCode, _custInvoiceTrans.LineAmount);

        }

        salesInvoiceTmp.CurrencyCode = _custInvoiceTrans.CurrencyCode;


    }


    /// <summary>

    /// to get buffer based CustPackingSlipJour or CustPackingSlipTrans

    /// </summary>

    /// <param name = "_invoiceId">invoiced Id</param>

    /// <param name = "_PAckingSlipJourOrTrans"> 0 to get  journal and 1 to bet transaction buffer</param>

    /// <returns></returns>

    public void getPackingSlipTransFrmInvoice( CustInvoiceTrans _CustInvoiceTrans)

    {

        CustPackingSlipTrans CustPackingSlipTrans;

        

        select sum(Qty) from CustPackingSlipTrans

            where CustPackingSlipTrans.InvoiceTransRefRecId == _CustInvoiceTrans.RecId

                && CustPackingSlipTrans.ItemId == _CustInvoiceTrans.ItemId;

        salesInvoiceTmp.GOPShippedQty = CustPackingSlipTrans.Qty;


        CustPackingSlipTrans.clear();


        select maxOf(Ordered) from CustPackingSlipTrans

            where CustPackingSlipTrans.InvoiceTransRefRecId == _CustInvoiceTrans.RecId

                && CustPackingSlipTrans.ItemId == _CustInvoiceTrans.ItemId;

            

        salesInvoiceTmp.GOPPackSlipOrderedQty = CustPackingSlipTrans.Ordered;

        salesInvoiceTmp.GOPPackSlipRemain = salesInvoiceTmp.GOPPackSlipOrderedQty - salesInvoiceTmp.GOPShippedQty;

    }


    public void getBatchDetails(InventDimId _InventDimId, ItemId _ItemId)

    {

        InventBatch inventBatch;


        inventBatch = InventBatch::find(InventDim::find(_InventDimId).inventBatchId, _ItemId);

        salesInvoiceTmp.GOPInventBatchId = inventBatch.inventBatchId;

        salesInvoiceTmp.GOPProdDate = inventBatch.prodDate;

        salesInvoiceTmp.GOPExpDate = inventBatch.expDate;

    }


    public void getVatFromInvoiceLine(TaxGroup _TaxGroup, TaxItemGroup _TaxItemGroup, CurrencyCode _CurrencyCode, LineAmount _LineAmount)

    {

        salesInvoiceTmp.TaxAmount = Tax::calcTaxAmount(_TaxGroup, _TaxItemGroup, Systemdateget(),_CurrencyCode, _LineAmount, TaxModuleType::Sales);

        salesInvoiceTmp.TaxValue = (salesInvoiceTmp.TaxAmount*100)/salesInvoiceTmp.LineAmount;

    }


}

Comments

Popular posts from this blog

Create ledger journals in D365FO using X++ + LedgerDimensionACType

Excel Import into D365 using x++ code