/* 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_0004.pgc"
/* @tier medium @module rc @transform reconciliation-online */
/*
 * rc_ol_0004.pgc - 반송(return) 대사 (단건) 온라인 서비스 (RC_OL_0004)
 *
 * 요청 KEY 의 원장 1건을 읽어 매입사에서 통지된 "반송금액(입력 RTNAMT)"
 * 을 원거래금액(원장 amount)과 대사한다.
 *
 * 업무규칙:
 *   - 반송금액은 0 보다 커야 하며 원거래금액을 초과할 수 없다(TX_EINVAL).
 *   - 반송금액 == 원거래금액  → 전액반송(매입취소). 상태를 불일치/보류
 *     ('U') 로 전이하고 RESULT=FULLRETURN.
 *   - 0 < 반송금액 < 원거래금액 → 부분반송. 잔액이 남아 있으므로 접수
 *     ('R') 상태를 유지하고 RESULT=PARTIAL.
 *
 * 응답: KEY, RTNAMT, REMAIN(=amount-RTNAMT), STATUS, RESULT
 *
 * 상태전이 요약:
 *   [입력 RTNAMT]                 [원장 상태]      [RESULT]
 *   RTNAMT <= 0                    (거부)          TX_EINVAL
 *   RTNAMT >  amount               (거부)          TX_EINVAL
 *   RTNAMT == amount               R/… → U         FULLRETURN
 *   0 < RTNAMT < amount            R  유지         PARTIAL
 *
 * 주의: 본 서비스는 원장 금액(amount) 자체를 갱신하지 않는다. 부분반송의
 *       잔액(REMAIN)은 응답으로만 통지하며, 실제 금액 조정은 후속 정산
 *       배치에서 반영한다. 따라서 커서/트랜잭션 경계가 필요 없다.
 */
#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 36 "app/online/rc_ol_0004.pgc"


TX_SERVICE(RC_OL_0004, ctx)
{
    rc_rec_t rec;
    char key[16];
    long rtn_amt = 0;      /* 반송금액 */
    long remain;           /* 반송 후 잔액 */
    int  rc;
    const char *result;
    const char *final_st;

    tx_log(TX_LOG_INFO, "[RC_OL_0004] 반송 대사(단건) 서비스 진입");

    /* --- 요청 필드 추출 --- */
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0004] KEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_getlong(ctx->in, "RTNAMT", &rtn_amt) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0004] RTNAMT(반송금액) 누락 key=%s", key);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* --- 반송금액 유효성: 0 초과 --- */
    if (rtn_amt <= 0) {
        tx_log(TX_LOG_WARN, "[RC_OL_0004] 반송금액 오류 key=%s rtn=%ld",
               key, rtn_amt);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

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

    /* --- 반송금액이 원거래금액 초과 → 처리 불가 --- */
    if (rtn_amt > rec.amount) {
        tx_log(TX_LOG_WARN,
               "[RC_OL_0004] 반송금액 초과 key=%s rtn=%ld amount=%ld",
               key, rtn_amt, rec.amount);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    remain = rec.amount - rtn_amt;

    tx_log(TX_LOG_INFO,
           "[RC_OL_0004] 반송 대사 판정 key=%s 가맹점=%s 원거래=%ld 반송=%ld",
           key, rec.merch_id, rec.amount, rtn_amt);

    if (rtn_amt == rec.amount) {
        /* 전액반송 → 매입취소, 불일치/보류 전이 */
        rc = rc_rec_update_status(key, RC_ST_FAIL);
        if (rc != TX_OK) {
            tx_log(TX_LOG_ERROR, "[RC_OL_0004] 전액반송 전이 실패 key=%s rc=%d",
                   key, rc);
            tx_return(ctx, rc, ctx->out);
            return;
        }
        final_st = RC_ST_FAIL;
        result   = "FULLRETURN";
        tx_log(TX_LOG_INFO,
               "[RC_OL_0004] 전액반송 key=%s amount=%ld → 매입취소",
               key, rec.amount);
    } else {
        /* 부분반송 → 잔액 존재, 접수상태 유지 */
        final_st = RC_ST_RECV;
        result   = "PARTIAL";
        tx_log(TX_LOG_INFO,
               "[RC_OL_0004] 부분반송 key=%s rtn=%ld 잔액=%ld → 접수유지",
               key, rtn_amt, remain);
    }

    /* --- 응답 구성 --- */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "KEY", rec.key);
    tx_buf_setlong(ctx->out, "RTNAMT", rtn_amt);
    tx_buf_setlong(ctx->out, "REMAIN", remain);
    tx_buf_sets(ctx->out, "STATUS", final_st);
    tx_buf_sets(ctx->out, "RESULT", result);

    /* 반송 대사 결과를 반송이력(rc_return_log)에 임베디드 SQL 로 적재 */
    {
        /* exec sql begin declare section */
         
         
         
         
        
#line 129 "app/online/rc_ol_0004.pgc"
 char h_rl_key [ 16 ] ;
 
#line 130 "app/online/rc_ol_0004.pgc"
 long h_rl_rtn ;
 
#line 131 "app/online/rc_ol_0004.pgc"
 long h_rl_remain ;
 
#line 132 "app/online/rc_ol_0004.pgc"
 char h_rl_result [ 12 ] ;
/* exec sql end declare section */
#line 133 "app/online/rc_ol_0004.pgc"


        strncpy(h_rl_key, key, sizeof(h_rl_key) - 1);
        h_rl_key[sizeof(h_rl_key) - 1] = '\0';
        h_rl_rtn    = rtn_amt;
        h_rl_remain = remain;
        strncpy(h_rl_result, result, sizeof(h_rl_result) - 1);
        h_rl_result[sizeof(h_rl_result) - 1] = '\0';

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into rc_return_log ( rec_key , rtn_amt , remain_amt , return_result ) values ( $1  , $2  , $3  , $4  )", 
	ECPGt_char,(h_rl_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_rl_rtn),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_rl_remain),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_rl_result),(long)12,(long)1,(12)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 145 "app/online/rc_ol_0004.pgc"

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

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