/*
 * lg_dc_ratio_dbio.pgc - lg 모듈 DB 접근 함수 (lg_dc_ratio_dbio), archived into liblgdbio.a.
 * 당일 대변합이 차변합에서 차지하는 비율(퍼센트)을 산출한다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_dc_ratio_dbio.h"

/* 대차 비율(%): 대변합 * 100 / 차변합, CASE 로 0 나눗셈 방지. */
long lgqdb_credit_debit_pct(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pct = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT CASE WHEN coalesce(sum(amount) FILTER (WHERE dc = 'D'),0) > 0
                         THEN coalesce(sum(amount) FILTER (WHERE dc = 'C'),0) * 100
                              / sum(amount) FILTER (WHERE dc = 'D')
                         ELSE 0 END
        INTO :h_pct FROM lg_ledger_line WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("lgqdb_credit_debit_pct FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_pct;
}
