/*
 * lg_merch_having_dbio.pgc - lg 모듈 DB 접근 함수 (lg_merch_having_dbio), archived into liblgdbio.a.
 * 가맹점별 차변합과 대변합이 일치하지 않는 가맹점 수를 HAVING 으로 센다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_merch_having_dbio.h"

/* GROUP BY HAVING: 차/대 불일치 가맹점 수. */
long lgqdb_merch_imbalanced(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_cnt = 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_cnt FROM (
        SELECT merchant_id FROM lg_ledger_line WHERE biz_date = :h_bizdate
        GROUP BY merchant_id
        HAVING coalesce(sum(amount) FILTER (WHERE dc = 'D'),0)
             <> coalesce(sum(amount) FILTER (WHERE dc = 'C'),0)) m;
    if (sqlca.sqlcode < 0) { userlog("lgqdb_merch_imbalanced FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_cnt;
}
