/* 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_0032.pgc"
/* @tier easy @module lg @transform ledger-online */
/*
 * lg_ol_0032.pgc - 원장 온라인 서비스 (LG_OL_0032)  [tier=easy]
 *
 * 정산원장 대사: 지정 영업일의 정산완료(S) Σamount 와 처리완료(M) Σamount 를
 * 비교하여 미정산 차액(=M합계, 아직 정산되지 않은 금액)을 응답한다. (조회 전용)
 */
#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_0032.pgc"


/*
 * [업무 개요]
 *   정산 마감 전, 특정 영업일 원장에서 이미 정산확정(S) 된 금액과 아직
 *   정산되지 않은 처리완료(M) 금액을 대사(對査) 하여, 당일 정산 진행 상태를
 *   점검한다. 미정산 금액이 0 이면 당일 정산이 완결된 것으로 본다.
 *
 * [대사 산식]
 *   SETTLEDSUM = Σ amount (status='S')   정산확정 합계
 *   DONESUM    = Σ amount (status='M')   미정산(처리완료) 합계
 *   UNSETTLED  = DONESUM                 아직 정산 안 된 금액
 *   BALANCED   = (UNSETTLED == 0) ? "Y" : "N"
 *
 * [처리 절차]
 *   1) BIZDATE 추출 및 형식 검증.
 *   2) 정산확정(S) 합계 집계 SELECT.
 *   3) 처리완료(M) 합계 집계 SELECT.
 *   4) 미정산 차액과 균형 여부를 응답.
 *
 * [응답 필드]
 *   RESPCODE     처리결과코드
 *   BIZDATE      대상 영업일(에코)
 *   SETTLEDSUM   정산확정(S) 합계
 *   DONESUM      처리완료(M) 합계
 *   UNSETTLED    미정산 차액
 *   UNSETTLEDWON 미정산 원화표기
 *   BALANCED     정산완결 여부 Y/N
 *
 * [주의]
 *   조회/대사 전용. 원장을 변경하지 않으며 집계 결과는 coalesce 로 0 보장.
 */
TX_SERVICE(LG_OL_0032, ctx)
{
    /* exec sql begin declare section */
     
     
     
     
     
    
#line 51 "app/online/lg_ol_0032.pgc"
 char h_biz_date [ 9 ] ;
 
#line 52 "app/online/lg_ol_0032.pgc"
 char h_status_s [ 2 ] ;
 
#line 53 "app/online/lg_ol_0032.pgc"
 char h_status_m [ 2 ] ;
 
#line 54 "app/online/lg_ol_0032.pgc"
 long h_settled_sum ;
 
#line 55 "app/online/lg_ol_0032.pgc"
 long h_done_sum ;
/* exec sql end declare section */
#line 56 "app/online/lg_ol_0032.pgc"


    char bizdate[16];
    char wonbuf[32];
    long unsettled;

    tx_log(TX_LOG_INFO, "[LG_OL_0032] 정산원장 대사 진입");

    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[LG_OL_0032] 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_0032] 영업일 형식 오류 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_status_s, LG_ST_SETTLED, sizeof(h_status_s) - 1);
    h_status_s[sizeof(h_status_s) - 1] = '\0';
    strncpy(h_status_m, LG_ST_DONE, sizeof(h_status_m) - 1);
    h_status_m[sizeof(h_status_m) - 1] = '\0';

    /* 정산완료(S) 합계 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select coalesce ( sum ( amount ) , 0 ) from lg_ledger where biz_date = $1  and status = $2 ", 
	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_long,&(h_settled_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 91 "app/online/lg_ol_0032.pgc"

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

    /* 미정산(처리완료 M) 합계 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select coalesce ( sum ( amount ) , 0 ) from lg_ledger where biz_date = $1  and status = $2 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_status_m),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_done_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 105 "app/online/lg_ol_0032.pgc"

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

    /* 미정산 차액 = 아직 정산확정되지 않은 처리완료 금액 */
    unsettled = h_done_sum;
    amount_format_won(unsettled, wonbuf, sizeof(wonbuf));

    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, "SETTLEDSUM", h_settled_sum);
    tx_buf_setlong(ctx->out, "DONESUM", h_done_sum);
    tx_buf_setlong(ctx->out, "UNSETTLED", unsettled);
    tx_buf_sets(ctx->out, "UNSETTLEDWON", wonbuf);
    tx_buf_sets(ctx->out, "BALANCED", (unsettled == 0) ? "Y" : "N");
    tx_log(TX_LOG_INFO, "[LG_OL_0032] 정산대사 date=%s 정산=%ld 미정산=%ld",
           bizdate, h_settled_sum, unsettled);
    tx_return(ctx, TX_OK, ctx->out);
}
