/*
 * PAY_FILEGEN.pgc - py 모듈 서비스 PAY_FILEGEN (one service = one file).
 * 지급 파일 헤더 생성: 당일 승인(A) 지급건 집계 -> py_file.
 * Moved verbatim from the former inline py_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by py_svr at tpsvrinit.
 */
#include "PAY_FILEGEN.h"

void PAY_FILEGEN(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char bizdate[16], fname[64];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_cnt, h_sum;
    char h_bizdate[16], h_fname[64];
    EXEC SQL END DECLARE SECTION;

    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 count(*), coalesce(sum(net),0) INTO :h_cnt, :h_sum
        FROM py_payout WHERE biz_date = :h_bizdate AND status = 'A';
    if (sqlca.sqlcode < 0) FAIL(b);
    snprintf(fname, sizeof(fname), "PAYOUT_%s.dat", bizdate);
    strncpy(h_fname, fname, sizeof(h_fname)-1); h_fname[sizeof(h_fname)-1] = 0;
    EXEC SQL SELECT nextval('py_file_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) FAIL(b);
    EXEC SQL INSERT INTO py_file (file_id, biz_date, file_name, record_count, total_amount, status)
        VALUES (:h_id, :h_bizdate, :h_fname, :h_cnt, :h_sum, 'G');
    if (sqlca.sqlcode < 0) FAIL(b);
    setl(b, T_ID2, h_id);
    setl(b, T_COUNT, h_cnt);
    setl(b, T_GROSS, h_sum);
    Bchg(b, T_STR1, 0, fname, 0L);
    userlog("PAY_FILEGEN file_id=%ld name=%s recs=%ld amt=%ld", h_id, fname, h_cnt, h_sum);
    OK(b);
}
