Thursday, 30 June 2016

Upload AP Invoice Journal from Excel file through X++ code in ax 2009

Navigation : AP--> Journals-->Invoice Journal->

We create One Class::

Method1: ClassDeclaration:

public class kr_ImportAPInvJournal extends ObjectRun
{
 
}

Method2: Run

void run()
{

// 12-13-2012 change to use excel - Richard s
    Amount amount;
    LedgerJournalTable j;
    LedgerJournalTrans t,ledgerJournalTrans;
    LedgerPeriod p;
    LedgerJournalTable ledgerjournaltable;
    int k,i;

   Dialog dlg;
     DialogField dfFileName, dfJournalName, dfDate, dfAccountNum, dfOffsetAccount;
     DialogField dfVendAccount, dfFreightAccount, dfFuelAccount;
     DialogField dfProdLine;
    FileNameOPen fileName;
    LedgerJournalId jourId;
    transDate tDate;
    Voucher curVoucher;
    str 60 customer;
//    CustTable custTable;
//    CustTrans custTrans;
//    CustTransOpen custTransOpen;
    InvoiceId invoiceId;
//    CustAccount invoiceAccount;
    CurrencyCode currencyCode;

    AccountNum  glAccount, glOffsetAccount, glFuelAccount='556001',glFreightAccount='556000', glVendAccount='8093064';
    date docdate, duedate, transdate;
    num docnum;
    Amountmst amountmst, total;
    AmountCur amountcur;
    ExchRate exchrate;
    LedgerJournalNameID  journalName;
    container con;
//    ASCIIIO file;
//   TextIO file;
    str period;
    str 100 txt;
    int upd;
    int iYear, iMonth;

    SysExcelApplication         ExcelApp;
    boolean                     rowFound = true;
    DialogField                 dialogFieldStartLineNum;
    DialogField                 dialogFieldEndLineNum;
    int                         lineNum = 2;
    int                         lineNumEnd = 9;
    str                         testStr;
    counter                     readcounter = 0;
    counter                     insertCounter = 0;
    counter                     updateCounter = 0;
    counter                     errCounter = 0;
    Boolean                     errorEncounter = false;
    Boolean                     ret = true;
    //Begin XREN 1/10/2013
    SalesLine                   salesLine;
    SalesTable                  salesTable;
    CustTable                   custTable;
    real                        costCenter;
    str                         costCenterStr;
    str                         marketSegment;
    str                         customerDim;
    str                         productLine;
    SalesId                     salesId;
    Counter                     vendCount;
    Amount                      vendAmount;
  //StartJanardhan
    PaymTermId                  paymTermId, Payment;
    LedgerJournalEngine         ledgerJournalEngine;
    DueDate                     due;
    VendTable                   vendTable;
    PaymTerm                    paymTerm;
    PaymMode                    paymMode;
  //EndJanardhan
    ;

    dlg = new Dialog('Upload AP Invoice Journal from Excel file');
    dfFileName = dlg.addFieldValue(typeid(FileNameOpen),filename);
    dfJournalName = dlg.addFieldValue(typeid(LedgerJournalNameId),journalName,"Jrnl (APIMPT)","Name of Journal");

    dfVendAccount     = dlg.addFieldValue(typeid(VendAccount), glVendAccount, "Vendor Account", "Vendore Account Number");
    dfFreightAccount = dlg.addFieldValue(typeid(ledgerAccount), glFreightAccount, "Freight Account", "Freight Account Number");

    dfFuelAccount     = dlg.addFieldValue(typeid(LedgerAccount), glFuelAccount,"Fuel Account", "Fuel Account");

        dialogFieldStartLineNum = dlg.addField(typeid(Integer),"Starting Liine Number","start loading records at line number specified");
    dialogFieldStartLineNum.value(lineNum);
    dialogFieldEndLineNum = dlg.addField(typeid(Integer),"Ending Liine Number","stop loading records at line number specified");
    dialogFieldEndLineNum.value(lineNumEnd);

 //   dfDate = dlg.addFieldValue(typeid(transdate),tDate);
    if (!dlg.run())
       throw error('Cancelled by the user');
    filename = dfFileName.value();
    journalName = dfJournalName.value();        // 'APIMPT'; // -- or APINV
 //   jourId   = dfJournalNumber.value();    // ---------- need to create journal
       // use file for doc/invoice date
    glVendAccount = dfVendAccount.value();
    glfreightAccount = dfFreightAccount.value();
    glFuelAccount = dfFuelAccount.value();

    ttsbegin; //Xren 1/16/2013

   // ------------------------ j = new LedgerJournalTable();
    j = kr_ImportAPInvJournal::createLedgerJournalTable(journalName);
    jourId = j.JournalNum;
//    tDate    = dfDate.value();        // ? for posting date?

      //   glAccount = dfAccountNum.value();
      //   glOffsetAccount = dfOffsetAccount.value();

/*     file = new TextIO(filename,'rt');   -----change to use excel
//     file.inFieldDelimiter('\t');
     file.inFieldDelimiter(',');
     file.inRecordDelimiter('\n');
     info(strfmt('File %1',filename));
     */

        if (dialogFieldStartLineNum.value() > 0)
        {
            lineNum = dialogFieldStartLineNum.value();
            readCounter = lineNum - 1;
        }

        if (dialogFieldEndLineNum.value() > 0)
        {
            lineNumEnd = dialogFieldEndLineNum.value();
        }

        ExcelApp = SysExcelApplication::construct();
        ExcelApp.workbooks().open(filename);
     k = -1;
     select PeriodStart, PeriodEnd, PeriodMonth, PeriodYear from p
     where p.PeriodStart <= tDate
        && p.PeriodEnd >= tDate
        && p.PeriodMonth > 0
        && p.PeriodYear > 0;

    iMonth = p.PeriodMonth;
    iYear  = p.PeriodYear;

    try
    {
    while (rowFound && ExcelApp.activeSheet().cells().range(strfmt('A%1',lineNum)).item(lineNum))
    {
    //    while (file.status() == IO_Status::Ok)
    //begin looping through input file

              //          con = file.read();
 //        if (conlen(con) ==  0)
 //         continue;

         k++;
//         if (k == 0)
//          continue;

   /*      if (conlen(con) != 23)
         {
             warning(strfmt("line %1 skipped, found %2 columns", k, conlen(con)));
             continue;
         }
     */
 //      print k;
         readcounter++;
             if (lineNum > lineNumEnd)
             {
                    rowfound = false;
                    continue;
             }

             if (ExcelApp.activeSheet().cells().item(lineNum, 1).value().variantType()  == ComVariantType::VT_EMPTY &&
                 ExcelApp.activeSheet().cells().item(lineNum, 2).value().variantType()  == ComVariantType::VT_EMPTY )

             {
                    rowfound = false;
                    continue;
             }

    ttsbegin;

         total += amountmst;
         t.clear();
         t.initValue();
         t.LineNum = k;
         t.journalnum = jourId;  // '353830_010';  ---- need journalid will auto populate?
//         transdate = str2date(conpeek(con,2),213);
         transdate = ExcelApp.activeSheet().cells().item(lineNum, 2).value().date();

      //         t.TransDate = conpeek(con,2);
         t.TransDate = transdate;
             //      t.Voucher = strfmt('GENROY%1%2.%3', substr(int2str(iyear), 3, 2), substr(int2str(iMonth + 100), 2, 2), substr(strfmt('%1', 100000 + k),2, 5)); // year, month
   // first- create thevendor line

            //  t.AccountType = LedgerJournalACType::Ledger;
         t.AccountType = LedgerJournalAcType::Vend;
//         t.AccountNum = glAccount; //'471001';
         t.AccountNum = glVendAccount;
         t.OffsetAccountType = LedgerJournalACType::Ledger;
 //        t.OffsetAccount = glOffsetAccount; //'211060';
//         t.Txt = conpeek(con, 2);
         t.Txt = 'Unyson upload';
//         amountcur = str2num(conpeek(con, 23));
         amountcur = ExcelApp.activeSheet().cells().item(lineNum, 24).value().double();

         amountcur = decRound(amountcur, 2);
         amount =  amountcur;
         amountmst = amountmst+amount;
        /*( if(amount >0)
         {
            t.AmountCurDebit = amount;
            t.AmountCurCredit = 0;
         }
         else
         {
            t.AmountCurDebit = 0;
            t.AmountCurCredit = -amount;
         } */
         t.AmountCurCredit = amount;  // vendor account is always credit
         t.currencyCode = 'USD';
//         t.Invoice = conpeek(con,1);
         t.Invoice = ExcelApp.activeSheet().cells().item(lineNum, 1).value().bstr();
         t.Dimension[1]= curext();
//       t.Dimension[4] = conpeek(con, 7);   // customer
//       t.Dimension[4] = CustTable::find(ExcelApp.activeSheet().cells().item(lineNum, 8).value().bstr()).Dimension[4]; //XREN 1/22/2013
//        t.Dimension[5] = conpeek(con, 3);  // no default so far

        t.DocumentDate = ExcelApp.activeSheet().cells().item(lineNum, 9).value().date();
        t.editReasonComment(true,ExcelApp.activeSheet().cells().item(lineNum, 10).value().bstr());

        //Begin XREN 1/10/2013
        costCenter      = ExcelApp.activeSheet().cells().item(lineNum, 26).value().double();
        salesId         = ExcelApp.activeSheet().cells().item(lineNum, 6).value().bstr();
        t.DocumentNum   = salesId;
        salesTable      = SalesTable::find(salesId);
        custTable       = CustTable::find(ExcelApp.activeSheet().cells().item(lineNum, 8).value().bstr());
        t.Dimension[2]  = num2str(costCenter, 3, 0, 1, 0);
        if (!t.Dimension[2])
        {
            throw error(strfmt("Line %1 does not have valid cost center %2", lineNum, t.Dimension[2]));
        }
        t.Dimension[3]  = custTable.Dimension[3];
        if (!t.Dimension[3])
        {
            t.Dimension[3] = salesTable.Dimension[3];
        }
        if (!t.Dimension[3])
        {
            warning(strfmt("Line %1 does not have Market segment", lineNum));
        }

        t.Dimension[4] = salesTable.Dimension[4];
        if (!t.Dimension[4])
        {
            warning(strfmt("Line %1 does not have customer dimension asscoiated with sales order %2", lineNum, salesId));
        }
        t.Dimension[5] = salesTable.Dimension[5];
        if (!t.Dimension[5])
        {
            select firstonly salesLine
                where salesLine.SalesId         == salesId
                   && salesLine.Dimension[5]    != "";
            t.Dimension[5] = salesLine.Dimension[5];
        }
        if (!t.Dimension[5])
        {
            warning(strfmt("Line %1 does not have Product line associated with sales order %2", lineNum, salesId));
        }
        costCenterStr   = t.Dimension[2];
        marketSegment   = t.Dimension[3];
        customerDim     = t.Dimension[4];
        productLine     = t.Dimension[5];
        t.Approved      = NoYes::Yes;
        t.ApprovedBy    = curUserId();

        vendCount++;
        vendAmount += t.AmountCurCredit;
        //End
         t.validateWrite();
//       t.setSettleVoucher();
 //        _ledgerJournalTrans.Voucher = new JournalVoucherNum(JournalTableData::newTable(ledgerJournalTable)).getNew(false);
        t.Voucher = new JournalVoucherNum(JournalTableData::newTable(j)).getNew(false);
        curVoucher = t.Voucher;
        t.insert();
//Start Janardhan
        select vendTable where   vendTable.dataAreaId      == t.Company
                             &&  LedgerJournalACType::Vend == t.AccountType
                             &&  vendtable.AccountNum      == t.AccountNum;

          t.Payment  = vendTable.PaymTermId;
          paymTerm   = PaymTerm::find(t.Payment);
          t.Due      = paymTerm.NumOfDays +  t.TransDate;
          t.PaymMode=vendTable.PaymMode;
          t.Update();

//info(strfmt("Due date,Payment ,%1,%2",ledgerJournalTrans.Due, ledgerJournalTrans.Payment));
//End Janardhan
// now create the Freight entry
         t.clear();
         t.initValue();
         k++;
         t.LineNum = k;
         t.journalnum = jourId;

         t.AccountType = LedgerJournalACType::Ledger;
         t.TransDate = transdate;

         t.AccountNum = glFreightAccount;
         t.OffsetAccountType = LedgerJournalACType::Ledger;
         t.Txt = 'Unyson upload';
//         amountcur = str2num(conpeek(con, 20));
         amountcur = ExcelApp.activeSheet().cells().item(lineNum, 21).value().double();

         amountcur = decRound(amountcur, 2);
         amount =  amountcur;
         t.AmountCurDebit = amount;
         t.currencyCode = 'USD';
         t.Dimension[1]= curext();

//       t.Dimension[4] = conpeek(con, 7);   // customer
        //XREN 1/23/2013 t.Dimension[4] = ExcelApp.activeSheet().cells().item(lineNum, 8).value().bstr();

        t.Voucher = curVoucher;
        t.DocumentDate = ExcelApp.activeSheet().cells().item(lineNum, 9).value().date();
        t.editReasonComment(true,ExcelApp.activeSheet().cells().item(lineNum, 10).value().bstr());

        //Begin XREN 1/10/2013
        t.Dimension[2]  = costCenterStr;
        t.Dimension[3]  = marketSegment;
        t.Dimension[4]  = customerDim;
        t.Dimension[5]  = productLine;
        t.Approved      = NoYes::Yes;
        t.ApprovedBy    = curUserId();
        //End
         t.validateWrite();
         t.insert();
// now create the Fuel entry
         t.clear();
         t.initValue();
         k++;
         t.LineNum = k;
         t.journalnum = jourId;  //   ---- need journalid will auto populate?
         t.AccountType = LedgerJournalACType::Ledger;
         t.TransDate = transdate;
         t.AccountNum = glFuelAccount;
         t.OffsetAccountType = LedgerJournalACType::Ledger;
         t.Txt = 'Unyson upload';
//         amountcur = str2num(conpeek(con, 21));
         amountcur = ExcelApp.activeSheet().cells().item(lineNum, 22).value().double();
         amountcur = decRound(amountcur, 2);
         amount =  amountcur;
         t.AmountCurDebit = amount;
         t.currencyCode = 'USD';
         t.Dimension[1]= curext();

//         t.Dimension[4] = conpeek(con, 7);   // customer
        //XREN 1/22/2013 t.Dimension[4] = ExcelApp.activeSheet().cells().item(lineNum, 8).value().bstr();
        t.Voucher = curVoucher;
        t.DocumentDate = ExcelApp.activeSheet().cells().item(lineNum, 9).value().date();
        t.editReasonComment(true,ExcelApp.activeSheet().cells().item(lineNum, 10).value().bstr());

        //Begin XREN 1/10/2013
        t.Dimension[2]  = costCenterStr;
        t.Dimension[3]  = marketSegment;
        t.Dimension[4]  = customerDim;
        t.Dimension[5]  = productLine;
        t.Approved      = NoYes::Yes;
        t.ApprovedBy    = curUserId();
        //End

         t.validateWrite();
         t.insert();
         lineNum++;
      ttscommit;

      }
      }
      catch
      {
        excelapp.workbooks().close();
        excelapp.quit();
        throw error(strfmt('Error occured at rcd %1 for item: %2', linenum, t.Invoice)); //Xren 1/16/2013
      }
      excelapp.displayAlerts(true);
      excelapp.workbooks().close();
      excelapp.quit();

    ttscommit; //Xren 1/16/2013
      info(strfmt("loaded %1 lines, total $%2 USD",readcounter, total));
    info(strfmt("Vendor record: %1, Vendor amount: %2, Journal %3", vendCount, vendAmount,        jourId));
}

