let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('new', { description: 'Creates a new ticket and returns the id', accessType: 'WRITE', accepts: [{ arg: 'clientId', type: 'number', description: `The client id filter`, required: true }, { arg: 'shipped', type: 'date', description: `The shipment date filter` }, { arg: 'landed', type: 'date', description: `The landing date filter` }, { arg: 'warehouseId', type: 'number', description: `The warehouse id filter`, required: true }, { arg: 'companyId', type: 'number', description: `The company id filter` }, { arg: 'addressId', type: 'number', description: `The address id filter`, required: true }, { arg: 'agencyModeId', type: 'any', description: `The agencyMode id filter` }, { arg: 'routeId', type: 'number', description: `The route id filter` }], returns: { type: 'object', root: true }, http: { path: `/new`, verb: 'post' } }); Self.new = async(ctx, options) => { const args = ctx.args; const userId = ctx.req.accessToken.userId; const models = Self.app.models; const myOptions = {userId}; let tx; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const address = await models.Address.findOne({ where: {id: args.addressId}, fields: ['id', 'clientFk'], include: { relation: 'client' } }, myOptions); if (!address) throw new UserError(`This address doesn't exist`); let agencyMode; if (args.agencyModeId) agencyMode = await models.AgencyMode.findById(args.agencyModeId, null, myOptions); if (address.client().typeFk === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { const canCreateTicket = await models.Client.canCreateTicket(args.clientId, myOptions); if (!canCreateTicket) throw new UserError(`You can't create a ticket for an inactive client`); } if (!args.shipped && args.landed) { const shippedResult = await models.Agency.getShipped(ctx, args.landed, address.id, args.agencyModeId, args.warehouseId, myOptions); args.shipped = (shippedResult && shippedResult.shipped) || args.landed; } if (args.shipped && !args.landed) { const landedResult = await models.Agency.getLanded(args.shipped, address.id, args.agencyModeId, args.warehouseId, false, myOptions); args.landed = landedResult && landedResult.landed; } query = `CALL vn.ticket_add(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @result); SELECT @result newTicketId;`; const result = await Self.rawSql(query, [ args.clientId, args.shipped, args.warehouseId, args.companyId || 442, args.addressId, args.agencyModeId || null, args.routeId || null, args.landed, true, userId ], myOptions); const ticket = await models.Ticket.findById(result[1][0].newTicketId, null, myOptions); if (tx) await tx.commit(); return ticket; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };