/* 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_0030.pgc"
/* @tier easy @module rc @transform reconciliation-online */
/*
 * rc_ol_0030.pgc - 대사 취소 온라인 서비스 (RC_OL_0030)
 *
 * 요청 KEY 의 원장 1건에 대해 대사(매입/불일치) 결과를 취소하여 접수('R')
 * 상태로 되돌린다. 오취소를 막기 위해 확인 플래그(CFMFLAG="Y") 를 요구한다.
 *
 * 업무규칙:
 *   - CFMFLAG != "Y"          → RESULT=NOCONFIRM, 상태 변경 없음 (TX_OK)
 *   - status == 정산완료('S') → RESULT=REJECT, 취소 불가 (상태 유지)
 *   - status in {'M','U'}     → 접수('R') 로 전이, RESULT=CANCELLED
 *   - 그 외(이미 'R' 등)       → RESULT=REJECT (취소 대상 아님)
 *
 * 응답: KEY, OLDSTATUS, NEWSTATUS, RESULT  (조건부 갱신)
 */
#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 24 "app/online/rc_ol_0030.pgc"


TX_SERVICE(RC_OL_0030, ctx)
{
    rc_rec_t rec;
    char key[16];
    char cfmflag[4];
    char oldstatus[2];
    const char *newstatus;
    const char *result;
    int  rc;

    tx_log(TX_LOG_INFO, "[RC_OL_0030] 대사 취소 서비스 진입");

    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0030] KEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "CFMFLAG", cfmflag, sizeof(cfmflag)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[RC_OL_0030] CFMFLAG(확인 플래그) 누락");
        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_0030] 원장 조회 실패 key=%s rc=%d(%s)",
               key, rc, tx_strerror(rc));
        tx_return(ctx, rc, ctx->out);
        return;
    }

    memset(oldstatus, 0, sizeof(oldstatus));
    strncpy(oldstatus, rec.status, sizeof(oldstatus) - 1);
    newstatus = oldstatus;   /* 기본: 변경 없음 */

    /* --- 확인 플래그 미승인 → 변경 없이 종료 --- */
    if (strcmp(cfmflag, "Y") != 0) {
        result = "NOCONFIRM";
        tx_log(TX_LOG_WARN,
               "[RC_OL_0030] 확인 플래그 미승인 key=%s flag=%s → 취소 보류",
               key, cfmflag);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "KEY", rec.key);
        tx_buf_sets(ctx->out, "OLDSTATUS", oldstatus);
        tx_buf_sets(ctx->out, "NEWSTATUS", newstatus);
        tx_buf_sets(ctx->out, "RESULT", result);
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* --- 정산완료 건은 취소 불가 --- */
    if (strcmp(rec.status, RC_ST_SETTLED) == 0) {
        result = "REJECT";
        tx_log(TX_LOG_WARN,
               "[RC_OL_0030] 정산완료 취소불가 key=%s status=S", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "KEY", rec.key);
        tx_buf_sets(ctx->out, "OLDSTATUS", oldstatus);
        tx_buf_sets(ctx->out, "NEWSTATUS", newstatus);
        tx_buf_sets(ctx->out, "RESULT", result);
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* --- 매입확정/불일치 건만 접수('R') 로 되돌림 --- */
    if (strcmp(rec.status, RC_ST_DONE) == 0 ||
        strcmp(rec.status, RC_ST_FAIL) == 0) {
        rc = rc_rec_update_status(key, RC_ST_RECV);
        if (rc != TX_OK) {
            tx_log(TX_LOG_ERROR, "[RC_OL_0030] 취소 전이 실패 key=%s rc=%d",
                   key, rc);
            tx_return(ctx, rc, ctx->out);
            return;
        }
        newstatus = RC_ST_RECV;
        result = "CANCELLED";
        tx_log(TX_LOG_INFO,
               "[RC_OL_0030] 대사 취소 완료 key=%s %s→R", key, oldstatus);
    } else {
        result = "REJECT";
        tx_log(TX_LOG_WARN,
               "[RC_OL_0030] 취소 대상 아님 key=%s status=%s",
               key, oldstatus);
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "KEY", rec.key);
    tx_buf_sets(ctx->out, "OLDSTATUS", oldstatus);
    tx_buf_sets(ctx->out, "NEWSTATUS", newstatus);
    tx_buf_sets(ctx->out, "RESULT", result);
    /* 대사 취소 처리 이력을 rc_cancel_log 에 임베디드 SQL 로 적재 */
    {
        /* exec sql begin declare section */
         
         
         
        
#line 120 "app/online/rc_ol_0030.pgc"
 char h_cl_key [ 16 ] ;
 
#line 121 "app/online/rc_ol_0030.pgc"
 char h_cl_old [ 2 ] ;
 
#line 122 "app/online/rc_ol_0030.pgc"
 char h_cl_result [ 12 ] ;
/* exec sql end declare section */
#line 123 "app/online/rc_ol_0030.pgc"


        strncpy(h_cl_key, key, sizeof(h_cl_key) - 1);
        h_cl_key[sizeof(h_cl_key) - 1] = '\0';
        strncpy(h_cl_old, oldstatus, sizeof(h_cl_old) - 1);
        h_cl_old[sizeof(h_cl_old) - 1] = '\0';
        strncpy(h_cl_result, result, sizeof(h_cl_result) - 1);
        h_cl_result[sizeof(h_cl_result) - 1] = '\0';

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into rc_cancel_log ( rec_key , old_status , cancel_result ) values ( $1  , $2  , $3  )", 
	ECPGt_char,(h_cl_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_cl_old),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_cl_result),(long)12,(long)1,(12)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 135 "app/online/rc_ol_0030.pgc"

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

    tx_log(TX_LOG_INFO,
           "[RC_OL_0030] 대사 취소 서비스 종료 key=%s %s→%s 결과=%s",
           key, oldstatus, newstatus, result);
    tx_return(ctx, TX_OK, ctx->out);
}
