/* 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/cl_ol_0010.pgc"
/* @tier easy @module cl @transform closing-online */
/*
 * cl_ol_0010.pgc - 마감 온라인 서비스 (CL_OL_0010)  [tier=easy]
 *
 * 마감 리포트 조회. 요청 영업일(BIZDATE)의 상태별 건수를 접수(R)/처리완료(M)/
 * 불일치(U)/정산완료(S) 각각 개별 SELECT 로 산출하여 리포트 형태로 응답한다.
 * 마감 진척률(정산완료/전체)도 함께 계산한다. (read-only)
 *
 * ── 서비스 계약(Contract) ────────────────────────────────────────────
 *  입력 필드:
 *    BIZDATE    (필수) 영업일(YYYYMMDD)
 *  출력 필드:
 *    RESPCODE   0000=정상 / 9001=입력오류 / 9999=시스템오류
 *    BIZDATE    리포트 대상 영업일
 *    CNTRECV    접수(R) 건수
 *    CNTDONE    처리완료(M) 건수
 *    CNTFAIL    불일치(U) 건수
 *    CNTSETTLED 정산완료(S) 건수
 *    CNTTOTAL   전체 건수(R+M+U+S)
 *    PROGRESS   마감 진척률(%) = 정산완료 / 전체 * 100
 *
 * ── 리포트 규칙 ──────────────────────────────────────────────────────
 *    · 상태코드 R/M/U/S 각각에 대해 개별 count SELECT 를 순회 수행한다.
 *    · 진척률은 전체 건이 0 일 때 0% 로 처리(0 나눗셈 방지)한다.
 *    · 마감 담당자의 일일 마감현황 대시보드 소스로 사용된다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cl_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 35 "app/online/cl_ol_0010.pgc"


TX_SERVICE(CL_OL_0010, ctx)
{
    /* exec sql begin declare section */
     
     
      
    
#line 40 "app/online/cl_ol_0010.pgc"
 char h_biz_date [ 9 ] ;
 
#line 41 "app/online/cl_ol_0010.pgc"
 char h_status [ 2 ] ;
 
#line 42 "app/online/cl_ol_0010.pgc"
 int h_cnt ;
/* exec sql end declare section */
#line 43 "app/online/cl_ol_0010.pgc"


    char bizdate[16];
    long cnt_r = 0, cnt_m = 0, cnt_u = 0, cnt_s = 0, total = 0;
    long remain = 0;
    long progress = 0;
    int  i;
    const char *codes = "RMUS";

    tx_log(TX_LOG_INFO, "[CL_OL_0010] 마감 리포트 조회 서비스 진입");

    /* 1. 요청 검증 */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0010] BIZDATE 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[CL_OL_0010] 영업일 형식 오류 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';

    /* 2. 상태코드별 개별 count SELECT (R/M/U/S 순회) */
    for (i = 0; i < 4; i++) {
        long v;
        h_status[0] = codes[i];
        h_status[1] = '\0';

        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cl_ledger where biz_date = $1  and status = $2 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*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_EOIT, 
	ECPGt_int,&(h_cnt),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 83 "app/online/cl_ol_0010.pgc"

        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("CL_OL_0010 status count");
            tx_buf_reset(ctx->out);
            tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }
        v = (long)h_cnt;
        switch (codes[i]) {
            case 'R': cnt_r = v; break;
            case 'M': cnt_m = v; break;
            case 'U': cnt_u = v; break;
            case 'S': cnt_s = v; break;
            default:  break;
        }
    }

    /* 3. 합계 / 미정산 잔여(R+M+U) / 진척률(%) 계산 */
    total = cnt_r + cnt_m + cnt_u + cnt_s;
    remain = cnt_r + cnt_m + cnt_u;
    progress = (total > 0) ? (cnt_s * 100 / total) : 0;

    /* 4. 리포트 응답 구성 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_setlong(ctx->out, "CNTRECV", cnt_r);
    tx_buf_setlong(ctx->out, "CNTDONE", cnt_m);
    tx_buf_setlong(ctx->out, "CNTFAIL", cnt_u);
    tx_buf_setlong(ctx->out, "CNTSETTLED", cnt_s);
    tx_buf_setlong(ctx->out, "CNTTOTAL", total);
    tx_buf_setlong(ctx->out, "CNTREMAIN", remain);
    tx_buf_setlong(ctx->out, "PROGRESS", progress);
    tx_buf_sets(ctx->out, "COMPLETED", (remain == 0 && total > 0) ? "Y" : "N");
    tx_log(TX_LOG_INFO,
           "[CL_OL_0010] 리포트 date=%s R=%ld M=%ld U=%ld S=%ld 진척=%ld%%",
           bizdate, cnt_r, cnt_m, cnt_u, cnt_s, progress);
    tx_return(ctx, TX_OK, ctx->out);
}
