-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbook-into-a-clinic.js
More file actions
368 lines (322 loc) · 11.9 KB
/
Copy pathbook-into-a-clinic.js
File metadata and controls
368 lines (322 loc) · 11.9 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import { fakerEN_GB as faker } from '@faker-js/faker'
import wizard from '@x-govuk/govuk-prototype-wizard'
import _ from 'lodash'
import { ParentalRelationship, SessionPresets } from '../enums.js'
import { ClinicAppointment, ClinicBooking } from '../models.js'
import {
getAllAppointmentPaths,
getHealthQuestionPaths
} from '../utils/clinic-appointment.js'
import { kebabToCamelCase } from '../utils/string.js'
export const bookIntoClinicController = {
/**
* Record the session preset
*
* @param {*} request
* @param {*} response
* @param {*} next
* @param {*} session_preset_slug
*/
read(request, response, next, session_preset_slug) {
const serviceName = 'Book into a clinic'
response.locals.assetsName = 'public'
response.locals.serviceName = serviceName
response.locals.headerOptions = { service: { text: serviceName } }
// Record the session preset (aka "primary programme" to the parent)
const sessionPreset =
SessionPresets.find((preset) => preset.slug === session_preset_slug) ??
SessionPresets[0]
response.locals.sessionPreset = sessionPreset
// Allow us to offer a phone booking if not wanting online (start.njk)
response.locals.bookingPhoneNumber =
request.session.data.teams[0]?.tel ??
faker.helpers.replaceSymbols('01### ######')
next()
},
/**
* Send to the start page
*
* @param {*} request
* @param {*} response
*/
redirect(request, response) {
const { sessionPreset } = response.locals
response.redirect(`${request.baseUrl}/${sessionPreset.slug}/start`)
},
/**
* Start a new clinic booking for clinics with the primary programme we've been given
*
* @param {*} request
* @param {*} response
*/
new(request, response) {
const { data } = request.session
const { sessionPreset } = response.locals
// Create a new clinic booking in the wizard context
const booking = ClinicBooking.createInContext(
{
sessionPreset
},
data.wizard
)
// Redirect to the first page in the booking journey (after the start page, that is)
const redirectUrl = `${request.baseUrl}/${booking.bookingUri}/new/child-count`
response.redirect(redirectUrl)
},
/**
* Prepare a form-based page of the clinic booking journey.
*
* This includes code to set up radio button groups for various pages (we set them up
* regardless of which specific route we're handling).
*
* @param {*} request
* @param {*} response
* @param {*} next
*/
readForm(request, response, next) {
const { session_preset_slug, booking_uuid } = request.params
const appointment_uuid = request.params.appointment_uuid
const { data, referrer } = request.session
/** NOTE:
*
* The nature of the journey here is complex, as there are two separate sections in which we need to
* iterate over children. Or over appointments, if you want to think of it that way (each child has
* their own appointment). And the second iteration - the health questions - has pages that are
* dependent on the answers given during the appointment booking (specifically, the choice of vaccines
* per child).
*
* So, it goes:
* - Start page
* - How many children?
* - Child name <-- first page of the per-child appointment journey
* - Child DOB
* - ...
* - Appointment time <-- final page of the per-child appointment journey; iterate to next child if required
* - Parent info
* - Check answers
* - Health questions?
* - Health question 1 <-- first page of the per-child health question journey
* - ...
* - Health question n <-- final page of the per-child health question journey; iterate to next child if required
* - Confirmation
*
* */
// Create objects on the global context to allow us to check branching conditions, etc.
// And make them available to the view.
let booking, appointment
if (booking_uuid) {
booking = new ClinicBooking(
ClinicBooking.findOne(booking_uuid, data?.wizard),
data
)
response.locals.booking = booking
if (appointment_uuid) {
appointment = new ClinicAppointment(
ClinicAppointment.findOne(appointment_uuid, data?.wizard),
data
)
response.locals.appointment = appointment
response.locals.childNumber =
booking.appointments_ids.indexOf(appointment.uuid) + 1
response.locals.childCount = booking.appointments_ids.length
response.locals.firstName = appointment.firstName || 'your child'
response.locals.fullName = appointment.fullName || 'your child'
}
}
// Make sure the views have access to information about flow control e.g. for narrowing down a clinic search
let transaction
if (data.wizard?.transaction) {
transaction = data.wizard?.transaction
response.locals.transaction = transaction
}
const journey = {
[`/${session_preset_slug}`]: {},
[`/${session_preset_slug}/${booking_uuid}/new/child-count`]: {},
// Appointment journey; once per child
...getAllAppointmentPaths(request.session.data, booking),
// Parent journey
[`/${session_preset_slug}/${booking_uuid}/new/parent`]: {
[`/${session_preset_slug}/${booking_uuid}/new/offer-health-questions`]:
() => !request.session.data.booking?.parent?.tel
},
[`/${session_preset_slug}/${booking_uuid}/new/contact-preference`]: {},
// Check answers
[`/${session_preset_slug}/${booking_uuid}/new/check-answers`]: {},
// Health questions (optional)
[`/${session_preset_slug}/${booking_uuid}/new/offer-health-questions`]: {
[`/${session_preset_slug}/${booking_uuid}/new/confirmation`]: {
data: 'transaction.optedIntoHealthQuestions',
value: 'false'
}
},
// For each child being booked in, and their selected vaccinations, ask the
// relevant health questions and impairments/adjustments questions
...getHealthQuestionPaths(
`/${session_preset_slug}/${booking_uuid}/new/`,
booking_uuid,
data.wizard,
data
),
// Confirmation! \o/
[`/${session_preset_slug}/${booking_uuid}/new/confirmation`]: {}
}
const paths = wizard(journey, request)
paths.back = referrer || paths.back
response.locals.paths = paths // used later to redirect in updateForm
// Prepare the radio options for the parental relationship page
response.locals.parentalRelationshipItems = Object.values(
ParentalRelationship
)
.filter((relationship) => relationship !== ParentalRelationship.Unknown)
.map((relationship) => ({
text: relationship,
value: relationship
}))
next()
},
/**
* Render the requested form page
*
* @param {*} request
* @param {*} response
*/
showForm(request, response) {
const { appointment } = response.locals
let { booking_uuid, view } = request.params
// All health questions use the same view
let key
if (view.startsWith('health-question-')) {
key = kebabToCamelCase(view.replace('health-question-', ''))
view = 'health-question'
}
// Only ask for details if question does not have sub-questions
const hasSubQuestions =
appointment?.getHealthQuestionsForSelectedProgrammes(
request.session.data
)[key]?.conditional
// Build the options for the selection of a home address address from those already entered
if (view === 'address-selection') {
const booking = ClinicBooking.findOne(
booking_uuid,
request.session.data.wizard
)
const previousAddressItems = booking.appointments
.map((appointment) => {
if (appointment.child?.address) {
const oneLineAddress = Object.values(appointment.child.address)
.filter((string) => string)
.join(', ')
return {
text: oneLineAddress,
value: appointment.uuid
}
}
return null
})
.filter(Boolean)
response.locals.previousAddressItems = [
...previousAddressItems,
{
divider: 'or'
},
{
text: 'Enter a different address',
value: 'new'
}
]
}
/////////////////////
// console.log(`view: ${view}`)
// console.log(
// `data.wizard: ${JSON.stringify(request.session.data.wizard, null, 2)}`
// )
// console.log(
// `data.appointment: ${JSON.stringify(request.session.data.appointment, null, 2)}`
// )
/////////////////////
response.render(`book-into-a-clinic/form/${view}`, { key, hasSubQuestions })
},
/**
* Store the latest values entered into a form in the booking journey
*
* @param {*} request
* @param {*} response
*/
updateForm(request, response) {
const { booking_uuid, appointment_uuid, view } = request.params
const { data } = request.session
const { paths } = response.locals
// Store values from the posted form
if (request.body.booking) {
ClinicBooking.update(booking_uuid, request.body.booking, data.wizard)
}
if (request.body.appointment) {
ClinicAppointment.update(
appointment_uuid,
request.body.appointment,
data.wizard
)
}
if (request.body.transaction) {
data.wizard.transaction = data.wizard.transaction ?? {}
_.merge(data.wizard.transaction, request.body.transaction)
}
let nextUrl = paths.next
if (view === 'child-count') {
// We've just set the child count, so create the appointments we'll need
const booking = ClinicBooking.findOne(booking_uuid, data.wizard)
let desiredCount = Number(data.wizard.transaction.childCount)
desiredCount = isNaN(desiredCount) || desiredCount < 1 ? 1 : desiredCount
const existingCount = booking.appointments_ids.length
const childrenToAdd = Math.max(0, desiredCount - existingCount)
const childrenToRemove = Math.max(0, existingCount - desiredCount)
for (let index = 0; index < childrenToAdd; index++) {
const appointment = ClinicAppointment.createInContext(
{ primary_programme_ids: booking.primaryProgrammeIDs },
data.wizard
)
booking.addAppointment(appointment)
}
for (let index = 0; index < childrenToRemove; index++) {
const appointment_uuid = booking.removeLastAppointment()
ClinicAppointment.delete(appointment_uuid, data.wizard)
}
// Start the appointment journey for the first child
const firstAppointment = booking.appointments[0]
const firstAppointmentUrl = `${request.baseUrl}/${booking.bookingUri}/new/${firstAppointment.appointmentUri}/child`
nextUrl = firstAppointmentUrl
} else if (
view === 'address-selection' &&
request.body.transaction.previousAddress !== 'new'
) {
// We've just selected a previous child's address for the current appointment, so copy
// that detail to the child record
const previous_appointment_uuid = request.body.transaction.previousAddress
const previousAppointment = ClinicAppointment.findOne(
previous_appointment_uuid,
data.wizard
)
const currentAppointment = ClinicAppointment.findOne(
appointment_uuid,
data.wizard
)
if (previousAppointment && currentAppointment) {
currentAppointment.child.address = previousAppointment.child.address
}
}
// NB: request.session.save was needed to avoid race condition issues on heroku
request.session.save((err) => {
if (!err) response.redirect(nextUrl)
})
},
/**
* Catch-all for pages not needing to reference a given clinic booking
*
* @param {*} request
* @param {*} response
*/
show(request, response) {
const view = request.params.view || 'start'
response.render(`book-into-a-clinic/${view}`)
}
}