/* 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/mg_ol_0018.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0018.pgc - 전문게이트웨이 응답전문 생성 서비스 (MG_OL_0018)  [tier=medium]
 *
 * 승인처리 결과(승인/거절/사유코드)와 원거래 식별정보를 받아 응답전문
 * (0210)을 조립한다. 승인이면 resp_code=0000, 거절이면 요청 사유코드를
 * 반영(미지정시 9001)하며, 승인번호가 없으면 채번규칙으로 생성한다.
 * 완성된 전문을 msg_pack 으로 고정길이 직렬화하여 RAWMSG 로 반환한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "mg_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 18 "app/online/mg_ol_0018.pgc"


TX_SERVICE(MG_OL_0018, ctx)
{
    acq_msg_t resp;
    char outraw[MSG_ACQ_LEN + 1];
    char merch[16], card[20], trans[8], approval[12], reason[8];
    char apnbuf[12];
    long amount = 0;
    long approved = 0;
    const char *rcode;

    tx_log(TX_LOG_INFO, "[MG_OL_0018] 응답전문 생성 서비스 진입");

    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK ||
        tx_buf_get(ctx->in, "CARDNO", card, sizeof(card)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0018] 필수 필드 누락(MERCHID/CARDNO)");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    tx_buf_getlong(ctx->in, "AMOUNT", &amount);
    tx_buf_getlong(ctx->in, "APPROVED", &approved);

    if (tx_buf_get(ctx->in, "TRANSCODE", trans, sizeof(trans)) != TX_OK)
        strcpy(trans, "000000");
    if (tx_buf_get(ctx->in, "REASON", reason, sizeof(reason)) != TX_OK)
        reason[0] = '\0';

    /* 승인/거절에 따른 응답코드 결정 */
    if (approved != 0) {
        rcode = RESP_OK;
    } else if (reason[0] != '\0') {
        rcode = reason;                /* 요청이 지정한 거절사유 */
    } else {
        rcode = RESP_INVALID;          /* 사유 미지정 기본 거절 */
    }

    /* 승인번호: 요청값 우선, 없으면 가맹점+금액 기반 채번 */
    if (tx_buf_get(ctx->in, "APPROVAL", approval, sizeof(approval)) != TX_OK ||
        approval[0] == '\0') {
        /* 승인번호 채번: 승인번호 시퀀스 마스터(mg_appr_seq)에서 임베디드 SQL 로 채번 */
        /* exec sql begin declare section */
         
         
        
#line 60 "app/online/mg_ol_0018.pgc"
 char h_seq_name [ 8 ] ;
 
#line 61 "app/online/mg_ol_0018.pgc"
 long h_last_no ;
/* exec sql end declare section */
#line 62 "app/online/mg_ol_0018.pgc"


        strcpy(h_seq_name, "APPR");
        h_last_no = 0;

        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select last_no from mg_appr_seq where seq_name = $1 ", 
	ECPGt_char,(h_seq_name),(long)8,(long)1,(8)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_last_no),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 70 "app/online/mg_ol_0018.pgc"


        if (sqlca.sqlcode == TX_SQL_OK) {
            if (tx_begin() == TX_OK) {
                { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update mg_appr_seq set last_no = last_no + 1 where seq_name = $1 ", 
	ECPGt_char,(h_seq_name),(long)8,(long)1,(8)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 76 "app/online/mg_ol_0018.pgc"

                if (sqlca.sqlcode != TX_SQL_OK) {
                    TX_DBIO_LOG_ERR("UPDATE mg_appr_seq");
                    tx_abort();
                } else {
                    tx_commit();
                }
            }
            snprintf(apnbuf, sizeof(apnbuf), "%08ld", ((h_last_no + 1) % 100000000L));
        } else {
            if (sqlca.sqlcode != TX_SQL_NOTFOUND)
                TX_DBIO_LOG_ERR("SELECT mg_appr_seq");
            /* 시퀀스 미비 시 금액기반 폴백 채번 */
            snprintf(apnbuf, sizeof(apnbuf), "%08ld", (amount % 100000000L));
        }
    } else {
        strncpy(apnbuf, approval, sizeof(apnbuf) - 1);
        apnbuf[sizeof(apnbuf) - 1] = '\0';
    }

    /* 응답전문(0210) 필드 세팅 (고정길이 우측공백/좌측영 규칙은 유틸 준수) */
    memset(&resp, 0, sizeof(resp));
    msg_field_set(resp.msg_type,  MSG_TYPE_RESP, FLD_MSG_TYPE_LEN);
    msg_field_set(resp.trans_code, trans,        FLD_TRANS_CODE_LEN);
    msg_field_set(resp.merch_id,  merch,         FLD_MERCH_ID_LEN);
    msg_field_set(resp.card_no,   card,          FLD_CARD_NO_LEN);
    msg_field_set(resp.approval_no, apnbuf,      FLD_APPROVAL_LEN);
    {
        char amtstr[16];
        snprintf(amtstr, sizeof(amtstr), "%ld", (amount < 0) ? 0 : amount);
        msg_field_set_num(resp.amount, amtstr, FLD_AMOUNT_LEN);
    }
    msg_field_set(resp.resp_code, rcode, FLD_RESP_LEN);

    memset(outraw, 0, sizeof(outraw));
    if (msg_pack(&resp, outraw, MSG_ACQ_LEN) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0018] 응답전문 패킹 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", rcode);
    tx_buf_sets(ctx->out, "RAWMSG", outraw);
    tx_buf_sets(ctx->out, "APPROVAL", apnbuf);
    tx_buf_setlong(ctx->out, "APPROVED", approved);
    tx_log(TX_LOG_INFO, "[MG_OL_0018] 응답전문 생성완료 rcode=%s apn=%s approved=%ld",
           rcode, apnbuf, approved);
    tx_return(ctx, TX_OK, ctx->out);
}