//Method 3 : createLedgerJournalTable

Static LedgerJournalTable createLedgerJournalTable(LedgerJournalNameID _ledgerJournalNameID)
{
    LedgerJournalTable journalTable;
    ;
    journalTable.journalType   = LedgerJournalType::VendInvoicePoolNotPosted ;
//   journalTable.JournalName   = PSAParameters::find().ExpenseJournalNameId;//Customized field
     journalTable.JournalName   = _ledgerJournalNameID;
    journalTable.initFromLedgerJournalName(journalTable.JournalName);
//    journalTable.JournalNum    = JournalTableData::newTable(journalTable).nextJournalId();

    journalTable.insert();
    return journalTable;
}

//
Method 4: Main

static void Main(Args _args)
{
  kr_ImportAPInvJournal krImportAPInvJournal;
  krImportAPInvJournal = new kr_ImportAPInvJournal();
  krImportAPInvJournal.run();

}

Thursday, 28 April 2016

inventoryOnHandUploadKraco on ax 2009

static void _kr_inventoryOnHandUploadKraco(Args _args)
{
  Price price;
  InventJournalCheckPost inventJournalCheckPost;
  ItemId itemId;
  ASCIIIo file;
  Dialog dlg;
  FileNameOpen filename;
  Date conversionDate;
  DialogField dfFileName;
  DialogField dfConversionDate;
  container con;
  int linenum, read, added, skipped, last;
  str 4 slast;
  inventqty qty;
  str 10  whse;
  InventJournalCopy inventJournalCopy;
  real convFactor;

  InventJournalTable InventJournalTable, retInventJournalTable;
  InventJournalTrans InventJournalTrans;
  InventLocationId inventLocationId;
  InventDim InventDim;
  LedgerTrans ledgerTrans;
  InventItemPrice  inventItemPrice;
  InventTable      invent;
  InventTableModule inventMod;
  InventItemLocation inventLoc;
  UnitConvert      unitConv;
  ;
//  changecompany('t1uk')
  {
//     filename = 'C:\\Users\\DDyachenko\\Desktop\\1.txt';
//     conversiondate = today();
     linenum = 0;
     InventJournalTable = null; InventJournalTrans = null;inventDim = null;
     dlg = new Dialog('Open inventory onhand file');
     dfFileName = dlg.addFieldValue(typeid(FileNameOpen),filename);
     dfConversionDate = dlg.addFieldValue(typeid(TransDate),conversiondate, "Conversion date");
     if (!dlg.run())
       throw error('Cancelled by the user');
     ttsbegin;

     filename = dfFileName.value();
     conversionDate = dfConversionDate.value();
     if (conversionDate == datenull())
     {
        throw (error("Conversion date must be populated"));
     }
     file = new ASCIIIO(filename,'rt');
     file.inFieldDelimiter('\t');
     file.inRecordDelimiter('\n');
     info(strfmt('File %1',filename));
     select  inventJournalTable  order by journalid desc where inventjournaltable.journalid  like 'conv*';
     if (inventJournalTAble.RecId)
     {
           last = str2int(substr(inventJournalTable.JournalId,5,strlen(inventJournalTable.JournalId)-4));
           info(strfmt("Previous journal found %1",inventJournalTable.JournalId));

        slast = int2str(last);
        if (strlen(slast)<4)
           slast = strfmt("%1%2",strrep('0',4-strlen(slast)),slast);

        retInventJournaltable = InventJournalTable::find(strfmt("Conv%1rev",slast));
        if (!retInventJournalTable.RecId)
        {
           inventJournalCopy = InventJournalCopy::newStandard(null,inventJournalTable.JournalId);
           inventJournalCopy.krParmReverseSign(true);
           inventJournalCopy.krparmJournalIdTo(strfmt("Conv%1rev",slast));
           inventJournalCopy.run();
           retInventJournalTable = InventJournalTable::find(inventJournalCopy.krParmJournalIdTo());
           info(strfmt('Reversing journal %1 created',retInventJournalTable.JournalId));
           if (inventjournaltable.Posted)
           {
             inventJournalCheckPost = InventJournalCheckPost::newPostJournal(retinventJournalTable);
             inventJournalCheckPost.run();
             info(strfmt("Inventory journal %1 posted",retinventjournalTAble.JournalId));
           }
        }
        else
          info(strfmt("Reversing journal %1 exists",retInventJournaltable.JournalId));

     }
     else
       info('No previous journal found');

     last++;
     slast = int2str(last);
     if (strlen(slast)<4)
        slast = strfmt("%1%2",strrep('0',4-strlen(slast)),slast);
     info(strfmt("New journal %1",strfmt("Conv%1",slast)));
     InventJournalTable.clear();
     InventJournalTable.JournalId = strfmt("Conv%1",slast);
     InventJournalTable.Description = "Inventory on-hand balance";
     InventJournalTable.Reservation = ItemReservation::None;
     InventJournalTable.JournalType = InventJournalType::Movement;
     InventJournalTable.JournalNameId = "IMov";
     InventJournalTable.VoucherDraw = JournalVoucherDraw::Post;
     InventJournalTable.VoucherChange = InventJournalVoucherChange::DateChange;
     InventJournalTable.VoucherSeqId = "Inve_72";
     InventJournalTable.DetailSummary = DetailSummary::Summary;
     InventJournalTable.LedgerAccountIdOffset = "124710";  // JimB  12/23/11  Changed to balance 431001 in GL
     if (inventjournaltable.validateWrite())
        InventJournalTable.insert();
     else
       throw error('script aborted');

     while (file.status() == IO_Status::Ok)
     {
        read++;

        con = file.read();
        if (read == 1)
         continue;
        if (conlen(con) == 0)
          continue;
        if (conlen(con) < 2 )
        {
           warning(strfmt("line: %1, number of columns %2",read, conlen(con)));
           continue;
        }
        itemId = conpeek(con,1);

        IF (itemId == 'A106800'
         || itemId == 'HR9600'
         || itemId == 'HRA9600'
         || itemId == 'HRBJ5400'
         || itemId == 'KGAD1100'
         || itemId == 'KGAD4R00'
         || itemId == 'KGAF400'
         || itemId == 'KGAF1200'
         || itemId == 'KGBKLT00'
         || itemId == 'KGBR9R00'
         || itemId == 'KGCQCB00'
         || itemId == 'KGCQ4G00'
         || itemId == 'KGCQ4T00'
         || itemId == 'KGCQ8T00'
         || itemId == 'KGFB4000'
         || itemId == 'KGMD1T00'
         || itemId == 'KGMM1T00'
         || itemId == 'KGMR3T00'
         || itemId == 'NA400'
         || itemId == 'NA1200'
         || itemId == 'NA1600'
         || itemId == 'RPR2000' )
            itemId = substr(itemId, 1, strlen(itemId) - 2);


        if( !InventTable::find(itemid).RecId)
        {
            warning(strfmt('item %1 not found in the Item Master table',itemid));
            continue;
        }
        whse = 'CWA'; //conpeek(con,2);
        inventlocationid = whse;
/*        switch(whse)
        {
           case 'GHT':
             inventlocationid  = 'GHEA';
             break;
           default:
             inventLocationId = whse;
        }
*/

        select UnitId from inventMod
        where inventMod.ItemId == itemId
           && inventMod.ModuleType == ModuleInventPurchSales::Invent;

        select Factor from unitConv
        where unitConv.FromUnit == 'EA'
           && unitConv.ToUnit == inventMod.UnitId
           && unitConv.ItemId == itemId;

        if ( unitConv.Factor )
            convFactor = unitConv.Factor;
        else
            convFactor = 1;

//        InventDim.clear();
//        inventDim.inventSiteId = InventLocation::find(inventLocationId).InventSiteId;
/*        if ( !inventLocationId )
        {
            warning(strfmt("Location does not exit in %1 for item %2", whse, itemid));
            continue;
        }

        inventDim.InventLocationId = inventLocationId;

        inventDim = inventDim::findOrCreate(inventdim);
*/
        select inventDimId from inventLoc
        where inventLoc.ItemId == itemId
       join InventDim
       where InventDim.wMSLocationId == inventLoc.WMSLocationIdDefaultIssue
          && InventDim.InventLocationId == whse
          && InventDim.InventSiteId == 'KE'
          && InventDim.wMSLocationId like '*P*';

        if ( !InventLoc.inventDimId )
        {
/*           select inventDimId from InventDim
          where InventDim.InventLocationId == whse
//            && InventDim.InventSiteId == 'KE'
             && InventDim.wMSLocationId == '9999999999';
*/
           inventDim.clear();
           inventDim.InventSiteId = InventLocation::find(whse).InventSiteId;
           inventDim.InventLocationId = whse;
           inventDim.wMSLocationId = '9999999999';
           inventDim = InventDim::findOrCreate(inventDim);
        }


        if ( !InventLoc.inventDimId  && !InventDim.inventDimId )
        {
            warning(strfmt("Location does not exist in %1 for item %2", whse, itemid));
            continue;
        }


        qty = conpeek(con,2);
        if (qty ==0)
        {
           warning(strfmt("line %1, item %2 - zero qty",read, itemid));
           continue;
        }
        qty = qty / convFactor;
        // Look up price  JimB  10/26/11

        select Price, PriceUnit, ActivationDate  from inventItemPrice
        order by ActivationDate desc
        where inventItemPrice.ItemId == itemid;

        qty = round(qty, 1.0);
        //price = conpeek(con,4);
        price = inventItemPrice.Price;
        linenum++;

        InventJournalTrans.clear();
        InventJournalTrans.initFromInventJournalTable(InventJournalTable);
        InventJournalTrans.LineNum = linenum;
        InventJournalTrans.TransDate = conversionDate;
        InventJournalTrans.Voucher = "Conversion";
        InventJournalTrans.ItemId = itemid;
        InventJournalTrans.initFromInventTable(InventTable::find(itemid));
        inventJournalTrans.InventDimId = inventDim.inventDimId;

        InventJournalTrans.Qty = qty;
        InventJournalTrans.CostPrice = price;
        inventJournalTrans.CostAmount  = InventJournalTrans.calcCostAmount();
        if (inventJournaltrans.validateWrite())
        {
           InventJournalTrans.insert();
           added++;
        }
        else
          throw error('script aborted');

     }
     if (added >0)
     {

       info(strfmt("New journal %1 created. %2 lines added",inventJournalTable.JournalId, added));
       inventJournaltable.NumOfLines = added;
       inventJournaltable.update();
//       inventJournalCheckPost = InventJournalCheckPost::newPostJournal(inventJournalTable);
//       inventJournalCheckPost.run();
//       info(strfmt("Inventory journal %1 posted",inventjournalTAble.JournalId));

     }
     ttscommit;

  }
}