Wednesday, July 20, 2011

Create Electronic Invoice to Text File Format - Ax 2009 -

 The following code is to create a company country specific requirement. In addition, the logic is specific to the needs of my customer, but I'm sure you will be able to find great examples on how to create directories with WinApi and manipulate text files with the TextIO function.

The project flow is as follow:

1- The user posts an invoice
2- After the invoice has been posted, the KMN_eInvoiceCreation class is called with parameters  (This call is not posted here)
3- The class has several methods from creating the path file name, to writing a very specific logic into a text file.
4- The class saves the file into a specific location

The project produces the following text file contents:

DC|3.0|||15/07/2011|Pago en una sola exhibición||150.22|||||270.02||I
EM|KIE9512187VA|Compania de Ventanas S.A.

DF|Juytyu|130|Piso 7 y 8, Desp.801|Lostre|||MiguelHidalgo|DF|Mexico|999
RC|TORE621221HP9|Elizabeth Araya Reyes
DM|Teaneck|308||Warrrr|||Guadalupe|NL|Mexico|986589

CN|1.00|||Libro de Respuestas 3A/2A/A|25.00|25.00
CN|1.00|||Diploma de Finalización 7A|2.61|2.61
CN|1.00|||Diploma de Finalización 6A|2.61|2.61
CN|1.00|||Flashcards 1-50|120.00|120.00
IA|102433660003476|08/10/2010|Laredo
IT|IVA|33.80|16.00
TI||33.80


This project uses a custom table to store all the SalesParmTable data as we needed to provide a way for the user to re-run a posted invoice.

The following are the base enums I'm using.



The following are the tables and fields:



The following is the class - Enjoy : )
class KMN_eInvoiceCreation
{
    //KMN Tables
    KMN_eInvoiceHeaderSessionTable  eInvoiceHeaderSessionTable;
    KMN_eInvoiceDepositoryTXTFile   invoiceFilePath;
    KMN_eInvoiceSessionId           kmn_sessionId;
    KMN_eInvoiceDocType             kmn_docType;
    KMNInvoiceFormat                invoiceFormat;

    //Sales
    SalesId                         salesId;
    ItemId                          itemId;
    LineNum                         lineNum;
    SalesQty                        salesQty;
    SalesPrice                      salesPrice;
    CustAccount                     custAccount;
    AmountMST                       amountMST;
    SalesParmTable                  salesParmTable;
    SalesTable                      salesTable;
    Description                     description;

    //Markup
    MarkupCategoryType              markupCategoryType;
    MarkupCode                      markupCode;
    MarkupValue                     markupValue;
    TransTxt                        transTxt;

    //Batch
    InventBatchId                   inventBatchId;
    InventBatchProdDate             inventBatchProdDate;
    InventBatchTxt                  inevntBatchtxt;


    //Invoice
    CustInvoiceJour                 custInvoiceJournal;
    CustInvoiceTable                custInvoiceTable;
    InvoiceId                       invoiceId;
    TransDate                       invoiceDate;
    Voucher                         voucher;

    //Tax
    TaxTrans                        taxTrans;
    TaxTrans                        taxTransCode;
    TaxCode                         taxCode;


    DataAreaId                      companyAreaId;

    container                       _container;
    FileName                        fileName;
    Common                          common;
    NoYes                           freeTextInvoice;
    NoYes                           hasErrors;
    NoYes                           errors;
    str                             KmnYear;
    str                             KmnMonth;

}

protected void eInvoiceCreateDirectories(str _directory)
{
    boolean ret;
    ;


    try
    {
        if(!WinApi::folderExists(_directory))
            WinApi::createDirectory(_directory);
    }
    catch(Exception::Error)
    {
        this.eInvoiceProcessTextWriteError();
        KMN_LocalizationSetInfoErrors::routeMessage(KMN_ErrorType::DirectoryCreationFailed,
                                                        KMN_InfoErrorOutputType::Error);
    }
    catch(Exception::CLRError)
    {
        this.eInvoiceProcessTextWriteError();
        KMN_LocalizationSetInfoErrors::routeMessage(KMN_ErrorType::DirectoryCreationFailed,
                                                        KMN_InfoErrorOutputType::Error);
    }

}

protected void eInvoiceCreateElectronicInvoice()
{
    TextIO                          textIoWrite;
    FileIOPermission                permission;
    KMN_eInvoiceHeaderSessionLines  eInvoiceLines;
    KMN_eInvoiceHeaderSessionLines  eInvoiceLines2;
    CustInvoiceLine                 _custInvoiceLine;
    MarkupTrans                     _markupTrans;
    SalesLine                       salesLine;
    SalesTable                      _salesTable;
    InventTrans                     inventTrans;
    InventTrans                     inventTrans2;
    InventDim                       inventDim;
    str                             contData = '';
    int                             i;
    CLRObject                       exc;
    CLRObject                       clrExcMessage;
    CLRObject                       innerExc;
    str                             strError
    ;


    this.eInvoiceGenerateFileName();

    //Get Directory File Path
    if(!CompanyInfo::find().KUMDepositoryPDFFilesPath)
    {
        this.parmErrors(NoYes::Yes);
        KMN_LocalizationSetInfoErrors::routeMessage(KMN_ErrorType::NoFilePath, KMN_InfoErrorOutputType::Error);
    }

    //Set the File Path
    this.parmInvoiceFilePath(CompanyInfo::find().KUMDepositoryPDFFilesPath);

    //Set the company DataAreId
    this.parmDataAreaName(this.eInvoiceGetCompanyName());

    //Set the current month and year for folders name
    this.parmMonth(this.eInvoiceGetMonthYear(KMN_eInvoiceDateParmType::Month));
    this.parmYear(this.eInvoiceGetMonthYear(KMN_eInvoiceDateParmType::Year));

    //Check-Create Company, Year, Month Folders in Directory
    this.eInvoiceDefineDirectoryPath();

    invoiceFilePath += '\\' + fileName;

    try
    {

        //perm.assert();
        if(WinApi::fileExists(invoiceFilePath))
            WinApi::deleteFile(invoiceFilePath);

        //sw = new System.IO.StreamWriter(invoiceFilePath);
        permission = new FileIOPermission(invoiceFilePath,"RW");
        permission.assert();

        textIoWrite = New TextIo(invoiceFilePath, "W");
        if(textIoWrite == null)
        {
            KMN_LocalizationSetInfoErrors::routeMessage(KMN_ErrorType::CLRError, KMN_InfoErrorOutputType::Error);
            this.parmErrors(NoYes::Yes);
        }

        //Write in file
        switch(invoiceFormat)
        {
            case KMNInvoiceFormat::Mexico:
                //Document - begin
                contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Document_DC, 0);
                textIoWrite.write(contData);
                //sw.WriteLine(contData);
                //Document - end

                //Issuer_EM - begin
                contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Issuer_EM);
                textIoWrite.write(contData);
                //Issuer_EM - end

                //Issuer_DF - begin
                contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Issuer_DF);
                textIoWrite.write(contData);
                //Issuer_DF - end

                //Recipient_RC - begin
                contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Receipient_RC);
                textIoWrite.write(contData);
                //Recipient_RC - end

                //Recipient_DM - begin
                contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Receipient_DM);
                textIoWrite.write(contData);
                //Recipient_DM - end

