/*
 * VL_BALANCE.pgc - vl 모듈 서비스 VL_BALANCE (one service = one file).
 * 기능: 가맹점 순액 대차 검증 (sum(purchase.net) vs sum(settlement.net)).
 * 기존 인라인 vl_svr.pgc에서 분리; caller의 XA 브랜치에서 실행(EXEC SQL CONNECT 없음).
 * vl_svr가 tpsvrinit에서 이 서비스를 tpadvertise 한다.
 */
#include "VL_BALANCE.h"

void VL_BALANCE(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char merch[64], bizdate[16];
    long rc = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pnet, h_snet;
    char h_merch[64], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    gets_(b, T_MERCHANT, merch, sizeof(merch));
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_merch, merch, sizeof(h_merch)-1); h_merch[sizeof(h_merch)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(sum(net),0) INTO :h_pnet FROM purchase
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate AND status = 'S';
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL SELECT coalesce(sum(net),0) INTO :h_snet FROM settlement
        WHERE merchant_id = :h_merch AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) FAIL(b);
    if (h_pnet != h_snet) rc = 1;
    setl(b, T_GROSS, h_pnet);
    setl(b, T_NET, h_snet);
    setl(b, T_DELTA, h_pnet - h_snet);
    setl(b, T_RC, rc);
    OK(b);
}
