salix/modules/ticket/back/methods/sale/clone.js

77 lines
2.6 KiB
JavaScript

module.exports = async function clone(ctx, Self, sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, isRefund, myOptions) {
const models = Self.app.models;
const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))];
const [firstTicketId] = ticketsIds;
const now = Date.vnNew();
let refundTickets = [];
let refundTicket;
if (!group) {
for (const ticketId of ticketsIds) {
refundTicket = await createTicketRefund(
ticketId,
now,
refundAgencyMode,
refoundZoneId,
null,
myOptions
);
refundTickets.push(refundTicket);
}
} else {
refundTicket = await createTicketRefund(
firstTicketId,
now,
refundAgencyMode,
refoundZoneId,
withWarehouse,
myOptions
);
}
for (const sale of sales) {
const createdSale = await models.Sale.create({
ticketFk: (group) ? refundTicket.id : sale.ticketFk,
itemFk: sale.itemFk,
quantity: (isRefund) ? - sale.quantity : sale.quantity,
concept: sale.concept,
price: sale.price,
discount: sale.discount,
}, myOptions);
const components = sale.components();
for (const component of components)
component.saleFk = createdSale.id;
await models.SaleComponent.create(components, myOptions);
}
if (servicesIds && servicesIds.length > 0) {
const servicesFilter = {
where: {id: {inq: servicesIds}}
};
const services = await models.TicketService.find(servicesFilter, myOptions);
for (const service of services) {
await models.TicketService.create({
description: service.description,
quantity: (isRefund) ? - service.quantity : service.quantity,
price: service.price,
taxClassFk: service.taxClassFk,
ticketFk: (group) ? refundTicket.id : service.ticketFk,
ticketServiceTypeFk: service.ticketServiceTypeFk,
}, myOptions);
}
}
const query = `CALL vn.ticket_recalc(?, NULL)`;
if (refundTickets.length > 0) {
for (const refundTicket of refundTickets)
await Self.rawSql(query, [refundTicket.id], myOptions);
return refundTickets.map(refundTicket => refundTicket.id);
} else {
await Self.rawSql(query, [refundTicket.id], myOptions);
return refundTicket;
}
};