|
| 1 | +import _ from 'lodash'; |
| 2 | +import { middleware as tcMiddleware } from 'tc-core-library-js'; |
| 3 | + |
| 4 | +import models from '../../models'; |
| 5 | +import { ADMIN_ROLES } from '../../constants'; |
| 6 | +import util from '../../util'; |
| 7 | + |
| 8 | +const permissions = tcMiddleware.permissions; |
| 9 | + |
| 10 | +module.exports = [ |
| 11 | + permissions('copilotApplications.view'), |
| 12 | + (req, res, next) => { |
| 13 | + |
| 14 | + const canAccessAllApplications = util.hasRoles(req, ADMIN_ROLES) || util.hasProjectManagerRole(req); |
| 15 | + const userId = req.authUser.userId; |
| 16 | + const opportunityId = _.parseInt(req.params.id); |
| 17 | + |
| 18 | + let sort = req.query.sort ? decodeURIComponent(req.query.sort) : 'createdAt desc'; |
| 19 | + if (sort.indexOf(' ') === -1) { |
| 20 | + sort += ' asc'; |
| 21 | + } |
| 22 | + const sortableProps = ['createdAt asc', 'createdAt desc']; |
| 23 | + if (_.indexOf(sortableProps, sort) < 0) { |
| 24 | + return util.handleError('Invalid sort criteria', null, req, next); |
| 25 | + } |
| 26 | + const sortParams = sort.split(' '); |
| 27 | + |
| 28 | + // Admin can see all requests and the PM can only see requests created by them |
| 29 | + const whereCondition = _.assign({ |
| 30 | + opportunityId, |
| 31 | + }, |
| 32 | + canAccessAllApplications ? {} : { createdBy: userId }, |
| 33 | + ); |
| 34 | + |
| 35 | + return models.CopilotApplication.findAll({ |
| 36 | + where: whereCondition, |
| 37 | + include: [ |
| 38 | + { |
| 39 | + model: models.CopilotOpportunity, |
| 40 | + as: 'copilotOpportunity', |
| 41 | + }, |
| 42 | + ], |
| 43 | + order: [[sortParams[0], sortParams[1]]], |
| 44 | + }) |
| 45 | + .then(copilotApplications => res.json(copilotApplications)) |
| 46 | + .catch((err) => { |
| 47 | + util.handleError('Error fetching copilot applications', err, req, next); |
| 48 | + }); |
| 49 | + }, |
| 50 | +]; |
0 commit comments