/*
 * LG_APPLY.pgc - lg 모듈 서비스 LG_APPLY (one service = one file).
 * 전표 전기확정(P): 라인들의 계정잔액을 잔액테이블에 반영.
 * 이전 인라인 lg_svr.pgc 에서 분리; 호출자의 XA 브랜치에서 수행(EXEC SQL CONNECT 없음).
 * lg_svr 가 tpsvrinit 에서 tpadvertise 로 광고한다.
 */
#include "LG_APPLY.h"

void LG_APPLY(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_vid;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    h_vid = getl(b, T_ID1);
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL INSERT INTO lg_account_bal (acct, biz_date, debit_total, credit_total, balance)
        SELECT acct, :h_bizdate,
               coalesce(sum(CASE WHEN dc = 'D' THEN amount ELSE 0 END), 0),
               coalesce(sum(CASE WHEN dc = 'C' THEN amount ELSE 0 END), 0),
               coalesce(sum(CASE WHEN dc = 'D' THEN amount ELSE -amount END), 0)
        FROM lg_ledger_line WHERE voucher_id = :h_vid
        GROUP BY acct
        ON CONFLICT (acct, biz_date) DO UPDATE
        SET debit_total  = lg_account_bal.debit_total + EXCLUDED.debit_total,
            credit_total = lg_account_bal.credit_total + EXCLUDED.credit_total,
            balance      = lg_account_bal.balance + EXCLUDED.balance,
            updated_at   = now();
    if (sqlca.sqlcode < 0) FAIL(b);
    if (lgdb_update_voucher_status(h_vid, "P") < 0) FAIL(b);
    Bchg(b, T_STATUS, 0, "P", 0L);
    OK(b);
}

/* vim: set ts=4 sw=4 et smartindent: */
