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

void LG_CARRY(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char bizdate[16], nextday[16];
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_next[16];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;

    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    if (acq_next_bizday(bizdate, nextday) < 0) strcpy(nextday, bizdate);
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(h_next, nextday, sizeof(h_next)-1); h_next[sizeof(h_next)-1] = 0;

    EXEC SQL INSERT INTO lg_account_bal (acct, biz_date, debit_total, credit_total, balance)
        SELECT acct, :h_next, debit_total, credit_total, balance
        FROM lg_account_bal WHERE biz_date = :h_bizdate
        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_CARRY %s -> %s 계정 %ld건 이월", bizdate, nextday, h_cnt);
    OK(b);
}

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