/*
 * st_ratejoin_dbio.pgc - 구간 요율 적용 (st_ratejoin_dbio), libstdbio.a.
 * ECPG; st_settle_dtl 를 st_fee_rate 와 fee_type + band_min 조건으로 조인, 커서로 요율 적용액 합.
 */
#include <string.h>
#include <userlog.h>
#include "st_ratejoin_dbio.h"

long stdb_apply_band_rate(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ft[16];
    long h_amt, h_bps, total = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE rjc CURSOR FOR
        SELECT d.fee_type, d.amount, r.rate_bps
        FROM st_settle_dtl d
        JOIN st_fee_rate r ON r.fee_type = d.fee_type AND d.amount >= r.band_min
        WHERE d.biz_date = :h_bizdate
        ORDER BY d.dtl_id;
    EXEC SQL OPEN rjc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH rjc INTO :h_ft, :h_amt, :h_bps;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rjc; return -1; }
        total += h_amt * h_bps / 10000;
    }
    EXEC SQL CLOSE rjc;
    return total;
}