//                if(kmn_docType == KMN_eInvoiceDocType::Invoice)
//                {
//                    //Issuer_EE - begin
//                    contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Issuer_EE);
//                    textIoWrite.write(contData);
//                    //Issuer_EE - end
//                }

                switch(kmn_docType)
                {
                    case KMN_eInvoiceDocType::Invoice:
                    case KMN_eInvoiceDocType::CreditNote:
                        // </Invoice Lines - begin>
                        while select eInvoiceLines where eInvoiceLines.SessionId == kmn_sessionId &&
                                                         eInvoiceLines.InvoiceId == invoiceId
                        {
                            while select salesLine join inventTrans where salesLine.SalesId == eInvoiceLines.SalesOrderId           &&
                                                                          inventTrans.InventTransId == salesLine.InventTransId      &&
                                                                          inventTrans.InvoiceId == eInvoiceLines.InvoiceId          &&
                                                                          inventTrans.StatusIssue == this.eInvoiceGetStatusIssue()  &&
                                                                          (salesLine.SalesStatus == SalesStatus::Invoiced       ||
                                                                           salesLine.SalesStatus == SalesStatus::Backorder)
                            {

                                if(salesLine.SalesPrice != 0)
                                {
                                    this.parmItemId(inventTrans.ItemId);
                                    this.parmSalesId(salesLine.SalesId);
                                    this.parmLineNum(salesLine.LineNum);
                                    this.parmSalesQty(inventTrans.Qty);
                                    this.parmSalesPrice(salesLine.SalesPrice);

                                    //Invoice Lines_CN - begin
                                    contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::ItemLines_CN);
                                    textIoWrite.write(contData);
                                    //Invoice Lines_CN - end

                                    //Invoice Lines_IA - begin
                                    if(InventTable::find(inventTrans.ItemId).DimGroupId == 'N-W')
                                    {
                                        while select inventTrans2 where inventTrans2.InventTransId == salesLine.InventTransId       &&
                                                                        inventTrans.InvoiceId == eInvoiceLines.InvoiceId            &&
                                                                        inventTrans.StatusIssue == this.eInvoiceGetStatusIssue()    &&
                                                                        inventtrans.ItemId == salesLine.ItemId
                                        {
                                            this.parmInventBatchId(InventDim::find(inventTrans2.inventDimId).inventBatchId);
                                            this.parmInventBatchProdDate(InventBatch::find(inventBatchId, inventTrans.ItemId).prodDate);
                                            this.parmInventBatchTxt(InventBatch::find(inventBatchId, inventTrans.ItemId).description);

                                            contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::ItemLines_IA);
                                            textIoWrite.write(contData);
                                            break;
                                            //Invoice Lines_IA - end
                                        }
                                    }
                                }
                            }
                        }
                        break;

                        case KMN_eInvoiceDocType::FreeTextInvoice:
                        case KMN_eInvoiceDocType::freeTextCreditNote:
                            while select eInvoiceLines where eInvoiceLines.SessionId == kmn_sessionId   &&
                                                             eInvoiceLines.InvoiceId == invoiceId       &&
                                                             eInvoiceLines.FreeTextRecId == custInvoiceTable.RecId
                            {
                                while select _custInvoiceLine where _custInvoiceLine.ParentRecId == custInvoiceTable.RecId
                                {
                                    if(_custInvoiceLine.AmountCur != 0)
                                    {
                                        //this.parmItemId(inventTrans.ItemId);
                                        this.parmSalesId(custInvoiceTable.SalesId);
                                        this.parmLineNum(_custInvoiceLine.LineNum);
                                        this.parmSalesQty(-1); //Needs to be a negative number to allow proper conversion
                                        this.parmSalesPrice(_custInvoiceLine.AmountCur);
                                        this.parmDescription(_custInvoiceLine.Description);

                                        //Invoice Lines_CN - begin
                                        contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::ItemLines_CN, 0);
                                        textIoWrite.write(contData);
                                        //Invoice Lines_CN - end
                                    }
                                }
                            }
                            break;
                }

                //Invoice Lines_CP - begin -Not in Use
                //contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::ItemLines_CP);
                //sw.WriteLine(contData);
                //Invoice Lines_CP - end

                //MicCharges_CN
                if(kmn_docType == KMN_eInvoiceDocType::Invoice)
                {
                    while select eInvoiceLines where eInvoiceLines.SessionId == kmn_sessionId &&
                                                             eInvoiceLines.InvoiceId == invoiceId
                    {
                        while select _salesTable join custInvoiceJournal join _markupTrans
                              where _salesTable.SalesId == eInvoiceLines.SalesOrderId &&
                                    custInvoiceJournal.SalesId == _salesTable.SalesId &&
                                    _markupTrans.TransRecId == custInvoiceJournal.RecId
                        {

                            this.parmMarkupCode(_markupTrans.MarkupCode);
                            this.parmMarkupValue(_markupTrans.Value);
                            this.parmTransTxt(_markupTrans.Txt);
                            contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::MicCharges_CN);
                            textIoWrite.write(contData);
                        }
                    }
                }

                //MicCharges_CN

                //</Tax - begin>
                while select TaxCode, sum(TaxAmount), TaxAmount from taxTransCode Group by TaxCode
                                                    where taxTransCode.Voucher == voucher
                {
                    this.parmTaxCode(taxTransCode.TaxCode);
                    //Tax_IT - begin
                    contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Tax_IT, taxTransCode.TaxAmount);
                    textIoWrite.write(contData);
                    //Tax_IT - end
                }

                //Tax_TI - begin
                contData = this.eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX::Tax_TI, 0);
                textIoWrite.write(contData);
                //</Tax - end>

                textIoWrite = null;
                CodeAccessPermission::revertAssert();
                break;
        }
    }
    catch(Exception::Internal)
    {
        this.eInvoiceProcessTextWriteError();
        exc = CLRInterop::getLastException();
        if( exc )
        {
            clrExcMessage = exc.get_Message();
            // BP Deviation Documented
            strError = CLRInterop::getAnyTypeForObject( clrExcMessage );

            throw error(strError);
        }
    }
    catch(Exception::CLRError)
    {
        this.eInvoiceProcessTextWriteError();
        exc = CLRInterop::getLastException();
        if( exc )
        {
            clrExcMessage = exc.get_Message();
            // BP Deviation Documented
            strError = CLRInterop::getAnyTypeForObject( clrExcMessage );

            innerExc = exc.get_InnerException();
            while(innerExc != null)
            {
                clrExcMessage = innerExc.get_Message();
                // BP Deviation Documented
                strError = strError + '\n' + CLRInterop::getAnyTypeForObject( clrExcMessage );
                innerExc = innerExc.get_InnerException();
            }

            throw error(strError);
        }
    }
    catch(Exception::Error)
    {
        this.eInvoiceProcessTextWriteError();
    }
}

