/*
 * lg_recv_pay_gap_dbio.pgc - lg 모듈 DB 접근 함수 (lg_recv_pay_gap_dbio), archived into liblgdbio.a.
 * 미수(RECV) 차변 vs 미지급(MERCH_PAY) 대변 차액.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_recv_pay_gap_dbio.h"

/* RECV 차변합과 MERCH_PAY 대변합의 차액 (미결제 잔량 점검). */
int lgqdb_recv_pay_gap(const char *bizdate, long *recv, long *pay, long *gap)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_recv, h_pay;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT
        coalesce(sum(amount) FILTER (WHERE acct='RECV' AND dc='D'), 0),
        coalesce(sum(amount) FILTER (WHERE acct='MERCH_PAY' AND dc='C'), 0)
        INTO :h_recv, :h_pay FROM lg_ledger_line WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("lgqdb_recv_pay_gap FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    *recv = h_recv; *pay = h_pay; *gap = h_recv - h_pay;
    return 0;
}
