No problem
collection.addAction('Traiter la demande de remboursement', {
scope: 'Single',
form: [
{
label: 'Traiter la demande',
type: 'Enum',
enumValues: ['Valider', 'Refuser', 'A modifier'],
isRequired: true,
},
{
label: 'montant',
type: 'Number',
value: async context => {
const refundRequestData = await context.getRecord(['amount']);
const refundStatus = await context.formValues['Traiter la demande'];
if (refundStatus === 'Valider') {
return refundRequestData.amount;
}
return 0;
},
isRequired: true
},
{
label: 'commentaire',
type: 'String',
widget: 'TextArea',
placeholder: "Commentaire visible au client, attention en cas de suppression de l'ancien message ce dernier sera perdu. Privilégiez un saut à la ligne si vous souhaiter compléter le message.",
defaultValue: async context => {
const refundRequestData = await context.getRecord(['agentComment']);
if (refundRequestData.agentComment) {
return refundRequestData.agentComment;
}
return null;
},
isRequired: async context => {
const refundStatus = context.formValues['Traiter la demande'];
if (refundStatus === 'Refuser') {
return true;
}
return false;
}
},
],
execute: async (context, resultBuilder) => {
const sequelize = context.collection.nativeDriver.sequelize;
const transaction = await sequelize.transaction();
try {
// Get the values of the input fields entered by the admin user.
const attrs = context.formValues;
const refundAmount = attrs.montant;
const agentComment = attrs.commentaire;
const refundRequestFinalStatus = attrs['Traiter la demande'];
// Retrieve actual refund request beneficiary_firstname, user_email, invoiceAmount amount, fk_beneficiary.id, fk_user.id, fk_beneficiary.iban, fk_beneficiary.bic & fk_beneficiary.ibanHolderName
const refundRequest = await context.getRecord(['id', 'beneficiary_firstname', 'user_email', 'invoiceAmount', 'amount', 'fk_user:id', 'fk_beneficiary:id', 'fk_beneficiary:iban', 'fk_beneficiary:bic', 'fk_beneficiary:ibanHolderName']);
// Check refund compliance
if (attrs.montant < 0) {
console.error(`Can not process refund request ${refundRequest.id}, the amount input can not be inferior to 0`);
return resultBuilder.error('La demande ne peut être traitée, le montant que vous renseignez ne doit pas être négatif');
}
// Retrieve beneficiary cover fk_myCover.id, fk_myCover.fk_cover.title, fk_myCover.refundLimit, fk_myCover.fk_myCommonPot, fk_myCover.refundedBalanceEstimation, fk_myCover.refunded, fk_myCover.refundedQuantityEstimation, fk_myCover.refundedQuantity
const myCover = await context.getRecord(['fk_myCover:id', 'fk_myCover:fk_cover:title', 'fk_myCover:refundLimit', 'fk_myCover:fk_myCommonPot:id', 'fk_myCover:refundedBalanceEstimation', 'fk_myCover:refunded', 'fk_myCover:refundedQuantityEstimation', 'fk_myCover:refundedQuantity']);
const sendEmailData = {
userEmail: refundRequest.user_email,
beneficiaryFirstname: refundRequest.beneficiary_firstname,
receiptAmount: refundRequest.invoiceAmount,
refundAmount: refundRequest.amount,
guarantee: myCover.fk_myCover.fk_cover.title,
refundRequestDate: moment().format('DD/MM/YYYY'),
refundLimit: myCover.fk_myCover.refundLimit,
}
let message = {};
let pushContent = '';
let status = null;
switch (refundRequestFinalStatus) {
case 'Valider':
status = "VALIDATED";
message = 'La demande a été validée';
break;
case 'A modifier':
status = "EDITABLE";
message = 'La demande peut être modifiée par l\'utilisateur'
break;
default:
status = "REFUSED";
message = 'La demande a été refusée'
break;
}
// Process refund request
try {
// retrieve refunds attached to refund request
const refundsList = await context.dataSource.getCollection('NP_refunds').list(
{
conditionTree: {
field: "id",
operator: "Equal",
value: refundRequest.id,
},
},
["id", "amount", "status"],
);
let refundedAmount = 0;
for (const refund of refundsList) {
// set refund request refunded amount (sum of all refunds)
if (refund.status !== 'CLOSED') {
refundedAmount += refund.amount;
}
}
let myCommonPot, myCoverData, myCommonPotData = null;
// retrieve cover's attached common pot if exists
if (myCover.fk_myCover?.fk_myCommonPot?.id) {
// myCommonPot = await myCommonPots.findByPk(myCover.fkMyCommonPotIdKey);
myCommonPot = await context.dataSource.getCollection('NP_myCommonPots').list(
{
conditionTree: {
field: "id",
operator: "Equal",
value: myCover.fk_myCover.fk_myCommonPot.id,
},
},
["id", "refunded", "refundedBalanceEstimation", "refundedBalanceEstimation"],
);
};
// process refund request
if (status === 'VALIDATED') {
// set cover + common pot consumption + estimation
myCoverData = {
refunded: myCover.fk_myCover.refunded + refundAmount,
refundedQuantity: myCover.fk_myCover.refundedQuantity + 1
};
myCoverData.refundedBalanceEstimation = myCover.fk_myCover.refundedBalanceEstimation - refundRequest.amount + refundAmount;
if (myCommonPot) {
myCommonPotData = { refunded: myCommonPot[0].refunded + refundAmount };
myCommonPotData.refundedBalanceEstimation = myCommonPot[0].refundedBalanceEstimation - refundRequest.amount + refundAmount;
}
refundedAmount = refundAmount;
// add allowed amount to refunded amount
const currentRefundLimit = myCover.fk_myCover.refundLimit - myCover.fk_myCover.refunded - refundAmount;
const previousRefundLimit = myCover.fk_myCover.refundLimit - myCover.fk_myCover.refunded;
// Send email to beneficiary
// await mailjetAPI.sendConfirmationRefundRequest(sendEmailData.userEmail, sendEmailData.beneficiaryFirstname, sendEmailData.receiptAmount, sendEmailData.refundAmount, sendEmailData.guarantee, sendEmailData.refundRequestDate, currentRefundLimit, previousRefundLimit);
} else {
// rollback cover & common pot balance + quantity estimation
let refundedQuantityEstimation;
if (!myCover.fk_myCover.refundedQuantityEstimation || myCover.fk_myCover.refundedQuantityEstimation <= 0) {
refundedQuantityEstimation = 0;
} else {
refundedQuantityEstimation = myCover.fk_myCover.refundedQuantityEstimation - 1;
}
myCoverData = {
refundedBalanceEstimation: myCover.fk_myCover.refundedBalanceEstimation - refundRequest.amount,
refundedQuantityEstimation
};
if (myCommonPot) {
myCommonPotData = {
refundedBalanceEstimation: myCommonPot[0].refundedBalanceEstimation - refundRequest.amount
};
}
if (status === 'REFUSED') {
refundedAmount = 0;
// Send email to beneficiary
// await mailjetAPI.sendRefusedRefundRequest(sendEmailData.userEmail, sendEmailData.beneficiaryFirstname, sendEmailData.receiptAmount, sendEmailData.refundAmount, sendEmailData.guarantee);
} else {
refundedAmount = 0;
// Send email to beneficiary
// await mailjetAPI.sendEditableRefundRequest(sendEmailData.userEmail, sendEmailData.beneficiaryFirstname, sendEmailData.receiptAmount, sendEmailData.refundAmount, sendEmailData.guarantee);
}
}
// if everything ok, update cover
await sequelize.models.covers.update(myCoverData, {
where: {
id: myCover.fk_myCover.id
}, transaction
});
// if cover belongs to common pot, update common pot
if (myCommonPot) {
await sequelize.models.myCommonPots.update(myCommonPotData, { where: { id: myCommonPot[0].id }, transaction });
}
// create refund if refund request is validated
if (status === 'VALIDATED') {
await sequelize.models.refunds.create({
id: uuid.v4(),
amount: refundAmount,
comment: agentComment,
bic: refundRequest.fk_beneficiary.bic,
iban: refundRequest.fk_beneficiary.iban,
ibanHolderName: refundRequest.fk_beneficiary.ibanHolderName,
status: status,
fk_myCover: myCover.fk_myCover.id,
fk_refundRequest: refundRequest.id,
fk_userId: refundRequest.fk_user.id,
fk_beneficiaryId: refundRequest.fk_beneficiary.id
}, { transaction });
}
// update refund request
await sequelize.models.refundRequests.update({
status,
processingDateNostrumCare: new Date(),
refundedAmount,
agentComment
}, { where: { id: refundRequest.id }, transaction });
// Commit transaction if everything's ok
await transaction.commit();
} catch (error) {
console.error(`Error processing refund request (${refundRequest.id}), error : ${error}`);
await transaction.rollback();
return resultBuilder.success(`Problème survenue lors de la procédure, veuillez contacter un developpeur backend`);
}
return resultBuilder.success(message);
} catch (error) {
console.error(`[POST /actions/traiter-la-demande-de-remboursement] : error : ${error}`);
await transaction.rollback();
return resultBuilder.success(`Problème survenue lors de la procédure, veuillez contacter un developpeur backend`);
}
},
});
then everything’s ok it’s just that the ids for fk_refundRequest and fk_myCover aren’t added in the create, yet I have the ids when I log them