protected void eInvoiceDefineDirectoryPath()
{
    str Directory;
    ;
         if(WinApi::pathExists(invoiceFilePath))
         {
            Directory = invoiceFilePath;
            Directory += '\\' + companyAreaId;
            this.eInvoiceCreateDirectories(Directory);

            Directory += '\\' + KmnYear;
            this.eInvoiceCreateDirectories(Directory);

            Directory += '\\' + KmnMonth;
            this.eInvoiceCreateDirectories(Directory);

            this.parmInvoiceFilePath(Directory);
         }

     //if(WinApi::fileExists(invoiceFilePath + '\\' + KmnYear + '\\' + KmnMonth + '\\' + fileName))
}

protected void eInvoiceDeleteRecordsWithNoInvoice(KMN_eInvoiceSessionId _sessionId)
{
    KMN_eInvoiceHeaderSessionTable  _headerSession;
    ;

    delete_from _headerSession where _headerSession.SessionId == _sessionId;
}

protected void eInvoiceFinalTableCleanup()
{
    KMN_eInvoiceHeaderSessionTable      _headerTable;
    ;

    try
    {
        //Update Fields with Errors
        delete_from _headerTable where _headerTable.ProcessEInvoice     == NoYes::No        &&
                                       _headerTable.SessionError        == NoYes::No;
    }
    catch(Exception::Error)
    {
        retry;
    }
}



protected void eInvoiceGenerateFileName()
{
    FileName        _fileName;
    ;

    _fileName = custAccount;
    _fileName += '_';
    _fileName += date2str(invoiceDate,
                          213,
                          DateDay::Digits2,
                          DateSeparator::None,
                          DateMonth::Digits2,
                          DateSeparator::None,
                          DateYear::Digits4);
    _fileName += '_';
    _fileName += invoiceId;
    _fileName += '.txt';
    this.parmFileName(_fileName);
}


protected DataAreaId eInvoiceGetCompanyName()
{
    return CompanyInfo::find().dataAreaId;
}


protected str eInvoiceGetContainerValues(container c, KMN_eInvoiceSectionTypeMX type = KMN_eInvoiceSectionTypeMX::Document_DC)
{
    str contData = "";
    int i;
    int length;
    ;

    length = conlen(c);

    for(i = 1; i <= conlen(c); i++)
    {
        switch(invoiceFormat)
        {
            case KMNInvoiceFormat::Mexico:
                //Count container and get rid off vertical line at the end

                if(i == length)
                    contData += strfmt("%1", conpeek(c, i));
                else
                    contData += strfmt("%1|", conpeek(c, i));
                break;

            default:
                contData += strfmt("%1|", conpeek(c, i));
                break;
        }

    }
        //info(strfmt("%1", conpeek(c, i)));

    return contData;
}

protected Address eInvoiceGetCustomerAdrress(RefRecId   _custTableRecId)
{
    Address _address;
    ;

    select * from _address where _address.AddrRecId == _custTableRecId &&
                                 _address.type == AddressType::Invoice;
    if(!_address)
        select * from _address where _address.AddrRecId == _custTableRecId  &&
                                     _address.type == AddressType::Delivery;

    if(!_address)
        select * from _address where _address.AddrRecId == _custTableRecId  &&
                                     _address.type == AddressType::Business;

    if(!_address)
        select * from _address where _address.AddrRecId == _custTableRecId  &&
                                     _address.type == AddressType::Payment;

    if(!_address)
        select * from _address where _address.AddrRecId == _custTableRecId  &&
                                     _address.type == AddressType::Home;

    if(!_address)
        this.eInvoiceProcessTextWriteError();

    return _address;
}

// Document
protected container eInvoiceGetHeaderValues(KMN_eInvoiceDocType _docType = KMN_eInvoiceDocType::Invoice)
{
    container           _containers;
    Amount              salesTotal;
    ;

    salesTotal = custInvoiceJournal.SalesBalance + custInvoiceJournal.SumMarkup;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            _containers = ["DC"]; //Type
            _containers += ["3.0"]; //Version
            _containers += [""]; // Series;
            _containers += [this.eInvoiceProcessInvoiceStr()]; // Folio;
            _containers += [""]; //Invoice Date
            _containers += ["Pago en una sola exhibición"]; // Form of Payment
            _containers += [""]; //Payment Conditions
            _containers += [this.eInvoiceSetResultSign(salesTotal)]; //Total Invoice Amount - Taxes
            _containers += [""]; //Discount Amount
            _containers += [""]; //Reason of the discount
            _containers += [""]; //Exchange rate
            _containers += [""]; //Currency
            _containers += [this.eInvoiceSetResultSign(custInvoiceJournal.InvoiceAmountMST)]; //Total Invoice + Taxes
            _containers += [""]; //Payment methods
            _containers += [this.eInvoiceReturnInvoiceType(_docType)]; //
            break;
    }

    return _containers;
}


protected container eInvoiceGetInvoiceLines(KMN_eInvoiceSectionTypeMX issuerType)
{
    container           _containers;
    Amount              totalLineAmt;
    ;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            totalLineAmt = salesQty * salesPrice * (-1);
            switch(issuerType)
            {
                case KMN_eInvoiceSectionTypeMX::ItemLines_CN:

                    _containers = ["CN"];
                    _containers += [this.eInvoiceResolveQtyAmountSign(salesQty)]; //Sales Qty
                    switch(kmn_docType)
                    {
                        case KMN_eInvoiceDocType::freeTextCreditNote:
                        case KMN_eInvoiceDocType::FreeTextInvoice:
                            _containers += ["Servicios"];
                            _containers += [""];
                            _containers += [description]; //Item Name
                            break;
                        default:
                            _containers += [""];
                            _containers += [""];
                            _containers += [InventTable::find(itemId).ItemName]; //Item Name
                            break;
                    }

                    _containers += [this.eInvoiceSetResultSign(salesPrice, KMN_eInvoiceSectionTypeMX::ItemLines_CN)]; //SalesPrice
                    _containers += [this.eInvoiceSetResultSign(totalLineAmt)]; // Total line Amount
                    break;
                case KMN_eInvoiceSectionTypeMX::ItemLines_IA:
                    _containers = ["IA"];
                    _containers += [inventBatchId]; //Number
                    _containers += [inventBatchProdDate]; //Date
                    _containers += [inevntBatchtxt];//Customs
                    break;
            }
            break;
    }

    return _containers;
}

