Monday, August 20, 2018

Marking Customer Transaction with Specific Amount - Unposted Settlement for AX 2012 R3

static void Create_CustSettleOpen(Args _args)
{
    CustVendOpenTransManager manager;
    LedgerJournalTrans ljt;
    CustTransOpen ctoselect,cto;
    CustTrans ctselect,ct;
    AccountNum accnnumx;
    Voucher vchx1,vchx2,vchx3,vchx4;
    Amount toBeSettlex,selectSettlex,selectSettleEndx,diffSettlex,totSettledx;
    ;
    accnnumx    = '3';
    vchx1       = 'ARCI00000001';
    vchx2       = 'ARCI00000002';
    vchx3       = 'ARCI00000004';
    vchx4       = 'ARCI00000005';
    toBeSettlex = 200000000; // Specifict amount to be settled to multiple voucher
    selectSettlex = 0;
   

    //Check existing CustTrans with criteria
    select count(RecId) from ctselect
    where ctselect.AccountNum == accnnumx
          && ctselect.TransDate == str2Date('01/07/2018',123)
          ;

    if(ctselect.RecId > 0)
    {
        // Fetch the added LedgerJournalTrans
        ljt = LedgerJournalTrans::find('G000001521', 'RINV1000011910', true);
        manager = CustVendOpenTransManager::construct(ljt);

        //loop find any open CustTrans based on criteria

        while select * from ctoselect join ct
        where ct.AccountNum == ctoselect.AccountNum
        && ct.RecId == ctoselect.RefRecId
        && ct.AccountNum == accnnumx
        && ct.TransDate == str2Date('01/07/2018',123)
        {
            if (ctoselect.AmountCur != ct.AmountCur)
            {
                throw error('invoice has been partially paid');
            }
            // Mark the invoice.
            selectSettlex = selectSettlex + ctoselect.AmountCur;
            diffSettlex = selectSettlex - toBeSettlex;

            //info(strFmt('%1 %2 %3',selectSettlex,toBeSettlex,ct.Voucher));

            if( selectSettlex > toBeSettlex)
            {
                manager.updateTransMarked(ctoselect, true);
                manager.updateSettleAmount(ctoselect, toBeSettlex-selectSettleEndx);
                //info(strFmt('IF %1 %2 diff %3 %4',selectSettlex,toBeSettlex,diffSettlex,ct.Voucher));
                break;
            }

            manager.updateTransMarked(ctoselect, true);
            selectSettleEndx = selectSettlex;
            //info('marked');

        }

        totSettledx = manager.getMarkedTotalDisplayCur();

        ttsBegin;
            // Update journal trans.
            ljt.MarkedInvoice = ct.Invoice;
            ljt.SettleVoucher = SettlementType::SelectedTransact;

            if(totSettledx > 0)
            { ljt.AmountCurCredit =  abs(totSettledx); }
            else
            { ljt.AmountCurDebit =  abs(totSettledx); }

            ljt.update();
        ttsCommit;      

    }
    else
    {
        throw error('voucher could not be found');
    }
    info(strFmt('done. total %1',totSettledx));
}