Files
Online-Topup-V1/application/modules/invoiceonline/invoice.model.js
T

341 lines
8.9 KiB
JavaScript

const sapPostingTable = 'payment.t_invoice_sap_posting';
// GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, repost, trx) => {
let result = await trx.raw(
'SELECT * FROM payment.sp_payment_req_topup_online(?, ?::boolean)',
[invoiceDate, repost]
);
return result.rows || result;
}
const insertPostingEt = async (invoice, trx) => {
let type = ['S', 'H']
let et = []
let posting_et = []
type.forEach((item, index) => {
let data = {
file_name: invoice.file_name,
tcode: invoice.tcode,
reversal: invoice.reversal,
doc_type: invoice.doc_type,
fiscal_year: invoice.fisc_year,
posting_date: invoice.posting_date,
doc_date: invoice.doc_date,
no_dok: invoice.c_invoice_no,
reference: invoice.c_invoice_no,
amount: invoice.amount,
ba: invoice.ba,
indeks: (index + 1),
totalidx: type.length,
doc_header_text: invoice.c_invoice_no,
pos_status: 3
}
if (item == 'H') {
data = {
...data, ...{
text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
debit_kredit: item,
account: invoice.c_account_topup,
customer: null
}
}
} else {
data = {
...data, ...{
text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
debit_kredit: item,
account: null,
customer: invoice.c_account_code_topup
}
}
}
et.push(data)
});
posting_et = await trx('public.posting_et').insert(et, ['indeks', 'customer', 'account', 'ba', 'fiscal_year', 'amount', 'no_dok', 'text', 'debit_kredit'])
return posting_et[0]
}
const getPostingEt = async (trx) => {
const result = await trx.raw(`
WITH params AS (
SELECT
EXTRACT(YEAR FROM CURRENT_DATE)::TEXT AS curr_year,
EXTRACT(YEAR FROM CURRENT_DATE - INTERVAL '1 year')::TEXT AS prev_year,
TO_CHAR(CURRENT_DATE, 'MM') AS curr_month
),
base AS (
SELECT
pe.doc_header_text,
pe.ba,
pe.doc_date,
pe.posting_date,
pe.fiscal_year,
TO_CHAR(pe.doc_date::DATE, 'MM') AS fis_period,
pe.doc_type,
pe.reference,
pe.tcode,
pe.amount,
pe.customer,
pe.account,
pe.text,
pe.debit_kredit
FROM public.posting_et pe
CROSS JOIN params p
WHERE
pe.tcode = 'FB70'
AND pe.pos_status = '3'
AND NOT EXISTS (
SELECT 1
FROM payment.t_invoice_sap_posting sap
WHERE sap.invoice_no = pe.reference
)
-- Prefix search still index friendly
AND pe.doc_header_text LIKE 'INV%'
AND (
-- Current year all months
pe.fiscal_year = p.curr_year
OR (
-- Previous year December only
-- only when current month is January
p.curr_month = '01'
AND pe.fiscal_year = p.prev_year
AND TO_CHAR(pe.doc_date::DATE, 'MM') = '12'
)
)
)
SELECT
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount,
'IDR'::VARCHAR AS currency,
MAX(b.customer) FILTER (
WHERE b.debit_kredit = 'S'
) AS customer,
MAX(b.account) FILTER (
WHERE b.debit_kredit = 'H'
) AS account,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'S'
) AS text1,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'H'
) AS text2
FROM base b
GROUP BY
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount
ORDER BY
b.fiscal_year,
b.doc_date,
b.reference
`);
return result.rows || result
}
async function claimSapPosting(db, invoiceNo, initialPosting) {
// Dokumen lama yang sudah tercatat di CMS juga tidak boleh dikirim ulang.
const invoice = await getInvoice(invoiceNo, db);
if (!invoice || invoice.c_return_sap) return false;
const postedEntry = await db('public.posting_et')
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 0 })
.first('no_dok');
if (postedEntry) return false;
const inserted = await db(sapPostingTable)
.insert({ invoice_no: invoiceNo, state: 'sending', initial_posting: initialPosting })
.onConflict('invoice_no').ignore()
.returning('invoice_no');
return inserted.length === 1;
}
function releaseUnsentPosting(db, invoiceNo) {
return db(sapPostingTable).where({ invoice_no: invoiceNo, state: 'sending' }).del();
}
function recordSapOutcome(db, invoiceNo, documentNo, outcome) {
return db.transaction(async (trx) => {
const [posting] = await trx(sapPostingTable)
.where({ invoice_no: invoiceNo, state: 'sending' })
.update({
state: documentNo ? 'accepted' : 'unknown',
document_no: documentNo,
outcome,
updated_at: trx.fn.now(),
})
.returning('initial_posting');
if (!posting || documentNo) return;
await trx('public.posting_et')
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 3 })
.update({ status0: 'E', status1: outcome });
const invoice = await getInvoice(invoiceNo, trx);
if (invoice) {
await writePaynentHistory(
invoice,
`SAP reconciliation required: ${outcome}`,
posting.initial_posting ? 102 : 118,
trx
);
}
});
}
function getAcceptedSapPostings(db) {
return db(sapPostingTable).where({ state: 'accepted' }).orderBy('invoice_no').pluck('invoice_no');
}
// Klaim finalisasi dan seluruh perubahan lokal di-commit bersama.
async function finishSapPosting(db, invoiceNo) {
return db.transaction(async (trx) => {
const [posting] = await trx(sapPostingTable)
.where({ invoice_no: invoiceNo, state: 'accepted' })
.update({ state: 'completed', updated_at: trx.fn.now() })
.returning(['document_no', 'initial_posting']);
if (!posting) return null;
const { document_no: documentNo, initial_posting: initialPosting } = posting;
const [invoice] = await trx('payment.t_d_invoice')
.where('c_invoice_no', invoiceNo)
.where(function () {
this.whereNull('c_return_sap').orWhereIn('c_return_sap', ['', documentNo]);
})
.update({ c_return_sap: documentNo })
.returning('*');
if (!invoice) throw new Error('Invoice missing or already associated with a different SAP document');
const paymentRequests = trx('payment.t_d_payment_request_topup_online')
.where('c_payment', invoiceNo)
.select('c_load_balance_no');
await trx('trx.t_d_load_balance')
.whereIn('c_load_balance_no', paymentRequests)
.update({ c_return_sap: documentNo });
await trx('public.posting_et')
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 3 })
.update({
pos_status: 0,
status0: 'S',
no_doksap: documentNo,
status1: 'SAP document confirmed',
});
await writePaynentHistory(
invoice,
initialPosting ? 'SUCCESSFULLY' : 'SUCCESS TO RETRY SAP',
initialPosting ? 102 : 118,
trx
);
return invoice;
});
}
const writePaynentHistory = async (data, message, i_log_name, trx) => {
const result = await trx('log.t_log_invoice').insert({
// i_log_name : 102,
i_log_name: i_log_name,
d_log: trx.raw('NOW()'),
c_invoice_no: data?.c_invoice_no || '',
c_partner_name: data?.c_partner_name || '',
j_new_data: JSON.stringify(data),
d_payment_date: trx.raw('NOW()'),
c_note: message,
c_status: 'S',
d_created: trx.raw('NOW()'),
m_amount: data?.amount || 0,
m_mdr_amount: 0,
m_mdr_net: data?.amount || 0
}, ['i_log_name', 'c_note'])
return result
}
async function getSapSettings(db) {
const codes = {
SAP_FI_URL_FOR_FB70: 'url',
SAP_AUTH_USERNAME: 'username',
SAP_AUTH_PASSWORD: 'password',
};
const rows = await db('public.t_m_global_parameter_sap')
.where('c_status', 'A')
.whereIn('c_code', Object.keys(codes))
.select('c_code', 'c_value');
return Object.fromEntries(rows.map(({ c_code, c_value }) => [codes[c_code], c_value]));
}
const getInvoice = async (code, trx) => {
const result = await trx('payment.t_d_invoice')
.where('c_invoice_no', '=', code)
.first()
return result
}
module.exports = {
generateInvoice,
insertPostingEt,
claimSapPosting,
releaseUnsentPosting,
recordSapOutcome,
getAcceptedSapPostings,
finishSapPosting,
getPostingEt,
writePaynentHistory,
getSapSettings,
getInvoice
};