// Issuer
protected container eInvoiceGetIssuerValues(KMN_eInvoiceSectionTypeMX issuerType)
{
    container           _containers;
    ;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            switch(issuerType)
            {
                case KMN_eInvoiceSectionTypeMX::Issuer_EM:
                    _containers = ["EM"];
                    _containers += ["KIE9512187VA"]; //Company RFC
                    _containers += [CompanyInfo::find().Name]; //Company Name
                    break;
                case KMN_eInvoiceSectionTypeMX::Issuer_DF:
                case KMN_eInvoiceSectionTypeMX::Issuer_EE:

                    if(issuerType == KMN_eInvoiceSectionTypeMX::Issuer_DF)
                        _containers = ["DF"];
                    else
                        _containers = ["EE"];

                    _containers += [CompanyInfo::find().Street]; //Company Street
                    _containers += [CompanyInfo::find().KMN_OutsideNumber_MX]; //Outside Number
                    _containers += [CompanyInfo::find().KMN_InsideNumber_MX]; //Inside Number
                    _containers += [CompanyInfo::find().KMN_Colony_MX]; //Colony
                    _containers += [""]; //Locality
                    _containers += [""]; //Reference
                    _containers += [CompanyInfo::find().City];
                    _containers += [CompanyInfo::find().State]; //State
                    _containers += [AddressCountryRegion::find(CompanyInfo::find().CountryRegionId).Name]; //Country
                    _containers += [CompanyInfo::find().ZipCode]; //Zip
                    break;
            }
            break;
    }

    return _containers;
}

protected container eInvoiceGetMiscChargesLines(KMN_eInvoiceSectionTypeMX issuerType = KMN_eInvoiceSectionTypeMX::None)
{
    container           _containers;
    Amount              totalLineAmt;
    ;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            _containers = ["CN"];
            _containers += ["1"];
            _containers += [""];
            _containers += [""];
            _containers += [transTxt];
            _containers += [this.eInvoiceSetResultSign(markupValue)];
            _containers += [this.eInvoiceSetResultSign(markupValue)];
            break;
    }
    return _containers;
}

protected str eInvoiceGetMonthYear(KMN_eInvoiceDateParmType parmType)
{
    str _monthyear;
    ;

    switch(parmType)
    {
        case KMN_eInvoiceDateParmType::Month:
            _monthyear = strfmt("%1", DateTimeUtil::month(DateTimeUtil::getSystemDateTime()));
            break;
        case KMN_eInvoiceDateParmType::Year:
            _monthyear = strfmt("%1", DateTimeUtil::year(DateTimeUtil::getSystemDateTime()));
            break;
    }

    return _monthyear;
}

// Recipient
protected container eInvoiceGetRecipient(KMN_eInvoiceSectionTypeMX recipientType)
{
    container           _containers;
    Address             _address;
    ;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            switch(recipientType)
            {
                case KMN_eInvoiceSectionTypeMX::Receipient_RC:
                    _containers = ["RC"];
                    _containers += [CustTable::find(custAccount).IdentificationNumber]; //Customer Identification Number
                    _containers += [CustTable::find(custAccount).Name]; //Customer Name
                    break;
                case KMN_eInvoiceSectionTypeMX::Receipient_DM:
                    _address = this.eInvoiceGetCustomerAdrress(CustTable::find(custAccount).RecId);
                    _containers += ["DM"];
                    _containers += [_address.Street]; //Company Street
                    _containers += [_address.KMN_OutsideNumber_MX]; //Outside Number
                    _containers += [_address.KMN_InsideNumber_MX]; //Inside Number
                    _containers += [_address.KMN_Colony_MX]; //Colony
                    _containers += [""]; //Locality
                    _containers += [""]; //Reference
                    _containers += [_address.City];
                    _containers += [_address.State]; //State
                    _containers += [AddressCountryRegion::find(CustTable::find(custAccount).CountryRegionId).Name]; //Country
                    _containers += [_address.ZipCode]; //Zip
                    break;
            }
            break;
    }

    return _containers;
}

private StatusIssue eInvoiceGetStatusIssue()
{
    StatusIssue     _statusIssue;
    ;

    switch(kmn_docType)
    {
        case KMN_eInvoiceDocType::Invoice:
            _statusIssue = StatusIssue::Sold;
            break;
        case KMN_eInvoiceDocType::CreditNote:
            _statusIssue = StatusIssue::None;
            break;
    }

    return _statusIssue;
}

//Tax
protected container eInvoiceGetTaxLines(KMN_eInvoiceSectionTypeMX type, TaxAmount _taxAmount = 0)
{
    container           _containers;
    TaxTrans            localTaxTrans;
    ;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            switch(type)
            {
                case KMN_eInvoiceSectionTypeMX::Tax_IT:
                    _containers = ["IT"];
                    _containers += [TaxPeriodHead::find(TaxTable::find(taxCode).TaxPeriod).Name]; //Settlement Tax

                    select firstonly localTaxTrans where localTaxTrans.Voucher == custInvoiceJournal.LedgerVoucher &&
                                                         localTaxTrans.TaxCode == taxCode;

                    _containers += [this.eInvoiceSetResultSign(_taxAmount, KMN_eInvoiceSectionTypeMX::Tax_IT)]; //Total amount per tax code line
                    _containers += [localTaxTrans.TaxValue]; //Tax Rate
                    break;
                case KMN_eInvoiceSectionTypeMX::Tax_TI:
                    _containers = ["TI"];
                    _containers += [""]; //Total witheld
                    _containers += [this.eInvoiceSetResultSign(amountMST, KMN_eInvoiceSectionTypeMX::Tax_TI)]; //Total tax amount
                    break;
            }
            break;
    }

    return _containers;
}

