/*
 * ST_BYMERCH.pgc - st 모듈 서비스 ST_BYMERCH (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 "ST_BYMERCH.h"

/* 15. ST_BYMERCH - 가맹점별 정산 집계 upsert (dbio). */
void ST_BYMERCH(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char merch[64], bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt, h_gross, h_fee, h_net;
    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 count(*), coalesce(sum(p.amount),0), coalesce(sum(p.fee),0), coalesce(sum(s.net),0)
        INTO :h_cnt, :h_gross, :h_fee, :h_net
        FROM settlement s JOIN purchase p ON p.purchase_id = s.purchase_id
        WHERE s.merchant_id = :h_merch AND s.biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) FAIL(b);
    if (stdb_upsert_merch_settle(merch, bizdate, h_gross, h_fee, h_net, h_cnt) < 0) FAIL(b);
    setl(b, T_COUNT, h_cnt); setl(b, T_GROSS, h_gross);
    OK(b);
}

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