module.exports = Self => { Self.remoteMethod('delete', { description: 'Delete sale trackings and item shelving sales', accessType: 'READ', accepts: [ { arg: 'saleFk', type: 'number', description: 'The sale id' }, { arg: 'stateCode', type: 'string' } ], returns: { type: ['object'], root: true }, http: { path: `/delete`, verb: 'POST' } }); Self.delete = async(saleFk, stateCode, 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 { if (stateCode === 'PREPARED') { const itemShelvingSales = await models.ItemShelvingSale.find({where: {saleFk: saleFk}}, myOptions); for (let itemShelvingSale of itemShelvingSales) await itemShelvingSale.destroy(myOptions); } const state = await models.State.findOne({ where: {code: stateCode} }, myOptions); const filter = { where: { saleFk: saleFk, stateFk: state.id } }; const saleTrackings = await models.SaleTracking.find(filter, myOptions); for (let saleTracking of saleTrackings) await saleTracking.destroy(myOptions); if (tx) await tx.commit(); return true; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };