module.exports = Self => { Self.remoteMethodCtx('deleteSales', { description: 'Deletes the selected sales', accessType: 'WRITE', accepts: [{ arg: 'sales', type: ['object'], required: true, description: 'The sales to remove' }, { arg: 'ticketId', type: 'number', required: true, description: 'The ticket id' }], returns: { type: ['object'], root: true }, http: { path: `/deleteSales`, verb: 'POST' } }); Self.deleteSales = async(ctx, sales, ticketId, options) => { const $t = ctx.req.__; // $translate 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 { const saleIds = sales.map(sale => sale.id); await models.Sale.canEdit(ctx, saleIds, myOptions); const ticket = await models.Ticket.findById(ticketId, { include: { relation: 'client', scope: { include: { relation: 'salesPersonUser', scope: { fields: ['id', 'name'] } } } } }, myOptions); const promises = []; let deletions = ''; for (let sale of sales) { const deletedSale = models.Sale.destroyById(sale.id, myOptions); deletions += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity})`; promises.push(deletedSale); } const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { const url = await Self.app.models.Url.getUrl(); const message = $t('Deleted sales from ticket', { ticketId: ticketId, ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); } const deletedSales = await Promise.all(promises); if (tx) await tx.commit(); return deletedSales; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };