/* 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/ac_ol_0025.pgc"
/* @tier easy @module ac @transform acquire-online */
/*
 * ac_ol_0025.pgc - 매입 온라인 서비스 (AC_OL_0025)  [tier=easy]
 *
 * 미매입 추출: 지정 영업일(BIZDATE) 이전(포함)까지 누적된 미매입 접수
 * (ac_ledger.status='R') 건을 집계한다. 정산 배치 실행 전, 처리 대상
 * 잔여 건수/합계금액과 최장 대기 건(최소 key)을 파악하기 위한 조회
 * 전용 서비스이다.
 *
 * 조회기준일이 시스템 영업일보다 미래이면 업무상 비정상 조회로 보고
 * 경고 로그만 남기고 조회는 계속 진행한다(운영 모니터링 목적).
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "ac_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 21 "app/online/ac_ol_0025.pgc"


TX_SERVICE(AC_OL_0025, ctx)
{
    /* ---- ECPG 호스트 변수 선언부 ---- */
    /* exec sql begin declare section */
      
      
      
      
     
    
#line 27 "app/online/ac_ol_0025.pgc"
 char h_biz_date [ 9 ] ;
 
#line 28 "app/online/ac_ol_0025.pgc"
 long h_cnt ;
 
#line 29 "app/online/ac_ol_0025.pgc"
 long h_totamt ;
 
#line 30 "app/online/ac_ol_0025.pgc"
 char h_oldest [ 16 ] ;
 
#line 31 "app/online/ac_ol_0025.pgc"
 short h_oldest_ind ;
/* exec sql end declare section */
#line 32 "app/online/ac_ol_0025.pgc"


    char bizdate[9];
    char totbuf[32];

    tx_log(TX_LOG_INFO, "[AC_OL_0025] 미매입 추출 서비스 진입");

    /* ---- 1. 입력 검증 ---- */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK ||
        bizdate[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[AC_OL_0025] 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, "[AC_OL_0025] 영업일 형식 오류 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);

    /* ---- 2. 조회기준일 업무 정합성 점검 (참고용 경고, 조회는 계속 진행) ---- */
    {
        char today[9];

        date_today(today);
        if (strcmp(bizdate, today) > 0) {
            tx_log(TX_LOG_WARN,
                   "[AC_OL_0025] 조회기준일이 시스템 영업일보다 미래임 date=%s today=%s",
                   bizdate, today);
        }
    }

    /* ---- 3. 미매입 접수건 집계 (건수 + 합계금액) ---- */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( SUM ( amount ) , 0 ) from ac_ledger where biz_date <= $1  and status = 'R'", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_totamt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 77 "app/online/ac_ol_0025.pgc"


    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("SELECT ac_ledger 미매입 집계");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (sqlca.sqlcode == TX_SQL_NOTFOUND || h_cnt < 0) {
        h_cnt    = 0;
        h_totamt = 0;
    }

    /* ---- 4. 최장 대기 건(최소 key) 조회 ---- */
    memset(h_oldest, 0, sizeof(h_oldest));
    h_oldest_ind = -1;

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select MIN ( key ) from ac_ledger where biz_date <= $1  and status = 'R'", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_char,(h_oldest),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_short,&(h_oldest_ind),(long)1,(long)1,sizeof(short), ECPGt_EORT);}
#line 100 "app/online/ac_ol_0025.pgc"


    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("SELECT ac_ledger 최장대기건");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (h_oldest_ind < 0 || h_cnt == 0)
        h_oldest[0] = '\0';

    amount_format_won(h_totamt, totbuf, sizeof(totbuf));

    /* ---- 5. 응답 구성 ---- */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_setlong(ctx->out, "CNT", h_cnt);
    tx_buf_setlong(ctx->out, "TOTAMT", h_totamt);
    tx_buf_sets(ctx->out, "OLDEST", h_oldest);

    tx_log(TX_LOG_INFO,
           "[AC_OL_0025] 미매입 추출완료 date=%s 건수=%ld 합계=%s 최장대기=%s",
           bizdate, h_cnt, totbuf, h_oldest[0] ? h_oldest : "-");
    tx_return(ctx, TX_OK, ctx->out);
}