protected void eInvoiceGroupInvoicesUpdate()
{
    KMN_eInvoiceHeaderSessionLines          eInvoiceHeaderLines;
    KMN_eInvoiceHeaderSessionLines          eInvoiceHeaderLines2;
    KMN_eInvoiceHeaderSessionTable          eInvoiceHeadeTableLocal;
    SalesTable                              localSalesTable;
    boolean                                 textWritten = false;
    ;


    try
    {

        while select forupdate eInvoiceHeaderLines where
                               eInvoiceHeaderLines.SessionId == eInvoiceHeaderSessionTable.SessionId    &&
                               eInvoiceHeaderLines.Processed == NoYes::No                               &&
                               eInvoiceHeaderLines.DocType   == kmn_docType                             &&
                               eInvoiceHeaderLines.InvoiceId != ''
        {
             ttsbegin;
             while select eInvoiceHeaderLines2 where
                         eInvoiceHeaderLines2.InvoiceId == eInvoiceHeaderLines.InvoiceId    &&
                         eInvoiceHeaderLines2.Processed == NoYes::No                        &&
                         eInvoiceHeaderLines2.InvoiceId != ''                               &&
                         eInvoiceHeaderLines2.DocType   == eInvoiceHeaderLines.DocType      &&
                         eInvoiceHeaderLines2.SessionId == eInvoiceHeaderLines.SessionId
            {

                eInvoiceHeaderLines.Processed = NoYes::Yes;
                eInvoiceHeaderLines.OpenOder = NoYes::No;
                eInvoiceHeaderLines.update();
            }

            ttscommit;

            this.parmInvoiceId(eInvoiceHeaderLines.InvoiceId);
            this.parmInvoiceDate(eInvoiceHeaderLines.InvoiceDate);
            this.eInvoiceSetTables();
            this.eInvoiceCreateElectronicInvoice();
            textWritten = true;
        }

        if(!textWritten)
            this.eInvoiceDeleteRecordsWithNoInvoice(eInvoiceHeaderSessionTable.SessionId);
    }
    catch
    {
        this.eInvoiceProcessTextWriteError();
    }
}

protected boolean eInvoiceIsSellingPrice(ItemId _itemId)
{
    boolean ret = false;
    ;

    if(InventTableModule::find(_itemId, ModuleInventPurchSales::Sales).Price != 0)
        ret = true;

    return ret;
}

protected str eInvoiceProcessFileValues(KMN_eInvoiceSectionTypeMX sectionType,
                                        TaxAmount _taxAmount = 0)
{

    str             contData = '';
    container       c;
    ;

    switch(invoiceFormat)
    {
        case KMNInvoiceFormat::Mexico:
            switch(sectionType)
            {
                case KMN_eInvoiceSectionTypeMX::Document_DC:
                                    //Document
                    c = this.eInvoiceGetHeaderValues(kmn_docType);
                    break;
                case KMN_eInvoiceSectionTypeMX::Issuer_DF:
                    c = this.eInvoiceGetIssuerValues(KMN_eInvoiceSectionTypeMX::Issuer_DF);
                    break;
                case KMN_eInvoiceSectionTypeMX::Issuer_EE:
                    //Issuer_EE - begin
                    c = this.eInvoiceGetIssuerValues(KMN_eInvoiceSectionTypeMX::Issuer_EE);
                    break;
                case KMN_eInvoiceSectionTypeMX::Issuer_EM:
                    //Issuer_EM - begin
                    c = this.eInvoiceGetIssuerValues(KMN_eInvoiceSectionTypeMX::Issuer_EM);
                    break;
                case KMN_eInvoiceSectionTypeMX::Receipient_DM:
                    //Recipient_DM - begin
                    c = this.eInvoiceGetRecipient(KMN_eInvoiceSectionTypeMX::Receipient_DM);
                    break;
                case KMN_eInvoiceSectionTypeMX::Receipient_RC:
                    //Recipient_RC - begin
                    c = this.eInvoiceGetRecipient(KMN_eInvoiceSectionTypeMX::Receipient_RC);
                    break;
                case KMN_eInvoiceSectionTypeMX::ItemLines_CN:
                    c = this.eInvoiceGetInvoiceLines(KMN_eInvoiceSectionTypeMX::ItemLines_CN);
                    break;
                case KMN_eInvoiceSectionTypeMX::ItemLines_IA:
                    c = this.eInvoiceGetInvoiceLines(KMN_eInvoiceSectionTypeMX::ItemLines_IA);
                    break;
                case KMN_eInvoiceSectionTypeMX::ItemLines_CP:
                    c = this.eInvoiceGetInvoiceLines(KMN_eInvoiceSectionTypeMX::ItemLines_CP);
                    break;
                case KMN_eInvoiceSectionTypeMX::ItemLines_PR:
                    c = this.eInvoiceGetInvoiceLines(KMN_eInvoiceSectionTypeMX::ItemLines_PR);
                    break;
                case KMN_eInvoiceSectionTypeMX::Tax_IT:
                    c = this.eInvoiceGetTaxLines(KMN_eInvoiceSectionTypeMX::Tax_IT, _taxAmount);
                    break;
                case KMN_eInvoiceSectionTypeMX::Tax_TI:
                    c = this.eInvoiceGetTaxLines(KMN_eInvoiceSectionTypeMX::Tax_TI, 0);
                    break;
                case KMN_eInvoiceSectionTypeMX::MicCharges_CN:
                    c = this.eInvoiceGetMiscChargesLines();
                    break;
            }

            contData = this.eInvoiceGetContainerValues(c, sectionType);
            c = conNull();
    }

    return contData;
}

protected str eInvoiceProcessInvoiceStr()
{
    return SubStr(invoiceId, 4, 8);
}

protected void eInvoiceProcessTextWriteError()
{
    KMN_eInvoiceHeaderSessionTable _headerSessionTable;
    KMN_eInvoiceHeaderSessionLines eInvoiceHeaderLines;
    ;

    try
    {
        ttsbegin;
        select forupdate _headerSessionTable where _headerSessionTable.SessionId == kmn_sessionId;
        _headerSessionTable.SessionError = NoYes::Yes;
        _headerSessionTable.Processed = NoYes::No;
        _headerSessionTable.ProcessEInvoice = NoYes::Yes;
        _headerSessionTable.update();

        while select forupdate eInvoiceHeaderLines where
                               eInvoiceHeaderLines.SessionId == _headerSessionTable.SessionId
        {
            eInvoiceHeaderLines.Processed = NoYes::No;
            eInvoiceHeaderLines.OpenOder = NoYes::Yes;
            eInvoiceHeaderLines.update();
        }
        ttscommit;
    }
    catch(Exception::Error)
    {
        retry;
    }
}

protected str eInvoiceResolveQtyAmountSign(Amount _amount)
{
    str ret;
    Amount calculatedAmt;
    ;
    switch(kmn_docType)
    {
        case KMN_eInvoiceDocType::freeTextCreditNote:
        case KMN_eInvoiceDocType::FreeTextInvoice:
        case KMN_eInvoiceDocType::Invoice:
            calculatedAmt = _amount * -1;
            ret = num2str(calculatedAmt, 1,0,0,0);
            break;
        case KMN_eInvoiceDocType::CreditNote:
            ret = num2str(_amount,1,0,0,0);
            break;
    }

    return ret;
}

protected str eInvoiceReturnInvoiceType(KMN_eInvoiceDocType _docType)
{
    str ret = "";
    switch(_docType)
    {
        case KMN_eInvoiceDocType::Invoice:
        case KMN_eInvoiceDocType::FreeTextInvoice:
            ret = "I"; // Type of receipt
            break;
        case KMN_eInvoiceDocType::CreditNote:
        case KMN_eInvoiceDocType::freeTextCreditNote:
            ret = "E"; // Type of receipt
            break;
    }

    return ret;
}

