Showing posts with label Entity Methods in AX7. Show all posts
Showing posts with label Entity Methods in AX7. Show all posts

Saturday, 26 May 2018

Entity Methods in AX7


Entity Methods
public class CGLSalesOrderHeaderEntity extends common
{
    public void initValue()
    {
        NumberSeqRecordFieldHandler::enableNumberSequenceControlForField(
            this, fieldNum(CGLSalesOrderHeaderEntity, SalesOrderNumber), SalesParameters::numRefSalesId());

        super();
    }

    /// <summary>
    /// Returns the table extension used for defaulting.
    /// </summary>
    /// <returns>An instance of the <c>SysTableExtension</c> class.</returns>
    public TableExtension getExtension()
    {
        return SysTableExtension::construct();
    }

    private void defaultDlvMode()
    {
        this.DeliveryModeCode = TMSCarrierService::findDlvModeId(this.ShippingCarrierId, this.ShippingCarrierServiceId);
    }

    /// <summary>
    /// Retrieves the defaulting dependencies.
    /// </summary>
    /// <returns>A container with the defaulting dependencies.</returns>
    public container getDefaultingDependencies()
    {
        return [
            [fieldNum(CGLSalesOrderHeaderEntity, DeliveryModeCode),
                [fieldNum(CGLSalesOrderHeaderEntity, ShippingCarrierServiceId),
                fieldNum(CGLSalesOrderHeaderEntity, ShippingCarrierId)]]
        ];
    }

    /// <summary>
    /// Populates default values in a field.
    /// </summary>
    /// <param name = "_fieldId">The Id of the field that gets defaulted.</param>
    public void defaultField(FieldId _fieldId)
    {
        super (_fieldId);

        switch (_fieldId)
        {
            case fieldNum(CGLSalesOrderHeaderEntity, DeliveryModeCode):
                this.defaultDlvMode();
                break;
        }
    }

