/* 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_0009.pgc"
/* @tier medium @module lg @transform ledger-online */
/*
 * lg_ol_0009.pgc - 원장 온라인 서비스 (LG_OL_0009)  [tier=medium]
 *
 * 계정별 집계 조회: 요청 가맹점(MERCHID)을 하나의 계정으로 보고
 * 해당 계정의 원장 총 건수, 총 거래금액(Σamount), 총 수수료(Σfee)를
 * 단일 집계 SELECT 로 산출한다. 여기에 정산완료(status='S') 금액과
 * 미정산(그 외) 금액을 분리 집계해 정산 진행 상태를 함께 보여주고,
 * 순매출(net = Σamount - Σfee)과 원화 표기를 응답한다 (조회 전용).
 *
 * 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_0009.pgc"


TX_SERVICE(LG_OL_0009, ctx)
{
    /* exec sql begin declare section */
     
     
      
     
     
     
    
#line 27 "app/online/lg_ol_0009.pgc"
 char h_merch_id [ 16 ] ;
 
#line 28 "app/online/lg_ol_0009.pgc"
 char h_st_settled [ 2 ] ;
 
#line 29 "app/online/lg_ol_0009.pgc"
 int h_cnt ;
 
#line 30 "app/online/lg_ol_0009.pgc"
 long h_sum_amt ;
 
#line 31 "app/online/lg_ol_0009.pgc"
 long h_sum_fee ;
 
#line 32 "app/online/lg_ol_0009.pgc"
 long h_settled_sum ;
/* exec sql end declare section */
#line 33 "app/online/lg_ol_0009.pgc"


    char merch[16];
    char wonbuf[32];
    long net = 0, unsettled = 0;

    tx_log(TX_LOG_INFO, "[LG_OL_0009] 계정별 집계 조회 서비스 진입");

    /* ---- 1. 요청 필드 수신 및 검증 ---- */
    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK ||
        merch[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[LG_OL_0009] 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. 단일 가맹점 계정 전체 집계 (singleton) ---- */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) , coalesce ( sum ( fee ) , 0 ) from lg_ledger where merch_id = $1 ", 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*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_amt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_sum_fee),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 60 "app/online/lg_ol_0009.pgc"


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

    if (h_cnt == 0) {
        /* 해당 가맹점 원장이 전혀 없음 */
        tx_log(TX_LOG_WARN, "[LG_OL_0009] 계정 원장 없음 merch=%s", merch);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_NOMERCH);
        tx_buf_sets(ctx->out, "MERCHID", merch);
        tx_buf_setlong(ctx->out, "CNT", 0);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }

    /* ---- 3. 정산완료(S) 금액 분리 집계 ---- */
    strncpy(h_st_settled, LG_ST_SETTLED, sizeof(h_st_settled) - 1);
    h_st_settled[sizeof(h_st_settled) - 1] = '\0';

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select 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_st_settled),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_settled_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 89 "app/online/lg_ol_0009.pgc"


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

    /* ---- 4. 파생값 산출 ---- */
    net       = h_sum_amt - h_sum_fee;      /* 순매출          */
    unsettled = h_sum_amt - h_settled_sum;  /* 미정산 잔여금액 */
    amount_format_won(net, wonbuf, sizeof(wonbuf));

    /* ---- 5. 응답 구성 ---- */
    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, "CNT", (long)h_cnt);
    tx_buf_setlong(ctx->out, "SUMAMT", h_sum_amt);
    tx_buf_setlong(ctx->out, "SUMFEE", h_sum_fee);
    tx_buf_setlong(ctx->out, "NETAMT", net);
    tx_buf_setlong(ctx->out, "SETTLED", h_settled_sum);
    tx_buf_setlong(ctx->out, "UNSETTLED", unsettled);
    tx_buf_sets(ctx->out, "NETWON", wonbuf);

    tx_log(TX_LOG_INFO,
           "[LG_OL_0009] 계정집계 merch=%s 건수=%d 금액=%ld 수수료=%ld 순액=%ld 미정산=%ld",
           merch, h_cnt, h_sum_amt, h_sum_fee, net, unsettled);
    tx_return(ctx, TX_OK, ctx->out);
}
