web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / i-am-ax-pankaj / Create custom services in D...

Create custom services in D365 FO

I AM AX PANKAJ Profile Picture I AM AX PANKAJ 419
Step 1 create Header class:

[DataContractAttribute]
Public class DLX_AM_Custom_TMS_VendPendingInvoiceContract
{
    private     str         dataAreaId;
    private     TransDate   transDate;
    public      str         purchaseOrderReference;
    private     str         packingSlipId;
    
    private     str         VendorId;
    private     str         InvoiceNumber;
    
    private     TransDate   InvoiceDate;
    private     str         InvoiceDescription;
    private     str         StoreDimensions;
    private     str         Legacyshopcode;
    List                    tms_vendPendingInvoiceContractArray;

    [DataMember("Legacyshopcode")]
    public str parmLegacyshopcode(str _value = Legacyshopcode)
    {
        if (!prmIsDefault(_value))
        {
            Legacyshopcode = _value;
        }
        return Legacyshopcode;
    }
    [DataMember("StoreDimensions")]
    public str parmStoreDimensions(str _value = StoreDimensions)
    {
        if (!prmIsDefault(_value))
        {
            StoreDimensions = _value;
        }
        return StoreDimensions;
    }
    [DataMember("InvoiceDescription")]
    public str parmInvoiceDescription(str _value = InvoiceDescription)
    {
        if (!prmIsDefault(_value))
        {
            InvoiceDescription = _value;
        }
        return InvoiceDescription;
    }
    [DataMember("InvoiceDate")]
    public TransDate parmInvoiceDate(TransDate _value = InvoiceDate)
    {
        if (!prmIsDefault(_value))
        {
            InvoiceDate = _value;
        }
        return InvoiceDate;
    }
    [DataMember("InvoiceNumber")]
    public str parmInvoiceNumber(str _value = InvoiceNumber)
    {
        if (!prmIsDefault(_value))
        {
            InvoiceNumber = _value;
        }
        return InvoiceNumber;
    }
    [DataMember("VendorId")]
    public str parmVendorId(str _value = VendorId)
    {
        if (!prmIsDefault(_value))
        {
            VendorId = _value;
        }
        return VendorId;
    }
   /* [DataMemberAttribute("Lines"),
    DataCollection(Types::Class, classStr(DLX_AM_Custom_TMS_VendPendingInvoiceLinesContract)),
    AifCollectionTypeAttribute('_tms_vendPendingInvoiceContractArray', Types::Class, classStr(DLX_AM_Custom_TMS_VendPendingInvoiceLinesContract)),
    AifCollectionTypeAttribute('return', Types::Class, classStr(DLX_AM_Custom_TMS_VendPendingInvoiceLinesContract))]
       
            
        public List parm_TMSVendContractArrayContractArray(List _tms_vendPendingInvoiceContractArray = tms_vendPendingInvoiceContractArray)
    {
        if (!prmIsDefault(_tms_vendPendingInvoiceContractArray))
        {
            tms_vendPendingInvoiceContractArray = _tms_vendPendingInvoiceContractArray;
        }
        return tms_vendPendingInvoiceContractArray;
    }    */
}

step 2 create line contract class
[DataContractAttribute]
 class DLX_AM_Custom_TMS_VendPenInvLinesContract
{
    
     real           InvoiceLineNo;
     str             LineDescription;
    private str     ProcurementCategoryName ;
    private real    TaxableAmount;
    private real    ReceiveNow;
    private str     HSNCode;
    private str     ServiceAccountingCode;
    private str     TaxRateType;
   // private str    TaxDetails ;
    private real    IGSTAmount;
    private real    CGSTAmount;
    private real    SGSTAmount;
    //
    private     str         StoreDimensions;
    private     str         Legacyshopcode;
    //
    [DataMember("InvoiceLineNo")]
    public real parmInvoiceLineNo(real _value = InvoiceLineNo)
    {
        if (!prmIsDefault(_value))
        {
            InvoiceLineNo = _value;
        }
        return InvoiceLineNo;
    }
    [DataMember("LineDescription")]
    public str parmLineDescription(str _value = LineDescription)
    {
        if (!prmIsDefault(_value))
        {
            LineDescription = _value;
        }
        return LineDescription;
    }
    [DataMember("Legacyshopcode")]
    public str parmLegacyshopcode(str _value = Legacyshopcode)
    {
        if (!prmIsDefault(_value))
        {
            Legacyshopcode = _value;
        }
        return Legacyshopcode;
    }
    [DataMember("StoreDimensions")]
    public str parmStoreDimensions(str _value = StoreDimensions)
    {
        if (!prmIsDefault(_value))
        {
            StoreDimensions = _value;
        }
        return StoreDimensions;
    }
    [DataMember("SGSTAmount")]
    public real parmSGSTAmount(real _value = SGSTAmount)
    {
        if (!prmIsDefault(_value))
        {
            SGSTAmount = _value;
        }
        return SGSTAmount;
    }
    [DataMember("CGSTAmount")]
    public real parmCGSTAmount(real _value = CGSTAmount)
    {
        if (!prmIsDefault(_value))
        {
            CGSTAmount = _value;
        }
        return CGSTAmount;
    }
    [DataMember("IGSTAmount")]
    public real parmIGSTAmount(real _value = IGSTAmount)
    {
        if (!prmIsDefault(_value))
        {
            IGSTAmount = _value;
        }
        return IGSTAmount;
    }
    [DataMember("TaxRateType")]
    public str parmTaxRateType(str _value = TaxRateType)
    {
        if (!prmIsDefault(_value))
        {
            TaxRateType = _value;
        }
        return TaxRateType;
    }
    [DataMember("ServiceAccountingCode")]
    public str parmServiceAccountingCode(str _value = ServiceAccountingCode)
    {
        if (!prmIsDefault(_value))
        {
            ServiceAccountingCode = _value;
        }
        return ServiceAccountingCode;
    }
    [DataMember("HSNCode")]
    public str parmHSNCode(str _value = HSNCode)
    {
        if (!prmIsDefault(_value))
        {
            HSNCode = _value;
        }
        return HSNCode;
    }
    [DataMember("ReceiveNow")]
    public real parmReceiveNow(real _value = ReceiveNow)
    {
        if (!prmIsDefault(_value))
        {
            ReceiveNow = _value;
        }
        return ReceiveNow;
    }
    [DataMember("TaxableAmount")]
    public real parmTaxableAmount(real _value = TaxableAmount)
    {
        if (!prmIsDefault(_value))
        {
            TaxableAmount = _value;
        }
        return TaxableAmount;
    }
    [DataMember("ProcurementCategoryName")]
    public str parmProcurementCategoryName(str _value = ProcurementCategoryName)
    {
        if (!prmIsDefault(_value))
        {
            ProcurementCategoryName = _value;
        }
        return ProcurementCategoryName;
    }
}

