|
| 1 | +import _ from 'lodash'; |
| 2 | + |
| 3 | +import models from '../../models'; |
| 4 | +import util from '../../util'; |
| 5 | +import { COPILOT_APPLICATION_STATUS, COPILOT_OPPORTUNITY_STATUS, COPILOT_REQUEST_STATUS } from '../../constants'; |
| 6 | +import { PERMISSION } from '../../permissions/constants'; |
| 7 | + |
| 8 | +module.exports = [ |
| 9 | + (req, res, next) => { |
| 10 | + if (!util.hasPermissionByReq(PERMISSION.CANCEL_COPILOT_OPPORTUNITY, req)) { |
| 11 | + const err = new Error('Unable to cancel copilot opportunity'); |
| 12 | + _.assign(err, { |
| 13 | + details: JSON.stringify({ message: 'You do not have permission to cancel copilot opportunity' }), |
| 14 | + status: 403, |
| 15 | + }); |
| 16 | + return Promise.reject(err); |
| 17 | + } |
| 18 | + // default values |
| 19 | + const opportunityId = _.parseInt(req.params.id); |
| 20 | + |
| 21 | + return models.sequelize.transaction(async (transaction) => { |
| 22 | + req.log.debug('Canceling Copilot opportunity transaction', opportunityId); |
| 23 | + const opportunity = await models.CopilotOpportunity.findOne({ |
| 24 | + where: { id: opportunityId }, |
| 25 | + transaction, |
| 26 | + }); |
| 27 | + |
| 28 | + if (!opportunity) { |
| 29 | + const err = new Error(`No opportunity available for id ${opportunityId}`); |
| 30 | + err.status = 404; |
| 31 | + throw err; |
| 32 | + } |
| 33 | + |
| 34 | + const copilotRequest = await models.CopilotRequest.findOne({ |
| 35 | + where: { |
| 36 | + id: opportunity.copilotRequestId, |
| 37 | + }, |
| 38 | + transaction, |
| 39 | + }); |
| 40 | + |
| 41 | + const applications = await models.CopilotApplication.findAll({ |
| 42 | + where: { |
| 43 | + opportunityId: opportunity.id, |
| 44 | + }, |
| 45 | + transaction, |
| 46 | + }); |
| 47 | + |
| 48 | + const promises = []; |
| 49 | + applications.forEach((application) => { |
| 50 | + promises.push(application.update({ |
| 51 | + status: COPILOT_APPLICATION_STATUS.CANCELED, |
| 52 | + }, { |
| 53 | + transaction, |
| 54 | + })); |
| 55 | + }); |
| 56 | + |
| 57 | + await Promise.all(promises); |
| 58 | + |
| 59 | + await copilotRequest.update({ |
| 60 | + status: COPILOT_REQUEST_STATUS.CANCELED, |
| 61 | + }, { |
| 62 | + transaction, |
| 63 | + }); |
| 64 | + |
| 65 | + await opportunity.update({ |
| 66 | + status: COPILOT_OPPORTUNITY_STATUS.CANCELED, |
| 67 | + }, { |
| 68 | + transaction, |
| 69 | + }); |
| 70 | + |
| 71 | + res.status(200).send({ id: opportunity.id }); |
| 72 | + }) |
| 73 | + |
| 74 | + .catch((err) => { |
| 75 | + if (err.message) { |
| 76 | + _.assign(err, { details: err.message }); |
| 77 | + } |
| 78 | + util.handleError('Error canceling copilot opportunity', err, req, next); |
| 79 | + }); |
| 80 | + }, |
| 81 | +]; |
0 commit comments