Wednesday, 26 July 2017

Text File import/ Export

class PrisonFileImport extends RunBaseBatch
{
    DialogField dialogImport;
    Dialog      dialog;
    CustTable   custTable;
    container   contain;
    AsciiIo     importFile;
    str         fileNameOnly;
    FilenameOpen fileNameOpen;

    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        filenameOpen
    #endmacro
}
public boolean canGoBatch()
{
    boolean ret;

    ret = super();

    return ret;
}
                protected Object dialog()
{
    ;
    Dialog = super();
    //Set a title for dialog
    dialog.caption("@CIT263");
    dialogImport = dialog.addField(extendedTypeStr(FilenameOpen),"@CIT238","@CIT239");
    return dialog;
}
                public boolean getFromDialog()
{
    // Retrieve values from Dialog
    fileNameOpen = dialogImport.value();

    return super();
}
public container pack()
{
    return [#CurrentVersion,#CurrentList];
}
public void processData()
{
    TextIo txIoRead;
    FileIOPermission fioPermission;
    container containFromRead;
    int    record,iConLength;
    str    sOneRecord;

    int    customersUpdated = 0;
    int    customersNotFound = 0;
    //str    Y,N;
    str      prisonFlag;
    CustAccount custAccount;
    #File
    ;
    // Assert permission.
    fioPermission = new FileIOPermission(fileNameOpen ,#IO_READ);
    fioPermission.assert();

    // Open the same file for reading.
    txIoRead = new TextIo(fileNameOpen ,#IO_READ);
    // Read the entire file into a container.
    containFromRead = txIoRead.read();

    // Loop through the container of file records.
    while (containFromRead)
    {
        sOneRecord = "";
        iConLength = conLen(containFromRead);
        // Loop through the token in the current record.
        for (record=1; record <= iConLength; record++)
        {
            if (record > 1)
            {
                sOneRecord += " ";
            }
            sOneRecord += conPeek(containFromRead ,record);
        }

        custAccount = subStr(sOneRecord,1,10);
        prisonFlag = subStr(sOneRecord,12,1);

        custTable = CustTable::find(custAccount,true);

        ttsBegin;
        if(custTable)
        {
            if (prisonFlag=="Y")
            {
                custTable.PrisonFlag = NoYes::Yes;
            }
            else if (prisonFlag=="N")
            {
                custTable.PrisonFlag = NoYes::No;
            }
            custTable.update();
            customersUpdated++;
        }
        else
        {
            customersNotFound++;
        }
        ttsCommit;
        // Read the next record from the container.
        containFromRead = txIoRead.read();
    }
        info("@CIT261" + int2str(customersupdated));
        info("@CIT262" + int2str(customersNotFound));
    // Close the test file.
    txIoRead = null;
    // revertAssert is not really necessary here,
    // because the job (or method) is ending.
    CodeAccessPermission::revertAssert();
}
public void run()
{
    //super();
    this.processData();
}
                public boolean unpack(container packedClass)
{
    Version version = RunBase::getVersion(packedClass);
;
    switch (version)
    {
        case #CurrentVersion:
            [version,#CurrentList] = packedClass;
            break;
        default:
            return false;
    }

    return true;
}
public static void main(Args _args)
{
    prisonFileImport   prisonFileImport = new prisonFileImport();

    if (prisonFileImport.prompt())
    {
        prisonFileImport.run();
    }
}

Wednesday, 19 July 2017

Email

static void EmailTemplateReport(Args _args)
{
     Map map = new Map(Types::String, Types::String);
    str email;

    SysEmailMessageTable message;
    str messageBody;

    SalesTable st = SalesTable::find("SO-00002778");
    map.insert('Order.SalesId',st.SalesId);
    map.insert('Order.ReturnReasonCodeId',st.ReturnReasonCodeId);
    map.insert('Brand.BrandName',OCSBrandTable::find(st.OSSBrandId).BrandName);
    map.insert('Order.CustAccount',st.CustAccount);

    message = SysEmailMessageTable::find("RefundChk", "en-us");

    if (message.LayoutType == SysEmailLayoutType::StaticLayout)
                messageBody = message.Mail;
            else
                messageBody = SysEmailBatch::doTransform("", message.xsltMail);


    messageBody = SysLabel::resolveLabels(messageBody, 'en-us');

    messageBody = SysEmailMessage::stringExpand(messageBody, SysEmailTable::htmlEncodeParameters(map));

    messageBody =  Web::stripHTML(messageBody);
}
=================================================================
static void email(Args _args)
    {
        SysMailer   mailer = new SysMailer();
        SysEmailParameters parameters = SysEmailParameters::find();
        str   filePathName;
        SalesTable  _lastSalesOrder = SalesTable::find("SO-00005921");
        OWIStoreTable OWIStoreTable;
        notes bodymsg, bodymsg1;
        str strsplit;
        ListIterator    iterator;
        List strlist=new List(Types::String);
        ;

        if (parameters.SMTPRelayServerName)
        {
            mailer.SMTPRelayServer(parameters.SMTPRelayServerName,
                               parameters.SMTPPortNumber,
                               parameters.SMTPUserName,
                               SysEmailParameters::password(),
                               parameters.NTLM);
        }
        else
        {
            mailer.SMTPRelayServer(parameters.SMTPServerIPAddress,
                               parameters.SMTPPortNumber,
                               parameters.SMTPUserName,
                               SysEmailParameters::password(),
                               parameters.NTLM);
        }

        select OWIStoreTable
            where OWIStoreTable.BrandId == _lastSalesOrder.OSSBrandId;
        //filePathName = "C:\\Users\\back\\Desktop"+ "ach.txt";
        mailer.fromAddress('NoReply.JohnsonSmith@JSLS1.com');
        mailer.tos().appendAddress('back@columbusglobal.com;tama@columbusglobal.com');
       // mailer.tos().appendAddress(OWIStoreTable.SystemTestEmail);
        //mailer.htmlBody('AZZZ');
        mailer.subject('Email test AX_webstore');



        strlist =strSplit(OWIStoreTable.EmailNotesWebstore,"\n");



        iterator = new ListIterator(strlist);

         while(iterator.more())
        {
            /*if(!strsplit)
                strsplit = iterator.value();
            else
            {
                strsplit = strsplit + '\n' + iterator.value();
            }*/

            //mailer.htmlBody(strFmt("<br>%1<br>",iterator.value()));

            bodymsg +=  strFmt("%1<br>",iterator.value());
            iterator.next();
        }

        //mailer.htmlBody(strsplit);




        bodymsg = strReplace(bodymsg,'\n','<br>');




       // bodymsg = bodymsg + '\n' + strFmt(" %1", OWIStoreTable.EmailNotesWebstore) + "\n";
        bodymsg =bodymsg + "\n" + strFmt("last order received for this webtore : %1", _lastSalesOrder.createdDateTime);


        bodymsg1= strFmtLB(bodymsg);
        /*
        mailer.htmlBody(strFmt(" %1", OWIStoreTable.EmailNotesWebstore));
        mailer.htmlBody(strFmt(" %1", OWIStoreTable.SystemTestEmail));
        mailer.htmlBody(strFmt("last order received for this webtore : %1", _lastSalesOrder.createdDateTime));*/

        mailer.htmlBody(bodymsg1);

        mailer.sendMail();


    }
=====================================================================

static void EmailTemplateSendEmail(Args _args)
{
    Map map = new Map(Types::String, Types::String);
    str email;
    SalesTable st = SalesTable::find("SO-00002778");
    map.insert('Order.SalesId',st.SalesId);
    map.insert('Order.ReturnReasonCodeId',st.ReturnReasonCodeId);
    map.insert('Brand.BrandName',OCSBrandTable::find(st.OSSBrandId).BrandName);
    map.insert('Order.CustAccount',st.CustAccount);
    email =  Web::stripHTML(SysEmailMessageTable::find(
                                                OCSBrandTemplates::findBrandTemplate(st.OSSBrandId,st.OSSOrderProfileId, fieldNum(OCSBrandTemplates, RefundTemplate)).RefundTemplate, 'en-us').Mail);


    SysEmailTable::sendMail("RefundChk","en-us",'back@columbusglobal.com',map,'','',true);


    //info(strFmt("%1",map));

}

==================================================================
static void emailThruSysMailer(Args _args)
    {
        SysMailer   mailer = new SysMailer();
        SysEmailParameters parameters = SysEmailParameters::find();
        ;

        if (parameters.SMTPRelayServerName)
        {
            mailer.SMTPRelayServer(parameters.SMTPRelayServerName,
                               parameters.SMTPPortNumber,
                               parameters.SMTPUserName,
                               SysEmailParameters::password(),
                               parameters.NTLM);
        }
        else
        {
            mailer.SMTPRelayServer(parameters.SMTPServerIPAddress,
                               parameters.SMTPPortNumber,
                               parameters.SMTPUserName,
                               SysEmailParameters::password(),
                               parameters.NTLM);
        }

        mailer.fromAddress(SysUserInfo::find().Email);
        mailer.tos().appendAddress('PKB@Columbusglobal.com');
        mailer.htmlBody('AZZZ');
        mailer.subject('Comunicazione AX');

        mailer.sendMail();
    }

Combine PDF's

 List           pdfList      = new List(Types::String);
    CombinePDF     CombinePDF   = new CombinePDF();
pdfList = this.getFilesFromDirectory(OGOParameters::find().PackingSlipPDFFile, _contract.parmPrintPriority());

        if(pdfList.elements() > 0)
        {
            // merge all pdfs to a single pdf
            this.mergePDFs(pdfList,OGOParameters::find().PackingSlipPDFFile +'\\' + enum2str(_contract.parmPrintPriority()) + '-' + date2str(systemDateGet(), 321,DateDay::Digits2,
                            DateSeparator::Hyphen,
                            DateMonth::Digits2,
                            DateSeparator::Hyphen,
                            DateYear::Digits4,DateFlags::None
                            )+ time2str(timeNow(),TimeSeparator::Space, TimeFormat::Hour24)+'_Combine.pdf');

            //delete all files from folder
            this.deleteFiles(pdfList);

=====================================================================

void mergePDFs(List _pdfList, FileName _file)
{

    PdfSharp.Pdf.PdfDocument  outPutPDFDocument = new PdfSharp.Pdf.PdfDocument();
    PdfSharp.Pdf.PdfDocument  inputPDFDocument  = new PdfSharp.Pdf.PdfDocument();
    PdfSharp.Pdf.PdfPages     pdfPages;
    int                       i, j, pageCount;
    FileName                  pdfFile;
    InteropPermission         permission;
    str                       errorMessage;
    //ListIterator              literator;
    Enumerator                en;
    //List    mergeListPdf    = new List(Types::String);
    ;

    try
    {
        permission = new InteropPermission(InteropKind::ClrInterop);

        permission.assert();
        en = _pdfList.getEnumerator();
        //literator = new ListIterator(_pdfList);

        while(en.moveNext())
        {
            pdfFile = en.current();
            if (!pdfFile)
            {
                continue;
            }

            inputPDFDocument = PdfSharp.Pdf.IO.PdfReader::Open(pdfFile, PdfSharp.Pdf.IO.PdfDocumentOpenMode::Import);

            outputPDFDocument.set_Version(inputPDFDocument.get_Version());

            pageCount = inputPDFDocument.get_PageCount();
            pdfPages  = inputPDFDocument.get_Pages();

            if (pageCount > 0)
            {
                for (j = 0; j < pageCount; j++)
                {
                    outputPDFDocument.AddPage(pdfPages.get_Item(j));
                }
            }
        }

        outputPDFDocument.Save(_file);
        CodeAccessPermission::revertAssert();
    }
    catch(Exception::CLRError)
    {
        // Get the CLR error before any other CLR operation
        errorMessage = AifUtil::getClrErrorMessage();

        CodeAccessPermission::revertAssert();

        throw error(errorMessage);
    }
}



working with Directories

static void clearDirectory(Args _args)

{

    System.String[] files;
    int             filecount;
    int             i;
    if (WinAPI::folderExists(OGOParameters::find().TIFFFileDirectory))
    {
        files = System.IO.Directory::GetFiles(OGOParameters::find().TIFFFileDirectory);
        filecount = files.get_Length();
        for(i=0; i < filecount; i++)
        {
            System.IO.File::Delete(files.get_Item(i));
        }
    }

}

Importing Sales Order & Sales Lines from CSV file

static void MultiSalesOrdersLineImport(Args _args)
{
SalesTable      salesTable;
SalesLine       salesLine;
InventDim       inventDim;
container readcon,readcon1;
NumberSeq        num;
CommaIo commaIo,commaIo1;
commaIo = new CommaIo('C:\\Users\\ax.user01\\Desktop\\SalesOrder&amp;Line.csv','r');
commaIo1 = new CommaIo('C:\\Users\\ax.user01\\Desktop\\SalesOrderNo.csv','r');
commaIo.infieldDelimiter(',');
try
{
ttsbegin;
// Order header
salesTable.clear();
readcon1  = commaIo1.read();
salesTable.CustAccount = conpeek(readcon1,1);
num = NumberSeq::newGetNum(SalesParameters::numRefSalesId());
salesTable.SalesId = num.num();
salesTable.initValue(SalesType::Sales);
salesTable.initFromCustTable();
 
if (salesTable.validateWrite())
{
salesTable.insert();
 
while(commaIo.status() == IO_Status::OK)
{
//Order line
readcon = commaIo.read();
salesLine.ItemId = conpeek(readcon,1);
 
if(salesLine.ItemId == "0")
break;
 
inventDim.clear();
inventDim.InventSiteId = conpeek(readcon,4);
inventDim.InventLocationId = conpeek(readcon,5);
 
salesLine.clear();
salesLine.initValue(salesTable.SalesType);
salesLine.initFromSalesTable(salesTable);
salesLine.ItemId = conpeek(readcon,1);
salesLine.initFromInventTable(InventTable::find(conpeek(readcon,1)));
 
salesLine.InventDimId = InventDim::findOrCreate(inventDim).inventDimId;
salesLine.SalesQty = conpeek(readcon,2);
salesLine.RemainSalesPhysical = salesLine.SalesQty;
salesLine.SalesUnit = conpeek(readcon,3);
salesLine.QtyOrdered = salesLine.calcQtyOrdered();
salesLine.RemainInventPhysical = salesLine.QtyOrdered;
 
salesLine.setPriceDisc(InventDim::find(salesLine.InventDimId));
 
if (salesLine.validateWrite())
{
salesLine.insert();
}
else
throw error("Order line");
}
}
else
throw error("Order header");
ttscommit;
}
catch
{
error("Error!");
return;
}
info("Done!");
}