step 3 create request class for header and lines

[DataContractAttribute]
 class DLX_AM_Custom_TMS_VendPenInvRequest
{
    public     str         dataAreaId;
    public     str         VendorId;
    DLX_AM_Custom_TMS_VendPendingInvoiceContract _TMS_VendPendingInvoiceContract ;
    //List tmsOrderLineClassArray;
    public List               tmsOrderLineClassArray = new List(Types::Class);
    [DataMember("DataAreaId")]
    public str parmDataAreaId(str _value = dataAreaId)
    {
        if (!prmIsDefault(_value))
        {
            dataAreaId = _value;
        }
        return dataAreaId;
    }
    [DataMember("VendorId")]
    public str parmVendorId(str _value = VendorId)
    {
        if (!prmIsDefault(_value))
        {
            VendorId = _value;
        }
        return VendorId;
    }
    [DataMember("Header")]
    public DLX_AM_Custom_TMS_VendPendingInvoiceContract parmtms_vendPen_HeaderClass(DLX_AM_Custom_TMS_VendPendingInvoiceContract _tms_vendPen_Header = _TMS_VendPendingInvoiceContract)
    {
        if (!prmIsDefault(_tms_vendPen_Header))
        {
            _TMS_VendPendingInvoiceContract = _tms_vendPen_Header;
        }
        return _TMS_VendPendingInvoiceContract;
    }
[DataMemberAttribute("lines"),
DataCollection(Types::Class, classStr(DLX_AM_Custom_TMS_VendPenInvLinesContract)),
AifCollectionTypeAttribute('_headerClassArray', Types::Class, classStr(DLX_AM_Custom_TMS_VendPenInvLinesContract)),
AifCollectionTypeAttribute('return', Types::Class, classStr(DLX_AM_Custom_TMS_VendPenInvLinesContract))]
public List parmTMSOrderLineClassArray(List _headerClassArray = tmsOrderLineClassArray)
    {
        if (!prmIsDefault(_headerClassArray))
        {
            tmsOrderLineClassArray = _headerClassArray;
        }
 
        return tmsOrderLineClassArray;
    }
}

cstep 4 create response class
[DataContractAttribute]
 class DLX_AM_Custom_TMSResponse
{
    private boolean     success;
    private str         errorMessage;
    private str         debugMessage;
    [DataMember("ErrorMessage")]
    public str parmErrorMessage(str _value = errorMessage)
    {
        if (!prmIsDefault(_value))
        {
            errorMessage = _value;
        }
        return errorMessage;
    }
    [DataMember("Success")]
    public Boolean parmSuccess(Boolean _value = success)
    {
        if (!prmIsDefault(_value))
        {
            success = _value;
        }
        return success;
    }
    [DataMember("DebugMessage")]
    public str parmDebugMessage(str _value = debugMessage)
    {
        if (!prmIsDefault(_value))
        {
            debugMessage = _value;
        }
        return debugMessage;
    }
}

step 5 create service class

class DLX_AM_Custom_TMS_VendService
{
    Notes           errorMsg;  //Final
    Log errorlogValidate;

