Files
bodyshop/server/intellipay/lib/handleInvoiceBasedPayment.js
Dave Richer 9bf6ba9cf0 feature/IO-2885-IntelliPay-App-Postback
- Refactor / Add Tests
2025-04-02 11:09:03 -04:00

102 lines
2.6 KiB
JavaScript

const handlePaymentValidationError = require("./handlePaymentValidationError");
const {
GET_JOBID_BY_MERCHANTID_RONUMBER,
INSERT_PAYMENT_RESPONSE,
INSERT_NEW_PAYMENT
} = require("../../graphql-client/queries");
const getPaymentType = require("./getPaymentType");
const moment = require("moment");
const gqlClient = require("../../graphql-client/graphql-client").client;
/**
* @description Handle invoice-based payment processing
* @param values
* @param logger
* @param logMeta
* @param res
* @returns {Promise<*>}
*/
const handleInvoiceBasedPayment = async (values, logger, logMeta, res) => {
// Validate required fields
if (!values.merchantid) {
return handlePaymentValidationError(
res,
logger,
"intellipay-postback-no-merchantid",
"Merchant ID is missing",
logMeta
);
}
// Fetch job data
const result = await gqlClient.request(GET_JOBID_BY_MERCHANTID_RONUMBER, {
merchantID: values.merchantid,
roNumber: values.invoice
});
if (!result?.jobs?.length) {
return handlePaymentValidationError(res, logger, "intellipay-postback-job-not-found", "Job not found", logMeta);
}
const job = result.jobs[0];
const bodyshop = job?.bodyshop;
if (!bodyshop) {
return handlePaymentValidationError(
res,
logger,
"intellipay-postback-bodyshop-not-found",
"Bodyshop not found",
logMeta
);
}
const ipMapping = bodyshop.intellipay_config?.payment_map;
logger.log("intellipay-postback-invoice-job-fetched", "DEBUG", "api", null, {
job,
...logMeta
});
// Create payment record
const paymentResult = await gqlClient.request(INSERT_NEW_PAYMENT, {
paymentInput: {
amount: values.total,
transactionid: values.authcode,
payer: "Customer",
type: getPaymentType(ipMapping, values.cardtype),
jobid: job.id,
date: moment(Date.now())
}
});
logger.log("intellipay-postback-invoice-payment-success", "DEBUG", "api", null, {
paymentResult,
...logMeta
});
// Create payment response record
const responseResults = await gqlClient.request(INSERT_PAYMENT_RESPONSE, {
paymentResponse: {
amount: values.total,
bodyshopid: bodyshop.id,
paymentid: paymentResult.id,
jobid: job.id,
declinereason: "Approved",
ext_paymentid: values.paymentid,
successful: true,
response: values
}
});
logger.log("intellipay-postback-invoice-response-success", "DEBUG", "api", null, {
responseResults,
...logMeta
});
return res.sendStatus(200);
};
module.exports = handleInvoiceBasedPayment;