/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/rc_ol_0011.pgc"
/* @tier medium @module rc @transform reconciliation-online */
/*
 * rc_ol_0011.pgc - 카드사별 대사 조회 (CURSOR) 온라인 서비스 (RC_OL_0011)
 *
 * 요청 BIZDATE(영업일) 의 원장을 카드번호 순으로 커서 순회하며, 카드번호
 * 접두(BIN, 카드사 식별자) 가 일치하는 건만 집계한다.
 * 업무규칙:
 *   - BIN 은 fetch 된 card_no 의 앞 strlen(BIN) 자리와 비교(전방일치)
 *   - 일치 건: 총건수(CNT), 금액합계(SUMAMT) 누적
 *   - 매입확정('M')/정산완료('S') 는 대사완료 건(MATCHED) 으로 누적
 *   - 대사율 RATE = MATCHED * 100 / CNT (0 나눗셈 방어)
 * 응답 BIN, CNT, MATCHED, SUMAMT, RATE 를 구성한다. (읽기 전용)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "rc_core.h"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 22 "app/online/rc_ol_0011.pgc"


TX_SERVICE(RC_OL_0011, ctx)
{
    /* exec sql begin declare section */
     
     
     
     
    
#line 27 "app/online/rc_ol_0011.pgc"
 char h_biz_date [ 9 ] ;
 
#line 28 "app/online/rc_ol_0011.pgc"
 char h_card_no [ 20 ] ;
 
#line 29 "app/online/rc_ol_0011.pgc"
 char h_status [ 2 ] ;
 
#line 30 "app/online/rc_ol_0011.pgc"
 long h_amount ;
/* exec sql end declare section */
#line 31 "app/online/rc_ol_0011.pgc"


    char bizdate[16];
    char bin[20];
    size_t binlen;
    long cnt = 0, matched = 0, sumamt = 0, rate = 0;
    int  opened = 0;

    tx_log(TX_LOG_INFO, "[RC_OL_0011] 카드사별 대사 조회 서비스 진입");

    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0011] BIZDATE 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "BIN", bin, sizeof(bin)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0011] BIN(카드사 식별 접두) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[RC_OL_0011] 영업일 오류 date=%s", bizdate);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    binlen = strlen(bin);
    if (binlen == 0) {
        tx_log(TX_LOG_WARN, "[RC_OL_0011] BIN 이 비어있음");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    memset(h_biz_date, 0, sizeof(h_biz_date));
    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);

    ECPGset_var( 0, ( h_biz_date ), __LINE__);\
 /* declare cur_rc_ol_0011 cursor for select card_no , status , amount from rc_ledger where biz_date = $1  order by card_no */
#line 71 "app/online/rc_ol_0011.pgc"

#line 71 "app/online/rc_ol_0011.pgc"


    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "declare cur_rc_ol_0011 cursor for select card_no , status , amount from rc_ledger where biz_date = $1  order by card_no", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 73 "app/online/rc_ol_0011.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_rc_ol_0011");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    opened = 1;

    for (;;) {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "fetch cur_rc_ol_0011", ECPGt_EOIT, 
	ECPGt_char,(h_card_no),(long)20,(long)1,(20)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_status),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_amount),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 83 "app/online/rc_ol_0011.pgc"


        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_rc_ol_0011");
            break;
        }

        /* 카드번호 전방일치: 앞 binlen 자리 비교 */
        if (strncmp(h_card_no, bin, binlen) != 0)
            continue;

        cnt++;
        sumamt += h_amount;
        if (strcmp(h_status, RC_ST_DONE) == 0 ||
            strcmp(h_status, RC_ST_SETTLED) == 0)
            matched++;
    }

    if (opened)
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_rc_ol_0011", ECPGt_EOIT, ECPGt_EORT);}
#line 104 "app/online/rc_ol_0011.pgc"


    rate = (cnt > 0) ? (matched * 100 / cnt) : 0;

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "BIN", bin);
    tx_buf_setlong(ctx->out, "CNT", cnt);
    tx_buf_setlong(ctx->out, "MATCHED", matched);
    tx_buf_setlong(ctx->out, "SUMAMT", sumamt);
    tx_buf_setlong(ctx->out, "RATE", rate);
    tx_log(TX_LOG_INFO,
           "[RC_OL_0011] 카드사별 집계 bin=%s 건수=%ld 완료=%ld 대사율=%ld%%",
           bin, cnt, matched, rate);
    tx_return(ctx, TX_OK, ctx->out);
}
