-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathQuestionPageController.ts
More file actions
666 lines (553 loc) · 17.6 KB
/
QuestionPageController.ts
File metadata and controls
666 lines (553 loc) · 17.6 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import {
ComponentType,
ControllerType,
Engine,
hasComponents,
hasNext,
hasRepeater,
type ComponentDef,
type Link,
type Page
} from '@defra/forms-model'
import Boom from '@hapi/boom'
import { type RouteOptions } from '@hapi/hapi'
import { type ValidationErrorItem } from 'joi'
import {
EXTERNAL_STATE_APPENDAGE,
EXTERNAL_STATE_PAYLOAD
} from '~/src/server/constants.js'
import { ComponentCollection } from '~/src/server/plugins/engine/components/ComponentCollection.js'
import { ComposableComponentCollection } from '~/src/server/plugins/engine/components/ComposableComponentCollection.js'
import { optionalText } from '~/src/server/plugins/engine/components/constants.js'
import { type BackLink } from '~/src/server/plugins/engine/components/types.js'
import {
getCacheService,
getErrors,
getSaveAndExitHelpers,
normalisePath,
proceed
} from '~/src/server/plugins/engine/helpers.js'
import { type FormModel } from '~/src/server/plugins/engine/models/index.js'
import { PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'
import {
type AnyFormRequest,
type FormContext,
type FormContextRequest,
type FormPageViewModel,
type FormPayload,
type FormPayloadParams,
type FormState,
type FormStateValue,
type FormSubmissionState
} from '~/src/server/plugins/engine/types.js'
import { getComponentsByType } from '~/src/server/plugins/engine/validationHelpers.js'
import {
FormAction,
type FormRequest,
type FormRequestPayload,
type FormRequestPayloadRefs,
type FormRequestRefs,
type FormResponseToolkit
} from '~/src/server/routes/types.js'
import {
actionSchema,
crumbSchema,
paramsSchema
} from '~/src/server/schemas/index.js'
import { merge } from '~/src/server/services/cacheService.js'
export class QuestionPageController extends PageController {
collection: ComponentCollection
errorSummaryTitle = 'There is a problem'
allowSaveAndExit = true
constructor(model: FormModel, pageDef: Page) {
super(model, pageDef)
const components = hasComponents(pageDef) ? pageDef.components : []
const hasComposable = components.some(
(c: ComponentDef) => c.before ?? c.after
)
const CollectionClass = hasComposable
? ComposableComponentCollection
: ComponentCollection
this.collection = new CollectionClass(components, { model, page: this })
this.collection.formSchema = this.collection.formSchema.keys({
crumb: crumbSchema,
action: actionSchema
})
}
get next(): Link[] {
const { def, pageDef } = this
if (!hasNext(pageDef)) {
return []
}
// Remove stale links
return pageDef.next.filter(({ path }) => {
const linkPath = normalisePath(path)
return def.pages.some((page) => {
const pagePath = normalisePath(page.path)
return pagePath === linkPath
})
})
}
get allowContinue(): boolean {
if (this.model.engine === Engine.V2) {
return this.pageDef.controller !== ControllerType.Terminal
}
return this.next.length > 0
}
getItemId(request?: FormContextRequest) {
const { itemId } = this.getFormParams(request)
return itemId ?? request?.params.itemId
}
/**
* Used for mapping form payloads and errors to govuk-frontend's template api, so a page can be rendered
* @param request - the hapi request
* @param context - the form context
*/
getViewModel(
request: FormContextRequest,
context: FormContext
): FormPageViewModel {
const { collection, viewModel } = this
const { query } = request
const { payload, errors } = context
let { pageTitle, showTitle } = viewModel
const components = collection.getViewModel(payload, errors, query)
const formComponents = components.filter(
({ isFormComponent }) => isFormComponent
)
// Single form component? Hide title and customise label or legend instead
if (formComponents.length === 1) {
const { model } = formComponents[0]
const { fieldset, label } = model
// Set as page heading when not following other content
const isPageHeading = formComponents[0] === components[0]
// Check for legend or label
const labelOrLegend = fieldset?.legend ?? label
// Use legend or label as page heading
if (labelOrLegend) {
const size = isPageHeading ? 'l' : 'm'
labelOrLegend.classes =
labelOrLegend === label
? `govuk-label--${size}`
: `govuk-fieldset__legend--${size}`
if (isPageHeading) {
labelOrLegend.isPageHeading = isPageHeading
// Check for optional in label
const isOptional =
this.collection.fields.at(0)?.options.required === false
if (pageTitle) {
labelOrLegend.text = isOptional
? `${pageTitle}${optionalText}`
: pageTitle
}
pageTitle = pageTitle || labelOrLegend.text
}
}
showTitle = !isPageHeading
} else if (formComponents.length > 1) {
// When there is more than one form component,
// adjust the label/legends to give equal prominence
for (const { model } of formComponents) {
if (model.fieldset?.legend) {
model.fieldset.legend.classes = 'govuk-fieldset__legend--m'
}
if (model.label) {
model.label.classes = 'govuk-label--m'
}
}
}
return {
...viewModel,
backLink: this.getBackLink(request, context),
context,
showTitle,
components,
errors,
allowSaveAndExit: this.shouldShowSaveAndExit(request.server)
}
}
getRelevantPath(request: AnyFormRequest, context: FormContext) {
const { paths } = context
const startPath = this.getStartPath()
const relevantPath = paths.at(-1) ?? startPath
return !paths.length
? startPath // First possible path
: relevantPath // Last possible path
}
/**
* Apply conditions to evaluation state to determine next page path
*/
getNextPath(context: FormContext) {
const { model, next, path } = this
const { evaluationState } = context
const summaryPath = this.getSummaryPath()
const statusPath = this.getStatusPath()
// Walk from summary page (no next links) to status page
let defaultPath = path === summaryPath ? statusPath : undefined
if (model.engine === Engine.V2) {
if (this.pageDef.controller !== ControllerType.Terminal) {
const { pages } = this.model
const pageIndex = pages.indexOf(this)
// The "next" page is the first found after the current which is
// either unconditional or has a condition that evaluates to "true"
const nextPage = pages.slice(pageIndex + 1).find((page) => {
const { condition } = page
if (condition) {
const conditionResult = condition.fn(evaluationState)
if (!conditionResult) {
return false
}
}
return true
})
return nextPage?.path ?? defaultPath
} else {
return defaultPath
}
}
const nextLink = next.find((link) => {
const { condition } = link
if (condition) {
return model.conditions[condition]?.fn(evaluationState) ?? false
}
defaultPath = link.path
return false
})
return nextLink?.path ?? defaultPath
}
/**
* Gets the form payload (from state) for this page only
*/
getFormDataFromState(
request: FormContextRequest | undefined,
state: FormSubmissionState
): FormPayload {
const { collection } = this
// Form params from request
const params = this.getFormParams(request)
// Form payload from state
const payload = collection.getFormDataFromState(state)
return {
...params,
...payload
}
}
/**
* Gets form params (from payload) for this page only
*/
getFormParams(request?: FormContextRequest): FormPayloadParams {
const { payload } = request ?? {}
const result = paramsSchema.validate(payload, {
abortEarly: false,
stripUnknown: true
})
return result.value as FormPayloadParams
}
getStateFromValidForm(
request: FormContextRequest,
state: FormSubmissionState,
payload: FormPayload
): FormState {
return this.collection.getStateFromValidForm(payload)
}
getErrors(details?: ValidationErrorItem[]) {
return getErrors(details)
}
async getState(request: AnyFormRequest) {
const { query } = request
// Skip get for preview URL direct access
if ('force' in query) {
return {}
}
const cacheService = getCacheService(request.server)
return cacheService.getState(request)
}
async setState(request: AnyFormRequest, state: FormSubmissionState) {
const { query } = request
// Skip set for preview URL direct access
if ('force' in query) {
return state
}
const cacheService = getCacheService(request.server)
return cacheService.setState(request, state)
}
async mergeState(
request: AnyFormRequest,
state: FormSubmissionState,
update: object
) {
const { query } = request
// Merge state before set
const updated = merge(state, update)
// Skip set for preview URL direct access
if ('force' in query) {
return updated
}
const cacheService = getCacheService(request.server)
return cacheService.setState(request, updated)
}
filterConditionalComponents(
viewModel: FormPageViewModel,
model: FormModel,
evaluationState: Partial<Record<string, FormStateValue>>
) {
// Filter our components based on their conditions using our evaluated state
let filtered = viewModel.components.filter((component) => {
if (
(!!component.model.content ||
component.type === ComponentType.Details) &&
component.model.condition
) {
const condition = model.conditions[component.model.condition]
return condition?.fn(evaluationState)
}
return true
})
/**
* For conditional reveal components (which we no longer support until GDS resolves the related accessibility issues {@link https://github.com/alphagov/govuk-frontend/issues/1991}
*/
filtered = filtered.map((component) => {
const evaluatedComponent = component
const content = evaluatedComponent.model.content
if (Array.isArray(content)) {
evaluatedComponent.model.content = content.filter((item) =>
item.condition
? model.conditions[item.condition]?.fn(evaluationState)
: true
)
}
// apply condition to items for radios, checkboxes etc
const items = evaluatedComponent.model.items
if (Array.isArray(items)) {
evaluatedComponent.model.items = items.filter((item) =>
item.condition
? model.conditions[item.condition]?.fn(evaluationState)
: true
)
}
return evaluatedComponent
})
return filtered
}
makeGetRouteHandler() {
return async (
request: FormRequest,
context: FormContext,
h: FormResponseToolkit
) => {
const { collection, model, viewName } = this
const { evaluationState } = context
const viewModel = this.getViewModel(request, context)
viewModel.errors = collection.getViewErrors(viewModel.errors)
/**
* Content components can be hidden based on a condition. If the condition evaluates to true, it is safe to be kept, otherwise discard it
*/
// Filter our components based on their conditions using our evaluated state
viewModel.components = this.filterConditionalComponents(
viewModel,
model,
evaluationState
)
viewModel.hasMissingNotificationEmail =
await this.hasMissingNotificationEmail(request, context)
return h.view(viewName, viewModel)
}
}
async hasMissingNotificationEmail(
request: FormRequest,
context: FormContext
) {
const { path } = this
const { params } = request
const { isForceAccess } = context
const startPath = this.getStartPath()
const summaryPath = this.getSummaryPath()
const { formsService } = this.model.services
const { getFormMetadata } = formsService
// Warn the user if the form has no notification email set only on start page and summary page
if ([startPath, summaryPath].includes(path) && !isForceAccess) {
const { notificationEmail } = await getFormMetadata(params.slug)
return !notificationEmail
}
return false
}
/**
* Get the back link for a given progress.
*/
protected getBackLink(
request: FormContextRequest,
context: FormContext
): BackLink | undefined {
const { pageDef } = this
const { path, query } = request
const { returnUrl } = query
const { paths } = context
const itemId = this.getItemId(request)
// Check answers back link
if (returnUrl) {
return {
text:
hasRepeater(pageDef) && itemId
? 'Go back to add another'
: 'Go back to check answers',
href: returnUrl
}
}
// Item delete pages etc
const backPath =
itemId && !path.endsWith(itemId)
? paths.at(-1) // Back to main page
: paths.at(-2) // Back to previous page
// No back link
if (!backPath) {
return
}
// Default back link
return {
text: 'Back',
href: this.getHref(backPath)
}
}
makePostRouteHandler() {
return async (
request: FormRequestPayload,
context: FormContext,
h: FormResponseToolkit
) => {
const { collection, viewName, model } = this
const { isForceAccess, state, evaluationState } = context
const action = request.payload.action
if (action?.startsWith(FormAction.External)) {
return this.dispatchExternal(request, h, context)
}
/**
* If there are any errors, render the page with the parsed errors
* @todo Refactor to match POST REDIRECT GET pattern
*/
if (context.errors || isForceAccess) {
const viewModel = this.getViewModel(request, context)
viewModel.errors = collection.getViewErrors(viewModel.errors)
// Filter our components based on their conditions using our evaluated state
viewModel.components = this.filterConditionalComponents(
viewModel,
model,
evaluationState
)
return h.view(viewName, viewModel)
}
// Save state
await this.setState(request, state)
// Check if this is a save-and-exit action
if (action === FormAction.SaveAndExit) {
return this.handleSaveAndExit(request, context, h)
}
// Proceed to the next page
return this.proceed(request, h, this.getNextPath(context))
}
}
private dispatchExternal(
request: FormRequestPayload,
h: FormResponseToolkit,
context: FormContext
) {
const { externalComponents } = getComponentsByType()
const action = request.payload.action ?? ''
// Find the external action and arguments
// `external-{componentName}--{argname1}:{argvalue1}--{argname2}:{argvalue2}`
// E.g. external-abcdef--amount:10--step:manual
const externalActionsWithArgs = action
.slice(`${FormAction.External}-`.length)
.split('--')
const externalActionArgs = externalActionsWithArgs
.slice(1)
.map((arg) => arg.split(':'))
const args = Object.fromEntries(externalActionArgs) as Record<
string,
string
>
const componentName = externalActionsWithArgs[0]
const component = this.model.componentDefMap.get(componentName)
const componentType = component?.type
if (!componentType) {
throw Boom.internal(
`External component of type ${componentType} not found`
)
}
const selectedComponent = externalComponents.get(componentType)
if (!selectedComponent) {
throw Boom.internal(`External component ${componentName} not found`)
}
// Stash payload without crumb and action
const stashedPayload = {
...context.payload,
crumb: undefined,
action: undefined
}
request.yar.flash(EXTERNAL_STATE_PAYLOAD, stashedPayload, true)
// Clear any previous state appendage
request.yar.clear(EXTERNAL_STATE_APPENDAGE)
return selectedComponent.dispatcher(request, h, {
component,
controller: this,
sourceUrl: request.url.toString(),
actionArgs: args
})
}
proceed(
request: FormContextRequest,
h: FormResponseToolkit,
nextPath?: string
) {
const nextUrl = nextPath
? this.getHref(nextPath) // Redirect to next page
: this.href // Redirect to current page (refresh)
return proceed(request, h, nextUrl)
}
/**
* Handle save-and-exit action
*/
handleSaveAndExit(
request: FormRequestPayload,
context: FormContext,
h: FormResponseToolkit
) {
const saveAndExit = getSaveAndExitHelpers(request.server)
if (!saveAndExit) {
throw Boom.internal('Server misconfigured for save and exit')
}
return saveAndExit(request, h, context)
}
/**
* {@link https://hapi.dev/api/?v=20.1.2#route-options}
*/
get getRouteOptions(): RouteOptions<FormRequestRefs> {
return {
ext: {
onPostHandler: {
method(_request, h) {
return h.continue
}
}
}
}
}
/**
* {@link https://hapi.dev/api/?v=20.1.2#route-options}
*/
get postRouteOptions(): RouteOptions<FormRequestPayloadRefs> {
return {
payload: {
parse: true,
maxBytes: Number.MAX_SAFE_INTEGER,
failAction: 'ignore'
},
ext: {
onPostHandler: {
method(_request, h) {
return h.continue
}
}
}
}
}
}