/* 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/batch/ac_bt_0017.pgc"
/* @tier hard @module ac @transform acquire-batch */
/*
 * ac_bt_0017.pgc - 매입 이체연계 배치  [tier=hard]
 *
 * 지정 영업일에 정산완료(status='S') 된 매입행을 가맹점별로 집계하여
 * 순지급액(매입금액-수수료 합계) 을 산출하고 이체지시를 생성한다.
 *   - 순지급액이 0원 이하이면 이체 대상에서 제외한다.
 *   - 순지급액이 최소이체금액(AC_BT_0017_MIN_TRANSFER) 미만이면 보류 처리하고
 *     다음 영업일로 넘긴다(이체지시 미생성).
 *   - 그 외에는 이체번호를 채번하여 settle 테이블에 이체지시('T') 로 적재한다.
 * 배치 main 엔트리 포함.
 *
 * 실행:  ac_bt_0017 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.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 24 "app/batch/ac_bt_0017.pgc"


#define AC_BT_0017_MIN_TRANSFER 1000L

/*
 * 이체상태 'T' 는 settle 테이블 전용 로컬 상태코드이며,
 * ac_core.h 의 AC_ST_* (ac_ledger 상태) 와는 별개의 값이다.
 */
#define AC_BT_0017_SETTLE_ST_XFER "T"

static int run_ac_bt_0017(const char *biz_date)
{
    /* exec sql begin declare section */
     
     
     
     
     
    
#line 37 "app/batch/ac_bt_0017.pgc"
 char h_biz_date [ 9 ] ;
 
#line 38 "app/batch/ac_bt_0017.pgc"
 char h_merch_id [ 16 ] ;
 
#line 39 "app/batch/ac_bt_0017.pgc"
 long h_net ;
 
#line 40 "app/batch/ac_bt_0017.pgc"
 char h_settle_no [ 20 ] ;
 
#line 41 "app/batch/ac_bt_0017.pgc"
 char h_status [ 2 ] ;
/* exec sql end declare section */
#line 42 "app/batch/ac_bt_0017.pgc"


    long merchants = 0, transferred = 0, held = 0, skipped = 0, errcnt = 0;
    long seq = 0;
    long grand_net = 0, held_sum = 0;

    strncpy(h_biz_date, biz_date, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';

    ECPGset_var( 0, ( h_biz_date ), __LINE__);\
 /* declare cur_ac_bt_0017 cursor for select merch_id , sum ( amount - fee ) as net from ac_ledger where biz_date = $1  and status = 'S' group by merch_id order by merch_id */
#line 57 "app/batch/ac_bt_0017.pgc"

#line 57 "app/batch/ac_bt_0017.pgc"


    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "declare cur_ac_bt_0017 cursor for select merch_id , sum ( amount - fee ) as net from ac_ledger where biz_date = $1  and status = 'S' group by merch_id order by merch_id", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 59 "app/batch/ac_bt_0017.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_ac_bt_0017");
        return TX_EDB;
    }

    if (tx_begin() != TX_OK)
        tx_log(TX_LOG_WARN, "[ac_bt_0017] tx_begin 경고");

    printf("========== 매입 이체연계 결과 [ac_bt_0017] ==========\n");
    printf("  영업일 : %s\n", biz_date);
    printf("  ------------------------------------------------------\n");

    for (;;) {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "fetch cur_ac_bt_0017", ECPGt_EOIT, 
	ECPGt_char,(h_merch_id),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_net),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 73 "app/batch/ac_bt_0017.pgc"


        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_ac_bt_0017");
            errcnt++;
            break;
        }

        merchants++;

        if (h_net <= 0) {
            tx_log(TX_LOG_WARN, "[ac_bt_0017] 순지급액 이하 제외 merch_id=%s net=%ld",
                   h_merch_id, h_net);
            skipped++;
            continue;
        }

        if (h_net < AC_BT_0017_MIN_TRANSFER) {
            tx_log(TX_LOG_INFO, "[ac_bt_0017] 최소이체금액 미만 보류 merch_id=%s net=%ld",
                   h_merch_id, h_net);
            held++;
            held_sum += h_net;
            continue;
        }

        seq++;
        snprintf(h_settle_no, sizeof(h_settle_no), "TR%s%05ld", h_biz_date, seq);
        strncpy(h_status, AC_BT_0017_SETTLE_ST_XFER, sizeof(h_status));

        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into settle ( settle_no , merch_id , biz_date , settle_amt , status ) values ( $1  , $2  , $3  , $4  , $5  )", 
	ECPGt_char,(h_settle_no),(long)20,(long)1,(20)*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_net),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_status),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 107 "app/batch/ac_bt_0017.pgc"


        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("INSERT ac_bt_0017 settle");
            tx_log(TX_LOG_ERROR, "[ac_bt_0017] 이체지시 생성 실패 merch_id=%s", h_merch_id);
            errcnt++;
            continue;
        }

        printf("  %-16s 이체번호=%-17s 이체금액=%ld\n", h_merch_id, h_settle_no, h_net);

        transferred++;
        grand_net += h_net;
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_ac_bt_0017", ECPGt_EOIT, ECPGt_EORT);}
#line 122 "app/batch/ac_bt_0017.pgc"


    if (errcnt == 0)
        tx_commit();
    else
        tx_abort();

    tx_log(TX_LOG_INFO,
           "[ac_bt_0017] 요약 date=%s 가맹점=%ld 이체=%ld 이체총액=%ld 보류=%ld 보류액=%ld 제외=%ld 오류=%ld",
           biz_date, merchants, transferred, grand_net, held, held_sum, skipped, errcnt);

    printf("  ------------------------------------------------------\n");
    printf("  대상 가맹점수 : %ld\n", merchants);
    printf("  이체 건수     : %ld\n", transferred);
    printf("  이체 총액     : %ld\n", grand_net);
    printf("  보류 건수     : %ld\n", held);
    printf("  보류 금액합   : %ld\n", held_sum);
    printf("  제외 건수     : %ld\n", skipped);
    printf("  오류 건수     : %ld\n", errcnt);
    printf("========================================================\n");

    return (errcnt == 0) ? TX_OK : TX_FAIL;
}

int main(int argc, char **argv)
{
    const char *biz_date;
    const char *target;
    int rc;

    tx_set_loglevel(TX_LOG_INFO);

    if (argc < 2) {
        fprintf(stderr, "사용법: %s <YYYYMMDD> [db@host]\n", argv[0]);
        return 2;
    }
    biz_date = argv[1];
    target   = (argc >= 3) ? argv[2] : NULL;

    if (!date_is_valid(biz_date)) {
        fprintf(stderr, "오류: 유효하지 않은 영업일 '%s'\n", biz_date);
        return 2;
    }

    tx_log(TX_LOG_INFO, "[ac_bt_0017] 배치 시작 date=%s", biz_date);

    rc = ac_dbio_connect(target);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[ac_bt_0017] DB 접속 실패 rc=%d", rc);
        return 1;
    }

    rc = run_ac_bt_0017(biz_date);

    ac_dbio_disconnect();

    tx_log(TX_LOG_INFO, "[ac_bt_0017] 배치 종료 rc=%d(%s)", rc, tx_strerror(rc));
    return (rc == TX_OK) ? 0 : 1;
}