protected void eInvoiceSetCustAccount()
{

    ;
    switch(kmn_docType)
    {
        case KMN_eInvoiceDocType::Invoice:
        case KMN_eInvoiceDocType::CreditNote:
            this.parmCustAccount(CustTable::find(SalesTable::find(
                                KMN_eInvoiceHeaderSessionLines::find(
                                kmn_sessionId).SalesOrderId).CustAccount).AccountNum);
            break;
        case KMN_eInvoiceDocType::FreeTextInvoice:
        case KMN_eInvoiceDocType::freeTextCreditNote:
            this.parmCustAccount(CustTable::find(CustInvoiceTable::FindRecId(
                                KMN_eInvoiceHeaderSessionLines::find(
                                kmn_sessionId).FreeTextRecId).OrderAccount).AccountNum);
            break;
    }

}

public str eInvoiceSetResultSign(Amount _amount, KMN_eInvoiceSectionTypeMX section = KMN_eInvoiceSectionTypeMX::None)
{
    str     ret;
    Amount  calculatedAmount;

    ;

    calculatedAmount = _amount * -1;

    switch(kmn_docType)
    {
        case KMN_eInvoiceDocType::Invoice:
        case KMN_eInvoiceDocType::FreeTextInvoice:
            switch(section)
            {
                case KMN_eInvoiceSectionTypeMX::Tax_IT:
                    ret = num2str(calculatedAmount, 0,2,1,0);
                    break;
                default:
                    ret = num2str(_amount, 0,2,1,0);
                    break;
            }

            break;

        case KMN_eInvoiceDocType::CreditNote:
            switch(section)
            {
                case KMN_eInvoiceSectionTypeMX::Tax_IT:
                case KMN_eInvoiceSectionTypeMX::ItemLines_CN:
                    ret = num2str(_amount, 0,2,1,0);
                    break;
                default:
                    ret = num2str(calculatedAmount, 0,2,1,0);
                    break;
            }
            break;
        case KMN_eInvoiceDocType::freeTextCreditNote:
            switch(section)
            {
                case KMN_eInvoiceSectionTypeMX::Tax_IT:
                    ret = num2str(_amount, 0,2,1,0);
                    break;
                default:
                    ret = num2str(calculatedAmount, 0,2,1,0);
                    break;
            }
        break;
    }

    return ret;
}

protected void eInvoiceSetTables()
{
    ;

    //Cust Invoice Journal
    switch(kmn_docType)
    {
        case KMN_eInvoiceDocType::Invoice:
        case KMN_eInvoiceDocType::CreditNote:
            select firstonly custInvoiceJournal where custInvoiceJournal.InvoiceId == invoiceId         &&
                                              custInvoiceJournal.SalesId != ''                          &&
                                              custInvoiceJournal.RefNum == RefNum::SalesOrder;
            break;
        case KMN_eInvoiceDocType::FreeTextInvoice:
        case KMN_eInvoiceDocType::freeTextCreditNote:
            select firstonly custInvoiceJournal where custInvoiceJournal.InvoiceId == invoiceId         &&
                                              custInvoiceJournal.RefNum == RefNum::Cust;
            break;
    }

    this.parmCustInvoiceJournal(custInvoiceJournal);
    this.parmVoucher(custInvoiceJournal.LedgerVoucher);

    //Tax Trans
    select sum(TaxAmount) from taxTrans where taxTrans.Voucher == custInvoiceJournal.LedgerVoucher;
    this.parmTaxTrans(taxTrans);
    this.parmTaxAmountMST(custInvoiceJournal.SumTaxMST);
}

protected void eInvoiceUpdateHeaderLinesKMN()
{

    KMN_eInvoiceHeaderSessionLines          eInvoiceHeaderLines;
    KMN_eInvoiceHeaderSessionTable          eInvoiceHeadeTableLocal;
    SalesTable                              localSalesTable;

    ;



    try
    {
        ttsbegin;
        select forupdate eInvoiceHeadeTableLocal where
                             eInvoiceHeadeTableLocal.SessionId == eInvoiceHeaderSessionTable.SessionId &&
                                                                  eInvoiceHeaderSessionTable.DocType == kmn_docType;

                             eInvoiceHeadeTableLocal.SessionError = NoYes::No;
                             eInvoiceHeadeTableLocal.Processed = NoYes::Yes;
                             eInvoiceHeadeTableLocal.update();

        if(!hasErrors)
        {
            while select forupdate eInvoiceHeaderLines where
                                   eInvoiceHeaderLines.SessionId == eInvoiceHeaderSessionTable.SessionId    &&
                                   eInvoiceHeaderLines.Processed == NoYes::No                               &&
                                   eInvoiceHeaderLines.DocType   == kmn_docType                             &&
                                   eInvoiceHeaderLines.InvoiceId == ''
            {

                localSalesTable = SalesTable::find(eInvoiceHeaderLines.SalesOrderId);
                if(kmn_docType == KMN_eInvoiceDocType::Invoice || kmn_docType == KMN_eInvoiceDocType::CreditNote)
                    eInvoiceHeaderLines.InvoiceId = localSalesTable.lastInvoice();
                eInvoiceHeaderLines.Processed = NoYes::No;
                eInvoiceHeaderLines.update();

            }
        }
        ttscommit;
    }
    catch
    {
            this.eInvoiceProcessTextWriteError();
            //ToDo Throw Error
    }
}





public Common parmCommon(Common _common = common)
{
    ;
    common = _common;
    return common;
}

public CustAccount parmCustAccount(CustAccount _custAccount = custAccount)
{
    ;
    custAccount = _custAccount;
    return custAccount;
}

public CustInvoiceJour parmCustInvoiceJournal(CustInvoiceJour _custInvoiceJournal = custInvoiceJournal)
{
    ;
    custInvoiceJournal = _custInvoiceJournal;
    return custInvoiceJournal;
}

public CustInvoiceTable parmCustInvoiceTable(CustInvoiceTable _custInvoiceTable = custInvoiceTable)
{
    ;
    custInvoiceTable = _custInvoiceTable;
    return custInvoiceTable;
}

public DataAreaId parmDataAreaName(DataAreaId _companyName = companyAreaId)
{
    ;
    companyAreaId = _companyName;
    return companyAreaId;
}

public Description parmDescription(Description _description = description)
{
    ;
    description = _description;
    return description;
}

public KMN_eInvoiceDocType parmDocType(KMN_eInvoiceDocType _docType = kmn_docType)
{
    kmn_docType = _docType;

    return kmn_docType;
}

public NoYes parmErrors(NoYes _errors = errors)
{
    errors = _errors;
    return errors;
}

public FileName parmFileName(FileName _fileName = fileName)
{
    ;
    fileName = _fileName;
    return fileName;
}

