/* 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_0012.pgc"
/* @tier easy @module lg @transform ledger-online */
/*
 * lg_ol_0012.pgc - 원장 온라인 서비스 (LG_OL_0012)  [tier=easy]
 *
 * 미결원장 조회: 요청 가맹점(MERCHID)의 미결 상태 원장을 집계한다.
 * 미결이란 접수(status='R') 또는 불일치/실패(status='U') 상태로,
 * 아직 확정/정산으로 넘어가지 못한 건을 뜻한다. 접수 미결과 실패
 * 미결을 각각 구분 집계하고, 두 상태를 합한 전체 미결 건수/금액과
 * 원화 표기 문자열을 함께 응답한다 (조회 전용).
 *
 * TxCore TX_SERVICE 엔트리. 요청 TXBUF 를 검증하고 lg_ledger 에
 * 직접 임베디드 SQL(singleton 집계) 을 수행한 뒤 응답을 구성한다.
 */
#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 22 "app/online/lg_ol_0012.pgc"


TX_SERVICE(LG_OL_0012, ctx)
{
    /* exec sql begin declare section */
     
     
      
     
    
#line 27 "app/online/lg_ol_0012.pgc"
 char h_merch_id [ 16 ] ;
 
#line 28 "app/online/lg_ol_0012.pgc"
 char h_status [ 2 ] ;
 
#line 29 "app/online/lg_ol_0012.pgc"
 int h_cnt ;
 
#line 30 "app/online/lg_ol_0012.pgc"
 long h_sum ;
/* exec sql end declare section */
#line 31 "app/online/lg_ol_0012.pgc"


    char merch[16];
    char wonbuf[32];
    long recv_cnt = 0, recv_sum = 0;
    long fail_cnt = 0, fail_sum = 0;
    long open_cnt = 0, open_sum = 0;
    long open_avg = 0;

    tx_log(TX_LOG_INFO, "[LG_OL_0012] 미결원장 조회 서비스 진입");

    /* ---- 1. 요청 필드 수신 및 검증 ---- */
    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK ||
        merch[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[LG_OL_0012] MERCHID 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_merch_id, merch, sizeof(h_merch_id) - 1);
    h_merch_id[sizeof(h_merch_id) - 1] = '\0';

    /* ---- 2. 접수(R) 미결 집계 ---- */
    strncpy(h_status, LG_ST_RECV, sizeof(h_status) - 1);
    h_status[sizeof(h_status) - 1] = '\0';

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) from lg_ledger where merch_id = $1  and status = $2 ", 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*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_long,&(h_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 63 "app/online/lg_ol_0012.pgc"


    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("LG_OL_0012 recv");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    recv_cnt = (long)h_cnt;
    recv_sum = h_sum;

    /* ---- 3. 불일치/실패(U) 미결 집계 ---- */
    strncpy(h_status, LG_ST_FAIL, sizeof(h_status) - 1);
    h_status[sizeof(h_status) - 1] = '\0';

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) from lg_ledger where merch_id = $1  and status = $2 ", 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*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_long,&(h_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 83 "app/online/lg_ol_0012.pgc"


    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("LG_OL_0012 fail");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    fail_cnt = (long)h_cnt;
    fail_sum = h_sum;

    /* ---- 4. 전체 미결 합산, 건당 평균, 원화 표기 ---- */
    open_cnt = recv_cnt + fail_cnt;
    open_sum = recv_sum + fail_sum;
    if (open_cnt > 0)
        open_avg = open_sum / open_cnt;   /* 미결 건당 평균금액 */
    amount_format_won(open_sum, wonbuf, sizeof(wonbuf));

    /* ---- 5. 응답 구성 (미결 0건도 정상 응답) ---- */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "MERCHID", merch);
    tx_buf_setlong(ctx->out, "RECVCNT", recv_cnt);
    tx_buf_setlong(ctx->out, "RECVSUM", recv_sum);
    tx_buf_setlong(ctx->out, "FAILCNT", fail_cnt);
    tx_buf_setlong(ctx->out, "FAILSUM", fail_sum);
    tx_buf_setlong(ctx->out, "OPENCNT", open_cnt);
    tx_buf_setlong(ctx->out, "OPENSUM", open_sum);
    tx_buf_setlong(ctx->out, "OPENAVG", open_avg);
    tx_buf_sets(ctx->out, "OPENWON", wonbuf);
    tx_buf_sets(ctx->out, "HASOPEN", (open_cnt > 0) ? "Y" : "N");

    tx_log(TX_LOG_INFO,
           "[LG_OL_0012] 미결조회 merch=%s 접수=%ld건 실패=%ld건 계=%ld건 금액=%s",
           merch, recv_cnt, fail_cnt, open_cnt, wonbuf);
    tx_return(ctx, TX_OK, ctx->out);
}