    public void initializeEntityDataSource(DataEntityRuntimeContext _entityCtx, DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        super(_entityCtx, _dataSourceCtx);

        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable):
                // clear out 'isFieldSet' so the defaulting logic does not consider fields that were set by initValue as specified by the user
                _dataSourceCtx.setAllFieldStatesToNotSet();
                break;
        }
    }

    public Common findEntityDataSource(DataEntityRuntimeContext _entityCtx, DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        Common ret;

        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, LogisticsPostalAddressBaseEntity):
                ret = TradeEntitySpecificDeliveryAddress::findLogisticsPostalAddressBaseEntityDataSource();
                break;

            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable_W):
                ret = SalesTable_W::findBySalesTable(this.RecId, true);
                break;

            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, TMSSalesTable):
                ret = TMSSalesTable::find(this.SalesOrderNumber, true);
                break;

            default:
                ret = super(_entityCtx, _dataSourceCtx);
        }
   
        return ret;
    }

    public boolean insertEntityDataSource(DataEntityRuntimeContext _entityCtx, DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        CustTable custTable,custTableReturn, custTableDim;
        LogisticsPostalAddress address;
        SalesTable salesTable,salesTableReturn;

        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable):
                {
                    this.validateWriteSalesTableDataSource(_dataSourceCtx);
                    salesTable = _dataSourceCtx.getBuffer();

                    select firstonly1 DefaultDimension from custTableDim
                        where custTableDim.AccountNum == salesTable.CustAccount;

                    str businessPartnerValue = CGLDimensionsHelper::getDimensionValue(custTableDim.DefaultDimension,"BusinessPartner");

                    if(businessPartnerValue)
                    {
                        salesTable.DefaultDimension = CGLDimensionsHelper::setDefaultDimension(salesTable.DefaultDimension,"BusinessPartner", businessPartnerValue);
                    }

                    LogisticsLocationRecId locationRecId = LogisticsPostalAddressBaseEntity::saveAddress(_entityCtx,
                    dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, LogisticsPostalAddressBaseEntityInvoice));
                    this.MotoristDescription = salesTable.CGLMotoristName;
                    LogisticsLocationRecId locationRecId1 = LogisticsPostalAddressBaseEntity::saveAddress(_entityCtx,
                    dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, LogisticsPostalAddressBaseEntityMotorist));
                    select firstonly address where address.Location == locationRecId;
                    salesTable.CGLInvoiceAddress = address.RecId;
                    select firstonly address where address.Location == locationRecId1;
                    salesTable.CGLMotoristAddress = address.RecId;
                  
                    //CS CR_2371_STC-COLL : Motorist customer invoice with BP name added n=on 5th May 2017
                    DirPartyTable   partyName;
                    select party from custTable
                        where custTable.AccountNum == salesTable.CustAccount
                        join Name from partyName where partyName.RecId == custTable.Party;

                    salesTable.SalesName = partyName.Name;
                    //CE CR_2371_STC-COLL : Motorist customer invoice with BP name added n=on 5th May 2017
                   
                    if(!CustParameters::find().DefaultCust)
                        throw error("@CGL:CGL003100");

                    if(salesTable.CGLScenarioType == CGLScenarioType::FMT)
                    {
                        CustTable           defaultCustTable;
                        CustParameters      custParameters;

                        select firstonly1 DefaultDimension from defaultCustTable
                            exists join custParameters
                                where custParameters.DefaultCust == defaultCustTable.AccountNum;

                        if(defaultCustTable.DefaultDimension)
                        {
                            businessPartnerValue = CGLDimensionsHelper::getDimensionValue(defaultCustTable.DefaultDimension,"BusinessPartner");
                        }

                        if(businessPartnerValue)
                        {
                            salesTable.DefaultDimension = CGLDimensionsHelper::setDefaultDimension(salesTable.DefaultDimension,"BusinessPartner", businessPartnerValue);
                        }
                        else
                        {
                            salesTable.DefaultDimension = CGLDimensionsHelper::removeDimension(salesTable.DefaultDimension,"BusinessPartner");
                        }

                        if(salesTable.CGLIsReturnOrder)
                        {
                            select firstonly salesTableReturn
                                join custTableReturn
                            where salesTableReturn.CGLFSXInvoiceNum == salesTable.CGLCreditNoteOrigFSXNum && custTableReturn.AccountNum == salesTableReturn.CustAccount
                            && custTableReturn.CGLCustomerType == CGLCustomerType::Motorist;
                        }

                        if (salesTableReturn.CustAccount)
                        {
                            salesTable.CustAccount = salesTableReturn.CustAccount;
                            salesTable.InvoiceAccount = salesTable.CustAccount;
                            //CS CR_2371_STC-COLL : Motorist customer invoice with BP name added n=on 5th May 2017
                            //salesTable.SalesName = salesTable.CGLMotoristName;
                            DirPartyTable   party;
                            select party from custTable
                                 where custTable.AccountNum == salesTable.CustAccount
                                join Name from party where party.RecId == custTable.Party;
                            salesTable.SalesName = party.Name;
                            //CE CR_2371_STC-COLL : Motorist customer invoice with BP name added n=on 5th May 2017
                        }
                        else
                        {  
                            salesTable.DeliveryName = salesTable.CGLMotoristName;
                            salesTable.CustAccount = CustTable::createOneTimeAccount(salesTable, true);
                            salesTable.InvoiceAccount = salesTable.CustAccount;
                            salesTable.SalesName = salesTable.CGLMotoristName;
                            select custTable where custTable.AccountNum == salesTable.CustAccount;
                            ttsbegin;
                           
                            DirPerson dirPerson;
                           
                            select forupdate dirPerson where dirPerson.RecId == custTable.Party;
                            dirPerson.Name = salesTable.CGLMotoristName;
                            dirPerson.PersonalTitle = DirNameAffix::find(DirNameAffixType::PersonalPrefix, this.CGLCustomerTitle).RecId;
                            dirPerson.doUpdate();

                            custTable.selectForUpdate(true);
                            custTable.CGLCustomerType = CGLCustomerType::Motorist;
                            if(custTable.Party && locationRecId1)
                            DirPartyLocation::create(custTable.Party,locationRecId1,true,true);
                            if(custTable.Party && salesTable.CGLMotoristEmail)
                            LogisticsElectronicAddress::createElectronicAddressFromUnsolicited(custTable.Party, LogisticsElectronicAddressMethodType::Email, salesTable.CGLMotoristEmail, NoYes::Yes);
                            //Start - santosp CR#2188
                            if(custTable.Party && salesTable.CGLMotoristPhone)
                                LogisticsElectronicAddress::createElectronicAddressFromUnsolicited(custTable.Party, LogisticsElectronicAddressMethodType::Phone, salesTable.CGLMotoristPhone, NoYes::Yes);
                            //End - santosp CR#2188
                            custTable.doupdate();
                            ttscommit;
                        }
                    }
                   

                    select custTable where custTable.AccountNum == salesTable.CustAccount;
                    if(custTable.CGLCustomerType == CGLCustomerType::BusinessPartner)
                    {
                        if(strLen( salesTable.CGLFSXInvoiceNum) > 7)
                        {
                            System.String invoiceNum = salesTable.CGLFSXInvoiceNum;
                            salesTable.CGLFSXInvoiceNumCalculated = invoiceNum.Substring(strLen( salesTable.CGLFSXInvoiceNum) -8)+ '-1';
                        }
                        else
                        {
                            salesTable.CGLFSXInvoiceNumCalculated = salesTable.CGLFSXInvoiceNum + '-1';
                        }
                    }
                    else if(custTable.CGLCustomerType == CGLCustomerType::Motorist)
                    {
                        if(strLen(salesTable.CGLFSXInvoiceNum) > 7)
                        {
                            System.String invoiceNum = salesTable.CGLFSXInvoiceNum;
                            salesTable.CGLFSXInvoiceNumCalculated = invoiceNum.Substring(strLen( salesTable.CGLFSXInvoiceNum) -8)+ '-2';
                        }
                        else
                        {
                            salesTable.CGLFSXInvoiceNumCalculated = salesTable.CGLFSXInvoiceNum + '-2';
                        }
                    }
                    DirPartyTable dirPartyTable;
                    select forupdate dirPartyTable where dirPartyTable.RecId == custTable.Party;
                    salesTable.LanguageId = dirPartyTable.LanguageId;
                }
                break;

            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, TMSSalesTable):
                _entityCtx.detectConflictForDatasource(_dataSourceCtx);
                break;

            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable_W):
                // SalesTable_W was created during SalesTable.insert(), so need to resolve the conflict:
                _entityCtx.detectConflictForDatasource(_dataSourceCtx);
                this.validateWriteDataSourceSalesTable_W(_dataSourceCtx);
                break;
        }
       
        boolean ret = super(_entityCtx, _dataSourceCtx);

        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(PurchPurchaseOrderHeaderEntity, LogisticsPostalAddressBaseEntity):
                this.TradeEntitySpecificDeliveryAddress::postInsertLogisticsPostalAddressBaseEntityDataSource(_dataSourceCtx);
                break;
        }

        return ret;
    }

    public boolean updateEntityDataSource(DataEntityRuntimeContext _entityCtx, DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable):
                if (this.CurrencyCode != this.orig().CurrencyCode)
                {
                    SalesTable salesTable = _dataSourceCtx.getBuffer();
                    salesTable.convertCurrencyCode(this.CurrencyCode, TradeCurencyConversion::TradeAgreements);
                }
                this.validateWriteSalesTableDataSource(_dataSourceCtx);
                LogisticsLocationRecId locationRecId = LogisticsPostalAddressBaseEntity::saveAddress(_entityCtx,
                dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, LogisticsPostalAddressBaseEntityInvoice));
               
                SalesTable salesTable = _dataSourceCtx.getBuffer();
                salesTable.CGLInvoiceAddress = locationRecId;

                locationRecId = LogisticsPostalAddressBaseEntity::saveAddress(_entityCtx,
                dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, LogisticsPostalAddressBaseEntityMotorist));
               
                salesTable = _dataSourceCtx.getBuffer();
                salesTable.CGLMotoristAddress = locationRecId;
                break;

            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable_W):
                this.validateWriteDataSourceSalesTable_W(_dataSourceCtx);
                break;

            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, TMSSalesTable):
                _entityCtx.detectConflictForDatasource(_dataSourceCtx);
                break;
        }
       
        return super(_entityCtx, _dataSourceCtx);
    }

    private void validateWriteSalesTableDataSource(DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        SalesTable salesTable = _dataSourceCtx.getBuffer() as SalesTable;
        SalesTableType salesTableType = salesTable.type();

        boolean isValid = true;

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, OrderingCustomerAccountNumber)) && !salesTableType.editCustAccount())
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, OrderingCustomerAccountNumber));
        }

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, InvoiceCustomerAccountNumber)) && !salesTableType.editInvoiceAccount())
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, InvoiceCustomerAccountNumber));
        }

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, TaxExemptNumber)) && !salesTableType.editVATNum())
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, TaxExemptNumber));
        }

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, ArePricesIncludingSalesTax)) && !salesTableType.editInclTax())
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, ArePricesIncludingSalesTax));
        }

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, CurrencyCode)) && !salesTableType.editCurrencyCode())
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, CurrencyCode));
        }

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, DirectDebitMandateId)) && !CustPaymModeTable::find(salesTable.PaymMode).IsSEPA)
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, DirectDebitMandateId));
        }

        if (salesTable.isMarkedForBankLC())
        {
            List fields = new List(Types::Integer);
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, PaymentTermsName));
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, FixedDueDate));
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, CustomerPaymentMethodName));
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, CustomerPaymentMethodSpecificationName));
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, PaymentScheduleName));
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, CashDiscountCode));
            fields.addEnd(fieldNum(CGLSalesOrderHeaderEntity, CustomerTransactionSettlementType));
            isValid = isValid & this.checkFieldsAreNotModified(fields);
        }
       
        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, WillAutomaticInventoryReservationConsiderBatchAttributes)) && !salesTable.canEditPdsBatchAttribAutoRes())
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, WillAutomaticInventoryReservationConsiderBatchAttributes));
        }

        if (!isValid)
        {
            _dataSourceCtx.throwValidateWriteFailed();
        }
    }

    private void validateWriteDataSourceSalesTable_W(DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        CustParameters custParameters = CustParameters::find();
        SalesTable_W salesTable_w = _dataSourceCtx.getBuffer() as SalesTable_W;

        boolean isValid = true;

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, IsEntryCertificateRequired))
            && !custParameters.EntryCertificateManagementEnabled_W)
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, IsEntryCertificateRequired));
        }

        if (this.isFieldModified(fieldNum(CGLSalesOrderHeaderEntity, IsOwnEntryCertificateIssued))
            && !salesTable_w.EntryCertificateRequired_W
            && !custParameters.EntryCertificateIssuingEnabled_W)
        {
            isValid = this.allowEditCheckFailed(fieldPName(CGLSalesOrderHeaderEntity, IsOwnEntryCertificateIssued));
        }

        if (!isValid)
        {
            _dataSourceCtx.throwValidateWriteFailed();
        }
    }

    public void mapEntityToDataSource(DataEntityRuntimeContext _entityCtx, DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, LogisticsPostalAddressBaseEntity):
                this.TradeEntitySpecificDeliveryAddress::mapLogisticsPostalAddressBaseEntityDataSourceToEntity(_dataSourceCtx);
                break;
        }

        super(_entityCtx, _dataSourceCtx);

        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable):
                SalesTable salesTable = _dataSourceCtx.getBuffer();
                // Setting the values here so the defaulting in the <c>initValue_Server</c> method in <c>SalesTable</c> is not used.
                // Table extension defaulting on SalesTable ensures that values set are not overridden if they are marked as set, so if the below 2 fields
                // are set on the entity (even if they have no value), then the corresponding SFKs on the sales table should also be marked as set, and the
                // entity framework is not doing this today (Dynamics: Bug 3667212).
                salesTable.fieldState(fieldNum(SalesTable, WorkerSalesTaker), this.fieldState(fieldNum(CGLSalesOrderHeaderEntity, OrderTakerPersonnelNumber)));
                salesTable.fieldState(fieldNum(SalesTable, WorkerSalesResponsible), this.fieldState(fieldNum(CGLSalesOrderHeaderEntity, OrderResponsiblePersonnelNumber)));

                if(!salesTable.InvoiceAccount)
                    salesTable.InvoiceAccount = salesTable.CustAccount;

                salesTable.SalesType        = SalesType::Sales;
                this.MotoristDescription    = salesTable.CGLMotoristName;
                //this.CGLCustomerTitle       = If this is required in future get title from customer dirperson, dirnameaffix

                if (this.isFieldSet(fieldNum(CGLSalesOrderHeaderEntity, CreditNoteReasonCode)))
                {
                    DataEntityDataSourceRuntimeContext dataSourceCtx = _entityCtx.getRuntimeContextByName(dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, CreditNoteReasonTableRef));

                    if (this.CreditNoteReasonCode)
                    {
                        salesTable.editReasonCode(true, this.CreditNoteReasonCode);

                        ReasonTableRef reasonTableRef = ReasonTableRef::find(salesTable.CreditNoteReasonCode);

                        if(!reasonTableRef.validateField(fieldNum(ReasonTableRef,Reason)))
                        {
                            throw error(strfmt("@ApplicationFoundation:DataEntitiesDataSourceValidateFieldFailed", fieldStr(CGLSalesOrderHeaderEntity, CreditNoteReasonCode)));
                        }

                        if (reasonTableRef)
                        {
                            dataSourceCtx.setBuffer(reasonTableRef);
                        }
                    }

                    dataSourceCtx.setDatabaseOperation(DataEntityDatabaseOperation::None);
                }

                if (this.scopeIdentifier())
                {
                    // Skip creation of markup when doing data migration
                    salesTable.SkipCreateMarkup = NoYes::Yes;
                }
                break;
        }
    }

    public void mapDataSourceToEntity(DataEntityRuntimeContext _entityCtx, DataEntityDataSourceRuntimeContext _dataSourceCtx)
    {
        super(_entityCtx, _dataSourceCtx);

        switch (_dataSourceCtx.name())
        {
            case dataEntityDataSourceStr(CGLSalesOrderHeaderEntity, SalesTable):
                SalesTable salesTable = _dataSourceCtx.getBuffer();
                this.TradeEntitySpecificDeliveryAddress::mapSavedPostalAddressToEntity(_entityCtx,  salesTable.DeliveryPostalAddress);

                TMSSalesTable tmsSalesTable = TMSSalesTable::find(this.SalesOrderNumber);
                this.ShippingCarrierId = tmsSalesTable.CarrierCode;
                this.ShippingCarrierServiceId = tmsSalesTable.CarrierServiceCode;
                this.TransportationModeId = tmsSalesTable.ModeCode;
                break;
        }
    }

    public boolean validateWrite()
    {
        if (this.RecId)
        {
            if (ReverseChargeParameters_W::find().Enabled)
            {
                return checkFailed("@SCM:SalesOrderHeaderEntityDoesNotSupportUpdatesWhenReverseChargesAreEnabled");
            }

            if (RetailParameters::isRetailEnabledAndInUse()
                && RetailSalesTable::find(this.SalesOrderNumber).RetailChannel)
            {
                return checkFailed("@SCM:SalesOrderHeaderEntityDoesNotSupportUpdatesOfRetailOrders");
            }

            if (!SalesTable::find(this.SalesOrderNumber).checkUpdate(true, true, true))
            {
                return false;
            }
        }

        SalesTable salesTableLocal;

        if (this.CGLCustomerTitle != '')
        {
            DirNameAffix    cglNameAffix =        DirNameAffix::find(DirNameAffixType::PersonalPrefix, this.CGLCustomerTitle);

            if (cglNameAffix.RecId == 0)
            {
                return checkFailed(strFmt("@SYP4986038", fieldStr(DirPerson, PersonalTitle), this.CGLCustomerTitle, fieldStr(DirNameAffix, Affix)));
            }
        }

        // NS Devlpoed by Ram for Bug IDD6 - FSX Invoice Number coming Twice
        select count(RecId) from salesTableLocal
            where salesTableLocal.CGLFSXInvoiceNum == this.CGLFSXInvoiceNum
            &&    salesTableLocal.SalesStatus == SalesStatus::Invoiced; //Aman Kedia IDD 6 bug

        if(salesTableLocal.RecId)
        {
            return checkFailed("@CGL:CGL003076");
        }
        // NE Devlpoed by Ram for Bug IDD6 - FSX Invoice Number coming Twice
        return super();
    }

    public boolean validateDelete()
    {
        if (!SalesTable::find(this.SalesOrderNumber).type().checkDelete(true, true))
        {
            return false;
        }

        return super();
    }

    public void insert()
    {
        LogisticsPostalAddress postalAddress;
        CustTable custTable,custTableReturn;
        LogisticsLocationParty logisticsLocationParty;
        SalesTable salesTableReturn;
        super();
        if(this.CGLScenarioType == CGLScenarioType::SPTI)
        {
            ttsbegin;
            SalesTable salesTable;
            select salesTable where salesTable.SalesId == this.SalesOrderNumber;
            salesTable salesTableLocal ;
            salesTableLocal.data(salesTable);
            salesTableLocal.SalesId = NumberSeq::newGetNum(SalesParameters::numRefSalesId() , true).num();
            salesTableLocal.OneTimeCustomer = true;
            salesTableLocal.DeliveryPostalAddress = salesTable.CGLMotoristAddress;

            if(salesTable.CGLIsReturnOrder)
            {
                select firstonly salesTableReturn
                    join custTableReturn
                where salesTableReturn.CGLFSXInvoiceNum == salesTable.CGLCreditNoteOrigFSXNum && custTableReturn.AccountNum == salesTableReturn.CustAccount
                && custTableReturn.CGLCustomerType == CGLCustomerType::Motorist;
            }

            if (salesTableReturn.CustAccount)
            {
                salesTableLocal.CustAccount = salesTableReturn.CustAccount;
                salesTableLocal.InvoiceAccount = salesTableLocal.CustAccount;
                //CS CR_2371_STC-COLL : Motorist customer invoice with BP name added n=on 5th May 2017
                //salesTable.SalesName = salesTable.CGLMotoristName;
                DirPartyTable   party;
                select party from custTable
                                 where custTable.AccountNum == salesTable.CustAccount
                                join Name from party where party.RecId == custTable.Party;
                salesTableLocal.SalesName = party.Name;
                //CE CR_2371_STC-COLL : Motorist customer invoice with BP name added n=on 5th May 2017
            }
            else
            {
                salesTableLocal.DeliveryName = salesTable.CGLMotoristName;
                salesTableLocal.CustAccount = CustTable::createOneTimeAccount(salesTableLocal, true);

               

                salesTableLocal.InvoiceAccount = salesTableLocal.CustAccount;
                salesTableLocal.SalesName = salesTable.CGLMotoristName;
                select custTable where custTable.AccountNum == salesTableLocal.CustAccount;
                DirPartyLocation dirPartyLocation;
                select forupdate dirPartyLocation where dirPartyLocation.Party == custTable.Party;
                select postalAddress where postalAddress.RecId == salesTableLocal.CGLMotoristAddress;
                dirPartyLocation.Location = postalAddress.Location;
                dirPartyLocation.doUpdate();

                DirPerson dirPerson;
                           
                select forupdate dirPerson where dirPerson.RecId == custTable.Party;
                dirPerson.Name = salesTable.CGLMotoristName;
                dirPerson.PersonalTitle = DirNameAffix::find(DirNameAffixType::PersonalPrefix, this.CGLCustomerTitle).RecId;
                dirPerson.doUpdate();


                custTable.selectForUpdate(true);
                custTable.CGLCustomerType = CGLCustomerType::Motorist;
                if(custTable.Party && salesTableLocal.CGLMotoristEmail)
                    LogisticsElectronicAddress::createElectronicAddressFromUnsolicited(custTable.Party, LogisticsElectronicAddressMethodType::Email, salesTableLocal.CGLMotoristEmail, NoYes::Yes);
                //Start - santosp CR#2188
                if(custTable.Party && salesTableLocal.CGLMotoristPhone)
                    LogisticsElectronicAddress::createElectronicAddressFromUnsolicited(custTable.Party, LogisticsElectronicAddressMethodType::Phone, salesTableLocal.CGLMotoristPhone, NoYes::Yes);
                //End - santosp CR#2188
                custTable.doupdate();
            }
          
            if(strLen( salesTableLocal.CGLFSXInvoiceNum) > 7)
            {
                System.String invoiceNum = salesTableLocal.CGLFSXInvoiceNum;
                salesTableLocal.CGLFSXInvoiceNumCalculated = invoiceNum.Substring(strLen( salesTableLocal.CGLFSXInvoiceNum) -8)+ '-2';
            }
            else
            {
                salesTableLocal.CGLFSXInvoiceNumCalculated = salesTableLocal.CGLFSXInvoiceNum + '-2';
            }

            CustTable           defaultCustTable;
            CustParameters      custParameters;
            str                 businessPartnerValue;

            select firstonly1 DefaultDimension from defaultCustTable
                exists join custParameters
                    where custParameters.DefaultCust == defaultCustTable.AccountNum;

            if(defaultCustTable.DefaultDimension)
            {
                businessPartnerValue = CGLDimensionsHelper::getDimensionValue(defaultCustTable.DefaultDimension,"BusinessPartner");
            }

            if(businessPartnerValue)
            {
                salesTableLocal.DefaultDimension = CGLDimensionsHelper::setDefaultDimension(salesTableLocal.DefaultDimension,"BusinessPartner", businessPartnerValue);
            }
            else
            {
                salesTableLocal.DefaultDimension = CGLDimensionsHelper::removeDimension(salesTableLocal.DefaultDimension,"BusinessPartner");
            }

            salesTableLocal.insert();
            if(!salesTable.CGLIsReturnOrder)
            {
                DirPartyTable dirPartyTable;
                select forupdate dirPartyTable where dirPartyTable.RecId == custTable.Party;
                dirPartyTable.Name = salesTable.CGLMotoristName;
                dirPartyTable.NameAlias = salesTable.CGLMotoristName;
                dirPartyTable.doUpdate();
            }
            ttscommit;
        }
    }

    // This method implements the interface defined by <c>TradeEntitySpecificDeliveryAddress</c>
    public RecId deliveryAddressPartyRecId()
    {
        return CustTable::find(this.OrderingCustomerAccountNumber).Party;
    }

    private static str isDeliveryAddressOrderSpecificComputedColumnDefinition()
    {
        // The <c>IsDeliveryAddressOrderSpecific</c> field is only designed for import scenarios
        // so we will always return 'No' for export scnearios to save performance.
        return SysComputedColumn::returnLiteral(NoYes::No);
    }

    private boolean allowEditCheckFailed(FieldLabel _fieldLabel)
    {
        return checkFailed(strFmt("@ApplicationFoundation:DataEntitiesNoAllowEdit", _fieldLabel));
    }

    private boolean isFieldModified(FieldId _fieldId)
    {
        return DataEntityDataSourceRuntimeContextAppSuite_Extension::isFieldModified(this, _fieldId);
    }

    private boolean checkFieldsAreNotModified(List _fieldIds)
    {
        var enumerator = _fieldIds.getEnumerator();
        boolean result = true;

        while (enumerator.moveNext())
        {
            FieldId fieldId = enumerator.current();
            if (this.isFieldModified(fieldId))
            {
                result = this.allowEditCheckFailed(fieldId2PName(tableNum(CGLSalesOrderHeaderEntity), fieldId));
            }
        }

        return result;
    }

    /// <summary>
    /// Updates Sales table for scenario types
    /// </summary>
    /// <param name = "_dmfDefinitionGroupExecution">A data management framework definition group being executed.</param>
    /// <remark>This method is called automatically by the data management framework.</remark>
    public static void postGetStagingData(DMFDefinitionGroupExecution _dmfDefinitionGroupExecution)
    {
        CGLSalesOrderHeaderStaging staging,stagingLocal;
        CustTable custTable;
        CustParameters custParameters;

        while select staging where staging.DefinitionGroup == _dmfDefinitionGroupExecution.DefinitionGroup
                && staging.ExecutionId == _dmfDefinitionGroupExecution.ExecutionId
                && staging.TransferStatus == DMFTransferStatus::NotStarted
        {
           
            switch(staging.CGLScenarioType)
            {
                case CGLScenarioType::FMT:
                    {
                        ttsbegin;
                        staging.selectForUpdate(true);
                        staging.IsOneTimeCustomer = NoYes::Yes;
                        staging.doupdate();
                        ttscommit;
                    }
                    break;
                 //Aman Kedia IDD 6 bug
                //case CGLScenarioType::SPTI:
                    //ttsbegin;
                    //staging.selectForUpdate(true);
                    //staging.CGLVATAmount = 0;
                    //staging.doupdate();
                    //ttscommit;
                    //break;
                case CGLScenarioType::WASO:
                    {
                      
                        custParameters = CustParameters::find();
                        if(!custParameters.CGLDefaultWarrantyCustomer)
                        {
                            throw error("@CGL:CGL003075");
                        }
                        ttsbegin;
                        staging.selectForUpdate(true);
                        staging.OrderingCustomerAccountNumber = custParameters.CGLDefaultWarrantyCustomer;
                        staging.CGLVATAmount = 0;
                        staging.doupdate();
                        ttscommit;
                    }
                    break;
            }
        }
    }

}