11/03/2016

Programmatically settle a payment journal trans against a specific open transaction.

In the following example, I used a customer invoice as an example of open transaction, the logic applies to vendor open transaction as well.
To make sure the amount can be fully settled, I checked if the payment amount matches the open transaction amount. According to the specific requirement, we can ajust the logic.
The key point of this code snippet is the use of CustVendOpenTransManager.

static void SettleCustOpenTrans(Args _args)
{
    CustVendOpenTransManager manager;
    LedgerJournalTrans ljt;
    CustTransOpen cto;
    CustTrans ct;
    ;
    ct = CustTrans::findFromInvoice('Invoice Number', 'Customer Account');

    // Get cust trans open.
    if (ct.RecId)
    {
        cto = CustTransOpen::findRefId(ct.RecId);

        // Check amount to make sure the open trans was not partially settled before.
        if (cto.AmountCur != ct.AmountCur)
            throw error('invoice has been partially paid');
    }
    else
    {
        throw error('invoice could not be found');
    }

    // Fetch the added LedgerJournalTrans.
    ljt = LedgerJournalTrans::find('Journal number', 'Jounal trans voucher', true);

    // Check if the journal trans is paying the invoice wholly.
    if (ljt.AmountCurCredit - ljt.AmountCurDebit != cto.AmountCur)
        throw error('this payment journal line is not paying the invoice wholly');


    ttsBegin;
    // Mark the invoice.
    manager = CustVendOpenTransManager::construct(ljt);
    manager.updateTransMarked(cto, true);

    // Update journal trans.
    ljt.MarkedInvoice = ct.Invoice;
    ljt.SettleVoucher = SettlementType::SelectedTransact;
    ljt.update();
    ttsCommit;

    info('done');
}