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: 'stateCodes', type: ['string'] }, ], returns: { type: 'boolean', root: true }, http: { path: `/delete`, verb: 'POST' } }); Self.delete = async(saleFk, stateCodes, 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 { const itemShelvingSales = await models.ItemShelvingSale.find({where: {saleFk: saleFk}}, myOptions); for (let itemShelvingSale of itemShelvingSales) await itemShelvingSale.destroy(myOptions); const states = await models.State.find({ fields: ['id'], where: { code: {inq: stateCodes} } }, myOptions); const stateIds = states.map(state => state.id); const filter = { where: { saleFk: saleFk, stateFk: {inq: stateIds} } }; 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; } }; };