/* 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/ac_ol_0017.pgc"
/* @tier hard @module ac @transform acquire-online */
/*
 * ac_ol_0017.pgc - 매입 온라인 서비스 (AC_OL_0017)  [tier=hard]
 *
 * 매입 세금계산서 연계: 지정 가맹점의 특정 영업일 처리완료(M) 매입 합계를
 * 집계하여 세금계산서를 발행하고, 대상 매입 원장에 세금계산서번호를 반영한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "ac_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 16 "app/online/ac_ol_0017.pgc"


TX_SERVICE(AC_OL_0017, ctx)
{
    /* exec sql begin declare section */
     
     
     
     
     
     
     
    
#line 21 "app/online/ac_ol_0017.pgc"
 char h_merch_id [ 16 ] ;
 
#line 22 "app/online/ac_ol_0017.pgc"
 char h_biz_date [ 9 ] ;
 
#line 23 "app/online/ac_ol_0017.pgc"
 char h_key [ 16 ] ;
 
#line 24 "app/online/ac_ol_0017.pgc"
 char h_tax_no [ 17 ] ;
 
#line 25 "app/online/ac_ol_0017.pgc"
 long h_supply ;
 
#line 26 "app/online/ac_ol_0017.pgc"
 long h_vat ;
 
#line 27 "app/online/ac_ol_0017.pgc"
 long h_supply_amt ;
/* exec sql end declare section */
#line 28 "app/online/ac_ol_0017.pgc"


    char merch[16], bizdate[9], won[32];
    long tagged = 0;

    tx_log(TX_LOG_INFO, "[AC_OL_0017] 매입 세금계산서 연계 진입");

    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK ||
        tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[AC_OL_0017] 필수 필드(MERCHID/BIZDATE) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[AC_OL_0017] 영업일 형식 오류 date=%s", bizdate);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_merch_id, merch, sizeof(h_merch_id) - 1);
    h_merch_id[sizeof(h_merch_id) - 1] = '\0';
    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';

    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[AC_OL_0017] 트랜잭션 시작 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 처리완료(M) 매입 합계 집계 (부가세 포함 총액) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select coalesce ( sum ( amount ) , 0 ) from ac_ledger where merch_id = $1  and biz_date = $2  and status = 'M'", 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_supply),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 65 "app/online/ac_ol_0017.pgc"


    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("SELECT sum ac_ledger(tax)");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    if (h_supply <= 0) {
        tx_log(TX_LOG_WARN, "[AC_OL_0017] 집계대상 없음 merch=%s date=%s",
               merch, bizdate);
        tx_abort();
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }

    /* 부가세 10% 계산, 공급가액 = 매입합계 - 부가세 */
    h_vat        = h_supply / 10;
    h_supply_amt = h_supply - h_vat;

    /* 세금계산서번호 채번: TX + 영업일 + 가맹점번호(6자리) */
    snprintf(h_tax_no, sizeof(h_tax_no), "TX%s%.6s", bizdate, merch);

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into tax_invoice ( tax_no , merch_id , biz_date , supply_amt , vat_amt , status ) values ( $1  , $2  , $3  , $4  , $5  , 'I' )", 
	ECPGt_char,(h_tax_no),(long)17,(long)1,(17)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_supply_amt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_vat),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 92 "app/online/ac_ol_0017.pgc"


    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("INSERT tax_invoice");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 대상 매입 원장 커서 순회, 발행된 세금계산서번호 반영 */
    ECPGset_var( 0, ( h_biz_date ), __LINE__);\
 ECPGset_var( 1, ( h_merch_id ), __LINE__);\
 /* declare cur_ac_ol_0017 cursor for select key from ac_ledger where merch_id = $1  and biz_date = $2  and status = 'M' */
#line 107 "app/online/ac_ol_0017.pgc"

#line 107 "app/online/ac_ol_0017.pgc"


    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "declare cur_ac_ol_0017 cursor for select key from ac_ledger where merch_id = $1  and biz_date = $2  and status = 'M'", 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 109 "app/online/ac_ol_0017.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_ac_ol_0017");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    for (;;) {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "fetch cur_ac_ol_0017", ECPGt_EOIT, 
	ECPGt_char,(h_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 118 "app/online/ac_ol_0017.pgc"

        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_ac_ol_0017");
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_ac_ol_0017", ECPGt_EOIT, ECPGt_EORT);}
#line 123 "app/online/ac_ol_0017.pgc"

            tx_abort();
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }

        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update ac_ledger set tax_no = $1  where key = $2 ", 
	ECPGt_char,(h_tax_no),(long)17,(long)1,(17)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 131 "app/online/ac_ol_0017.pgc"


        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("UPDATE ac_ledger tax_no");
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_ac_ol_0017", ECPGt_EOIT, ECPGt_EORT);}
#line 135 "app/online/ac_ol_0017.pgc"

            tx_abort();
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }
        tagged += sqlca.sqlerrd[2];
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_ac_ol_0017", ECPGt_EOIT, ECPGt_EORT);}
#line 143 "app/online/ac_ol_0017.pgc"


    tx_commit();

    amount_format_won(h_supply_amt, won, sizeof(won));

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "TAXNO", h_tax_no);
    tx_buf_setlong(ctx->out, "SUPPLY", h_supply_amt);
    tx_buf_setlong(ctx->out, "VAT", h_vat);
    tx_buf_setlong(ctx->out, "TAGGED", tagged);

    tx_log(TX_LOG_INFO,
           "[AC_OL_0017] 완료 taxno=%s 공급가액=%s(%ld) 부가세=%ld 반영=%ld건",
           h_tax_no, won, h_supply_amt, h_vat, tagged);
    tx_return(ctx, TX_OK, ctx->out);
}
