Sunday, 3 November 2013

Create a batch to Save report as PDF and sending mail with Email template Created in ax

Organization Administration >> Setup >> Email template.
Class Declaration :
class EmailInvoice  extends RunBase
{
    SysEmailId                      emailTemplate;
    DialogRunbase                   dialog;
    DialogField                     dlgTemplate;
    str                             multipleRecords;
    Filename                        filename;
    SRSPrintDestinationSettings     printDestinationSetting;
    Common                          custInvoiceJourRecordset;
    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        emailTemplate
    #endmacro
}
==================================================
 public boolean canGoBatch()
{
    return true;
}
================================================================
protected void createFileName()
{
    int attemptCount = 1;
    boolean fileIsValid = false;
    str attachmentPath = SysEmailParameters::find().AttachmentsPath;
    if (!attachmentPath)
    {
        throw error("@SYS135893");
    }
    if (substr(attachmentPath, strlen(attachmentPath), 1) != '\\')
    {
        attachmentPath = attachmentPath + '\\';
    }
    // Generate the file using the current UTC date time (without the ':' character)
    // since it is not allowed for file names.
    fileName = strfmt('%1%2%3',
        attachmentPath,
        Global::strReplace(DateTimeUtil::toStr(DateTimeUtil::utcNow()), ':', ''),
        '.PDF');
    //filename = "C:\\Temp\\Test.pdf";
    if (WinAPI::fileExists(fileName))
    {
        // Since it already exists, make it unique
        fileName = fileNameNext(fileName);
    }
}
=======================================================================
public Object dialog()
{
    dialog  = super();
    dlgTemplate = dialog.addField(extendedTypeStr(SysEmailId),"@SYS125266");
    dlgTemplate.value(emailTemplate);
    return dialog;
}
================================================================
public boolean getFromDialog()
{
    boolean ret;
    ret = super();
    emailTemplate = dlgTemplate.value();
    return ret;
}
===========================================================================
private void getRecords(Args _args)
{
    multipleRecords = _args.parm();
}
=======================================
public void initDatasource(Common _common)
{
    custInvoiceJourRecordset = _common;
}
======================================================
public void new()
{
    super();
}
==========================================================
public container pack()
{
    return [#CurrentVersion,#CurrentList];
}
===================================================================
private void printerSetup()
{
    ;
    printDestinationSetting = new SRSPrintDestinationSettings();
    printDestinationSetting.printMediumType(SRSPrintMediumType::File);
    printDestinationSetting.fileFormat(SRSReportFileFormat::PDF);
    printDestinationSetting.fileName(filename);
    printDestinationSetting.overwriteFile(true);
}
======================================================================
Public void run()
{
    CustTable                       custTable;
    SalesTable                      salesTable;
    DirPartyTable                   dirPartyTable;
    DirPartyLocation                partyLocation;
    LogisticsLocation               logisticsLocation;
    LogisticsElectronicAddress      electronicAddress;
    CustInvoiceJour                 custinvoicejourloc;

    CustInvoiceJour                 custInvoiceJour;
    FormDataSource                  fds = custInvoiceJourRecordset.dataSource();
    Email                           email;
    for (custInvoiceJour = fds.getFirst(true)?fds.getFirst(true):custinvoicejourRecordset; custInvoiceJour; custInvoiceJour=fds.getNext())
    {
        custInvoiceJourLoc.data(custInvoiceJour);
        salesTable = SalesTable::find(custinvoicejourloc.SalesId);
        email = salesTable.Email;
        if(!email)
        {
            select firstOnly AccountNum, party from custTable
                where custTable.AccountNum == custinvoicejourloc.InvoiceAccount
                    join RecId from dirPartyTable
                        where custTable.Party == dirPartyTable.RecId
                           join Party, Location, IsPrimary from partyLocation
                                order by IsPrimary desc
                                where partyLocation.Party == dirPartyTable.RecId
                                join RecId from logisticsLocation
                                    where logisticsLocation.RecId == partyLocation.Location
                                        join  electronicAddress
                                            where electronicAddress.Location == logisticsLocation.RecId
                                               && electronicAddress.Type     == LogisticsElectronicAddressMethodType::Email;
            email = electronicAddress.Locator;
        }
        if (email)
        {
            this.createFileName();
            this.printerSetup();
            this.savereport(custinvoicejourloc);
            this.sendEmailTemplate(email, custinvoicejourloc.InvoiceId);
        }
        else
        {
            error(strFmt("Invoice '%1' on sales order '%2' invoice account '%3' has no email address", custinvoicejourloc.InvoiceId,custinvoicejourloc.SalesId,custinvoicejourloc.InvoiceAccount));
        }
    }

/*
    for (loop thru datasource records)
    {
        (get email address (from SO, Customer, etc))

        if(email address valid)
        {
            // build filename
            this.createFileName()
            // code to print email to PDF at filename
            this.printerSetup();   // set printer to PDF
            this.savereport();  //"reprint an Invoice" code
            this.sendEmailTemplate(emailAddress, custInvoiceJour.InvoiceId);
        }
        else
            an error will be given "Invoice '%1' on sales order '%2' invoice account '%3' has no email address"
    }*/
}
======================================================================
public void saveReport(CustInvoiceJour     _custInvoiceJour)
{
    MenuFunction                    menufunction;
    Args                            parameter = new Args();

    // we need to get the printer info (printDestinationSetting) into the menufunction below (so the report knows where to print).
    SalesInvoiceController  salesInvoiceController;
    SalesInvoiceContract    salesInvoiceContract;
    Args                    args = new Args();
    SrsReportRunImpl        srsReportRun;
    CustInvoiceJour         custInvoiceJour;
    ReportName              reportName = "SalesInvoice.Report";
    ;  
   
    args.record(_custInvoiceJour);
    salesInvoiceController = new SalesInvoiceController();
    salesInvoiceController.parmReportName(reportName);
    salesInvoiceContract = salesInvoiceController.parmReportContract().parmRdpContract();
    salesInvoiceContract.parmRecordId(_custInvoiceJour.RecId);
    salesInvoiceContract.parmCountryRegionISOCode(SysCountryRegionCode::countryInfo());
    salesInvoiceController.parmArgs(args);
    srsReportRun = salesInvoiceController.parmReportRun() as SrsReportRunImpl;
    salesInvoiceController.parmReportRun(srsReportRun);
    salesInvoiceController.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::File);
    salesInvoiceController.parmReportContract().parmPrintSettings().overwriteFile(true);
    salesInvoiceController.parmReportContract().parmPrintSettings().fileFormat(SRSReportFileFormat::PDF);
    salesInvoiceController.parmReportContract().parmPrintSettings().fileName(filename);
    salesInvoiceController.runReport();
}
============================================================================
Private void sendEmailTemplate(str _emailTo, str _invoiceId)
{
    #define.Invoice('Invoice')
    Map                 mappings = new Map(Types::String, Types::String);
    mappings.insert(#Invoice, _invoiceId);
    SysEmailTable::sendMail(emailTemplate,
                            '',
                            _emailTo,
                            mappings,
                            filename,
                            '',
                            true,
                            curUserId(),
                            true);
}
======================================================================
public boolean unpack(container packedClass)
{
    Version version = RunBase::getVersion(packedClass);
    ;
    switch (version)
    {
        case #CurrentVersion:
            [version, #CurrentList] = packedClass;
            break;
        default :
            return false;
    }
    return true;
}
===========================================================
server static EmailInvoice construct()
{
    return new EmailInvoice();
}
================================================================
server static void main(Args _args)
{
    EmailInvoice   emailInvoice = EmailInvoice::construct();

    if(!_args || !_args.dataset() == tableNum(CustInvoiceJour))
    {
        throw error(error::wrongUseOfFunction(funcName()));
    }
    emailInvoice.initDatasource(_args.record());
    if (emailInvoice.prompt())
        emailInvoice.run();
}
================================================================

No comments:

Post a Comment