/* 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_0018.pgc"
/* @tier hard @module cl @transform closing-online */
/*
 * cl_ol_0018.pgc - 마감 온라인 서비스 (CL_OL_0018)  [tier=hard]
 *
 * 마감 집계 반영: 요청 영업일(BIZDATE)의 원장 전체를 Σamount/count 로
 * 집계한 뒤, 그 결과를 집계요약행으로 원장에 반영한다. 요약행은
 * merch_id='*AGG', key=BIZDATE+"AG", status='S'(정산완료) 로 식별하며
 * amount 에 합계금액, fee 에 집계건수를 적재한다. 이미 요약행이 있으면
 * 재집계값으로 UPDATE, 없으면 INSERT 하는 멱등 upsert 로 처리한다.
 * 집계 조회 + 반영은 하나의 트랜잭션으로 커밋한다.
 */
#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 20 "app/online/cl_ol_0018.pgc"


TX_SERVICE(CL_OL_0018, ctx)
{
    /* exec sql begin declare section */
     
     
     
      
      
    
#line 25 "app/online/cl_ol_0018.pgc"
 char h_biz_date [ 9 ] ;
 
#line 26 "app/online/cl_ol_0018.pgc"
 char h_agg_key [ 16 ] ;
 
#line 27 "app/online/cl_ol_0018.pgc"
 long h_sum ;
 
#line 28 "app/online/cl_ol_0018.pgc"
 int h_cnt ;
 
#line 29 "app/online/cl_ol_0018.pgc"
 int h_exist ;
/* exec sql end declare section */
#line 30 "app/online/cl_ol_0018.pgc"


    char bizdate[16];

    tx_log(TX_LOG_INFO, "[CL_OL_0018] 마감 집계 반영 서비스 진입");

    /* 1) 입력 수신 및 검증 */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0018] 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_0018] 영업일 형식 오류 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    memset(h_biz_date, 0, sizeof(h_biz_date));
    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);

    /* 집계 요약행 키 = 영업일 + "AG" (실집계 대상에서 요약행은 제외) */
    snprintf(h_agg_key, sizeof(h_agg_key), "%.8sAG", h_biz_date);

    /* 2) 트랜잭션 시작 */
    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0018] 트랜잭션 시작 실패");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 3) 당일 실거래 집계 (요약행 '*AGG' 는 제외) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select coalesce ( sum ( amount ) , 0 ) , count ( * ) from cl_ledger where biz_date = $1  and merch_id <> '*AGG'", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_int,&(h_cnt),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 72 "app/online/cl_ol_0018.pgc"


    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("cl_ol_0018 집계");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 4) 기존 집계요약행 존재 여부 확인 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cl_ledger where key = $1 ", 
	ECPGt_char,(h_agg_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_int,&(h_exist),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 87 "app/online/cl_ol_0018.pgc"


    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("cl_ol_0018 요약존재확인");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 5) 멱등 upsert: 있으면 갱신, 없으면 삽입 (금액=합계, 수수료=건수) */
    if (h_exist > 0) {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update cl_ledger set amount = $1  , fee = $2  , status = 'S' , upd_ts = now ( ) where key = $3 ", 
	ECPGt_long,&(h_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_int,&(h_cnt),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_agg_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 102 "app/online/cl_ol_0018.pgc"

    } else {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into cl_ledger ( key , merch_id , card_no , amount , biz_date , status , fee ) values ( $1  , '*AGG' , '*AGGREGATE*' , $2  , $3  , 'S' , $4  )", 
	ECPGt_char,(h_agg_key),(long)16,(long)1,(16)*sizeof(char), 
	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_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_int,&(h_cnt),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 107 "app/online/cl_ol_0018.pgc"

    }

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("cl_ol_0018 요약반영");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_commit();

    /* 6) 응답 구성 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_sets(ctx->out, "AGGKEY", h_agg_key);
    tx_buf_setlong(ctx->out, "AGGCNT", (long)h_cnt);
    tx_buf_setlong(ctx->out, "AGGSUM", h_sum);
    tx_buf_sets(ctx->out, "AGGMODE", h_exist > 0 ? "UPDATE" : "INSERT");

    tx_log(TX_LOG_INFO, "[CL_OL_0018] 집계반영 완료 date=%s 건수=%d 합계=%ld mode=%s",
           bizdate, h_cnt, h_sum, h_exist > 0 ? "UPDATE" : "INSERT");
    tx_return(ctx, TX_OK, ctx->out);
}
