/* 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_0019.pgc"
/* @tier easy @module cl @transform closing-online */
/*
 * cl_ol_0019.pgc - 마감 온라인 서비스 (CL_OL_0019)  [tier=easy]
 *
 * 마감 취소 승인
 * ----------------------------------------------------------------------
 * 요청 KEY 의 원장이 취소요청 상태(status='U')인지 확인한 뒤, 승인되면
 * 처리완료(status='M') 로 재개방 갱신한다. 대상이 취소요청 상태가
 * 아니면 승인 불가로 반려한다. 상태 조회 후 갱신은 하나의 트랜잭션으로
 * 커밋하며, 승인/반려 결과와 원거래 요약(가맹점/금액/영업일)을 응답에
 * 함께 실어 상위 화면이 감사표시를 할 수 있게 한다. 감사추적을 위해
 * 선택 입력 REQID/OPER 를 로그·응답에 반영한다.
 */
#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 22 "app/online/cl_ol_0019.pgc"


TX_SERVICE(CL_OL_0019, ctx)
{
    cl_rec_t rec;
    char key[16];
    char reqid[32];
    char oper[32];
    char won[32];
    int  rc;

    tx_log(TX_LOG_INFO, "[CL_OL_0019] 마감 취소 승인 서비스 진입");

    /* 1) 입력 수신 */
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] KEY 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "REQID", reqid, sizeof(reqid)) != TX_OK)
        strncpy(reqid, "-", sizeof(reqid) - 1);
    if (tx_buf_get(ctx->in, "OPER", oper, sizeof(oper)) != TX_OK)
        strncpy(oper, "SUPERV", sizeof(oper) - 1);

    /* 2) 현재 상태 조회 */
    memset(&rec, 0, sizeof(rec));
    rc = cl_rec_select(key, &rec);
    if (rc == TX_ENOENT) {
        tx_log(TX_LOG_WARN, "[CL_OL_0019] 대상없음 key=%s reqid=%s", key, reqid);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_buf_sets(ctx->out, "MESSAGE", "취소승인 대상 원장 없음");
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] 조회 실패 key=%s rc=%d", key, rc);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, rc, ctx->out);
        return;
    }

    /* 3) 취소요청(U) 상태만 승인 가능 */
    if (strcmp(rec.status, CL_ST_FAIL) != 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0019] 승인불가 상태 key=%s status=%s reqid=%s",
               key, rec.status, reqid);
        amount_format_won(rec.amount, won, sizeof(won));
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "STATUS", rec.status);
        tx_buf_sets(ctx->out, "MERCHID", rec.merch_id);
        tx_buf_setlong(ctx->out, "AMOUNT", rec.amount);
        tx_buf_sets(ctx->out, "AMOUNTWON", won);
        tx_buf_sets(ctx->out, "MESSAGE", "취소요청(U) 상태가 아니어서 승인 불가");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 4) 재개방 승인: U -> M 갱신 (트랜잭션) */
    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] 트랜잭션 시작 실패 key=%s", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    rc = cl_rec_update_status(key, CL_ST_DONE);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] 승인갱신 실패 key=%s rc=%d", key, rc);
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_return(ctx, rc, ctx->out);
        return;
    }

    tx_commit();

    /* 5) 승인 결과 응답 (원거래 요약 포함) */
    amount_format_won(rec.amount, won, sizeof(won));
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "KEY", key);
    tx_buf_sets(ctx->out, "REQID", reqid);
    tx_buf_sets(ctx->out, "OPER", oper);
    tx_buf_sets(ctx->out, "APPROVED", "Y");
    tx_buf_sets(ctx->out, "PREVSTATUS", CL_ST_FAIL);
    tx_buf_sets(ctx->out, "STATUS", CL_ST_DONE);
    tx_buf_sets(ctx->out, "MERCHID", rec.merch_id);
    tx_buf_sets(ctx->out, "BIZDATE", rec.biz_date);
    tx_buf_setlong(ctx->out, "AMOUNT", rec.amount);
    tx_buf_sets(ctx->out, "AMOUNTWON", won);
    tx_buf_sets(ctx->out, "MESSAGE", "마감 취소 승인(재개방) 완료");

    tx_log(TX_LOG_INFO, "[CL_OL_0019] 취소 승인 완료 key=%s U->M oper=%s reqid=%s",
           key, oper, reqid);
    tx_return(ctx, TX_OK, ctx->out);
}