public NoYes parmHasErrors(NoYes _hasErrors = hasErrors)
{
    hasErrors = _hasErrors;
    return hasErrors;
}


public InventBatchId parmInventBatchId(InventBatchId _inventBatchId = inventBatchId)
{
    ;
    inventBatchId = _inventBatchId;
    return inventBatchId;
}

public InventBatchProdDate parmInventBatchProdDate(InventBatchProdDate _inventBatchProdDate = inventBatchProdDate)
{
    ;
    inventBatchProdDate = _inventBatchProdDate;
    return inventBatchProdDate;
}

public InventBatchTxt parmInventBatchTxt(InventBatchTxt _inevntBatchtxt = inevntBatchtxt)
{
    ;
    inevntBatchtxt = _inevntBatchtxt;
    return inevntBatchtxt;
}

public TransDate parmInvoiceDate(TransDate _invoiceDate = invoiceDate)
{
    ;
    invoiceDate = _invoiceDate;
    return invoiceDate;
}

public KMN_eInvoiceDepositoryTXTFile parmInvoiceFilePath(KMN_eInvoiceDepositoryTXTFile _invoiceFilePath = invoiceFilePath)
{
    ;
    invoiceFilePath = _invoiceFilePath;
    return invoiceFilePath;
}

public KMNInvoiceFormat parmInvoiceFormat(KMNInvoiceFormat _invoiceFormat = invoiceFormat)
{
    ;
    invoiceFormat = _invoiceFormat;
    return invoiceFormat;
}

public KMN_eInvoiceHeaderSessionTable parmInvoiceHeaderSessionTable(KMN_eInvoiceHeaderSessionTable _eInvoiceHeaderSessionTable = eInvoiceHeaderSessionTable)
{
    ;
    eInvoiceHeaderSessionTable = _eInvoiceHeaderSessionTable;
    return eInvoiceHeaderSessionTable;
}



public InvoiceId parmInvoiceId(InvoiceId _invoiceId = invoiceId)
{
    ;
    invoiceId = _invoiceId;
    return invoiceId;
}

public KMN_eInvoiceSessionId parmInvoiceSessionId(KMN_eInvoiceSessionId _eInvoiceSessionId = kmn_sessionId)
{
    ;
    kmn_sessionId = _eInvoiceSessionId;
    return kmn_sessionId;
}

public ItemId parmItemId(ItemId _itemId = itemId)
{
    ;
    itemId = _itemId;
    return itemId;
}

public LineNum parmLineNum(LineNum _lineNum = lineNum)
{
    ;
    lineNum = _lineNum;
    return lineNum;
}

public MarkupCode parmMarkupCode(MarkupCode _markupCode = markupCode)
{;
    markupCode = _markupCode;
    return markupCode;
}

public MarkupValue parmMarkupValue(MarkupValue _markupValue = markupValue)
{;
    markupValue = _markupValue;
    return markupValue;
}


public str parmMonth(str _month = KmnMonth)
{
    ;
    KmnMonth = _month;
    return KmnMonth;
}

public SalesId parmSalesId(SalesId _salesId = salesId)
{
    ;
    salesId = _salesId;
    return salesId;
}

public SalesParmTable parmSalesParmTable(SalesParmTable _salesParmTable = salesParmTable)
{
    ;
    salesParmTable = _salesParmTable;
    return salesParmTable;
}

public SalesPrice parmSalesPrice(SalesPrice _salesPrice = salesPrice)
{
    ;
    salesPrice = _salesPrice;
    return salesPrice;
}

public SalesQty parmSalesQty(SalesQty _salesQty = salesQty)
{
    ;
    salesQty = _salesQty;
    return salesQty;
}

public SalesTable parmSalesTable(SalesTable _salesTable = salesTable)
{
    ;
    salesTable = _salesTable;
    return salesTable;
}

public AmountMST parmTaxAmountMST(AmountMST _amountMST = amountMST)
{
    ;
    amountMST = _amountMST;
    return amountMST;
}

public TaxCode parmTaxCode(TaxCode _taxCode = taxCode)
{
    ;
    taxCode = _taxCode;
    return taxCode;
}

public TaxTrans parmTaxTrans(TaxTrans _taxTrans = taxTrans)
{
    ;
    taxTrans = _taxTrans;
    return taxTrans;
}

public TaxTrans parmTaxTransCode(TaxTrans _taxTransCode = taxTransCode)
{
    ;
    taxTransCode = _taxTransCode;
    return taxTransCode;
}

public TransTxt parmTransTxt(TransTxt _transTxt = transTxt)
{;
    transTxt  = _transTxt;
    return transTxt ;
}

public Voucher parmVoucher(Voucher _voucher = voucher)
{
    ;
    voucher = _voucher;
    return voucher;
}


public str parmYear(str _year = KmnYear)
{
    ;
    KmnYear = _year;
    return KmnYear;
}

public void run()
{
    ;

    //Get Invoices
    this.eInvoiceUpdateHeaderLinesKMN();
    this.eInvoiceGroupInvoicesUpdate();
    this.eInvoiceFinalTableCleanup();
}



public static KMN_eInvoiceCreation construct(Common common,
                                             KMNInvoiceFormat _invoiceFormat,
                                             KMN_eInvoiceSessionId _eInvoiceSessionId,
                                             KMN_eInvoiceDocType _docType, NoYes _hasErrors)
{
    SalesParmTable                      localSalesParmTable;
    KMN_eInvoiceCreation                eInvoiceCreation;
    CustInvoiceTable                    localCustInvoiceTable;
    KMN_eInvoiceHeaderSessionTable      localKMN_eInvoiceHeaderSessionTable
    ;

    if(!_invoiceFormat == KMNInvoiceFormat::Mexico)
        throw error('@KUM297');

    eInvoiceCreation = new KMN_eInvoiceCreation();
    eInvoiceCreation.parmInvoiceFormat(_invoiceFormat);
    eInvoiceCreation.parmCommon(common);
    eInvoiceCreation.parmInvoiceSessionId(_eInvoiceSessionId);
    eInvoiceCreation.parmDocType(_docType);
    eInvoiceCreation.parmHasErrors(_hasErrors);

    switch(common.TableId)
    {
        case tablenum(SalesParmTable):
            localSalesParmTable = common;
            eInvoiceCreation.parmSalesParmTable(localSalesParmTable);
            break;
        case tablenum(KMN_eInvoiceHeaderSessionTable):
            localKMN_eInvoiceHeaderSessionTable = common;
            eInvoiceCreation.parmInvoiceHeaderSessionTable(localKMN_eInvoiceHeaderSessionTable);
            eInvoiceCreation.eInvoiceSetCustAccount();
            break;
        case tableNum(CustInvoiceTable):
            localCustInvoiceTable = common;
            eInvoiceCreation.parmCustInvoiceTable(localCustInvoiceTable);
            KMN_eInvoiceCreation::eInvoiceSaveHeaderInvoiceParameters(_eInvoiceSessionId, NoYes::Yes, _docType);

            eInvoiceCreation.parmInvoiceHeaderSessionTable(KMN_eInvoiceHeaderSessionTable::find(_eInvoiceSessionId));

            KMN_eInvoiceCreation::eInvoiceSaveLineInvoiceParameters(_eInvoiceSessionId,
                                                                    '',
                                                                    localCustInvoiceTable.OrderAccount,
                                                                    '',
                                                                    '',
                                                                    '',
                                                                    localCustInvoiceTable.CurrencyCode,
                                                                    localCustInvoiceTable.SalesId,
                                                                    localCustInvoiceTable.InvoiceDate,
                                                                    localCustInvoiceTable.DocumentDate,
                                                                    localCustInvoiceTable.BankCentralBankPurposeCode,
                                                                    _docType,
                                                                    localCustInvoiceTable.InvoiceId,
                                                                    localCustInvoiceTable.RecId);
            eInvoiceCreation.eInvoiceSetCustAccount();

            break;


    }

    return eInvoiceCreation;
}
public static KMN_eInvoiceSessionId eInvoiceGetSessionNumbSeq()
{
    NumberSeq                       numberseq;
    NumberSequenceReference         numberSequenceReference;
    ;

    numberSequenceReference = CompanyInfo::numRefKMN_eInvoiceSessionId();
    numberSeq = numberseq::newGetNumFromCode(numberSequenceReference.NumberSequence);

    return numberSeq.num();

}

