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

void LG_DAILYSUM(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;
    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 biz_date = :h_bizdate
        GROUP BY acct
        ON CONFLICT (acct, biz_date) DO UPDATE
        SET debit_total  = EXCLUDED.debit_total,
            credit_total = EXCLUDED.credit_total,
            balance      = EXCLUDED.balance,
            updated_at   = now();
    if (sqlca.sqlcode < 0) FAIL(b);
    h_cnt = sqlca.sqlerrd[2];
    setl(b, T_COUNT, h_cnt);
    userlog("LG_DAILYSUM %s 계정 %ld건 집계", bizdate, h_cnt);
    OK(b);
}

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