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

/* ========================================================================= */
void SETTLE(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char merch[64], bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pid, h_sid, h_net;
    char h_merch[64], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    h_pid = getl(b, T_PURCHASE_ID);
    h_net = getl(b, T_NET);
    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 nextval('settlement_seq') INTO :h_sid;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO settlement (settlement_id, purchase_id, merchant_id, net, biz_date, status)
        VALUES (:h_sid, :h_pid, :h_merch, :h_net, :h_bizdate, 'SETTLED');
    if (sqlca.sqlcode < 0) { userlog("SETTLE INSERT settlement FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); FAIL(b); }
    EXEC SQL INSERT INTO ledger (ledger_id, purchase_id, entry_type, amount, biz_date)
        VALUES (nextval('ledger_seq'), :h_pid, 'SETTLE', :h_net, :h_bizdate);
    if (sqlca.sqlcode < 0) FAIL(b);

    setl(b, T_SETTLE_ID, h_sid);
    Bchg(b, T_STATUS, 0, "S", 0L);
    userlog("SETTLE pid=%ld settlement_id=%ld net=%ld", h_pid, h_sid, h_net);
    OK(b);
}

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