-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFileUploadField.ts
More file actions
390 lines (333 loc) · 10.4 KB
/
FileUploadField.ts
File metadata and controls
390 lines (333 loc) · 10.4 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
import {
type FileUploadFieldComponent,
type FormMetadata
} from '@defra/forms-model'
import Boom from '@hapi/boom'
import joi, { type ArraySchema } from 'joi'
import {
FormComponent,
isUploadState
} from '~/src/server/plugins/engine/components/FormComponent.js'
import { InvalidComponentStateError } from '~/src/server/plugins/engine/pageControllers/errors.js'
import { messageTemplate } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'
import {
FileStatus,
UploadStatus,
type ErrorMessageTemplateList,
type FileState,
type FileUpload,
type FileUploadMetadata,
type FormContext,
type FormPayload,
type FormState,
type FormStateValue,
type FormSubmissionError,
type FormSubmissionState,
type SummaryList,
type SummaryListAction,
type SummaryListRow,
type UploadState,
type UploadStatusFileResponse,
type UploadStatusResponse
} from '~/src/server/plugins/engine/types.js'
import { render } from '~/src/server/plugins/nunjucks/index.js'
import {
type FormQuery,
type FormRequestPayload
} from '~/src/server/routes/types.js'
export const uploadIdSchema = joi.string().uuid().required()
export const fileSchema = joi
.object<FileUpload>({
fileId: joi.string().uuid().required(),
filename: joi.string().required(),
contentLength: joi.number().required()
})
.required()
export const tempFileSchema = fileSchema.append({
fileStatus: joi
.string()
.valid(FileStatus.complete, FileStatus.rejected, FileStatus.pending)
.required(),
errorMessage: joi.string().optional()
})
export const formFileSchema = fileSchema.append({
fileStatus: joi.string().valid(FileStatus.complete).required()
})
export const metadataSchema = joi
.object<FileUploadMetadata>()
.keys({
retrievalKey: joi.string().email().required()
})
.required()
export const tempStatusSchema = joi
.object<UploadStatusFileResponse>({
uploadStatus: joi
.string()
.valid(UploadStatus.ready, UploadStatus.pending)
.required(),
metadata: metadataSchema,
form: joi.object().required().keys({
file: tempFileSchema
}),
numberOfRejectedFiles: joi.number().optional()
})
.required()
export const formStatusSchema = joi
.object<UploadStatusResponse>({
uploadStatus: joi.string().valid(UploadStatus.ready).required(),
metadata: metadataSchema,
form: joi.object().required().keys({
file: formFileSchema
}),
numberOfRejectedFiles: joi.number().valid(0).required()
})
.required()
export const itemSchema = joi.object<FileState>({
uploadId: uploadIdSchema
})
export const tempItemSchema = itemSchema.append({
status: tempStatusSchema
})
export const formItemSchema = itemSchema.append({
status: formStatusSchema
})
export class FileUploadField extends FormComponent {
declare options: FileUploadFieldComponent['options']
declare schema: FileUploadFieldComponent['schema']
declare formSchema: ArraySchema<FileState>
declare stateSchema: ArraySchema<FileState>
constructor(
def: FileUploadFieldComponent,
props: ConstructorParameters<typeof FormComponent>[1]
) {
super(def, props)
const { options, schema } = def
let formSchema = joi
.array<FileState>()
.label(this.label)
.single()
.required()
if (options.required === false) {
formSchema = formSchema.optional()
}
if (typeof schema.length !== 'number') {
if (typeof schema.max === 'number') {
formSchema = formSchema.max(schema.max)
}
if (typeof schema.min === 'number') {
formSchema = formSchema.min(schema.min)
} else if (options.required !== false) {
formSchema = formSchema.min(1)
}
} else {
formSchema = formSchema.length(schema.length)
}
this.formSchema = formSchema.items(formItemSchema)
this.stateSchema = formSchema
.items(formItemSchema)
.default(null)
.allow(null)
this.options = options
this.schema = schema
}
getFormValueFromState(state: FormSubmissionState) {
const { name } = this
return this.getFormValue(state[name])
}
getFormValue(value?: FormStateValue | FormState) {
return this.isValue(value) ? value : undefined
}
getDisplayStringFromFormValue(files: FileState[] | undefined): string {
if (!files?.length) {
return ''
}
const unit = files.length === 1 ? 'file' : 'files'
return `Uploaded ${files.length} ${unit}`
}
getDisplayStringFromState(state: FormSubmissionState) {
const files = this.getFormValueFromState(state)
return this.getDisplayStringFromFormValue(files)
}
getContextValueFromFormValue(
files: UploadState | undefined
): string[] | null {
return files?.map(({ status }) => status.form.file.fileId) ?? null
}
getContextValueFromState(state: FormSubmissionState) {
const files = this.getFormValueFromState(state)
return this.getContextValueFromFormValue(files)
}
getViewModel(
payload: FormPayload,
errors?: FormSubmissionError[],
query: FormQuery = {}
) {
const { options, page } = this
// Allow preview URL direct access
const isForceAccess = 'force' in query
const viewModel = super.getViewModel(payload, errors)
const { attributes, id, value } = viewModel
const files = this.getFormValue(value) ?? []
const filtered = files.filter(
(file) => file.status.form.file.fileStatus === FileStatus.complete
)
const count = filtered.length
const rows: SummaryListRow[] = filtered.map((item, index) => {
const { status } = item
const { form } = status
const { file } = form
const tag = { classes: 'govuk-tag--green', text: 'Uploaded' }
const valueHtml = render
.view('components/fileuploadfield-value.html', {
context: { params: { tag } }
})
.trim()
const keyHtml = render
.view('components/fileuploadfield-key.html', {
context: {
params: {
name: file.filename,
errorMessage: errors && file.errorMessage
}
}
})
.trim()
const items: SummaryListAction[] = []
// Remove summary list actions from previews
if (!isForceAccess) {
const path = `/${item.uploadId}/confirm-delete`
const href = page?.getHref(`${page.path}${path}`) ?? '#'
items.push({
href,
text: 'Remove',
classes: 'govuk-link--no-visited-state',
attributes: { id: `${id}__${index}` },
visuallyHiddenText: file.filename
})
}
return {
key: {
html: keyHtml
},
value: {
html: valueHtml
},
actions: {
items
}
} satisfies SummaryListRow
})
// Set up the `accept` attribute
if ('accept' in options && options.accept) {
attributes.accept = options.accept
}
const summaryList: SummaryList = {
classes: 'govuk-summary-list--long-key',
rows
}
return {
...viewModel,
// File input can't have a initial value
value: '',
// Override the component name we send to CDP
name: 'file',
upload: {
count,
summaryList
}
}
}
isValue(value?: FormStateValue | FormState): value is UploadState {
return isUploadState(value)
}
/**
* For error preview page that shows all possible errors on a component
*/
getAllPossibleErrors(): ErrorMessageTemplateList {
return FileUploadField.getAllPossibleErrors()
}
async onSubmit(
request: FormRequestPayload,
metadata: FormMetadata,
context: FormContext
) {
const notificationEmail = metadata.notificationEmail
if (!notificationEmail) {
// this should not happen because notificationEmail is checked further up
// the chain in SummaryPageController before submitForm is called.
throw new Error('Unexpected missing notificationEmail in metadata')
}
if (!request.app.model?.services.formSubmissionService) {
throw new Error('No form submission service available in app model')
}
const { formSubmissionService } = request.app.model.services
const values = this.getFormValueFromState(context.state) ?? []
const files = values.map((value) => ({
fileId: value.status.form.file.fileId,
initiatedRetrievalKey: value.status.metadata.retrievalKey
}))
if (!files.length) {
return
}
try {
await formSubmissionService.persistFiles(files, notificationEmail)
} catch (error) {
if (
Boom.isBoom(error) &&
(error.output.statusCode === 403 || // Forbidden - retrieval key invalid
error.output.statusCode === 410) // Gone - file expired (took to long to submit, etc)
) {
// Failed to persist files. We can't recover from this, the only real way we can recover the submissions is
// by resetting the problematic components and letting the user re-try.
// Scenarios: file missing from S3, invalid retrieval key (timing problem), etc.
throw new InvalidComponentStateError(
this,
'There was a problem with your uploaded files. Re-upload them before submitting the form again.'
)
}
throw error
}
}
/**
* Static version of getAllPossibleErrors that doesn't require a component instance.
*/
static getAllPossibleErrors(): ErrorMessageTemplateList {
return {
baseErrors: [
{ type: 'selectRequired', template: messageTemplate.selectRequired },
{
type: 'filesMimes',
template: 'The selected file must be a {{#limit}}'
},
{
type: 'filesSize',
template: 'The selected file must be smaller than 100MB'
},
{ type: 'filesEmpty', template: 'The selected file is empty' },
{ type: 'filesVirus', template: 'The selected file contains a virus' },
{
type: 'filesPartial',
template: 'The selected file has not fully uploaded'
},
{
type: 'filesError',
template: 'The selected file could not be uploaded – try again'
}
],
advancedSettingsErrors: [
{
type: 'filesMin',
template: 'You must upload {{#limit}} files or more'
},
{
type: 'filesMax',
template: 'You can only upload {{#limit}} files or less'
},
{
type: 'filesExact',
template: 'You must upload exactly {{#limit}} files'
}
]
}
}
}