module.exports = Self => { Self.remoteMethodCtx('regularize', { description: 'Sends items to the trash', accessType: 'WRITE', accepts: [{ arg: 'itemFk', type: 'number', required: true, description: 'The item id', }, { arg: 'quantity', type: 'number', required: true, description: 'The visible quantity', }, { arg: 'warehouseFk', type: 'number', required: true, description: 'The id of the wharehouse where the inventory happened', }], returns: { type: 'boolean', root: true }, http: { path: `/regularize`, verb: 'post' } }); Self.regularize = async (ctx, itemFk, quantity, warehouseFk) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; const itemDestination = await models.ClaimDestination.findOne({ include: { relation: 'address', scope: { fields: ['clientFk'] } }, where: {description: 'Corregido'} }); let transaction = await Self.beginTransaction({}); try { let item = await models.Item.findById(itemFk); let ticketFk = await getTicketId({ clientFk: itemDestination.address.clientFk, addressFk: itemDestination.addressFk, warehouseFk: warehouseFk }, transaction); if (!ticketFk) { ticketFk = await createTicket({ clientFk: itemDestination.address().clientFk, addressFk: itemDestination.addressFk, warehouseFk: warehouseFk, userId: userId }, transaction); } let query = ` CALL vn.getItemVisibleAvailable(?,curdate(),?,?)`; let options = [itemFk, warehouseFk, true]; let [res] = await Self.rawSql(query, options, {transaction: transaction}); let newQuantity = res[0].visible - quantity; await models.Sale.create({ ticketFk: ticketFk, itemFk: itemFk, concept: item.name, quantity: newQuantity, discount: 100 }, {transaction: transaction}); await transaction.commit(); return ticketFk; } catch (e) { await transaction.rollback(); throw e; } async function createTicket(params, transaction) { let ticket = await Self.app.models.Ticket.new({ shipped: new Date(), landed: new Date(), clientFk: params.clientFk, warehouseFk: params.warehouseFk, companyFk: params.companyFk, addressFk: params.addressFk, userId: params.userId }, {transaction: transaction}); return ticket.id; } async function getTicketId(params, transaction) { const currentDate = new Date(); currentDate.setHours(null, null, null); let ticket = await Self.app.models.Ticket.findOne({ where: { addressFk: params.addressFk, warehouseFk: params.warehouseFk, shipped: currentDate, landed: currentDate } }, {transaction: transaction}); return ticket && ticket.id; } }; };