/* 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/lg_ol_0026.pgc"
/* @tier easy @module lg @transform ledger-online */
/*
 * lg_ol_0026.pgc - 원장 온라인 서비스 (LG_OL_0026)  [tier=easy]
 *
 * 금액구간 통계: 지정 영업일에서 기준금액(THRESHOLD) 이상 구간과 미만 구간의
 * 건수/합계를 각각 집계 SELECT 로 산출하여 응답한다. (조회 전용)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "lg_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 16 "app/online/lg_ol_0026.pgc"


/*
 * [업무 개요]
 *   이상거래 모니터링/리스크 부서가 특정 영업일의 매출 분포를 파악할 때,
 *   기준금액(THRESHOLD) 을 경계로 고액구간과 소액구간의 건수·합계를 한 번에
 *   조회한다. 예: 100만원 이상 고액 승인건이 몇 건/얼마인지 즉시 확인.
 *
 * [구간 정의]
 *   고액구간(HI) : amount >= THRESHOLD
 *   소액구간(LO) : amount <  THRESHOLD
 *   (두 구간은 상호배타적이므로 HICNT + LOCNT = 당일 전표 총건수)
 *
 * [처리 절차]
 *   1) BIZDATE, THRESHOLD 추출 및 검증(음수 기준금액 불가).
 *   2) 고액구간 집계 SELECT (count, sum).
 *   3) 소액구간 집계 SELECT (count, sum).
 *   4) 두 구간 결과를 응답 TXBUF 로 구성.
 *
 * [응답 필드]
 *   RESPCODE  처리결과코드
 *   BIZDATE   대상 영업일(에코)
 *   THRESHOLD 구간 기준금액(에코)
 *   HICNT     고액구간 건수
 *   HISUM     고액구간 합계
 *   LOCNT     소액구간 건수
 *   LOSUM     소액구간 합계
 *
 * [주의]
 *   조회 전용. 집계이므로 결과 없음(NOTFOUND) 도 coalesce/count 로 0 이 보장.
 */
TX_SERVICE(LG_OL_0026, ctx)
{
    /* exec sql begin declare section */
     
     
     
     
     
     
    
#line 50 "app/online/lg_ol_0026.pgc"
 char h_biz_date [ 9 ] ;
 
#line 51 "app/online/lg_ol_0026.pgc"
 long h_threshold ;
 
#line 52 "app/online/lg_ol_0026.pgc"
 long h_hi_cnt ;
 
#line 53 "app/online/lg_ol_0026.pgc"
 long h_hi_sum ;
 
#line 54 "app/online/lg_ol_0026.pgc"
 long h_lo_cnt ;
 
#line 55 "app/online/lg_ol_0026.pgc"
 long h_lo_sum ;
/* exec sql end declare section */
#line 56 "app/online/lg_ol_0026.pgc"


    char bizdate[16];
    long threshold = 0;

    tx_log(TX_LOG_INFO, "[LG_OL_0026] 금액구간 통계 진입");

    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[LG_OL_0026] BIZDATE 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    tx_buf_getlong(ctx->in, "THRESHOLD", &threshold);

    if (!date_is_valid(bizdate) || threshold < 0) {
        tx_log(TX_LOG_WARN, "[LG_OL_0026] 입력 검증 실패 date=%s threshold=%ld",
               bizdate, threshold);
        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';
    h_threshold = threshold;

    /* 기준금액 이상 구간 집계 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) from lg_ledger where biz_date = $1  and amount >= $2 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_threshold),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_hi_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_hi_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 90 "app/online/lg_ol_0026.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("lg_ol_0026 high");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 기준금액 미만 구간 집계 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) from lg_ledger where biz_date = $1  and amount < $2 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_threshold),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_lo_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_lo_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 104 "app/online/lg_ol_0026.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("lg_ol_0026 low");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    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, "THRESHOLD", threshold);
    tx_buf_setlong(ctx->out, "HICNT", h_hi_cnt);
    tx_buf_setlong(ctx->out, "HISUM", h_hi_sum);
    tx_buf_setlong(ctx->out, "LOCNT", h_lo_cnt);
    tx_buf_setlong(ctx->out, "LOSUM", h_lo_sum);
    tx_log(TX_LOG_INFO, "[LG_OL_0026] 구간통계 date=%s 이상=%ld/%ld 미만=%ld/%ld",
           bizdate, h_hi_cnt, h_hi_sum, h_lo_cnt, h_lo_sum);
    tx_return(ctx, TX_OK, ctx->out);
}
