salix/modules/ticket/back/methods/ticket/transferClient.js

76 lines
2.4 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('transferClient', {
description: 'Transferring ticket to another client',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'the ticket id',
http: {source: 'path'}
}, {
arg: 'clientFk',
type: 'number',
required: true,
}],
http: {
path: `/:id/transferClient`,
verb: 'PATCH'
}
});
Self.transferClient = async(ctx, id, clientFk, options) => {
const models = Self.app.models;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
await Self.isEditableOrThrow(ctx, id, myOptions);
const ticketRefund = await models.TicketRefund.findOne({
where: {or: [{originalTicketFk: id}, {refundTicketFk: id}]},
include: [{relation: 'refundTicket'}, {relation: 'originalTicket'}]
}, myOptions);
const client = await models.Client.findById(clientFk,
{fields: ['id', 'defaultAddressFk']}, myOptions);
const address = await models.Address.findById(client.defaultAddressFk,
{fields: ['id', 'nickname']}, myOptions);
const attributes = {clientFk, addressFk: client.defaultAddressFk, nickname: address.nickname};
const tickets = [];
const ticketIds = [];
if (ticketRefund) {
const {refundTicket, originalTicket} = ticketRefund;
tickets.push(refundTicket(), originalTicket());
for (const ticket of tickets) {
await ticket.updateAttributes(attributes, myOptions);
ticketIds.push(ticket.id);
}
} else {
await Self.updateAll({id}, attributes, myOptions);
ticketIds.push(id);
}
await models.Claim.updateAll({ticketFk: {inq: ticketIds}}, {clientFk}, myOptions);
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};