/*
 * st_merchupsert_dbio.pgc - 가맹점 정산 집계 증분 upsert (st_merchupsert_dbio), libstdbio.a.
 * ECPG; 복합키 (merchant_id, biz_date) ON CONFLICT DO UPDATE 로 건수/총액/수수료/순액을 누적.
 */
#include <string.h>
#include <userlog.h>
#include "st_merchupsert_dbio.h"

int stdb_bump_merch(const char *merchant, const char *bizdate, long gross, long fee, long net)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_mid[32], h_bizdate[16];
    long h_g = gross, h_f = fee, h_n = net;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_mid, merchant, sizeof(h_mid)-1); h_mid[sizeof(h_mid)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL INSERT INTO st_merch_settle (merchant_id, biz_date, txn_count, gross_amount, fee_amount, net_amount)
        VALUES (:h_mid, :h_bizdate, 1, :h_g, :h_f, :h_n)
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET txn_count = st_merch_settle.txn_count + 1,
            gross_amount = st_merch_settle.gross_amount + EXCLUDED.gross_amount,
            fee_amount = st_merch_settle.fee_amount + EXCLUDED.fee_amount,
            net_amount = st_merch_settle.net_amount + EXCLUDED.net_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) { userlog("stdb_bump_merch FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return 0;
}
