/* 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/rc_ol_0013.pgc"
/* @tier medium @module rc @transform reconciliation-online */
/*
 * rc_ol_0013.pgc - 대사 허용오차(tolerance) 비교 (단건) 온라인 서비스 (RC_OL_0013)
 *
 * 요청 KEY 의 원장 1건을 읽어 "매입금액(원장 amount)" 과 승인계에서
 * 넘어온 "승인금액(APPRAMT)" 의 차액을 구한 뒤, 허용오차(TOL) 이내이면
 * 대사일치로 판정한다.
 *   diff = amount - APPRAMT,  absd = |diff|
 *   absd <= TOL  → 일치(MATCH)   → 매입확정('M')
 *   absd >  TOL  → 불일치(UNMATCH) → 실패('U')
 * 소액 정산 오차(반올림/수수료 잔돈)를 흡수하기 위한 판정 로직이다.
 *
 * 입력 TXBUF:
 *   KEY     (필수) 처리키
 *   APPRAMT (필수) 승인금액
 *   TOL     (선택) 허용오차, 미지정 시 0(완전일치)
 * 출력 TXBUF:
 *   KEY / APPRAMT / CAPAMT / DIFF / TOL / RESULT / STATUS
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "rc_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 28 "app/online/rc_ol_0013.pgc"


TX_SERVICE(RC_OL_0013, ctx)
{
    rc_rec_t rec;
    char key[16];
    long appr_amt = 0;   /* 승인금액(APPRAMT) */
    long tol      = 0;   /* 허용오차(TOL)     */
    long diff, absd;
    long tol_pct;        /* 매입금액 대비 오차율(‱, 만분율) */
    int  matched;
    int  rc;
    const char *new_st;
    const char *result;

    tx_log(TX_LOG_INFO, "[RC_OL_0013] 대사 허용오차 비교(단건) 서비스 진입");

    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0013] KEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (key[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[RC_OL_0013] KEY 공백");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_getlong(ctx->in, "APPRAMT", &appr_amt) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0013] APPRAMT(승인금액) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    /* 허용오차는 선택 입력(미지정 시 0 = 완전일치 요구) */
    if (tx_buf_getlong(ctx->in, "TOL", &tol) != TX_OK)
        tol = 0;
    if (tol < 0) {
        tx_log(TX_LOG_WARN, "[RC_OL_0013] 음수 허용오차 보정 tol=%ld → 0", tol);
        tol = 0;
    }

    memset(&rec, 0, sizeof(rec));
    rc = rc_rec_select(key, &rec);
    if (rc != TX_OK) {
        tx_log(TX_LOG_WARN, "[RC_OL_0013] 원장 조회 실패 key=%s rc=%d(%s)",
               key, rc, tx_strerror(rc));
        tx_return(ctx, rc, ctx->out);
        return;
    }

    tx_log(TX_LOG_INFO,
           "[RC_OL_0013] 대사대상 key=%s 매입=%ld 승인=%ld 허용오차=%ld",
           key, rec.amount, appr_amt, tol);

    /* 차액 및 절대차 계산 */
    diff = rec.amount - appr_amt;
    absd = (diff < 0) ? -diff : diff;
    matched = (absd <= tol);

    /* 참고지표: 매입금액 대비 오차율(만분율). 0 나눗셈 방지 */
    if (rec.amount > 0)
        tol_pct = (absd * 10000L) / rec.amount;
    else
        tol_pct = 0;
    tx_log(TX_LOG_INFO, "[RC_OL_0013] |차액|=%ld 오차율=%ld‱", absd, tol_pct);

    if (matched) {
        new_st = RC_ST_DONE;   /* 매입확정 */
        result = "MATCH";
        tx_log(TX_LOG_INFO,
               "[RC_OL_0013] 허용오차 이내 일치 key=%s 차액=%ld 오차=%ld",
               key, diff, tol);
    } else {
        new_st = RC_ST_FAIL;   /* 오차 초과 불일치 */
        result = "UNMATCH";
        tx_log(TX_LOG_WARN,
               "[RC_OL_0013] 허용오차 초과 불일치 key=%s |차액|=%ld 오차=%ld",
               key, absd, tol);
    }

    rc = rc_rec_update_status(key, new_st);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0013] 상태전이 실패 key=%s rc=%d", key, rc);
        tx_return(ctx, rc, ctx->out);
        return;
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "KEY", rec.key);
    tx_buf_setlong(ctx->out, "APPRAMT", appr_amt);
    tx_buf_setlong(ctx->out, "CAPAMT", rec.amount);
    tx_buf_setlong(ctx->out, "DIFF", diff);
    tx_buf_setlong(ctx->out, "TOL", tol);
    tx_buf_sets(ctx->out, "RESULT", result);
    tx_buf_sets(ctx->out, "STATUS", new_st);

    /* 허용오차 판정 이력을 rc_tolerance_log 에 임베디드 SQL 로 적재 */
    {
        /* exec sql begin declare section */
         
         
         
         
         
         
        
#line 126 "app/online/rc_ol_0013.pgc"
 char h_tl_key [ 16 ] ;
 
#line 127 "app/online/rc_ol_0013.pgc"
 long h_tl_appr ;
 
#line 128 "app/online/rc_ol_0013.pgc"
 long h_tl_cap ;
 
#line 129 "app/online/rc_ol_0013.pgc"
 long h_tl_diff ;
 
#line 130 "app/online/rc_ol_0013.pgc"
 long h_tl_tol ;
 
#line 131 "app/online/rc_ol_0013.pgc"
 char h_tl_result [ 12 ] ;
/* exec sql end declare section */
#line 132 "app/online/rc_ol_0013.pgc"


        strncpy(h_tl_key, key, sizeof(h_tl_key) - 1);
        h_tl_key[sizeof(h_tl_key) - 1] = '\0';
        h_tl_appr = appr_amt;
        h_tl_cap  = rec.amount;
        h_tl_diff = diff;
        h_tl_tol  = tol;
        strncpy(h_tl_result, result, sizeof(h_tl_result) - 1);
        h_tl_result[sizeof(h_tl_result) - 1] = '\0';

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into rc_tolerance_log ( rec_key , appr_amt , cap_amt , diff_amt , tol_amt , match_result ) values ( $1  , $2  , $3  , $4  , $5  , $6  )", 
	ECPGt_char,(h_tl_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_tl_appr),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_tl_cap),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_tl_diff),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_tl_tol),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_tl_result),(long)12,(long)1,(12)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 146 "app/online/rc_ol_0013.pgc"

            if (sqlca.sqlcode != TX_SQL_OK) {
                TX_DBIO_LOG_ERR("INSERT rc_tolerance_log");
                tx_abort();
            } else {
                tx_commit();
            }
        }
    }

    tx_return(ctx, TX_OK, ctx->out);
}
