/* 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/mg_ol_0032.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0032.pgc - 전문게이트웨이 전문 라우팅 통계 조회 서비스 (MG_OL_0032)  [tier=medium]
 *
 * 지정 영업일(BIZDATE)의 처리원장(mg_ledger)을 채널코드(chan_cd)별로 집계
 * (count GROUP BY)하여 채널 수·총 전문건수·최다 처리채널(상위채널)을 산출한다.
 * 커서로 집계결과를 순회하며 최상위 채널을 선별해 응답한다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "mg_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 18 "app/online/mg_ol_0032.pgc"


TX_SERVICE(MG_OL_0032, ctx)
{
    /* exec sql begin declare section */
     
     
     
    
#line 23 "app/online/mg_ol_0032.pgc"
 char h_biz_date [ 9 ] ;
 
#line 24 "app/online/mg_ol_0032.pgc"
 char h_chan_cd [ 9 ] ;
 
#line 25 "app/online/mg_ol_0032.pgc"
 long h_chan_cnt ;
/* exec sql end declare section */
#line 26 "app/online/mg_ol_0032.pgc"


    char bizdate[16];
    char top_chan[9];
    long top_cnt = 0, total_cnt = 0, chan_num = 0;

    tx_log(TX_LOG_INFO, "[MG_OL_0032] 전문 라우팅 통계 조회 서비스 진입");

    /* 1) 집계 대상 영업일 수신/검증 */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0032] BIZDATE 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[MG_OL_0032] 영업일 형식 오류 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", 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';
    memset(top_chan, 0, sizeof(top_chan));

    /* 2) 채널별 전문건수 집계 커서 (건수 내림차순) */
    ECPGset_var( 0, ( h_biz_date ), __LINE__);\
 /* declare cur_mg_ol_0032 cursor for select chan_cd , count ( * ) from mg_ledger where biz_date = $1  group by chan_cd order by count ( * ) desc */
#line 58 "app/online/mg_ol_0032.pgc"

#line 58 "app/online/mg_ol_0032.pgc"


    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "declare cur_mg_ol_0032 cursor for select chan_cd , count ( * ) from mg_ledger where biz_date = $1  group by chan_cd order by count ( * ) desc", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 60 "app/online/mg_ol_0032.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_mg_ol_0032");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 3) 집계결과 순회: 총건수 누적 + 최상위 채널 선별 */
    for (;;) {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "fetch cur_mg_ol_0032", ECPGt_EOIT, 
	ECPGt_char,(h_chan_cd),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_chan_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 71 "app/online/mg_ol_0032.pgc"

        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_mg_ol_0032");
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_mg_ol_0032", ECPGt_EOIT, ECPGt_EORT);}
#line 76 "app/online/mg_ol_0032.pgc"

            tx_buf_reset(ctx->out);
            tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }

        total_cnt += h_chan_cnt;
        chan_num++;
        if (h_chan_cnt > top_cnt) {
            top_cnt = h_chan_cnt;
            strncpy(top_chan, h_chan_cd, sizeof(top_chan) - 1);
            top_chan[sizeof(top_chan) - 1] = '\0';
        }
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_mg_ol_0032", ECPGt_EOIT, ECPGt_EORT);}
#line 92 "app/online/mg_ol_0032.pgc"


    /* 4) 집계대상 없음 처리 */
    if (chan_num == 0) {
        tx_log(TX_LOG_INFO, "[MG_OL_0032] 집계대상 없음 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_OK);
        tx_buf_sets(ctx->out, "BIZDATE", bizdate);
        tx_buf_setlong(ctx->out, "CHANNUM", 0);
        tx_buf_setlong(ctx->out, "TOTALCNT", 0);
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* 5) 통계결과 응답 (상위채널 포함) */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_setlong(ctx->out, "CHANNUM", chan_num);
    tx_buf_setlong(ctx->out, "TOTALCNT", total_cnt);
    tx_buf_sets(ctx->out, "TOPCHAN", top_chan);
    tx_buf_setlong(ctx->out, "TOPCNT", top_cnt);
    tx_log(TX_LOG_INFO, "[MG_OL_0032] 통계완료 date=%s 채널수=%ld 총건수=%ld 상위채널=%s(%ld)",
           bizdate, chan_num, total_cnt, top_chan, top_cnt);
    tx_return(ctx, TX_OK, ctx->out);
}
