/* 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_0030.pgc"
/* @tier easy @module lg @transform ledger-online */
/*
 * lg_ol_0030.pgc - 원장 온라인 서비스 (LG_OL_0030)  [tier=easy]
 *
 * 매출 집계반영: 지정 영업일의 실거래(요약행 제외) Σamount/건수를 집계하여
 * 요약행(key=영업일, merch_id='*SUMMARY', status=S) 을 새로 INSERT 한다.
 */
#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_0030.pgc"


#define LG_OL_0030_SUMMARY_ID "*SUMMARY"

/*
 * [업무 개요]
 *   특정 영업일의 실거래 매출을 집계하여 원장에 "요약행" 한 건으로 반영한다.
 *   요약행은 merch_id='*SUMMARY', status='S', key=영업일 규칙을 따르며, 집계
 *   시에는 기존 요약행을 제외하여 이중집계를 방지한다.
 *
 * [멱등성]
 *   같은 영업일에 재실행되어도 결과가 동일하도록, 기존 요약행(key=영업일) 을
 *   먼저 DELETE 한 뒤 새 요약행을 INSERT 한다. (delete-then-insert)
 *
 * [처리 절차]
 *   1) BIZDATE 추출/검증.
 *   2) 실거래(merch_id<>'*SUMMARY') Σamount/건수 집계.
 *   3) tx_begin → 기존 요약행 DELETE → 신규 요약행 INSERT → tx_commit.
 *
 * [응답 필드]
 *   RESPCODE  처리결과코드   BIZDATE 영업일(에코)   SUMKEY 요약행 key
 *   TOTAL     집계 합계금액   CNT 집계 대상 건수
 */
TX_SERVICE(LG_OL_0030, ctx)
{
    /* exec sql begin declare section */
     
     
     
     
     
     
    
#line 42 "app/online/lg_ol_0030.pgc"
 char h_biz_date [ 9 ] ;
 
#line 43 "app/online/lg_ol_0030.pgc"
 char h_sum_id [ 16 ] ;
 
#line 44 "app/online/lg_ol_0030.pgc"
 char h_status_s [ 2 ] ;
 
#line 45 "app/online/lg_ol_0030.pgc"
 char h_key [ 16 ] ;
 
#line 46 "app/online/lg_ol_0030.pgc"
 long h_total ;
 
#line 47 "app/online/lg_ol_0030.pgc"
 long h_cnt ;
/* exec sql end declare section */
#line 48 "app/online/lg_ol_0030.pgc"


    char bizdate[16];

    tx_log(TX_LOG_INFO, "[LG_OL_0030] 매출 집계반영 진입");

    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[LG_OL_0030] 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, "[LG_OL_0030] 영업일 형식 오류 date=%s", bizdate);
        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';
    strncpy(h_sum_id, LG_OL_0030_SUMMARY_ID, sizeof(h_sum_id) - 1);
    h_sum_id[sizeof(h_sum_id) - 1] = '\0';
    strncpy(h_status_s, LG_ST_SETTLED, sizeof(h_status_s) - 1);
    h_status_s[sizeof(h_status_s) - 1] = '\0';
    strncpy(h_key, bizdate, sizeof(h_key) - 1);   /* 요약행 key = 영업일 */
    h_key[sizeof(h_key) - 1] = '\0';

    /* 실거래만 집계 (요약행 자체는 제외) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select coalesce ( sum ( amount ) , 0 ) , count ( * ) from lg_ledger where biz_date = $1  and merch_id <> $2 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_sum_id),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_total),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 83 "app/online/lg_ol_0030.pgc"

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

    if (tx_begin() != TX_OK) {
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 기존 요약행 제거 후 재삽입 (멱등) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "delete from lg_ledger where key = $1 ", 
	ECPGt_char,(h_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 98 "app/online/lg_ol_0030.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("lg_ol_0030 delete old");
        tx_abort();
        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, "insert into lg_ledger ( key , merch_id , card_no , amount , biz_date , status , fee ) values ( $1  , $2  , '' , $3  , $4  , $5  , 0 )", 
	ECPGt_char,(h_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_sum_id),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_total),(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_char,(h_status_s),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 111 "app/online/lg_ol_0030.pgc"

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

    if (tx_commit() != TX_OK) {
        tx_abort();
        tx_return(ctx, TX_FAIL, 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_sets(ctx->out, "SUMKEY", h_key);
    tx_buf_setlong(ctx->out, "TOTAL", h_total);
    tx_buf_setlong(ctx->out, "CNT", h_cnt);
    tx_log(TX_LOG_INFO, "[LG_OL_0030] 집계반영 완료 date=%s 합계=%ld 건수=%ld",
           bizdate, h_total, h_cnt);
    tx_return(ctx, TX_OK, ctx->out);
}
