-
Notifications
You must be signed in to change notification settings - Fork 3
/
move-details.js
97 lines (78 loc) · 2.86 KB
/
move-details.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const { get, map, omitBy, set } = require('lodash')
const fieldHelpers = require('../../../../common/helpers/field')
const referenceDataHelpers = require('../../../../common/helpers/reference-data')
const referenceDataService = require('../../../../common/services/reference-data')
const CreateBaseController = require('./base')
class MoveDetailsController extends CreateBaseController {
middlewareSetup() {
super.middlewareSetup()
this.use(this.setMoveTypes)
this.use(this.setLocationItems('court', 'to_location_court_appearance'))
this.use(this.setLocationItems('prison', 'to_location_prison_transfer'))
}
setLocationItems(locationType, fieldName) {
return async (req, res, next) => {
const { fields } = req.form.options
if (!fields[fieldName]) {
return next()
}
try {
const locations = await referenceDataService.getLocationsByType(
locationType
)
const items = fieldHelpers.insertInitialOption(
locations
.filter(referenceDataHelpers.filterDisabled())
.map(fieldHelpers.mapReferenceDataToOption),
locationType
)
set(req, `form.options.fields.${fieldName}.items`, items)
next()
} catch (error) {
next(error)
}
}
}
setMoveTypes(req, res, next) {
const permittedMoveTypes = get(req.session, 'user.permissions', [])
.filter(permission => permission.includes('move:create:'))
.map(permission => permission.replace('move:create:', ''))
const existingItems = req.form.options.fields.move_type.items
const permittedItems = existingItems.filter(item =>
permittedMoveTypes.includes(item.value)
)
const removedConditionals = map(
existingItems.filter(item => !permittedMoveTypes.includes(item.value)),
'conditional'
)
// update move_type with only permitted items
set(req, 'form.options.fields.move_type.items', permittedItems)
// remove any conditionals fields that are no longer needed
req.form.options.fields = omitBy(req.form.options.fields, (value, key) =>
removedConditionals.includes(key)
)
next()
}
process(req, res, next) {
const { move_type: moveType } = req.form.values
// process locations
req.form.values.to_location = req.form.values[`to_location_${moveType}`]
next()
}
async successHandler(req, res, next) {
try {
const { to_location: toLocationId } = req.sessionModel.toJSON()
if (toLocationId) {
const locationDetail = await referenceDataService.getLocationById(
toLocationId
)
req.sessionModel.set('to_location', locationDetail)
req.sessionModel.set('to_location_type', locationDetail.location_type)
}
super.successHandler(req, res, next)
} catch (error) {
next(error)
}
}
}
module.exports = MoveDetailsController