Showing posts with label CODE. Show all posts
Showing posts with label CODE. Show all posts

Wednesday, November 22, 2017

THROW,ERROR,TRY,CATCH,:VIKAS,MEHTA,:,DYNAMICS,AX,X++,CODE

THROW ERROR TRY CATCH :VIKAS MEHTA : DYNAMICS AX X++ CODE

If you want the details of the error then in the throw error section of the code replace it by the following code.
This will give you the details of the error in the infolog.

System.Exception ex;
   try
   {
       FormletterService.Run()      
   }
   catch(Exception::CLRError)
   {
       ex = ClrInterop::getLastException();
        if (ex != null)
        {
           ex = ex.get_InnerException();
           if (ex != null)
           {
               throw error(ex.ToString());
           }
         }

}  

Tuesday, November 21, 2017

p EXPORT TO CSV WITH DATE DIRECT JOB X++ : VIKAS MEHTA :MICROSOFT DYNAMICS AX X++ CODE

EXPORT TO CSV DIRECT JOB X++ WITH DATE : VIKAS MEHTA


public static void export2csvInvJourTrans(InventJournalId _invJournalId)
{
    container           con, conHeader;
    InventJournalTrans  invJourTrans;
    InventJournalTable  invJourTable;
    InventDim           invDim;
    CommaIo              io;

    Dialog              dialog;
    DialogField         dlgFileName;
    Filename            csvfileName;
    FileIOPermission    permission;

    int                 recordCount = 0;

    SysOperationProgress exportprogress = new SysOperationProgress();

    #File
    #AviFiles


    ;


    try
    {
        exportprogress.setCaption("Exporting journal lines to CSV file....");
        exportprogress.setAnimation(#AviTransfer);

        // Header Column

        conHeader = ["JournalId","Date","ItemId","Description","LineNum","Site","Warehouse","Location","SerialNumber","OnHand","Counted","Quantity"];

        dialog = new Dialog("Export to CSV");
        dialog.filenameLookupFilter(["Excel Files","*.csv"]);
        dlgFileName = dialog.addField(extendedTypeStr(FilenameSave),"File Name");

        if(dialog.run())
        {
            csvfileName = dlgFileName.value();
            if(csvfileName)
            {
                permission = new FileIOPermission(csvfileName,#io_write);
                permission.assert();

                io = new CommaIo(csvfileName,#io_write);

                io.inFieldDelimiter(',');


                if(!io || io.status() != IO_Status::Ok)
                {
                    throw error("Error in opening file!");
                }

                // Write the header column
                io.writeExp(conHeader);

                invJourTable = InventJournalTable::find(_invJournalId);

                if(!invJourTable.Posted)
                {
                    recordcount = 1;
                    while select * from invJourTrans where invJourTrans.JournalId == _invJournalId
                    {
                         // Create rows
                        invDim   = InventDim::find(invJourTrans.InventDimId);

                        con= [ _invJournalId,
                               date2str(invJourTrans.TransDate,123,-1,-1,-1,-1,-1),
                               invJourTrans.ItemId,
                               invJourTrans.itemName(),
                               invJourTrans.LineNum,
                               invDim.InventSiteId,
                               invDim.InventLocationId,
                               invDim.wMSLocationId,
                               invDim.inventSerialId,
                               num2str(invJourTrans.InventOnHand,1,2,1,0),
                               num2str(invJourTrans.Counted,1,2,1,0),
                               num2str(invJourTrans.Qty,1,2,1,0)
                            ];

                        io.writeExp(con);

                        recordCount++;
                    }
                }


                CodeAccessPermission::revertAssert();


            }
            else
            {
                info("Invalid file name specified!");
            }
        }


    }
    catch(Exception::Error)
    {
        throw error("Erorr in exporting journal lines.");
    }

}


MULTISELECT VALUES FROM GRID AND EXECUTE ONE BY ONE :VIKAS MEHTA : MICROSOFT DYNAMICS AX x++ CODE MULTISELECT IN FORMS

MULTISELECT VALUES FROM GRID AND EXECUTE ONE BY ONE  :VIKAS MEHTA : MICROSOFT DYNAMICS AX x++ CODE MULTISELECT IN FORMS

Multiple select location warehouse ax x++ code helper class multiselect
Just write the below code on the clicked method event and the code will consider all the selected records in the grid and execute as per the requirement.
void clicked()
{
    InventLocation InventLocationLoc;
    MultiSelectionHelper helper = MultiSelectionHelper::construct();

    super();

    helper.parmDatasource(InventLocation_DS);

    InventLocationLoc = helper.getFirst();
    while (InventLocationLoc.RecId != 0)
    {
        select firstOnly selectWH where selectWH.InventLocationId == InventLocationLoc.InventLocationId
        ;
        if(!selectWH)
        {
            // your execution here
        }
        else
            info(strFmt("@VIK178",selectWH.InventLocationId));//warehouse already exist
        InventLocationLoc = helper.getNext();
    }

    info("warehouse assigned”);
}

THE FIELD WITH ID '0' DOES NOT EXIST IN TABLE - SOLUTION :DYNAMICS AX X++ CODE

THE FIELD WITH ID '0' DOES NOT EXIST IN TABLE - SOLUTION :DYNAMICS AX X++ CODE 
ISSUE :
THE FIELD WITH ID '0' DOES NOT EXIST IN TABLE - SOLUTION.


SOLUTION:
YOU WILL GET THIS ERROR WHEN ONE OF THE FIELDS IS NOT MAPPED PROPERLY MOSTLY IN THE MAPS BEING USED.

CREATE DYNAMIC QUERY IN AX X++ CODE ON THE FLY FILTER: DYNAMICS AX X++ CODE


CREATE DYNAMIC QUERY IN AX X++ CODE WITH FILTER

public void qUERYdYNAMICS()
{
    Query q;
    QueryRun qr;
    QueryBuildDataSource qbd;
    QueryBuildRange qbr;

    q = new Query();
    qbd = q.addDataSource(TableNum(CustTable));

    qbr = qbd.addRange(FieldNum(CustTable, AccountNum));
    qbr.value(">=4000"); // Default operator is ==.

    qbr = qbd.addRange(FieldNum(CustTable, AccountNum));
    qbr.value("<=4022");

    qbd.addSortField(FieldNum(CustTable, DlvMode));

    qr = new QueryRun(q);
    qr.prompt();

    pause;
}

JOB X++ MICROSOFT AX PULL /SAVE DATA IN CSV FILES :WINAPI FILES : DYNAMICS AX X++ CODE

JOB X++ MICROSOFT AX DATA IN CSV FILES WINAPI

static void VIK_VM_SalesLineToCSVTable(Args _args)
{
    PurchLine       purchLine;
    SalesLine       salesline;
    Query q;
    QueryBuildDataSource qbds;
    QueryBuildRange qbr;
    QueryRun qr;
    CommaIO commaIO;
    FileName fileName;
    InventTable inventTable;
    salestable  salestable;
    ;
    fileName = "C:\\Vicky\\" + "SAlesline_serial_newD" + ".txt"; //Destination of the file
    commaIO = new CommaIO(fileName,'W');

    commaIO.write("Sales Id", "Custaccount","Itemid","SalesStatus", "Serial Number"); //Header of the CSV File

    //Loop to insert values in the csv from the table
    while select salesline
            join salestable where SalesLine.salesid == SalesTable.salesid && salestable.salesstatus == SalesStatus::Backorder
                         //  && salesline.SalesId like "%SOD%"//(salestable.salesstatus == SalesStatus::Delivered || salestable.salesstatus == SalesStatus::Backorder)//&& salestable.SalesId like "%SOD%"
    {
    commaIO.write(salesline.SalesId, salestable.CustAccount, SalesLine.ItemId,SalesTable.SalesStatus,SalesLine.inventDim().inventSerialId);


    }
    WINAPI::shellExecute(fileName);
    info("DONE.");
}


Thursday, May 4, 2017

DATE FUNCTIONS IN AX 2012 AND AX 2009 : MICROSOFT DYNAMICS AX 2012 :X++ CODE DAY MONTH YEAR TIME ETC

static void date_Functions(Args _args)

{
    Transdate    d;
    ;
  
    d = today();
  
    info(strfmt("Date - %1",d));
  
    //Gets the month for the given date...
    info(strfmt("Month - %1",mthofYr(d)));
  
    //Gets the month name from the given date...
    info(strfmt("Month Name - %1",mthname(mthofYr(d))));
  
    //Gets the day for the given date...
    info(strfmt("Day - %1",dayOfMth(d)));
  
    //Gets the day name from the given date...
    info(strfmt("Day Name - %1",dayname(dayOfMth(d))));
  
    //Gets the year for the given date...
    info(strfmt("Year - %1",year(d)));
  
    //Gets the current weekday number from the date...
    info(strfmt("Weekday number - %1",dayOfwk(d)));
  
    //Gets the day of the year from the given date...
    info(strfmt("Day of year - %1",dayOfyr(d)));
  
    //Gets the week of the year from the given date...
    info(strfmt("Week of the year - %1",wkofyr(d)));
}

MICROSOFT DYNAMICS AX 2012 : CODE TO GET ON HAND OF AN ITEM STOCK COUNT

MICROSOFT DYNAMICS AX 2012 : GET ON HAND OF AN ITEM STOCK COUNT
static void stockOnHand(Args _args)
{
    InventOnhand        inventOnHand;
    InventDim           inventDim;
    InventDimParm       inventDimParm;
    InventQty           stockOnHand;
    ItemId              itemid = "00001aTestInter";
 
    inventDim.InventSiteId = "SITE"; // site
    inventDim.InventLocationId = "WAREHOUSE"; // warehouse
 
 
    inventDimParm.initFromInventDim(inventDim);
 
    inventOnHand = InventOnhand::newParameters(itemid,inventDim,inventDimParm);
 
    stockOnHand = inventOnHand.availPhysical();
 
    info (strFmt(" Stock on Hand for Item %1 is %2",itemid,stockOnHand));
 
}

MICROSOFT DYNAMICS AX 2012 : CODE TO DEPLOY SERVICE FROM AX

DEPLOY AX SERVICES FROM CODE

Below is the script for automatically deploy or undeploy  AIF service.
In this example update the port with current company and deploy the service.
static void AIFservices(Args _args)
{
    AifPort  port;
    AifPortName portName = "servicename";
    AifPortManager::undeployPort(portName);
    port = AifPort::find(portName,true);

    if(port)
    {
        ttsBegin;
        if(port.Company != curext() )
        {
            port.Company = curext();
            port.update();
        }
        ttsCommit;
    }
    AifPortManager::deployPort(portName);
}

AX 2012 CHECK IF DIMENSION EXIST OR NOT X++ CODE

CHECK IF DIMENSIONS EXIST OR NOT


The following code is used to check if the Dimension exist for item.
while select inventTable where inventTable.DefaultDimension == 0
    {
     
         if(EcoResStorageDimensionGroupItem::findByItem(inventTable.DataAreaId, inventTable.ItemId).StorageDimensionGroup
            && EcoResTrackingDimensionGroupItem::findByItem(inventTable.DataAreaId, inventTable.ItemId).TrackingDimensionGroup)
        {
            continue; // exist
        }
        else
        {
             // not exist do some thing.
        }
}

Monday, April 18, 2016

HOW TO CREATE A DIALOG IN DYNAMICS AX : X++ CODE

CREATE A DIALOG IN AX : X++ CODE 


class CustDialog extends RunBase
{
DialogField fieldAccount;
DialogField fieldName;
DialogField fieldGroup;
DialogField fieldCurrency;
}

pack() and unpack(0 are used to retain the last used values.
public container pack()
{
return conNull();
}
public boolean unpack(container _packedClass)
{
return true;
}
protected Object dialog()
{

Dialog dialog;
DialogGroup groupCustomer;
DialogGroup groupPayment;
dialog = super();
dialog.caption("Customer information"); dialog.allowUpdateOnSelectCtrl(true);
fieldAccount = dialog.addField(
extendedTypeStr(CustAccount), "Customer account");
fieldName = dialog.addField(extendedTypeStr(CustName));
fieldName.enabled(false);
dialog.addTabPage("Details");
groupCustomer = dialog.addGroup("Setup");
fieldGroup = dialog.addField(
extendedTypeStr(CustGroupId)); fieldCurrency = dialog.addField(
extendedTypeStr(CurrencyCode)); fieldGroup.enabled(false);
fieldCurrency.enabled(false);
groupPayment = dialog.addGroup("Payment");
return dialog;
}

Below method is used to dynamically assign the different values of the cust table
public void dialogSelectCtrl()
{
CustTable custTable;
custTable = CustTable::find(fieldAccount.value()); fieldName.value(custTable.name()); fieldGroup.value(custTable.CustGroup); fieldCurrency.value(custTable.Currency);
}
public static void main(Args _args)
CustSelect custSelect = new CustSelect();
if (CustSelect.prompt()) {
CustSelect.run();
}
}

READ COMMA SEPARATED FILES : DYNAMIC AX CODE X++

READ COMMA SEPARATED FILES : DYNAMIC AX CODE X++
PUBLIC VOID READCOMMAFILE()
{
CommaTextIo         file;
container           line;
#define.filename(@'C:\\accounts.csv') #File
file = new CommaTextIo(#filename, #io_read);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
line = file.read();
while (file.status() == IO_Status::Ok)
{
info(con2Str(line, ' - '));
line = file.read();
                }


}

CREATE COMMA SEPARATED FILES : DYNAMICS AX X++ CODE

CREATE COMMA SEPARATED FILES : DYNAMICS AX X++ CODE
public void createcommafiles()
{
CommaTextIo         file;
container            line;
MainAccount           mainAccount;
#define.filename(@'C:\accounts.csv') #File
file = new CommaTextIo(#filename, #io_write);
if (!file || file.status() != IO_Status::Ok)
{
throw error("File cannot be opened.");
}
while select MainAccountId, Name from mainAccount
{
line = [
mainAccount.MainAccountId,
mainAccount.Name];
file.writeExp(line);
}
info(strFmt("File %1 created.", #filename));

}

CODE TO ADD A NOTE IN A DOCUMENT REFERENCE FOR A TABLE

CODE TO ADD A NOTE IN A DOCUMENT REFERENCE 
FOR A TABLE

static void TabledocuAdd(Args _args) {
DocuRef      docuRef;
VendTable vendTable;
vendTable = VendTable::find('123');
docuRef.RefCompanyId = vendTable.dataAreaId;
docuRef.RefTableId    = vendTable.TableId;
docuRef.RefRecId        = vendTable.RecId;
docuRef.TypeId        = 'Note';
docuRef.Name            = 'Imported';
docuRef.Notes         = 'This vendor was imported.';
docuRef.insert();

}

Outbound and Inbound file generation using File system adapater in AX 2012

Outbound  and Inbound file generation using File system adapter in AX 2012


Below is the code to generate the outbound xml file for the selected record.
static void GenerateXmlSelectedRecord(Args _args)
{
    AxdSendContext      axdSendContext  = AxdSendContext::construct();
    AifEntityKey        aifEntityKey    = AifEntityKey::construct();
    AifEntityKeyList    aifEntityKeyList = AifEntityKeyList::construct();
    Map                 keyData;
    AifConstraintList   aifConstraintList   = new AifConstraintList();
    AifConstraint       aifConstraint       = new AifConstraint();
    CustTable           custTable;
    int i,j;
    CustCustomerService CustCustomerService = CustCustomerService::construct();
    ;
    custTable = CustTable::find('Cust001');

    keyData = SysDictTable::getKeyData(custTable);
    aifEntityKey.parmTableId(custTable.TableId);
    aifEntityKey.parmRecId(custTable.RecId);
    aifEntityKey.parmKeyDataMap(keyData);

    aifEntityKeyList.addEntityKey(aifEntityKey);


    axdSendContext.parmXMLDocPurpose(XMLDocPurpose::Original);
    axdSendContext.parmSecurity(false);


    aifConstraint.parmType(AifConstraintType::NoConstraint) ;
    aifConstraintList.addConstraint(aifConstraint) ;

    info(strFmt("%1",custTable.AccountNum));
    AifSendService::SubmitDefault(  classnum(CustCustomerService),
                                aifEntityKey,
                                aifConstraintList,
                                AifSendMode::Async,
                                axdSendContext.pack());
}

Example: Generating the outbound xml file for all records( i.e. specified criteria on the query).
Below is the code to generate the outbound xml for all the records or specified criteria.

static void GenerateMutiplerecords(Args _args)
{
    CustTable           custTable;
    AxdSendContext      axdSendContext      = AxdSendContext::construct();
    AifEntityKey        aifEntityKey        = AifEntityKey::construct();
    AifConstraintList   aifConstraintList   = new AifConstraintList();
    AifConstraint       aifConstraint       = new AifConstraint();
    AifEndpointList     endpointList;
    AifActionId         actionId;
    Query               query;
    QueryBuildDataSource    qbds;

    query               = new Query(queryStr(AxdCustomer));
    AxdSend::removeChildDs(query);

    actionId            = AifSendService::getDefaultSendAction(classnum(CustCustomerService), AifSendActionType::SendByQuery);
    aifConstraint.parmType(AifConstraintType::NoConstraint);
    aifConstraintList.addConstraint(aifConstraint) ;
    endpointList        = AifSendService::getEligibleEndpoints(actionId, aifConstraintList);

    AifSendService::SubmitFromQuery(actionId,endpointList,query,AifSendMode::Async);
}

Saturday, April 16, 2016

Change Color of your Dynamics AX Environments/Forms

 Change Color of your Dynamics AX  Environments/Forms


To change the color of the Dynamics forms to help indicate what environment is in use. It involved overriding the SysSetupFormRun.run() method, which will be called every time a form is opened. On the class SysSetupFormRun, create a new method with this code:
public void run()
{
SysSQLSystemInfo systemInfo = SysSQLSystemInfo::construct();
; 

super();
// Set the color scheme of this instance of the SysFormRun to RGB
this.design().colorScheme(FormColorScheme::RGB);
// If the database name is not the live version, change the color of the form
if (systemInfo.getloginDatabase() != 'DynamicsAX_test')
this.design().backgroundColor(0x112255);
}



 If your live and test systems use the same database name, but the AOS is running on different servers you can modify this code to to match on systemInfo.getLoginServer() != 'MyServerName'. You can change the color by setting the hex value. It uses the RGB values in reverse order: 0xBBGGRR. 

thanks,
Vikas Mehta

DYNAMICS AX X++ CODE TO CONNECT TO SQL DATABASE DSN ODBC CONNECTION LOGIN

How  to connect to an external DB from Dynamics AX using X++


1. Create a DSN
To create a Data Source Name (DSN) go to Administrative Tools > Data Sources (ODBC).
Create the DSN on the tier where the X++ code will call the DSN from
2. X++ code
static void TestOdbcJob()
{
    LoginProperty login;
    OdbcConnection con;
    Statement stmt;
    ResultSet rs;
    str strQuery, criteria;
    SqlStatementExecutePermission perm;
    ;

    // Set the information on the ODBC.
    login = new LoginProperty();
    login.setDSN("dsnName");
    login.setDatabase("databaseName");

    //Create a connection to external database.
    con = new OdbcConnection(login);

    if (con)
    {
        strQuery = strfmt("SELECT * from tableName WHERE XXX = ‘%1′ ORDER BY  FIELD1, FIELD2", criteria);

        //Assert permission for executing the sql string.
        perm = new SqlStatementExecutePermission(strQuery);
        perm.assert();

        //Prepare the sql statement.
        stmt = con.createStatement();
        rs = stmt.executeQuery(strQuery);
       
        //Cause the sql statement to run,
        //then loop through each row in the result.
        while (rs.next())
        {
            //It is not possible to get field 2 and then 1.
            //Always get fields in numerical order, such as 1 then 2 the 3 etc.
            print rs.getString(1);
            print rs.getString(2);
        }


        rs.close();
        stmt.close();
    }
    else
    {
        error("Failed to log on to the database through ODBC");
    }
}

SALES QUOTE UPDATION AX 2012 X++ CUSTOM WEB SERVICE

SALES QUOTE UPDATION AX 2012 
X++ CUSTOM WEB SERVICE
Sales Quote update
[AifCollectionTypeAttribute('return', Types::Container), SysEntryPointAttribute(true)]
public str updateQuote(QuotationIdBase _quoteId,CustCurrencyCode _currency, InventSiteName _site,ItemIdSmall _item,SalesQty _qty,comp_OrderType _orderType,comp_OrderCat _orderCategory,FormType_IN _saleTypeSalesTax,comp_SaleTypeExciseDuty   _saleTypeExcise,
                        String50 _domestic,String50 _export,String50 _e1Sale,string50 _price,TaxGroup _taxGroup,MarkupValue _freight)
{

    str                             log;
    str                             log_1,log_2,log_3,log_4,log_5,log_6,log_7,log_8,log_9;
    Inventsite                      site;
    InventLocation                  ware;
    SalesQuotationTable             quotation,quotationIdchk;
    SalesQuotationLine              line,line_2;
    InventDim                       dim;
    InventItemOrderSetupType        setupType   = InventItemOrderSetupType::Invent;
    InventTable                     inventTable;
    CustTable                       cust;
    InventDimCombination            comb;
    NoYes                           noyes;
    TmpTaxWorkTrans                 tmpTax;
    SalesQuotationTable             salesQuotationTable;
    SalesQuotationTotals_Sales      salesQuotationTotals;
    TaxTable                        taxtable;
    str                             component;
    container                       con;
    int                             i ;
    compProductMasterDefault         prodMasterDef;
    MarkupTable                             markTab;
    MarkupTrans                             trans;

    select * from prodMasterDef;

   if(_orderCategory == 'Dealer-Customer')
            changeCompany(prodMasterDef.DealerCompany)
    {  // Validating from masters
         select * from quotationIdchk where quotationIdchk.QuotationId == _quoteId;
     if(quotationIdchk.RecId && InventSite::exist(_site) && InventTable::exist(_item) && SalesTaxFormTypes_IN::exist(_saleTypeSalesTax)&&  TaxGroupHeading::exist(_taxGroup))

        {

            ttsBegin;
            //updating header
            quotation.clear();
            select forupdate quotation where quotation.QuotationId ==  _quoteId;
            if(quotation.RecId)
            {
                quotation.QuotationStatus  = SalesQuotationStatus::Created;
                quotation.CurrencyCode = _currency;
                quotation.ShippingDateRequested = systemDateGet();
                quotation.comp_OrderType = _orderType;
                quotation.comp_OrderCat  = _orderCategory;
                quotation.comp_SaleTypeExciseDuty = _saleTypeExcise;
                quotation.comp_E1Sale = str2enum(noyes,_e1Sale);
                quotation.comp_Domestic = str2enum(NoYes,_domestic);
                quotation.comp_Export = str2enum(NoYes,_export);
                quotation.update();
            }
            //updating line
            line.clear();
            select forUpdate line where line.QuotationId == quotation.QuotationId;
                               // && line.ItemId == _item;

            if(line.RecId)
            {
                 //line.ItemId = _item;
                line.initFromSalesQuotationLine(line);
                 line.SalesPrice = str2num(_price) - _freight;
                 line.TaxGroup = _taxGroup;
                 line.SalesQty = _qty;
                 line.CurrencyCode = _currency;
                 line.ShippingDateRequested = systemDateGet();
                 line.SalesTaxFormTypes_IN = SalesTaxFormTypes_IN::findbyFormType(_saleTypeSalesTax).RecId;
                 line.ExciseTariffCodes_IN = Inventtable::find(line.ItemId).ExciseTariffCodes_IN;
            }
            line.modifiedField(fieldnum(SalesQuotationLine,SalesPrice));
            line.update();


            markTab = MarkupTable::find((MarkupModuleType::Cust),'6');

            select forupdate trans where Trans.TransTableId == line.TableId
                    && Trans.TransRecId == line.RecId;
           trans.ModuleType  =  MarkupModuleType::Cust;
           trans.CurrencyCode = line.CurrencyCode;
           trans.MarkupCode    = markTab.MarkupCode;
           trans.Txt            = markTab.Txt;
           trans.MarkupCategory = MarkupCategory::Pcs;
           trans.Value = _Freight;
           Trans.update();
            ttsCommit;
            salesQuotationTable  = SalesQuotationTable::find(_quoteId);
            salesQuotationTotals = SalesQuotationTotals_Sales::construct(salesQuotationTable);

            // Calculate Tax
            salesQuotationTotals.calc();

            // Load tmpTaxWorkTrans
            tmpTax.setTmpData(salesQuotationTotals.tax().tmpTaxWorkTrans());

            // Showing taxes with tax value
            while
                select tmpTax
            {
                i++;
                select taxtable where taxtable.taxcode == tmpTax.TaxCode;
                component = TaxComponentTable_IN::find(taxtable.TaxComponentTable_IN).Name;
               log_7  = component;
//             log_8 = num2str(abs(tmpTax.TaxAmount),0,2,1,1);
               log_8 =  num2str(abs((tmpTax.TaxAmount)/_qty),0,2,0,0);
               con = conins(Con,i,log_7+':'+log_8);


            }
            i =0 ;
            log = con2StrUnlimited(con,'|');

         }
        else
        {
            //strFmt('Warehouse %1 is not valid for Sales Quote : %2',ware,_quoteId);
            if(!InventTable::exist(_item))
            {
                log_3 = strFmt('Item %1 is not valid for %2 company %3',_item,_quoteId,curext());
            }
            if(!SalesTaxFormTypes_IN::exist(_saleTypeSalesTax))
            {
                log_4 = strFmt('SalesTax FormType %1 is not valid for %2',_saleTypeSalesTax,_quoteId);
            }
            if(!TaxGroupHeading::exist(_taxGroup))
            {
                log_5 = strFmt('Tax Group is %1 not valid for %2',_taxGroup,_quoteId);
            }
            if(!quotationIdchk.RecId )
            {
                log_9 = strFmt('Quote %1 does not exist',_quoteId);
            }
            log = strFmt("%1\n%2\n%3\n%4",log_3,log_4,log_5,log_9);

        }

      }
      else
      {
           changeCompany(prodMasterDef.delCompany)
          {
       // validating masters
           select * from quotationIdchk where quotationIdchk.QuotationId == _quoteId;
      if( quotationIdchk.RecId && InventTable::exist(_item) && SalesTaxFormTypes_IN::exist(_saleTypeSalesTax)&&  TaxGroupHeading::exist(_taxGroup))

        {
             ttsBegin;
            //creating header
            quotation.clear();
            select forUpdate quotation where quotation.QuotationId == _quoteId;
            if(quotation.RecId)
            {
                quotation.QuotationStatus  = SalesQuotationStatus::Created;
                quotation.CurrencyCode = _currency;
                quotation.ShippingDateRequested = systemDateGet();
                quotation.LanguageId = SystemParameters::getSystemLanguageId();
                quotation.comp_OrderType = _orderType;
                quotation.comp_OrderCat  = _orderCategory;
                quotation.comp_SaleTypeExciseDuty = _saleTypeExcise;
                quotation.comp_E1Sale = str2enum(noyes,_e1Sale);
                quotation.comp_Domestic = str2enum(NoYes,_domestic);
                quotation.comp_Export = str2enum(NoYes,_export);
                quotation.update();
            }
            //updating lines
            line.clear();
            select forUpdate line where line.QuotationId == quotation.QuotationId;
                      //  && line.ItemId == _item;

            if(line.RecId)
            {
                 //line.ItemId = _item;
                 line.initFromSalesQuotationLine(line);
                 line.SalesPrice = str2num(_price) - _freight;
                 line.TaxGroup = _taxGroup;
                 line.SalesQty = _qty;
                 line.CurrencyCode = _currency;
                 line.ShippingDateRequested = systemDateGet();
                 line.SalesTaxFormTypes_IN = SalesTaxFormTypes_IN::findbyFormType(_saleTypeSalesTax).RecId;
                 line.ExciseTariffCodes_IN = Inventtable::find(line.ItemId).ExciseTariffCodes_IN;
            }
            line.modifiedField(fieldnum(SalesQuotationLine,SalesPrice));
            line.update();

             markTab = MarkupTable::find((MarkupModuleType::Cust),'6');

            select forupdate trans where Trans.TransTableId == line.TableId
                    && Trans.TransRecId == line.RecId;
               trans.ModuleType  =  MarkupModuleType::Cust;
               trans.CurrencyCode = line.CurrencyCode;
               trans.MarkupCode    = markTab.MarkupCode;
               trans.Txt            = markTab.Txt;
               trans.MarkupCategory = MarkupCategory::Pcs;
               trans.Value = _Freight;
               Trans.update();
            ttsCommit;
            salesQuotationTable  = SalesQuotationTable::find(_quoteId);
            salesQuotationTotals = SalesQuotationTotals_Sales::construct(salesQuotationTable);

            // Calculate Tax
            salesQuotationTotals.calc();

            // Load tmpTaxWorkTrans
            tmpTax.setTmpData(salesQuotationTotals.tax().tmpTaxWorkTrans());

            // Showing taxes with tax value
             while
                select tmpTax
            {
                i++;
                select taxtable where taxtable.taxcode == tmpTax.TaxCode;
                component = TaxComponentTable_IN::find(taxtable.TaxComponentTable_IN).Name;
               log_7  = component;
               log_8 = num2str(abs((tmpTax.TaxAmount)/_qty),0,2,0,0);
               con = conins(Con,i,log_7+':'+log_8);


            }
            i =0 ;
            log = con2StrUnlimited(con,'|');

         }
        else
        {
              if(!InventTable::exist(_item))
            {
                log_3 = strFmt('Item %1 is not valid for %2 for company %3',_item,_quoteId,curext());
            }
            if(!SalesTaxFormTypes_IN::exist(_saleTypeSalesTax))
            {
                log_4 = strFmt('SalesTax FormType %1 is not valid for %2',_saleTypeSalesTax,_quoteId);
            }
            if(!TaxGroupHeading::exist(_taxGroup))
            {
                log_5 = strFmt('Tax Group is %1 not valid for %2',_taxGroup,_quoteId);
            }
             if(!quotationIdchk.RecId )
            {
                log_9 = strFmt('Quote %1 does not exist for company %2',_quoteId,curext());
            }
            log = strFmt("%1\n%2\n%3\n%4",log_3,log_4,log_5,log_9);
        }
      }
    }

     info(strFmt("Sales Quote Update: %1 - %2 ",_quoteId,log));
     comp_RetailExceptionActivityLog::logEvent('Sales Quote Update',infolog.export());
     return log ;
    }
Related Posts Plugin for WordPress, Blogger...