/* 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_0009.pgc"
/* @tier hard @module cl @transform closing-online */
/*
 * cl_ol_0009.pgc - 마감 온라인 서비스 (CL_OL_0009)  [tier=hard]
 *
 * 마감 순번 채번(採番). 요청 영업일(BIZDATE)에 대해 기존 마감완료(S) 건수를
 * 세어 다음 마감 순번(next = 기존건수 + 1)을 산출한다. 아울러 원장 전체
 * max(key) 기반 채번 참조값도 함께 조회하여, 영업일+순번 형식의 채번키를
 * 생성해 반환한다. 실제 원장을 변경하지 않는 read-only 채번 서비스이다.
 */
#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 18 "app/online/cl_ol_0009.pgc"


TX_SERVICE(CL_OL_0009, ctx)
{
    /* exec sql begin declare section */
     
      
      
     
     
    
#line 23 "app/online/cl_ol_0009.pgc"
 char h_biz_date [ 9 ] ;
 
#line 24 "app/online/cl_ol_0009.pgc"
 int h_settled_cnt ;
 
#line 25 "app/online/cl_ol_0009.pgc"
 int h_all_cnt ;
 
#line 26 "app/online/cl_ol_0009.pgc"
 char h_max_key [ 16 ] ;
 
#line 27 "app/online/cl_ol_0009.pgc"
 short h_maxkey_ind ;
/* exec sql end declare section */
#line 28 "app/online/cl_ol_0009.pgc"


    char bizdate[16];
    long next_seq = 0;
    char seq_key[24];
    char maxkey_out[16];

    tx_log(TX_LOG_INFO, "[CL_OL_0009] 마감 순번 채번 서비스 진입");

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

    /* 2. 당일 기존 마감완료(S) 건수 채번 기준 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cl_ledger where biz_date = $1  and status = 'S'", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_int,&(h_settled_cnt),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 61 "app/online/cl_ol_0009.pgc"

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

    /* 3. 당일 전체 건수 (참조 지표) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cl_ledger where biz_date = $1 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_int,&(h_all_cnt),(long)1,(long)1,sizeof(int), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 74 "app/online/cl_ol_0009.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0009 all count");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 4. 당일 max(key) 참조 (없으면 널 → indicator 로 감지) */
    h_maxkey_ind = 0;
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select max ( key ) from cl_ledger where biz_date = $1 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_char,(h_max_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_short,&(h_maxkey_ind),(long)1,(long)1,sizeof(short), ECPGt_EORT);}
#line 88 "app/online/cl_ol_0009.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("CL_OL_0009 max key");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (h_maxkey_ind < 0) {
        strncpy(maxkey_out, "(none)", sizeof(maxkey_out) - 1);
        maxkey_out[sizeof(maxkey_out) - 1] = '\0';
    } else {
        h_max_key[sizeof(h_max_key) - 1] = '\0';
        strncpy(maxkey_out, h_max_key, sizeof(maxkey_out) - 1);
        maxkey_out[sizeof(maxkey_out) - 1] = '\0';
    }

    /* 5. 다음 순번 = 기존 마감건수 + 1, 채번키 = 영업일+순번(4자리) */
    next_seq = (long)h_settled_cnt + 1;
    snprintf(seq_key, sizeof(seq_key), "%.8s%04ld", h_biz_date, next_seq);

    /* 6. 응답 구성 (read-only) */
    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, "SETTLEDCNT", (long)h_settled_cnt);
    tx_buf_setlong(ctx->out, "ALLCNT", (long)h_all_cnt);
    tx_buf_setlong(ctx->out, "NEXTSEQ", next_seq);
    tx_buf_sets(ctx->out, "SEQKEY", seq_key);
    tx_buf_sets(ctx->out, "MAXKEY", maxkey_out);
    tx_log(TX_LOG_INFO, "[CL_OL_0009] 채번완료 date=%s 다음순번=%ld 채번키=%s",
           bizdate, next_seq, seq_key);
    tx_return(ctx, TX_OK, ctx->out);
}