    public DLX_AM_Custom_TMSResponse create(DLX_AM_Custom_TMS_VendPenInvRequest _request)
    {
        List                lines, lineslistlog;
        ListIterator        literator;
        DLX_AM_Custom_TMS_VendPenInvLinesContract vendPenInvContractLines,vendPenInvContractLinesloc;
        VendInvoiceInfoTable vendInvoiceInfoTable;
        int i;
        int                                         numofLines;
        RecId           checkrecId,checkrecIdFailed;
        Log             errorlogHeader,falselog;
        DLX_AM_Custom_TMSVendInvCustomLog  _tmsVendInvCustomLogcheck, _tmsVendInvCustomLogupdate;
        boolean islogerrortrans = false;
        var response = new DLX_AM_Custom_TMSResponse();
        changecompany(_request.parmDataAreaId())
        {
            try
            {
                ttsbegin;
               // errorlog      = this.checkFields(_request.parmtms_vendPen_HeaderClass(),_request.parmTMSOrderLineClassArray()) ;
                errorlogHeader = this.checkFieldsHeader(_request.parmtms_vendPen_HeaderClass());
                if(!errorlogHeader)
                {
                    vendInvoiceInfoTable  =   this.createHeader(_request.parmtms_vendPen_HeaderClass());
                }
                //Create lines
              lines = _request.parmTMSOrderLineClassArray();
                if (lines && vendInvoiceInfoTable)
                {
                    literator = new ListIterator(lines);
                    while (literator.more())
                    {
                        vendPenInvContractLines = literator.value();
                        checkrecId  =         this.createLog(_request.parmtms_vendPen_HeaderClass(),vendPenInvContractLines,errorlogHeader).RecId;
                       
                    //    select RecId ,Log,CreatedTransactionId from _tmsVendInvCustomLogcheck
                     //       where _tmsVendInvCustomLogcheck.RecId ==  checkrecId;
                     islogerrortrans   =   this.checkLogTransTable(checkrecId);
                        if(islogerrortrans)
                        {
                            numofLines =       this.createLine(vendInvoiceInfoTable , vendPenInvContractLines);
                        }
                        literator.next();
                    }
                }
                if(numofLines)
                {
                   ttscommit;
                    response.parmDebugMessage(_request.parmtms_vendPen_HeaderClass().parmInvoiceNumber());
                    response.parmSuccess(true);
                }
                else 
                {
                    ttsabort;
                    response.parmSuccess(false);
                    
                   // checkrecIdFailed  = this.createLog(_request.parmtms_vendPen_HeaderClass(),vendPenInvContractLines).RecId;
                    //select RecId ,Log,CreatedTransactionId from _tmsVendInvCustomLogcheck
                       //     where _tmsVendInvCustomLogcheck.RecId ==  checkrecIdFailed;
                    //
                    lineslistlog = _request.parmTMSOrderLineClassArray();
                    literator = new ListIterator(lineslistlog);
                    while (literator.more())
                    {
                        vendPenInvContractLinesloc = literator.value();
                        checkrecIdFailed  =         this.createLog(_request.parmtms_vendPen_HeaderClass(),vendPenInvContractLinesloc,errorlogHeader).RecId;
                                      
                        literator.next();
                    } 
                //
                    response.parmErrorMessage(DLX_AM_Custom_TMSVendInvCustomLog::findlog(checkrecIdFailed));
                   // ttscommit;
                    //update_recordset _tmsVendInvCustomLogupdate
                      ///  setting TMSINVStatus = DLX_AM_Custom_TMSINVStatus::Error
               // where _tmsVendInvCustomLogupdate.RecId == checkrecIdFailed;
                    
                }
                
            }
            catch (Exception::CLRError)
            {
                System.Exception interopException = CLRInterop::getLastException();
                response.parmSuccess(false);
                this.appendToMsg(interopException.ToString());
            }    
            return response;
        }  
    }
    /*public log checkFields(DLX_AM_Custom_TMS_VendPendingInvoiceContract _headerContract,
        DLX_AM_Custom_TMS_VendPenInvLinesContract _linesContract)
    {
        Log                   errorLog;
        container             ConDisplayValueSpilt;
        str                   displayDimValue;
        // check vendor
        if(!VendTable::exist(_headerContract.parmVendorId()))
        {
            errorLog = strFmt('Vendor Id – Not available in D365 F&O :: %1 does not exist in master table',_headerContract.parmVendorId());
        }
        // check Invoice Number – Missing
        if(!_headerContract.parmInvoiceNumber())
        {
            errorLog += errorLog == '' ?  'Invoice Number – Missing' : '\n' + 'Invoice number not available';
        }
        if(VendInvoiceInfoTable::findFromVendInvoiceJour_without_PO_Bata(_headerContract.parmInvoiceNumber())) 
        {
            errorLog += errorLog == '' ? 'Invoice Number – Already available in D365 F&O' :  '\n' + _headerContract.parmInvoiceNumber(); //strFmt('Invoice Number – Already available in D365 F&O :: %1',_headerContract.parmInvoiceNumber());
        }
        if(!_headerContract.parmInvoiceDate())
        {
            errorLog += errorLog == '' ?  'Invoice date – Missing' : '\n' + 'Invoice date not available';
        }
        LogisticsLocation LogisticsLocation;
        select firstOnly LogisticsLocation
            where LogisticsLocation.DLX_AM_Custom_LegacyShopCode == _headerContract.parmLegacyshopcode();
        if(!LogisticsLocation)
        {
            errorLog += errorLog == '' ?  'Legacy Shop code – Missing' : '\n' + _headerContract.parmLegacyshopcode();
            
        }
        if(!_linesContract.parmProcurementCategoryName())
        {
            errorLog += errorLog == '' ?  'Procurement category name – Missing' : '\n' + 'Procurement category name not available';
        }
        EcoResCategory EcoResCategory;
        select firstonly   EcoResCategory
            where EcoResCategory.Name ==  _linesContract.parmProcurementCategoryName();
        if(!EcoResCategory)
        {
            errorLog += errorLog == '' ?  'Procurement category name – not available in D365 F&O' : '\n' + _linesContract.parmProcurementCategoryName();
        }

        if(!_linesContract.parmTaxableAmount())
        {
            errorLog += errorLog == '' ?  'Taxable amount – Missing' : '\n' + 'please check the taxable amount';
            //checkFailed(errorLog);
        }
        if(!_linesContract.parmServiceAccountingCode())
        {
            errorLog += errorLog == '' ?  'Service account code – Missing' : '\n' + 'Service account code is not defined';
        }
       // ServiceAccountingCodeTable_IN    ServiceAccountingCodeTable_IN;

        if(!ServiceAccountingCodeTable_IN::findByServiceAccountingCode(_linesContract.parmServiceAccountingCode()))
        {
            errorLog = strFmt('Service account code is not matching with D365  :: %1 Invalid Service account code',_linesContract.parmServiceAccountingCode());
        }
        if(!_linesContract.parmTaxRateType())
        {
            errorLog += errorLog == '' ?  'Tax rate type – Missing (taxable amount ≠0)' : '\n' + 'Tax rate type is not defined';
            
        }
        
        if(!TaxRateType::findByName(_linesContract.parmTaxRateType()))
        {
          errorLog += errorLog == '' ?  'Tax rate type – Not matching with D365 F&O' : '\n' + _linesContract.parmTaxRateType();
        }
        if(!_linesContract.parmStoreDimensions())
        {
            errorLog += errorLog == '' ?  'StoreDimension – Missing ' : '\n' + 'StoreDimension is not defined';
        }
     //   else 
       // {
          //  errorLog += errorLog == '' ?  'StoreDimension – Missing ' : '\n' + DLX_AM_Custom_TMS_VendService::validateStorageDimension(_linesContract.parmStoreDimensions());
        //}
        if(!DLX_AM_Custom_TMS_VendService::validateStorageDimension(_linesContract.parmStoreDimensions())  )
        {
            errorLog += errorLog == '' ?  'StoreDimension –  ' : '\n' + DLX_AM_Custom_TMS_VendService::validateStorageDimension(_linesContract.parmStoreDimensions());
        }
        return errorLog;
         //old
    }     */
    public Log checkFieldsHeader(
    DLX_AM_Custom_TMS_VendPendingInvoiceContract _headerContract
    )
    {
        Log errorLog = "";
        // Helper inline method pattern (manual append)
        #define.NewLine("\n")
        // Vendor check
        if (!VendTable::exist(_headerContract.parmVendorId()))
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("vendor is missing: %1", _headerContract.parmVendorId());
        }
        // Invoice Number
        if (!_headerContract.parmInvoiceNumber())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Invoice Number is missing";
        }
        if (VendInvoiceInfoTable::findFromVendInvoiceJour_without_PO_Bata(
                _headerContract.parmInvoiceNumber()))
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("Invoice Number already exists in D365 F&O: %1",
                _headerContract.parmInvoiceNumber());
        }
        // Invoice Date
        if (!_headerContract.parmInvoiceDate())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Invoice date is missing";
        }
        if (_headerContract.parmInvoiceDate() > today())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Invoice date can't be future date";
        }
       
        // Storage Dimension
        if (!_headerContract.parmStoreDimensions())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Store dimension is missing";
        }
        /*  else
        {
            str dimError =
            DLX_AM_Custom_TMS_VendService::validateStorageDimension(
                _headerContract.parmStoreDimensions());
            if (dimError)
            {
                errorLog += (errorLog == "" ? "" : #NewLine) +
                strFmt("Store dimension error: %1", dimError);
            }
        } */
        return errorLog;
    }
    public Log checkFields(
    DLX_AM_Custom_TMS_VendPendingInvoiceContract _headerContract,
    DLX_AM_Custom_TMS_VendPenInvLinesContract _linesContract)
    {
        Log errorLog = "";
        // Helper inline method pattern (manual append)
        #define.NewLine("\n")
        // Vendor check
       /* if (!VendTable::exist(_headerContract.parmVendorId()))
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("vendor is missing: %1", _headerContract.parmVendorId());
        }
        // Invoice Number
        if (!_headerContract.parmInvoiceNumber())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Invoice Number is missing";
        }
         if (VendInvoiceInfoTable::findFromVendInvoiceJour_without_PO_Bata(
                _headerContract.parmInvoiceNumber()))
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("Invoice Number already exists in D365 F&O: %1",
                _headerContract.parmInvoiceNumber());
        }
        // Invoice Date
        if (!_headerContract.parmInvoiceDate())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Invoice date is missing";
        }
        if (_headerContract.parmInvoiceDate() > today())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Invoice date can't be future date";
        }
        // Legacy Shop Code
        LogisticsLocation logisticsLocation;
        select firstOnly logisticsLocation
        where logisticsLocation.DLX_AM_Custom_LegacyShopCode ==
            _headerContract.parmLegacyshopcode();
        if (!logisticsLocation.RecId)
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("Legacy shop code not found: %1",
                _headerContract.parmLegacyshopcode());
        } */
          //line number
        if (!_linesContract.parmInvoiceLineNo())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Line no is missing";
        }
        // Procurement Category
        if (!_linesContract.parmProcurementCategoryName())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Procurement category name is missing";
        }
        else
        {
            EcoResCategory ecoResCategory;
            select firstOnly ecoResCategory
            where ecoResCategory.Name ==
                _linesContract.parmProcurementCategoryName();
            if (!ecoResCategory.RecId)
            {
                errorLog += (errorLog == "" ? "" : #NewLine) +
                strFmt("Wrong procurement category: %1",
                    _linesContract.parmProcurementCategoryName());
            }
        }
        // Taxable Amount
        if (!_linesContract.parmTaxableAmount())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Taxable amount is missing or zero";
        }
        // Service Accounting Code
        if (!_linesContract.parmServiceAccountingCode())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Service account code is missing";
        }
        else if (!ServiceAccountingCodeTable_IN::findByServiceAccountingCode(
                _linesContract.parmServiceAccountingCode()))
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("Invalid service account code: %1",
                _linesContract.parmServiceAccountingCode());
        }
        // Tax Rate Type
        if (!_linesContract.parmTaxRateType())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Tax rate type is missing";
        }
        else if (!TaxRateType::findByName(_linesContract.parmTaxRateType()))
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            strFmt("Tax rate type not found in D365 F&O: %1",
                _linesContract.parmTaxRateType());
        }
        // Storage Dimension
        if (!_linesContract.parmStoreDimensions())
        {
            errorLog += (errorLog == "" ? "" : #NewLine) +
            "Store dimension is missing";
        }
      /*  else
        {
            str dimError =
            DLX_AM_Custom_TMS_VendService::validateStorageDimension(
                _linesContract.parmStoreDimensions());
            if (dimError)
            {
                errorLog += (errorLog == "" ? "" : #NewLine) +
                strFmt("Store dimension error: %1", dimError);
            }
        } */
        return errorLog;
    }
    public VendInvoiceInfoTable createHeader(DLX_AM_Custom_TMS_VendPendingInvoiceContract _headerContract)
    {
        VendInvoiceInfoTable        vendInvoiceInfoTable;
        VendInvoiceInfoSubTable     vendInvoiceInfoSubTable;
        LogisticsPostalAddress      postalAddress;
        dirPartyTable               dirPartyTable;
        LogisticsLocation           LogisticsLocation;
        LogisticsPostalAddress      TmsPostalAddress;
        VendTable                   vendTable;
        PaymTerm                    paymTerm;
       // container                   conAttr = ["AStore", "BProfitCenter", "CCostCenter","DProjects", "ECountryRegion","FSite","GIntercompany", "HBusinessUnit", "IBrand"];
      //  List                        list                    = Global::strSplit("IN3783-2010-9999999--IN01-INDC27-520-BATA-",'-');
        //Container                   con                     = DLX_AM_Custom_TMS_VendService::ConverList2Container(list);
        DimensionDynamicAccount     ledgerDimension         = DLX_AM_Custom_TMS_VendService::createDefaultDimensionFromContainer(_headerContract.parmStoreDimensions());//"IN3783-2010-9999999--IN01-INDC27-520-BATA-");//_request.parmStoreDimensions());
                
        
        select firstOnly vendTable
            where vendTable.AccountNum == _headerContract.parmVendorId();
        
        str _invoiceId = _headerContract.parmVendorId();
        select firstOnly postalAddress
            where postalAddress.RecId == vendTable.postalAddress().RecId;
        select dirPartyTable
            where dirPartyTable.RecId == vendTable.Party;
        select firstOnly LogisticsLocation
            where LogisticsLocation.DLX_AM_Custom_LegacyShopCode == _headerContract.parmLegacyshopcode(); //_request.parmLegacyshopcode();
        select firstOnly TmsPostalAddress
            where TmsPostalAddress.Location == LogisticsLocation.RecId;
        select firstOnly TmsPostalAddress
             order by TmsPostalAddress.RecId desc
             where TmsPostalAddress.Location ==  LogisticsLocation.RecId;
        select firstOnly PaymTerm where paymTerm.PAYMTERMID == vendTable.PaymTermId;
                         
        if (vendTable.RecId)
        {
            vendInvoiceInfoTable.clear();
            vendInvoiceInfoTable.initValue();
            vendInvoiceInfoTable.DocumentOrigin          = DocumentOrigin::Manual;
            vendInvoiceInfoTable.InvoiceAccount          = _invoiceId;
            vendInvoiceInfoTable.defaultRow(null, null, true);
            vendInvoiceInfoTable.DocumentDate           = _headerContract.parmInvoiceDate();
            vendInvoiceInfoTable.Description            = _headerContract.parmInvoiceDescription();
            vendInvoiceInfoTable.num                    = _headerContract.parmInvoiceNumber();
            vendInvoiceInfoTable.LegacySystem_dlx       = 'TMS';
            vendInvoiceInfoTable.PostingProfile         = 'GEN';
            vendInvoiceInfoTable.ExchRate               = 1;
            vendInvoiceInfoTable.Approved               = NoYes::Yes;
            vendInvoiceInfoTable.Payment                = vendtable.PaymTermId;
            
            //
            vendInvoiceInfoTable.PaymMode               = 'BKTR';//vendtable.PaymMode;
            vendInvoiceInfoTable.VendBankAccountID      = vendTable.BankAccount;
            
            
            vendInvoiceInfoTable.RemittanceLocation     = postalAddress.Location;
           // vendInvoiceInfoTable.DeliveryName           = LogisticsLocation.Description;
           // vendInvoiceInfoTable.DeliveryPostalAddress  = TmsPostalAddress.Location;
           vendInvoiceInfoTable.setLocation(TmsPostalAddress.Location);
                   
           
            vendInvoiceInfoTable.CurrencyCode               = 'INR';//vendTable.Currency;
            vendInvoiceInfoTable.Approver                   = HcmWorker::userId2Worker(curUserId());
            vendInvoiceInfoTable.VendorRequestedWorkerEmail = HcmWorker::find(vendInvoiceInfoTable.Approver).email();
            
            vendInvoiceInfoTable.ListCode                   = Listcode::IncludeNot;
            vendInvoiceInfoTable.VendInvoiceSaveStatus      = VendInvoiceSaveStatus::Pending;
            vendInvoiceInfoTable.PurchName                  = vendTable.name();
            vendInvoiceInfoTable.Hold                       = NoYes::No;
            vendInvoiceInfoTable.ParmJobStatus              = ParmJobStatus::Waiting;
            vendInvoiceInfoTable.Approved                   = NoYes::Yes;
            vendInvoiceInfoTable.ExchRate                   = 1;
            vendInvoiceInfoTable.Ordering                   = DocumentStatus::Invoice;
            vendInvoiceInfoTable.StartDateTime              = DateTimeUtil::utcNow();
            //vendInvoiceInfoTable.DocumentDate               = today();
            vendInvoiceInfoTable.TransDate                  = today();
            //vendInvoiceInfoTable.FixedDueDate               =  PaymTerm.calcBaseDateOfDueDate( _request.parmInvoiceDate());
            vendInvoiceInfoTable.RequestStatus              = VendInvoiceRequestStatus::Draft;
            vendInvoiceInfoTable.SettleVoucher              = SettlementType::None;
            vendInvoiceInfoTable.Storno                     = NoYes::No;
            vendInvoiceInfoTable.LastMatchVariance          = LastMatchVarianceOptions::Unknown;
            vendInvoiceInfoTable.DefaultDimension           = ledgerDimension;
           if(vendInvoiceInfoTable.validateWrite())
            vendInvoiceInfoTable.insert();
                      
        }
        if (vendInvoiceInfoTable.RecId)
        {
            vendInvoiceInfoSubTable.clear();
            vendInvoiceInfoSubTable.initValue();
            vendInvoiceInfoSubTable.defaultRow();
            vendInvoiceInfoSubTable.ParmId       = vendInvoiceInfoTable.ParmId;
            vendInvoiceInfoSubTable.TableRefId   = vendInvoiceInfoTable.TableRefId;
            vendInvoiceInfoSubTable.PurchName =    vendTable.name();
                        
            if (vendInvoiceInfoTable.RecId)
            {
                vendInvoiceInfoSubTable.SourceAccountingEvent = AccountingEvent::getLastEvent(vendInvoiceInfoTable.SourceDocumentHeader).RecId;
            }
            vendInvoiceInfoSubTable.insert();
        }
      //  Info('done');
        return vendInvoiceInfoTable;
    }
    public int createLine(VendInvoiceInfoTable vendInvoiceInfoTable, DLX_AM_Custom_TMS_VendPenInvLinesContract linesContract)
    {
        VendInvoiceInfoLine                                     vendInvoiceInfoLine,vendInvoiceInfoLineExisting;
      //  DLX_AM_Custom_TMS_VendPenInvLinesContract               TMS_VendPendingInvoiceLines;
        ListIterator                                            literator;
        EcoResCategory                                          EcoResCategory;
        int                                                     numJournalLines ;
              
       // container                   conAttr = ["AStore", "BProfitCenter", "CCostCenter","DProjects", "ECountryRegion","FSite","GIntercompany", "HBusinessUnit", "IBrand"];
       // Container                   con                     = DLX_AM_Custom_TMS_VendService::ConverList2Container(list);
        DimensionDynamicAccount     ledgerDimension  = DLX_AM_Custom_TMS_VendService::createDefaultDimensionFromContainer(linesContract.parmStoreDimensions());
        LogisticsLocation           LogisticsLocation;
        LogisticsPostalAddress      TmsPostalAddress,TmsPostalAddressLoc;
        LogisticsPostalAddress      postalAddress;
        VendTable                   vendTable;
       
        select firstOnly vendTable
            where vendTable.AccountNum == vendInvoiceInfoTable.InvoiceAccount;
        select firstOnly postalAddress
            where postalAddress.RecId == vendTable.postalAddress().RecId;
        
        select firstOnly LogisticsLocation
            where LogisticsLocation.DLX_AM_Custom_LegacyShopCode == linesContract.parmLegacyshopcode();
        select Location from TmsPostalAddress
            where TmsPostalAddress.Location == LogisticsLocation.RecId;
        select firstOnly TmsPostalAddress
             order by TmsPostalAddress.RecId desc
             where TmsPostalAddress.Location ==  LogisticsLocation.RecId;
   
        select maxof(LineNum) from vendInvoiceInfoLineExisting where
            vendInvoiceInfoLineExisting.TableRefId ==  vendInvoiceInfoTable.TableRefId;
                vendInvoiceInfoLine.clear();
                vendInvoiceInfoLine.initValue();
     
          if(vendInvoiceInfoTable)
           {
               
            select firstonly   EcoResCategory
            where EcoResCategory.Name ==  linesContract.parmProcurementCategoryName();
 
            EcoResCategoryTranslation EcoResCategoryTranslation;
            select firstonly EcoResCategoryTranslation
            where  EcoResCategoryTranslation.CATEGORY == EcoResCategory.RecId
                && EcoResCategoryTranslation.LanguageId == 'en-us' ;
            vendInvoiceInfoLine.currencyCode              =  vendInvoiceInfoTable.CurrencyCode;
            vendInvoiceInfoLine.InvoiceAccount            =  vendInvoiceInfoTable.InvoiceAccount;
            vendInvoiceInfoLine.OrderAccount              =  vendInvoiceInfoTable.InvoiceAccount;
            vendInvoiceInfoLine.DeliveryName              =  vendInvoiceInfoTable.DeliveryName;
            vendInvoiceInfoLine.ParmId                    = vendInvoiceInfoTable.ParmId;
            vendInvoiceInfoLine.TableRefId                =   vendInvoiceInfoTable.TableRefId;
            vendInvoiceInfoLine.LineNum                   =  linesContract.parmInvoiceLineNo();
            vendInvoiceInfoLine.ProcurementCategory       =   EcoResCategory.RecId;
            
            vendInvoiceInfoLine.ReceiveNow                = linesContract.parmReceiveNow();
            vendInvoiceInfoLine.modifiedField(fieldnum(VendInvoiceInfoLine, ReceiveNow));
            vendInvoiceInfoLine.InventNow                 =  linesContract.parmReceiveNow();
            vendInvoiceInfoLine.PurchUnit                  =  'ea'  ;
                
            // vendInvoiceInfoLine.DefaultDimension           =  vendInvoiceInfoTable.DefaultDimension;
            vendInvoiceInfoLine.InventDimId                = 'AllBlank' ;
            vendInvoiceInfoLine.DeliveryName               =   LogisticsLocation.Description;
            vendInvoiceInfoLine.setDeliveryPostalAddress(TmsPostalAddress.Location);    
            vendInvoiceInfoLine.TaxWithholdGroup           =   TaxInformationVendTable_IN::findByVendTable(vendInvoiceInfoTable.InvoiceAccount).TDSGroup;//VendTable.TaxGroup;
            vendInvoiceInfoLine.LineAmount                 =     linesContract.parmTaxableAmount();
            if(0 < linesContract.parmReceiveNow())
            {   vendInvoiceInfoLine.InventNow =  linesContract.parmReceiveNow();
                vendInvoiceInfoLine.CGSTAmount_dlx             =  abs(linesContract.parmCGSTAmount());
                vendInvoiceInfoLine.IGSTAmount_dlx             =   abs(linesContract.parmIGSTAmount());
                vendInvoiceInfoLine.SGSTAmount_dlx             =   abs(linesContract.parmSGSTAmount());
            }
            else 
            {
                vendInvoiceInfoLine.CGSTAmount_dlx             =  linesContract.parmCGSTAmount();
                vendInvoiceInfoLine.IGSTAmount_dlx             =   linesContract.parmIGSTAmount();
                vendInvoiceInfoLine.SGSTAmount_dlx             =   linesContract.parmSGSTAmount();
            }
           // vendInvoiceInfoLine.TDSAmount_dlx                  =
            
            vendInvoiceInfoLine.DefaultDimension               =   ledgerDimension;
            vendInvoiceInfoLine.Description                    =   EcoResCategoryTranslation.Description;
        
            vendInvoiceInfoLine.DocumentOrigin                 =     DocumentOrigin::Manual;
            if(vendInvoiceInfoLine.validateWrite())
            {
                vendInvoiceInfoLine.insert();
                boolean             ret;
                ret  =  VendTable::find(vendInvoiceInfoLine.InvoiceAccount).TaxWithholdCalculate;
                if(ret)
                {
                    this.creationTDSGroup(vendInvoiceInfoLine);
                }
                this.updateSACandHSNCode(vendInvoiceInfoLine,linesContract);
                numJournalLines++  ;
            }
                        
           }
                VendInvoiceInfoSubLine       VendInvoiceInfoSubLine;
                if(vendInvoiceInfoLine)
                {
                    VendInvoiceInfoSubLine.clear();
                    VendInvoiceInfoSubLine.initValue();
                    VendInvoiceInfoSubLine.defaultRow();
                    VendInvoiceInfoSubLine.ParmId =       vendInvoiceInfoTable.ParmId;
                    VendInvoiceInfoSubLine.LineRefRecId =  vendInvoiceInfoLine.RecId;
                    VendInvoiceInfoSubLine.ReceiveNow =   vendInvoiceInfoLine.ReceiveNow;
                    VendInvoiceInfoSubLine.InventNow =      vendInvoiceInfoLine.ReceiveNow;
                    VendInvoiceInfoSubLine.insert();
                   
                }
        return numJournalLines;
        }
    public static DimensionDefault createDefaultDimensionFromContainer(str _dimString)
    {
        DimensionAttributeValueSetStorage   storage = new DimensionAttributeValueSetStorage();
        DimensionAttribute                  dimAttr;
        DimensionAttributeValue             dimAttrValue;
        List dimNames = new List(Types::String);
        ListEnumerator nameEnum;
        container values;
        int i;
       
        dimNames.addEnd("AStore");
        dimNames.addEnd("BProfitCenter");
        dimNames.addEnd("CCostCenter");
        dimNames.addEnd("DProjects");
        dimNames.addEnd("ECountryRegion");
        dimNames.addEnd("FSite");
        dimNames.addEnd("GIntercompany");
        dimNames.addEnd("HBusinessUnit");
        dimNames.addEnd("IBrand");
        
        // Remove leading '-'
        if (substr(_dimString, 1, 1) == "-")
        {
            _dimString = subStr(_dimString, 2, strLen(_dimString));
        }
        // Split values
        List                    list                    = Global::strSplit(_dimString,'-');
        Container               con                     = DLX_AM_Custom_TMS_VendService::ConverList2Container(list);
        values = con;
        nameEnum = dimNames.getEnumerator();
        i = 1;
        while (nameEnum.moveNext() && i <= conLen(values))
        {
            str dimName  = nameEnum.current();
            str dimValue = conPeek(values, i);
            dimAttr = DimensionAttribute::findByName(dimName);
            if (dimAttr && dimValue)
            {
                dimAttrValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttr,
                                dimValue,
                                false,   // create if missing
                                true);
                               
                if (dimAttrValue)
                {
                    storage.addItem(dimAttrValue);
                }
            }
            i++;
        }
        
        return storage.save();
    }
    public void appendToMsg(Notes _responseMsg)
    {
        if(errorMsg != '')
        {
            errorMsg += '\n' + _responseMsg;
        }
        else
        {
            errorMsg = _responseMsg;
        }
    }
    public static container converList2Container(list _list)
    {
        container       con;
        int             i= 1;
        ListEnumerator  le;
        le              = _list.getEnumerator();
        while(le.moveNext())
        {
            con         = conIns(con,i,le.current());
            i++;
        }
        return con;
    }
    public DLX_AM_Custom_TMSVendInvCustomLog createLog(DLX_AM_Custom_TMS_VendPendingInvoiceContract _headerContract,
        DLX_AM_Custom_TMS_VendPenInvLinesContract _linesContract,log _headerlog)
    {
        DLX_AM_Custom_TMSVendInvCustomLog logTable;
        Log errorlogcatch ,linelog;
        logTable.VendorId               =  _headerContract.parmVendorId();
        logTable.InvoiceNumber          =   _headerContract.parmInvoiceNumber();
        logTable.InvoiceDate            =   _headerContract.parmInvoiceDate();
        logTable.InvoiceDescription     =  _headerContract.parmInvoiceDescription();
        logTable.HeaderStoreDimensions  =  _headerContract.parmStoreDimensions();
        logTable.HeaderLegacyshopcode   = _headerContract.parmLegacyshopcode();
        logTable.InvoiceLineNo          = _linesContract.parmInvoiceLineNo();
        logTable.LineDescription        = _linesContract.parmLineDescription();
        logTable.ProcurementCategoryName = _linesContract.parmProcurementCategoryName();
        logTable.TaxableAmount = _linesContract.parmTaxableAmount();
        logTable.ReceiveNow = _linesContract.parmReceiveNow();
        logTable.HSNCode = _linesContract.parmHSNCode();
        logTable.ServiceAccountingCode = _linesContract.parmServiceAccountingCode();
        logTable.LinesStoreDimensions = _linesContract.parmStoreDimensions();
        //logTable.TaxRateType = _linesContract.parmTaxRateType();
        logTable.CGSTAmount = _linesContract.parmCGSTAmount();
        logTable.IGSTAmount = _linesContract.parmIGSTAmount();
        logTable.SGSTAmount = _linesContract.parmSGSTAmount();
        logTable.LinesLegacyshopcode = _linesContract.parmLegacyshopcode();
       // logTable.Log  = this.checkFields(_headerContract,_linesContract);
        linelog = this.checkFields(_headerContract,_linesContract);
        errorlogcatch = _headerlog;
        logTable.Log = errorlogcatch +  linelog;
        if(logTable.Log == '')
        { 
            Logtable.TMSINVStatus = DLX_AM_Custom_TMSINVStatus::None;
           
        }
        else
        {
            Logtable.TMSINVStatus = DLX_AM_Custom_TMSINVStatus::Error;
           
        }
        logTable.insert();
        return    logTable;
             
    }
  /*  static log validateStorageDimension(str dimStr)
    {
       
        List                    list                       = Global::strSplit(dimStr,'-');
        Container               values                     = DLX_AM_Custom_TMS_VendService::ConverList2Container(list)   ;
        Log errorlog;
     
        container names  = ["AStore","BProfitCenter","CCostCenter","DProjects","ECountryRegion","FSite","GIntercompany","HBusinessUnit","IBrand"];
       
        DimensionAttribute dimAttr;
        DimensionAttributeValue dimValue;
        int i;
        str val, name;
        for (i = 1; i <= conLen(values); i++)
        {
            val  = conPeek(values, i);
            name = conPeek(names, i);
            if (!val)
            continue;
            dimAttr = DimensionAttribute::findByName(name);
            dimValue = DimensionAttributeValue::findByDimensionAttributeAndValue(
            dimAttr,
            val,
            false,
            false
        );
            
            if (!dimValue.RecId)
            {
             errorlog =   strFmt("Invalid value %1 for %2", val, name);
               
            }
           
        }
        // info("All dimension values are valid.");
        return errorlog;
    }     */
    static log validateStorageDimension(str dimStr)
    {
        List        list   = Global::strSplit(dimStr,'-');
        Container   values = DLX_AM_Custom_TMS_VendService::ConverList2Container(list);
        Log         errorLog = '';
        container names = [
        "AStore","BProfitCenter","CCostCenter","DProjects",
        "ECountryRegion","FSite","GIntercompany","HBusinessUnit","IBrand"
    ];
        DimensionAttribute dimAttr;
        DimensionAttributeValue dimValue;
        int i;
        str val, name;
        for (i = 1; i <= conLen(values); i++)
        {
            val  = strLRTrim(conPeek(values, i));
            name = conPeek(names, i);
            // ✅ Skip blank values
            if (strLen(val) == 0)
            continue;
            dimAttr = DimensionAttribute::findByName(name);
            // ✅ Skip if dimension not configured
            if (!dimAttr.RecId)
            continue;
            dimValue = DimensionAttributeValue::findByDimensionAttributeAndValue(
            dimAttr,
            val,
            false,
            false
        );
            // ❌ Log error per dimension
            if (!dimValue.RecId)
            {
                errorLog += strFmt("Invalid value '%1' for dimension '%2'\n", val, name);
            }
        }
        return errorLog;
    }
    public void creationTDSGroup( VendInvoiceInfoLine _vendInvoiceInfoLine)
    {
        VendInvoiceInfoLineTaxExtension_IN      taxExt;
       
            taxExt.clear();
            taxExt.VendInvoiceInfoLine              = _vendInvoiceInfoLine.RecId;
            taxExt.TDSGroup                         = TaxInformationVendTable_IN::findByVendTable(_vendInvoiceInfoLine.InvoiceAccount).TDSGroup;//VendTable.TaxGroup;
            taxExt.insert();
      
    }
    public void updateSACandHSNCode( VendInvoiceInfoLine _vendInvoiceInfoLine,DLX_AM_Custom_TMS_VendPenInvLinesContract linesContract)
    {
        TransTaxInformationRelationView                 taxInfoView;
        TransTaxInformation                             transTaxInformation;
       
        TaxModelDocLineFactory::newTaxModelDocLine(_vendInvoiceInfoLine);
        select firstonly forupdate transTaxInformation
                exists join taxInfoView
                where   taxInfoView.TransTaxInformationRefRecId == transTaxInformation.RecId
                &&      taxInfoView.TransactionRefTableId       == _vendInvoiceInfoLine.TableId
                &&      taxInfoView.TransactionRefRecId         == _vendInvoiceInfoLine.RecId;
        if (transTaxInformation.RecId)
        {
           
            transTaxInformation.ServiceAccountingCodeTable  = ServiceAccountingCodeTable_IN::findByServiceAccountingCode(linesContract.parmServiceAccountingCode());
            transTaxInformation.HSNCodeTable                = HSNCodeTable_IN::findByCode(linesContract.parmHSNCode());
            ttsbegin;
            transTaxInformation.update();
            ttscommit;
        }
          
      }
      public boolean checkLogTransTable(RecId _recid)
      {
          DLX_AM_Custom_TMSVendInvCustomLog _tmsVendInvCustomLog, _selectVendInvCustomLog;
          boolean isError = true;
          select RecId, CreatedTransactionId from _selectVendInvCustomLog where _selectVendInvCustomLog.RecId ==  _recid;
        while select CreatedTransactionId,Log,TMSINVStatus from   _tmsVendInvCustomLog
              where _tmsVendInvCustomLog.CreatedTransactionId    ==    _selectVendInvCustomLog.CreatedTransactionId
          {
              if (_tmsVendInvCustomLog.TMSINVStatus == DLX_AM_Custom_TMSINVStatus::Error)
              {
                  isError = false;
              }
          }
        return isError;
      
      }
    public log checkLogFalse(RecId _recid)
    {
        DLX_AM_Custom_TMSVendInvCustomLog _tmsVendInvCustomLog, _selectVendInvCustomLog;
        log isError = '';
        select RecId, CreatedTransactionId from _selectVendInvCustomLog where _selectVendInvCustomLog.RecId ==  _recid;
        while select CreatedTransactionId,Log,TMSINVStatus from   _tmsVendInvCustomLog
              where _tmsVendInvCustomLog.CreatedTransactionId    ==    _selectVendInvCustomLog.CreatedTransactionId
        {
            if (_tmsVendInvCustomLog.TMSINVStatus == DLX_AM_Custom_TMSINVStatus::Error)
            {
                isError += _tmsVendInvCustomLog.Log;
            }
        }
        return isError;
      
    }
}   //end


Last step create service and service group




Comments