|
| 1 | +import validate from 'express-validation'; |
| 2 | +import _ from 'lodash'; |
| 3 | +import Joi from 'joi'; |
| 4 | + |
| 5 | +import models from '../../models'; |
| 6 | +import util from '../../util'; |
| 7 | +import { COPILOT_OPPORTUNITY_TYPE } from '../../constants'; |
| 8 | +import { PERMISSION } from '../../permissions/constants'; |
| 9 | + |
| 10 | +const updateCopilotRequestValidations = { |
| 11 | + body: Joi.object().keys({ |
| 12 | + data: Joi.object() |
| 13 | + .keys({ |
| 14 | + projectId: Joi.number().required(), |
| 15 | + copilotUsername: Joi.string(), |
| 16 | + complexity: Joi.string().valid('low', 'medium', 'high'), |
| 17 | + requiresCommunication: Joi.string().valid('yes', 'no'), |
| 18 | + paymentType: Joi.string().valid('standard', 'other'), |
| 19 | + otherPaymentType: Joi.string(), |
| 20 | + opportunityTitle: Joi.string(), |
| 21 | + projectType: Joi.string().valid(_.values(COPILOT_OPPORTUNITY_TYPE)), |
| 22 | + overview: Joi.string().min(10), |
| 23 | + skills: Joi.array().items( |
| 24 | + Joi.object({ |
| 25 | + id: Joi.string().required(), |
| 26 | + name: Joi.string().required(), |
| 27 | + }), |
| 28 | + ), |
| 29 | + startDate: Joi.date().iso(), |
| 30 | + numWeeks: Joi.number().integer().positive(), |
| 31 | + tzRestrictions: Joi.string(), |
| 32 | + numHoursPerWeek: Joi.number().integer().positive(), |
| 33 | + }) |
| 34 | + .required(), |
| 35 | + }), |
| 36 | +}; |
| 37 | + |
| 38 | +module.exports = [ |
| 39 | + validate(updateCopilotRequestValidations), |
| 40 | + async (req, res, next) => { |
| 41 | + const copilotRequestId = _.parseInt(req.params.copilotRequestId); |
| 42 | + const patchData = req.body.data; |
| 43 | + |
| 44 | + if (!util.hasPermissionByReq(PERMISSION.MANAGE_COPILOT_REQUEST, req)) { |
| 45 | + const err = new Error('Unable to update copilot request'); |
| 46 | + _.assign(err, { |
| 47 | + details: JSON.stringify({ message: 'You do not have permission to update copilot request' }), |
| 48 | + status: 403, |
| 49 | + }); |
| 50 | + util.handleError('Permission error', err, req, next); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + try { |
| 55 | + const copilotRequest = await models.CopilotRequest.findOne({ |
| 56 | + where: { id: copilotRequestId }, |
| 57 | + }); |
| 58 | + |
| 59 | + if (!copilotRequest) { |
| 60 | + const err = new Error(`Copilot request not found for id ${copilotRequestId}`); |
| 61 | + err.status = 404; |
| 62 | + throw err; |
| 63 | + } |
| 64 | + |
| 65 | + // Only update fields provided in patchData |
| 66 | + await copilotRequest.update(_.extend({ |
| 67 | + data: patchData, |
| 68 | + updatedBy: req.authUser.userId, |
| 69 | + })); |
| 70 | + |
| 71 | + res.status(200).json(copilotRequest); |
| 72 | + } catch (err) { |
| 73 | + if (err.message) { |
| 74 | + _.assign(err, { details: err.message }); |
| 75 | + } |
| 76 | + util.handleError('Error updating copilot request', err, req, next); |
| 77 | + } |
| 78 | + }, |
| 79 | +]; |
0 commit comments