/*
 * ac_settle_join_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_settle_join_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: purchase p JOIN settlement s ON p.purchase_id=s.purchase_id 집계.
 */
#include <string.h>
#include <userlog.h>
#include "ac_settle_join_dbio.h"

/* 특정 가맹점의 정산 완료된 매입 net 합계 (조인 기준 매입측 net). */
long acdb_settled_net_by_merchant(const char *merch, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[64], h_bizdate[16];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    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(p.net),0) INTO :h_v
        FROM purchase p JOIN settlement s ON p.purchase_id = s.purchase_id
        WHERE p.merchant_id = :h_merch AND s.biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}

/* 당일 정산행과 매입행이 조인 매칭된 건수. */
long acdb_settled_match_count(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT count(*) INTO :h_v
        FROM settlement s JOIN purchase p ON s.purchase_id = p.purchase_id
        WHERE s.biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}
