-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforms_controller.ts
More file actions
348 lines (296 loc) · 10.3 KB
/
forms_controller.ts
File metadata and controls
348 lines (296 loc) · 10.3 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
import { inject } from "@adonisjs/core";
import type { HttpContext } from "@adonisjs/core/http";
import Event from "#models/event";
import Form from "#models/form";
import { FormService } from "#services/form_service";
import {
createFormValidator,
formSubmitValidator,
toggleFormOpenValidator,
updateFormValidator,
} from "#validators/form";
@inject()
export default class FormsController {
// eslint-disable-next-line no-useless-constructor
constructor(private formService: FormService) {}
/**
* @index
* @operationId getForms
* @description Returns an array of event forms
* @tag forms
* @responseBody 200 - <Form[]>.with(relations, attributes).exclude(event).paginated("data", "meta")
*/
public async index({ params, request, bouncer }: HttpContext) {
const eventId = Number(params.eventId);
await bouncer.authorize("manage_form", await Event.findOrFail(eventId));
const page = Number(request.input("page", 1));
const perPage = Number(request.input("perPage", 10));
const forms = await Form.query()
.where("event_id", eventId)
.preload("attributes")
.paginate(page, perPage);
for (const form of forms) {
await this.formService.checkFormClosure(form);
}
return forms;
}
/**
* @store
* @operationId createForm
* @description Creates a form for the specified event
* @tag forms
* @requestBody <createFormValidator>
* @responseBody 201 - <Form>
*/
public async store({ params, request, response, bouncer }: HttpContext) {
const eventId = Number(params.eventId);
const event = await Event.query()
.where("id", eventId)
.preload("firstForm")
.preload("attributes")
.firstOrFail();
await bouncer.authorize("manage_form", event);
const { attributes, ...newFormData } =
await request.validateUsing(createFormValidator);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (newFormData.isFirstForm === true && event.firstForm !== null) {
return response.badRequest({
message: "Event already has a registration form",
});
}
const form = await event.related("forms").create(newFormData);
const eventAttributesIdsSet = new Set(
event.attributes.map((attribute) => attribute.id),
);
const attributesFromDifferentEvent = attributes.filter(
(attribute) => !eventAttributesIdsSet.has(attribute.id),
);
if (attributesFromDifferentEvent.length > 0) {
return response.badRequest({
message: `Attributes with ids ${JSON.stringify(attributesFromDifferentEvent.map((attribute) => attribute.id))}, do not belong to this event`,
});
}
await form.related("attributes").attach(
attributes.reduce(
(acc, attribute) => {
acc[attribute.id] = {
is_required: attribute.isRequired,
is_editable: attribute.isEditable,
order: attribute.order,
};
return acc;
},
{} as Record<
number,
{ is_required?: boolean; is_editable?: boolean; order?: number }
>,
),
);
return response.created(
await Form.query()
.where("id", form.id)
.andWhere("event_id", eventId)
.preload("attributes"),
);
}
/**
* @show
* @operationId getForm
* @description Returns a form
* @tag forms
* @responseBody 200 - <Form>.with(relations, attributes).exclude(event)
* @responseBody 404 - { message: "Row not found", "name": "Exception", status: 404},
*/
public async show({ params, bouncer }: HttpContext) {
const eventId = Number(params.eventId);
const formId = Number(params.id);
await bouncer.authorize("manage_form", await Event.findOrFail(eventId));
const form = await Form.query()
.where("event_id", eventId)
.where("id", formId)
.preload("attributes")
.firstOrFail();
await this.formService.checkFormClosure(form);
return form;
}
/**
* @update
* @operationId updateForm
* @description Updates form details
* @requestBody <updateFormValidator>
* @responseBody 200 - <Form>
* @responseBody 404 - { "message": "Row not found", "name": "Exception", "status": 404 }
* @tag forms
*/
public async update({ params, request, bouncer, response }: HttpContext) {
const eventId = Number(params.eventId);
const formId = Number(params.id);
const event = await Event.query()
.where("id", eventId)
.preload("firstForm")
.preload("attributes")
.firstOrFail();
await bouncer.authorize("manage_form", event);
const form = await Form.query()
.where("event_id", eventId)
.where("id", formId)
.preload("attributes")
.firstOrFail();
const { attributes, ...updates } =
await request.validateUsing(updateFormValidator);
if (
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
event.firstForm !== null &&
form.isFirstForm === false &&
updates.isFirstForm === true
) {
return response.badRequest({
message: "Event already has a registration form",
});
}
if (attributes !== undefined) {
const eventAttributesIdsSet = new Set(
event.attributes.map((attribute) => attribute.id),
);
const attributesFromDifferentEvent = attributes.filter(
(attribute) => !eventAttributesIdsSet.has(attribute.id),
);
if (attributesFromDifferentEvent.length > 0) {
return response.badRequest({
message: `Attributes with ids ${JSON.stringify(attributesFromDifferentEvent.map((attribute) => attribute.id))}, do not belong to this event`,
});
}
await form.related("attributes").detach();
await form.related("attributes").attach(
attributes.reduce(
(acc, attribute) => {
acc[attribute.id] = {
is_required: attribute.isRequired,
is_editable: attribute.isEditable,
order: attribute.order,
};
return acc;
},
{} as Record<
number,
{ is_required?: boolean; is_editable?: boolean; order?: number }
>,
),
);
}
form.merge(updates);
await form.save();
const updatedForm = await Form.query()
.where("event_id", eventId)
.where("id", formId)
.preload("attributes")
.firstOrFail();
return updatedForm;
}
/**
* @toggleOpen
* @operationId toggleFormOpen
* @description Allows superadmin to open and close forms.
* @tag form
* @paramPath eventId - Event identifier - @type(number) @required
* @paramPath formId - Form identifier - @type(number) @required
* @requestFormDataBody <toggleFormOpen>
* @responseBody 200 - <Form>
* @responseBody 401 - Unauthorized access
*/
public async toggleOpen({ request, params, bouncer }: HttpContext) {
const eventId = +params.eventId;
const formId = +params.formId;
await bouncer.authorize("manage_form", await Event.findOrFail(eventId));
const form = await Form.query()
.where("event_id", eventId)
.where("id", formId)
.firstOrFail();
const payload = await request.validateUsing(toggleFormOpenValidator);
form.isOpen = payload.isOpen;
await form.save();
return form;
}
/**
* @destroy
* @operationId deleteForm
* @description Deletes a form
* @tag forms
* @responseBody 204 - {}
* @responseBody 404 - { "message": "Row not found", "name": "Exception", "status": 404 }
*/
public async destroy({ params, response, bouncer }: HttpContext) {
const eventId = Number(params.eventId);
const formId = Number(params.id);
await bouncer.authorize("manage_form", await Event.findOrFail(eventId));
await Form.query()
.where("event_id", eventId)
.andWhere("id", formId)
.delete();
return response.noContent();
}
/**
* @submitForm
* @operationId submitForm
* @description An endpoint to receive data from a form.<br>If this is the first form submission, send an email to create a participant.<br>For subsequent submissions, send a participantSlug.
* @tag forms
* @requestFormDataBody <formSubmitValidator>
* @responseBody 201 - {}
* @responseBody 200 - { missingRequiredFields: { id: number, name: string }[] }
* @responseBody 404 - { "message": "Row not found", "name": "Exception", "status": 404 }
*/
public async submitForm({ params, request, response }: HttpContext) {
const formId = +params.id;
const eventSlug = params.eventSlug as string;
const event = await Event.findByOrFail("slug", eventSlug);
const form = await Form.query()
.where("id", formId)
.andWhere("event_id", event.id)
.preload("attributes", async (query) => {
await query.pivotColumns(["is_required"]);
})
.firstOrFail();
const { email, participantSlug, ...attributes } =
await request.validateUsing(formSubmitValidator, {
meta: { eventId: event.id },
});
// Transform attributes so that files work properly
const transformedAttributes = Object.fromEntries(
Object.entries(attributes).map(([key, value]) => {
if ((value as { isMultipartFile?: boolean }).isMultipartFile ?? false) {
return [key, request.file(key)];
}
return [key, value];
}),
);
const errorObject = await this.formService.submitForm(eventSlug, form, {
email,
participantSlug,
...transformedAttributes,
});
if (errorObject !== undefined) {
return response.status(errorObject.status).json(errorObject.error);
}
return response.created();
}
/**
* @showBySlug
* @operationId getFormBySlug
* @description Returns a form by slug
* @tag forms
* @responseBody 200 - <Form>.with(relations, attributes).exclude(event)
* @responseBody 404 - { message: "Row not found", "name": "Exception", status: 404},
*/
public async showBySlug({ params }: HttpContext) {
const eventSlug = params.eventSlug as string;
const formSlug = params.formSlug as string;
const form = await Form.query()
.where("slug", formSlug)
.whereHas("event", (q) => q.where("slug", eventSlug))
.preload("attributes", (q) =>
q.pivotColumns(["is_editable", "is_required", "order"]),
)
.firstOrFail();
return form;
}
}