-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPaymentField.ts
More file actions
370 lines (318 loc) · 9.99 KB
/
PaymentField.ts
File metadata and controls
370 lines (318 loc) · 9.99 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
import { randomUUID } from 'node:crypto'
import {
type FormMetadata,
type PaymentFieldComponent
} from '@defra/forms-model'
import { StatusCodes } from 'http-status-codes'
import joi, { type ObjectSchema } from 'joi'
import { FormComponent } from '~/src/server/plugins/engine/components/FormComponent.js'
import { type PaymentState } from '~/src/server/plugins/engine/components/PaymentField.types.js'
import { getPluginOptions } from '~/src/server/plugins/engine/helpers.js'
import {
PaymentErrorTypes,
PaymentPreAuthError,
PaymentSubmissionError
} from '~/src/server/plugins/engine/pageControllers/errors.js'
import {
type AnyFormRequest,
type FormContext,
type FormRequestPayload,
type FormResponseToolkit
} from '~/src/server/plugins/engine/types/index.js'
import {
type ErrorMessageTemplateList,
type FormPayload,
type FormState,
type FormStateValue,
type FormSubmissionError,
type FormSubmissionState
} from '~/src/server/plugins/engine/types.js'
import { createPaymentService } from '~/src/server/plugins/payment/helper.js'
export class PaymentField extends FormComponent {
declare options: PaymentFieldComponent['options']
declare formSchema: ObjectSchema
declare stateSchema: ObjectSchema
isAppendageStateSingleObject = true
constructor(
def: PaymentFieldComponent,
props: ConstructorParameters<typeof FormComponent>[1]
) {
super(def, props)
this.options = def.options
const paymentStateSchema = joi
.object({
paymentId: joi.string().required(),
reference: joi.string().required(),
amount: joi.number().required(),
description: joi.string().required(),
uuid: joi.string().uuid().required(),
formId: joi.string().required(),
isLivePayment: joi.boolean().required(),
preAuth: joi
.object({
status: joi
.string()
.valid('success', 'failed', 'started')
.required(),
createdAt: joi.string().isoDate().required()
})
.required()
})
.unknown(true)
.label(this.label)
this.formSchema = paymentStateSchema
// 'required()' forces the payment page to be invalid until we have valid payment state
// i.e. the user will automatically be directed back to the payment page
// if they attempt to access future pages when no payment entered yet
this.stateSchema = paymentStateSchema.required()
}
/**
* Gets the PaymentState from form submission state
*/
getPaymentStateFromState(
state: FormSubmissionState
): PaymentState | undefined {
const value = state[this.name]
return this.isPaymentState(value) ? value : undefined
}
getDisplayStringFromState(state: FormSubmissionState): string {
const value = this.getPaymentStateFromState(state)
if (!value) {
return ''
}
return `£${value.amount.toFixed(2)} - ${value.description}`
}
getViewModel(payload: FormPayload, errors?: FormSubmissionError[]) {
const viewModel = super.getViewModel(payload, errors)
// Payload is pre-populated from state if a payment has already been made
const paymentState = this.isPaymentState(payload[this.name] as unknown)
? (payload[this.name] as unknown as PaymentState)
: undefined
// When user initially visits the payment page, there is no payment state yet so the amount is read form the form definition.
const amount = paymentState?.amount ?? this.options.amount
const formattedAmount = amount.toFixed(2)
return {
...viewModel,
amount: formattedAmount,
description: this.options.description,
paymentState
}
}
/**
* Type guard to check if value is PaymentState
*/
isPaymentState(value: unknown): value is PaymentState {
return PaymentField.isPaymentState(value)
}
/**
* Static type guard to check if value is PaymentState
*/
static isPaymentState(value: unknown): value is PaymentState {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return false
}
const state = value as PaymentState
return (
typeof state.paymentId === 'string' &&
typeof state.amount === 'number' &&
typeof state.description === 'string'
)
}
/**
* Override base isState to validate PaymentState
*/
isState(value?: FormStateValue | FormState): value is FormState {
return this.isPaymentState(value)
}
getFormValue(value?: FormStateValue | FormState) {
return this.isPaymentState(value)
? (value as unknown as NonNullable<FormStateValue>)
: undefined
}
getContextValueFromState(state: FormSubmissionState) {
return this.isPaymentState(state)
? `Reference: ${state.reference}\nAmount: ${state.amount.toFixed(2)}`
: ''
}
/**
* For error preview page that shows all possible errors on a component
*/
getAllPossibleErrors(): ErrorMessageTemplateList {
return PaymentField.getAllPossibleErrors()
}
/**
* Static version of getAllPossibleErrors that doesn't require a component instance.
*/
static getAllPossibleErrors(): ErrorMessageTemplateList {
return {
baseErrors: [
{
type: 'paymentRequired',
template: 'Complete the payment to continue'
}
],
advancedSettingsErrors: []
}
}
/**
* Dispatcher for external redirect to GOV.UK Pay
*/
static async dispatcher(
request: FormRequestPayload,
h: FormResponseToolkit,
args: PaymentDispatcherArgs
): Promise<unknown> {
const { options, name: componentName } = args.component
const { model } = args.controller
const state = await args.controller.getState(request)
const { baseUrl } = getPluginOptions(request.server)
const summaryUrl = `${baseUrl}/${model.basePath}/summary`
const existingPaymentState = state[componentName]
if (
PaymentField.isPaymentState(existingPaymentState) &&
existingPaymentState.preAuth?.status === 'success'
) {
return h.redirect(summaryUrl).code(StatusCodes.SEE_OTHER)
}
const isLivePayment = args.isLive && !args.isPreview
const formId = args.controller.model.formId
const paymentService = createPaymentService(isLivePayment, formId)
const uuid = randomUUID()
const reference = state.$$__referenceNumber as string
const amount = options.amount
const description = options.description
const slug = `/${model.basePath}`
const payCallbackUrl = `${baseUrl}/payment-callback?uuid=${uuid}`
const paymentPageUrl = args.sourceUrl
const amountInPence = Math.round(amount * 100)
const payment = await paymentService.createPayment(
amountInPence,
description,
payCallbackUrl,
reference,
{ formId, slug }
)
const sessionData: PaymentSessionData = {
uuid,
formId,
reference,
amount,
description,
paymentId: payment.paymentId,
componentName,
returnUrl: summaryUrl,
failureUrl: paymentPageUrl,
isLivePayment
}
request.yar.set(`payment-${uuid}`, sessionData)
return h.redirect(payment.paymentUrl).code(StatusCodes.SEE_OTHER)
}
/**
* Called on form submission to capture the payment
* @see https://docs.payments.service.gov.uk/delayed_capture/#delay-taking-a-payment
*/
async onSubmit(
request: FormRequestPayload,
_metadata: FormMetadata,
context: FormContext
): Promise<void> {
const paymentState = this.getPaymentStateFromState(context.state)
if (!paymentState) {
throw new PaymentPreAuthError(
this,
'Complete the payment to continue',
true,
PaymentErrorTypes.PaymentIncomplete
)
}
if (paymentState.capture?.status === 'success') {
return
}
const { paymentId, isLivePayment, formId } = paymentState
const paymentService = createPaymentService(isLivePayment, formId)
/**
* @see https://docs.payments.service.gov.uk/api_reference/#payment-status-lifecycle
*/
const status = await paymentService.getPaymentStatus(paymentId)
PaymentSubmissionError.checkPaymentAmount(
status.amount,
this.options.amount,
this
)
if (status.state.status === 'success') {
await this.markPaymentCaptured(request, paymentState)
return
}
if (status.state.status !== 'capturable') {
throw new PaymentPreAuthError(
this,
'Your payment authorisation has expired. Please add your payment details again.',
true,
PaymentErrorTypes.PaymentExpired
)
}
const captured = await paymentService.capturePayment(
paymentId,
status.amount
)
if (!captured) {
throw new PaymentPreAuthError(
this,
'There was a problem and your form was not submitted. Try submitting the form again.',
false
)
}
await this.markPaymentCaptured(request, paymentState)
}
/**
* Updates payment state to mark capture as successful
* This ensures we don't try to re-capture on submission retry
*/
private async markPaymentCaptured(
request: FormRequestPayload,
paymentState: PaymentState
): Promise<void> {
const updatedState: PaymentState = {
...paymentState,
capture: {
status: 'success',
createdAt: new Date().toISOString()
}
}
if (this.page) {
const currentState = await this.page.getState(request)
await this.page.mergeState(request, currentState, {
[this.name]: updatedState
})
}
}
}
export interface PaymentDispatcherArgs {
controller: {
model: {
formId: string
basePath: string
name: string
}
getState: (request: AnyFormRequest) => Promise<FormSubmissionState>
}
component: PaymentField
sourceUrl: string
isLive: boolean
isPreview: boolean
}
/**
* Session data stored when dispatching to GOV.UK Pay
*/
export interface PaymentSessionData {
uuid: string
formId: string
reference: string
amount: number
description: string
paymentId: string
componentName: string
returnUrl: string
failureUrl: string
isLivePayment: boolean
}