/*
 * ACQ_UNMATCH.pgc - ac 모듈 서비스 ACQ_UNMATCH (one service = one file).
 * Moved verbatim from the former inline ac_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by ac_svr at tpsvrinit.
 */
#include "ACQ_UNMATCH.h"

void ACQ_UNMATCH(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char bizdate[16];
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL INSERT INTO ac_unmatch (unmatch_id, purchase_id, reason, biz_date)
        SELECT nextval('ac_unmatch_seq'), p.purchase_id, 'NO_LEDGER', p.biz_date
        FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND NOT EXISTS (SELECT 1 FROM ledger l WHERE l.purchase_id = p.purchase_id)
          AND NOT EXISTS (SELECT 1 FROM ac_unmatch u WHERE u.purchase_id = p.purchase_id);
    if (sqlca.sqlcode < 0) { userlog("ACQ_UNMATCH FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); FAIL(b); }
    h_cnt = sqlca.sqlerrd[2];
    setl(b, T_COUNT, h_cnt);
    OK(b);
}
