/*
 * vl_apprsum_batch.pgc - 일자별 매입-승인 금액 대사 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 취소 제외 매입 총액과 가결 승인이 붙은 매입 총액을 대조한 뒤
 * tpcommit drives XA 2PC.
 * Usage: vl_apprsum_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_apprsum_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : VL_APPRSUM_DEF_DATE;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_all, h_appr;
    EXEC SQL END DECLARE SECTION;
    vl_apprsum_rec_t rec;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_all FROM purchase
        WHERE biz_date = :h_bizdate AND status <> 'C';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_apprsum_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    EXEC SQL SELECT coalesce(sum(p.amount),0) INTO :h_appr FROM purchase p
        WHERE p.biz_date = :h_bizdate AND p.status <> 'C'
          AND EXISTS (SELECT 1 FROM approval a
                      WHERE a.purchase_id = p.purchase_id AND a.approved);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_apprsum_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    rec.total_amt = h_all; rec.appr_amt = h_appr; rec.gap_amt = h_all - h_appr;
    printf(">>> vl_apprsum_batch COMMIT: bizdate=%s 매입총액=%ld 승인보유=%ld 미승인=%ld\n",
           bizdate, rec.total_amt, rec.appr_amt, rec.gap_amt);

    tpclose(); tpterm();
    return 0;
}
