const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('canEdit', { description: 'Check if all the received sales are aditable', accessType: 'READ', accepts: [{ arg: 'sales', type: ['number'], required: true }], returns: { type: 'boolean', root: true }, http: { path: `/canEdit`, verb: 'GET' } }); Self.canEdit = async(ctx, sales, options) => { const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const salesData = await models.Sale.find({ fields: ['id', 'itemFk', 'ticketFk'], where: {id: {inq: sales}}, include: { relation: 'item', scope: { fields: ['id', 'isFloramondo'], } } }, myOptions); const ticketId = salesData[0].ticketFk; const isTicketEditable = await models.Ticket.isEditable(ctx, ticketId, myOptions); if (!isTicketEditable) throw new UserError(`The sales of this ticket can't be modified`); const hasSaleTracking = await models.SaleTracking.findOne({where: {saleFk: {inq: sales}}}, myOptions); const hasSaleCloned = await models.SaleCloned.findOne({where: {saleClonedFk: {inq: sales}}}, myOptions); const isTicketWeekly = await models.TicketWeekly.findOne({where: {ticketFk: ticketId}}, myOptions); const hasSaleFloramondo = salesData.find(sale => sale.item().isFloramondo); const canEditTracked = await models.ACL.checkAccessAcl(ctx, 'Sale', 'editTracked'); const canEditCloned = await models.ACL.checkAccessAcl(ctx, 'Sale', 'editCloned'); const canEditWeekly = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'editWeekly'); const canEditFloramondo = await models.ACL.checkAccessAcl(ctx, 'Sale', 'editFloramondo'); const shouldEditTracked = canEditTracked || !hasSaleTracking; const shouldEditCloned = canEditCloned || !hasSaleCloned; const shouldEditWeekly = canEditWeekly || !isTicketWeekly; const shouldEditFloramondo = canEditFloramondo || !hasSaleFloramondo; return shouldEditTracked && shouldEditCloned && shouldEditWeekly && shouldEditFloramondo; }; };