salix/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js

213 lines
7.6 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('importToNewRefundTicket', {
description: 'Import lines of claimBeginning to new ticket with shipped, landed dates, agency and company',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'the claim id',
http: {source: 'path'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/importToNewRefundTicket`,
verb: 'POST'
}
});
Self.importToNewRefundTicket = async(ctx, id, options) => {
const models = Self.app.models;
const token = ctx.req.accessToken;
const userId = token.userId;
const filter = {
where: {id: id},
include: [
{
relation: 'ticket',
scope: {
fields: ['id', 'clientFk', 'warehouseFk', 'companyFk', 'addressFk'],
include: {
relation: 'address',
scope: {
fields: ['nickname']
}
}
}
}
]
};
const salesFilter = {
where: {claimFk: id},
include: [
{
relation: 'sale',
scope: {
fields: [
'id',
'itemFk',
'concept',
'price',
'discount',
'reserved',
'isPicked',
'created',
'priceFixed',
'isPriceFixed']
}
}
]
};
let tx;
const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const claim = await models.Claim.findOne(filter, myOptions);
const today = Date.vnNew();
let agencyModeFk;
let nickname;
let state;
let discountValue = null;
let packages = 0;
const claimConfig = await models.ClaimConfig.findOne();
const warehouseFk = claimConfig.warehouseFk;
if (claim.pickup === null || claim.pickup == 'agency') {
state = await models.State.findOne({
where: {code: 'DELIVERED'}
}, myOptions);
const agencyMode = await models.AgencyMode.findOne({
where: {code: 'refund'}
}, myOptions);
agencyModeFk = agencyMode.id;
nickname = `Abono del: ${claim.ticketFk}`;
} else {
discountValue = 100;
packages = 1;
state = await models.State.findOne({
where: {code: 'WAITING_FOR_PICKUP'}
}, myOptions);
nickname = `Recogida pendiente del: ${claim.ticketFk}`;
agencyModeFk = claimConfig.pickupDeliveryFk;
}
const nextShipped = await models.Agency.getShipped(
ctx, today, claim.ticket().addressFk, agencyModeFk, warehouseFk, myOptions
);
const newRefundTicket = await models.Ticket.create({
clientFk: claim.ticket().clientFk,
shipped: nextShipped,
landed: null,
nickname,
warehouseFk,
companyFk: claim.ticket().companyFk,
addressFk: claim.ticket().addressFk,
agencyModeFk,
zoneFk: claim.ticket().zoneFk,
packages
}, myOptions);
if (claim.pickup == 'pickup') {
const observationDelivery =
await models.ObservationType.findOne({where: {code: 'delivery'}}, myOptions);
await saveObservation({
description: `recoger reclamación: ${claim.id}`,
ticketFk: newRefundTicket.id,
observationTypeFk: observationDelivery.id
}, myOptions);
}
await models.TicketRefund.create({
refundTicketFk: newRefundTicket.id,
originalTicketFk: claim.ticket().id
}, myOptions);
const salesToRefund = await models.ClaimBeginning.find(salesFilter, myOptions);
const createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, discountValue, myOptions);
await insertIntoClaimEnd(createdSales, id, userId, myOptions);
await models.Ticket.state(ctx, {
ticketFk: newRefundTicket.id,
stateFk: state.id,
userFk: userId
}, myOptions);
if (tx) await tx.commit();
return newRefundTicket;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
async function addSalesToTicket(salesToRefund, newTicketId, discountValue, options) {
const createdSales = [];
const models = Self.app.models;
for (const saleToRefund of salesToRefund) {
const oldSale = saleToRefund.sale();
const newSaleData = {
itemFk: oldSale.itemFk,
ticketFk: newTicketId,
concept: oldSale.concept,
quantity: -Math.abs(saleToRefund.quantity),
price: oldSale.price,
discount: discountValue ?? oldSale.discount,
reserved: oldSale.reserved,
isPicked: oldSale.isPicked,
created: oldSale.created
};
const newSale = await models.Sale.create(newSaleData, options);
const oldSaleComponents = await models.SaleComponent.find({
where: {saleFk: oldSale.id}
}, options);
const newComponents = oldSaleComponents.map(component => {
const data = component.toJSON ? component.toJSON() : {...component};
delete data.id;
data.saleFk = newSale.id;
return data;
});
await models.SaleComponent.create(newComponents, options);
createdSales.push(newSale);
}
return createdSales;
}
async function insertIntoClaimEnd(createdSales, claimId, workerId, options) {
const formatedSales = [];
createdSales.forEach(sale => {
let formatedSale = {
saleFk: sale.id,
claimFk: claimId,
workerFk: workerId
};
formatedSales.push(formatedSale);
});
await Self.app.models.ClaimEnd.create(formatedSales, options);
}
async function saveObservation(observation, options) {
const query = `INSERT INTO vn.ticketObservation (ticketFk, observationTypeFk, description) VALUES(?, ?, ?)
ON DUPLICATE KEY
UPDATE description = CONCAT(vn.ticketObservation.description, VALUES(description),' ')`;
await Self.rawSql(query, [
observation.ticketFk,
observation.observationTypeFk,
observation.description
], options);
}
};