/*
 * ac_purchase_incancel_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_purchase_incancel_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: IN 서브셀렉트 - 취소 이력이 있는 매입 집계.
 */
#include <string.h>
#include <userlog.h>
#include "ac_purchase_incancel_dbio.h"

/* 취소 테이블에 존재하는 purchase_id 를 가진 매입 건수. */
long acdb_cancelled_purchase_count(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT count(*) INTO :h_v FROM purchase
        WHERE biz_date = :h_bizdate
          AND purchase_id IN (SELECT purchase_id FROM ac_cancel);
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}

/* 취소 이력이 있는 매입들의 원매입 금액 합계. */
long acdb_cancelled_purchase_amount(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_v FROM purchase
        WHERE biz_date = :h_bizdate
          AND purchase_id IN (SELECT purchase_id FROM ac_cancel);
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}
