/*
 * LG_TRIALBAL.pgc - lg 모듈 서비스 LG_TRIALBAL (one service = one file).
 * 계정별 시산표 산출 후 lg_trial_bal upsert.
 * 이전 인라인 lg_svr.pgc 에서 분리; 호출자의 XA 브랜치에서 수행(EXEC SQL CONNECT 없음).
 * lg_svr 가 tpsvrinit 에서 tpadvertise 로 광고한다.
 */
#include "LG_TRIALBAL.h"

void LG_TRIALBAL(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char acct[32], bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_dr, h_cr;
    char h_acct[32], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    gets_(b, T_KEY1, acct, sizeof(acct)); if (acct[0] == 0) strcpy(acct, "RECV");
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_acct, acct, sizeof(h_acct)-1); h_acct[sizeof(h_acct)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT coalesce(sum(CASE WHEN dc = 'D' THEN amount ELSE 0 END), 0),
                    coalesce(sum(CASE WHEN dc = 'C' THEN amount ELSE 0 END), 0)
        INTO :h_dr, :h_cr FROM lg_ledger_line
        WHERE acct = :h_acct AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO lg_trial_bal (acct, biz_date, debit_total, credit_total, diff)
        VALUES (:h_acct, :h_bizdate, :h_dr, :h_cr, :h_dr - :h_cr)
        ON CONFLICT (acct, biz_date) DO UPDATE
        SET debit_total = EXCLUDED.debit_total, credit_total = EXCLUDED.credit_total,
            diff = EXCLUDED.diff, updated_at = now();
    if (sqlca.sqlcode < 0) FAIL(b);
    setl(b, T_AMT2, h_dr); setl(b, T_AMT3, h_cr); setl(b, T_DELTA, h_dr - h_cr);
    OK(b);
}

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