/*
 * RC_AMTDIFF.pgc - rc 모듈 서비스 RC_AMTDIFF (one service = one file).
 * Moved verbatim from the former inline rc_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by rc_svr at tpsvrinit.
 */
#include "RC_AMTDIFF.h"

/* 5. RC_AMTDIFF - 금액 차이 대사: 기대(net) vs 실제(원장합) 차이 기록. */
void RC_AMTDIFF(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid, h_exp, h_act, h_diff;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    h_pid = getl(b, T_PURCHASE_ID);
    h_exp = getl(b, T_NET);
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_act FROM ledger
        WHERE purchase_id = :h_pid AND entry_type = 'SETTLE';
    if (sqlca.sqlcode < 0) FAIL(b);
    h_diff = h_exp - h_act;
    EXEC SQL SELECT nextval('rc_diff_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO rc_diff (diff_id, purchase_id, expected_amt, actual_amt, diff_amt, diff_kind, biz_date)
        VALUES (:h_id, :h_pid, :h_exp, :h_act, :h_diff, 'AMT', :h_bizdate);
    if (sqlca.sqlcode < 0) { userlog("RC_AMTDIFF INSERT FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); FAIL(b); }
    setl(b, T_DELTA, h_diff);
    OK(b);
}

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