public static void eInvoiceSaveHeaderInvoiceParameters(KMN_eInvoiceSessionId kmn_SessionId,
                                                       NoYes _ProcessEInvoice,
                                                       KMN_eInvoiceDocType _docType)
{
    KMN_eInvoiceHeaderSessionTable      localeInvoiceHeaderSessionTable;
    NumberSequenceReference             numberSequenceReference;
    NumberSeq                           numberSeq;
    int                                 retryCount = 0;
    str test;
    ;

    try
    {

        localeInvoiceHeaderSessionTable.SessionId = kmn_SessionId;
        localeInvoiceHeaderSessionTable.PostingDate = systemdateget();
        localeInvoiceHeaderSessionTable.SessionError = NoYes::No;
        localeInvoiceHeaderSessionTable.ProcessEInvoice = _ProcessEInvoice;
        localeInvoiceHeaderSessionTable.DocType = _docType;
        switch(_docType)
        {
            case KMN_eInvoiceDocType::Invoice:
                localeInvoiceHeaderSessionTable.Invoice = NoYes::Yes;
                break;
            case KMN_eInvoiceDocType::FreeTextInvoice:
                localeInvoiceHeaderSessionTable.FreeTextInvoice = NoYes::Yes;
                break;
            case KMN_eInvoiceDocType::CreditNote:
                localeInvoiceHeaderSessionTable.CreditMemo = NoYes::Yes;
                break;
        }
        //localeInvoiceHeaderSessionTable.FreeTextInvoice = _freeTextInvoice;
        localeInvoiceHeaderSessionTable.insert();
    }
    catch(Exception::Error)
    {
        if(retryCount < 3)
        {
            retryCount ++;
            retry;
        }
        else
            throw error(strfmt('%1', Exception::Error));
    }

}

public static void eInvoiceSaveLineInvoiceParameters(KMN_eInvoiceSessionId kmn_SessionId,
                                                     ParmId _parmId,
                                                     CustAccount _custAccount,
                                                     InventSiteId _inventSiteId,
                                                     ExportInvoiceId_IN _customsInvoiceId_IN,
                                                     TradeLineRefId _tableRefId,
                                                     CurrencyCode _currencyCode,
                                                     SalesId _salesOrderId,
                                                     TransDate _invoiceDate,
                                                     TransDate _documentDate,
                                                     BankAccountID _bankAccount,
                                                     KMN_eInvoiceDocType _docType,
                                                     InvoiceId _invoiceId = '',
                                                     CustInvoiceTableRefRecId CustTableInvoiceRecId = 0)


{
    KMN_eInvoiceHeaderSessionLines      LocaleInvoiceHeaderSessionLines;
    NumberSequenceReference             numberSequenceReference;
    NumberSeq                           numberSeq;
    int                                 retryCount = 0;

    ;

    try
    {

        LocaleInvoiceHeaderSessionLines.SessionId            = kmn_SessionId;
        LocaleInvoiceHeaderSessionLines.SalesOrderId         = _salesOrderId;
        LocaleInvoiceHeaderSessionLines.DocumentDate         = _documentDate;
        LocaleInvoiceHeaderSessionLines.InventSiteId         = _inventSiteId;
        LocaleInvoiceHeaderSessionLines.CustAccount          = _custAccount;
        LocaleInvoiceHeaderSessionLines.CurrencyCode         = _currencyCode;
        LocaleInvoiceHeaderSessionLines.ParmId               = _parmId;
        LocaleInvoiceHeaderSessionLines.InvoiceDate          = _invoiceDate;
        LocaleInvoiceHeaderSessionLines.TableRefId           = _tableRefId;
        LocaleInvoiceHeaderSessionLines.ExportInvoiceId_IN   = _customsInvoiceId_IN;
        LocaleInvoiceHeaderSessionLines.BankAccount          = _bankAccount;
        LocaleInvoiceHeaderSessionLines.DocType              = _docType;
        LocaleInvoiceHeaderSessionLines.InvoiceId            = _invoiceId;
        LocaleInvoiceHeaderSessionLines.FreeTextRecId        = CustTableInvoiceRecId;
        LocaleInvoiceHeaderSessionLines.insert();
    }
    catch(Exception::Error)
    {
        if(retryCount < 3)
        {
            retryCount ++;
            retry;
        }
        else
            throw error(strfmt('%1', Exception::Error));
    }

}

public static void main(Common common,
                        KMNInvoiceFormat _invoiceFormat,
                        KMN_eInvoiceSessionId _eInvoiceSessionId,
                        KMN_eInvoiceDocType _docType, NoYes _hasErrors)
{
    KMN_eInvoiceCreation eInvoiceCreation;
    str test;
    ;

    eInvoiceCreation = KMN_eInvoiceCreation::construct(common, _invoiceFormat, _eInvoiceSessionId, _docType, _hasErrors);

    if(eInvoiceCreation)
        eInvoiceCreation.run();

    if(!eInvoiceCreation.parmErrors())
        KMN_LocalizationSetInfoErrors::routeMessage(KMN_ErrorType::ProcessSuccess, KMN_InfoErrorOutputType::Info);
}

No comments:

Post a Comment

Thank you for your thoughts. Your comment will appear in my blog shortly after review.

Have a great day!