-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSummaryPageController.ts
More file actions
497 lines (426 loc) · 13.1 KB
/
SummaryPageController.ts
File metadata and controls
497 lines (426 loc) · 13.1 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
import {
hasComponentsEvenIfNoNext,
type FormMetadata,
type Page,
type SubmitPayload
} from '@defra/forms-model'
import Boom from '@hapi/boom'
import { type RouteOptions } from '@hapi/hapi'
import {
COMPONENT_STATE_ERROR,
PAYMENT_EXPIRED_NOTIFICATION
} from '~/src/server/constants.js'
import { ComponentCollection } from '~/src/server/plugins/engine/components/ComponentCollection.js'
import { PaymentField } from '~/src/server/plugins/engine/components/PaymentField.js'
import {
checkEmailAddressForLiveFormSubmission,
checkFormStatus,
createError,
getCacheService
} from '~/src/server/plugins/engine/helpers.js'
import {
SummaryViewModel,
type FormModel
} from '~/src/server/plugins/engine/models/index.js'
import {
type Detail,
type DetailItem,
type DetailItemField
} from '~/src/server/plugins/engine/models/types.js'
import { QuestionPageController } from '~/src/server/plugins/engine/pageControllers/QuestionPageController.js'
import {
InvalidComponentStateError,
PaymentErrorTypes,
PaymentPreAuthError,
PaymentSubmissionError
} from '~/src/server/plugins/engine/pageControllers/errors.js'
import {
buildMainRecords,
buildRepeaterRecords
} from '~/src/server/plugins/engine/pageControllers/helpers/submission.js'
import {
type FormConfirmationState,
type FormContext,
type FormContextRequest
} from '~/src/server/plugins/engine/types.js'
import {
DEFAULT_PAYMENT_HELP_URL,
formatCurrency,
formatPaymentDate
} from '~/src/server/plugins/payment/helper.js'
import {
FormAction,
type FormRequest,
type FormRequestPayload,
type FormRequestPayloadRefs,
type FormResponseToolkit
} from '~/src/server/routes/types.js'
export class SummaryPageController extends QuestionPageController {
declare pageDef: Page
allowSaveAndExit = true
/**
* The controller which is used when Page["controller"] is defined as "./pages/summary.js"
*/
constructor(model: FormModel, pageDef: Page) {
super(model, pageDef)
this.viewName = 'summary'
// Components collection
this.collection = new ComponentCollection(
hasComponentsEvenIfNoNext(pageDef) ? pageDef.components : [],
{ model, page: this }
)
}
getSummaryViewModel(
request: FormContextRequest,
context: FormContext
): SummaryViewModel {
const viewModel = new SummaryViewModel(request, this, context)
const { query } = request
const { payload, errors, state } = context
const paymentField = context.relevantPages
.flatMap((page) => page.collection.fields)
.find((field): field is PaymentField => field instanceof PaymentField)
if (paymentField) {
const paymentState = paymentField.getPaymentStateFromState(state)
if (paymentState) {
viewModel.paymentState = paymentState
viewModel.paymentDetails = this.buildPaymentDetails(
paymentField,
paymentState
)
}
}
const components = this.collection.getViewModel(payload, errors, query)
viewModel.backLink = this.getBackLink(request, context)
viewModel.feedbackLink = this.feedbackLink
viewModel.phaseTag = this.phaseTag
viewModel.components = components
viewModel.allowSaveAndExit = this.shouldShowSaveAndExit(request.server)
viewModel.errors = errors
return viewModel
}
private buildPaymentDetails(
paymentField: PaymentField,
paymentState: NonNullable<
ReturnType<PaymentField['getPaymentStateFromState']>
>
) {
const rows = [
{
key: { text: 'Payment for' },
value: { text: paymentState.description }
},
{
key: { text: 'Total amount' },
value: { text: formatCurrency(paymentState.amount) }
},
{
key: { text: 'Reference' },
value: { text: paymentState.reference }
}
]
if (paymentState.preAuth?.createdAt) {
rows.push({
key: { text: 'Date of payment' },
value: { text: formatPaymentDate(paymentState.preAuth.createdAt) }
})
}
return {
title: { text: 'Payment details' },
summaryList: { rows }
}
}
/**
* Returns an async function. This is called in plugin.ts when there is a GET request at `/{id}/{path*}`,
*/
makeGetRouteHandler() {
return async (
request: FormRequest,
context: FormContext,
h: FormResponseToolkit
) => {
const { viewName } = this
const viewModel = this.getSummaryViewModel(request, context)
viewModel.hasMissingNotificationEmail =
await this.hasMissingNotificationEmail(request, context)
return h.view(viewName, viewModel)
}
}
/**
* Returns an async function. This is called in plugin.ts when there is a POST request at `/{id}/{path*}`.
* If a form is incomplete, a user will be redirected to the start page.
*/
makePostRouteHandler() {
return async (
request: FormRequestPayload,
context: FormContext,
h: FormResponseToolkit
) => {
const { action } = request.payload
if (action === FormAction.SaveAndExit) {
return this.handleSaveAndExit(request, context, h)
}
return this.handleFormSubmit(request, context, h)
}
}
async handleFormSubmit(
request: FormRequestPayload,
context: FormContext,
h: FormResponseToolkit
) {
const { model } = this
const { params } = request
const cacheService = getCacheService(request.server)
const { formsService } = this.model.services
const { getFormMetadata } = formsService
const formMetadata = await getFormMetadata(params.slug)
const { notificationEmail } = formMetadata
const { isPreview } = checkFormStatus(request.params)
checkEmailAddressForLiveFormSubmission(notificationEmail, isPreview)
if (notificationEmail) {
const viewModel = this.getSummaryViewModel(request, context)
try {
await submitForm(
context,
formMetadata,
request,
viewModel,
model,
notificationEmail,
formMetadata
)
} catch (error) {
return this.handleSubmissionError(error, request, h)
}
}
await cacheService.setConfirmationState(request, {
confirmed: true,
formId: context.state.formId,
referenceNumber: context.referenceNumber
} as FormConfirmationState)
await cacheService.clearState(request)
return this.proceed(request, h, this.getStatusPath())
}
/**
* Handles errors during form submission
*/
private async handleSubmissionError(
error: unknown,
request: FormRequestPayload,
h: FormResponseToolkit
) {
if (error instanceof InvalidComponentStateError) {
return this.handleInvalidComponentStateError(error, request, h)
}
if (error instanceof PaymentPreAuthError) {
return this.handlePaymentPreAuthError(error, request, h)
}
if (error instanceof PaymentSubmissionError) {
return this.handlePaymentSubmissionError(error, request, h)
}
throw error
}
/**
* Handles InvalidComponentStateError during submission
*/
private async handleInvalidComponentStateError(
error: InvalidComponentStateError,
request: FormRequestPayload,
h: FormResponseToolkit
) {
const cacheService = getCacheService(request.server)
const govukError = createError(error.component.name, error.userMessage)
request.yar.flash(COMPONENT_STATE_ERROR, govukError, true)
await cacheService.resetComponentStates(request, error.getStateKeys())
return this.proceed(request, h, error.component.page?.path)
}
/**
* Handles PaymentPreAuthError during submission
*/
private async handlePaymentPreAuthError(
error: PaymentPreAuthError,
request: FormRequestPayload,
h: FormResponseToolkit
) {
const cacheService = getCacheService(request.server)
if (error.shouldResetState) {
await cacheService.resetComponentStates(request, error.getStateKeys())
if (error.errorType === PaymentErrorTypes.PaymentExpired) {
request.yar.flash(PAYMENT_EXPIRED_NOTIFICATION, true, true)
return this.proceed(request, h, error.component.page?.path)
}
}
const govukError = createError(error.component.name, error.userMessage)
request.yar.flash(COMPONENT_STATE_ERROR, govukError, true)
const redirectPath = error.shouldResetState
? error.component.page?.path
: undefined
return this.proceed(request, h, redirectPath)
}
/**
* Handles PaymentSubmissionError during submission
*/
private handlePaymentSubmissionError(
error: PaymentSubmissionError,
request: FormRequestPayload,
h: FormResponseToolkit
) {
const helpUrl = error.helpLink ?? DEFAULT_PAYMENT_HELP_URL
const helpLinkHtml = ` or you can <a href="${helpUrl}" target="_blank" rel="noopener noreferrer" class="govuk-link">contact us (opens in new tab)</a> and quote your reference number to arrange a refund`
const govukError = createError(
'submission',
`There was a problem and your form was not submitted. Try submitting the form again${helpLinkHtml}.`
)
request.yar.flash(COMPONENT_STATE_ERROR, govukError, true)
return this.proceed(request, h)
}
get postRouteOptions(): RouteOptions<FormRequestPayloadRefs> {
return {
ext: {
onPreHandler: {
method(request, h) {
return h.continue
}
}
}
}
}
}
export async function submitForm(
context: FormContext,
metadata: FormMetadata,
request: FormRequestPayload,
summaryViewModel: SummaryViewModel,
model: FormModel,
emailAddress: string,
formMetadata: FormMetadata
) {
await finaliseComponents(request, metadata, context)
const paymentWasCaptured = hasPaymentBeenCaptured(context)
const formStatus = checkFormStatus(request.params)
const logTags = ['submit', 'submissionApi']
request.logger.info(logTags, 'Preparing email', formStatus)
const items = getFormSubmissionData(
summaryViewModel.context,
summaryViewModel.details
)
try {
request.logger.info(logTags, 'Submitting data')
const submitResponse = await submitData(
model,
items,
emailAddress,
request.yar.id
)
if (submitResponse === undefined) {
throw Boom.badRequest('Unexpected empty response from submit api')
}
await model.services.outputService.submit(
context,
request,
model,
emailAddress,
items,
submitResponse,
formMetadata
)
} catch (err) {
if (paymentWasCaptured) {
throw new PaymentSubmissionError(
context.referenceNumber,
formMetadata.contact?.online?.url
)
}
throw err
}
}
/**
* Checks if any payment component has been captured
*/
function hasPaymentBeenCaptured(context: FormContext): boolean {
for (const page of context.relevantPages) {
for (const field of page.collection.fields) {
if (field instanceof PaymentField) {
const paymentState = field.getPaymentStateFromState(context.state)
if (paymentState?.capture?.status === 'success') {
return true
}
}
}
}
return false
}
/**
* Finalises any components that need post-processing before form submission. Candidates usually involve
* those that have external state.
* Examples include:
* - file uploads which are 'persisted' before submission
* - payments which are 'captured' before submission
*/
async function finaliseComponents(
request: FormRequestPayload,
metadata: FormMetadata,
context: FormContext
) {
const relevantFields = context.relevantPages.flatMap(
(page) => page.collection.fields
)
for (const component of relevantFields) {
/*
Each component will throw InvalidComponent if its state is invalid, which is handled
by handleFormSubmit
*/
await component.onSubmit(request, metadata, context)
}
}
function submitData(
model: FormModel,
items: DetailItem[],
retrievalKey: string,
sessionId: string
) {
const { formSubmissionService } = model.services
const { submit } = formSubmissionService
const payload: SubmitPayload = {
sessionId,
retrievalKey,
main: buildMainRecords(items),
repeaters: buildRepeaterRecords(items)
}
return submit(payload)
}
export function getFormSubmissionData(context: FormContext, details: Detail[]) {
const items = context.relevantPages
.map(({ href }) =>
details.flatMap(({ items }) =>
items.filter(({ page }) => page.href === href)
)
)
.flat()
const paymentItems = getPaymentFieldItems(context)
return [...items, ...paymentItems]
}
/**
* Gets DetailItems for PaymentField components
* PaymentField is excluded from summaryDetails for UI but needs to be in submission data
*/
function getPaymentFieldItems(context: FormContext): DetailItemField[] {
const items: DetailItemField[] = []
for (const page of context.relevantPages) {
for (const field of page.collection.fields) {
if (field instanceof PaymentField) {
items.push({
name: field.name,
page,
title: field.title,
label: field.label,
field,
state: context.state,
href: page.href,
value: field.getDisplayStringFromState(context.state)
})
}
}
}
return items
}