-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseEditForm.ts
More file actions
338 lines (281 loc) · 8.6 KB
/
useEditForm.ts
File metadata and controls
338 lines (281 loc) · 8.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
import { useRequest } from "ahooks";
import { useEffect, useState } from "react";
import { useStatus } from "~/Services/Status";
import { StatusEnum } from "~/Services/Status.Entities";
import { Models } from "~/Services/Status.Models";
import { useAccessToken } from "../Auth/useAccessToken";
import { EventStatus, EventType, GetEventImpact, GetStatusString, IsIncident, IsOpenStatus } from "./Enums";
/**
* Custom hook for managing the edit form state and validation for an event.
*
* This hook provides state management and validation for various fields of an event,
* including title, type, update message, status, and end date. It also includes a
* submission handler to update the event and close the form.
*
* @param {Models.IEvent} event - The event object to be edited.
*
* @returns An object containing the state, actions, validation messages,
* and submission handler for the edit form.
*
* @property {Function} OnSubmit - Function to handle form submission, update the event,
* and close the form.
*
* @author Aloento
* @since 1.0.0
* @version 0.4.0
*/
export function useEditForm(event: Models.IEvent) {
const [title, _setTitle] = useState(event.Title);
const [valTitle, setValTitle] = useState<string>();
function setTitle(value = title) {
let err: boolean = false;
if (value.length < 8 || value.length > 100) {
setValTitle("Title must be between 8 and 100 characters.");
err = true;
}
if (!value) {
setValTitle("Title is required.");
err = true;
}
_setTitle(value);
!err && setValTitle(undefined);
return !err;
}
const [type, _setType] = useState(event.Type);
const [valType, setValType] = useState<string>();
function setType(value = type) {
if (!value) {
setValType("Type is required.");
return false;
}
if (!Object.values(EventType).includes(value)) {
setValType("Invalid event type.");
return false;
}
if (type !== value) {
_setStatus(undefined);
}
_setType(value);
setValType(undefined);
return true;
}
const [update, _setUpdate] = useState("");
const [valUpdate, setValUpdate] = useState<string>();
function setUpdate(value = update) {
let err: boolean = false;
if (value.length < 10 || value.length > 200) {
setValUpdate("Update Message must be between 10 and 200 characters.");
err = true;
}
if (!value) {
setValUpdate("Update Message is required.");
err = true;
}
_setUpdate(value);
!err && setValUpdate(undefined);
return !err;
}
const [description, _setDescription] = useState(event.Description || "");
const [valDescription, setValDescription] = useState<string>();
function setDescription(value = description) {
let err: boolean = false;
if (value && value.length > 500) {
setValDescription("Description must be less than 500 characters.");
err = true;
}
_setDescription(value);
!err && setValDescription(undefined);
return !err;
}
const [contactEmail, _setContactEmail] = useState(event.ContactEmail || "");
const [valContactEmail, setValContactEmail] = useState<string>();
function setContactEmail(value = contactEmail) {
let err: boolean = false;
if (type === EventType.Maintenance && !value) {
setValContactEmail("Contact Email is required for maintenance.");
err = true;
}
if (value && !value.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
setValContactEmail("Please enter a valid email address.");
err = true;
}
if (value && value.length > 100) {
setValContactEmail("Email must be less than 100 characters.");
err = true;
}
_setContactEmail(value);
!err && setValContactEmail(undefined);
return !err;
}
const [status, _setStatus] = useState<EventStatus | undefined>();
const [valStatus, setValStatus] = useState<string>();
function setStatus(value = status) {
if (!value) {
setValStatus("Status is required.");
return false;
}
if (!Object.values(EventStatus).includes(value)) {
setValStatus("Invalid event status.");
return false;
}
_setStatus(value);
setValStatus(undefined);
return true;
}
const [start, _setStart] = useState(event.Start);
const [valStart, setValStart] = useState<string>();
function setStart(value = start) {
let err: boolean = false;
const now = new Date();
if (end && value > end) {
setValStart("Start Date cannot be later than End Date.");
err = true;
}
if (value > now && IsIncident(type)) {
setValStart("Start Date cannot be in the future.");
err = true;
}
!err && setValStart(undefined);
_setStart(value);
return !err;
}
const [end, _setEnd] = useState<Date | undefined>(event.End);
const [valEnd, setValEnd] = useState<string>();
function setEnd(value = end) {
let err: boolean = false;
if (value && value < start) {
setValEnd("End Date cannot be before Start Date.");
err = true;
}
!err && setValEnd(undefined);
_setEnd(value);
return !err;
}
const [updateAt, _setUpdateAt] = useState<Date>(new Date());
const [valUpdateAt, setValUpdateAt] = useState<string>();
function setUpdateAt(value = updateAt) {
let err: boolean = false;
if (IsIncident(type) && value && value < start) {
setValUpdateAt("Update Date cannot be earlier than Start Date.");
err = true;
}
!err && setValUpdateAt(undefined);
_setUpdateAt(value);
return !err;
}
useEffect(() => {
setStart();
setEnd();
}, [start, end]);
const getToken = useAccessToken();
const { DB, Update } = useStatus();
const { runAsync, loading } = useRequest(async () => {
if (![setTitle(), setType(), setUpdate(), setDescription(), setContactEmail(), setStatus(), setStart(), setEnd(), setUpdateAt()].every(Boolean)) {
throw new Error("Validation failed.");
}
const url = process.env.SD_BACKEND_URL!;
const body: Record<string, any> = {
title,
status: GetStatusString(status!),
impact: GetEventImpact(type),
message: update,
update_date: updateAt.toISOString(),
description,
};
if (type === EventType.Maintenance && contactEmail) {
body.contact_email = contactEmail;
};
if (event.Type !== type) {
body.status = StatusEnum.ImpactChanged;
}
if (!IsIncident(event.Type)) {
body.start_date = start.toISOString();
}
if (end && !isNaN(end.getTime())) {
body.end_date = end.toISOString();
}
if (!IsOpenStatus(event.Status) && IsIncident(event.Type)) {
if (event.Status !== status) {
body.end_date = undefined;
body.status = StatusEnum.Reopened;
} else {
body.start_date = start.toISOString();
body.status = StatusEnum.Changed;
}
}
const raw = await fetch(`${url}/v2/incidents/${event.Id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${getToken()}`
},
body: JSON.stringify(body)
});
if (!raw.ok) {
throw new Error("Failed to update event: " + await raw.text());
}
const eventIndex = DB.Events.findIndex(e => e.Id === event.Id);
if (eventIndex !== -1) {
const updatedEvent = { ...DB.Events[eventIndex] };
updatedEvent.Title = title;
updatedEvent.Type = type;
updatedEvent.Status = status!;
updatedEvent.Start = start;
updatedEvent.End = end;
updatedEvent.Description = description;
updatedEvent.ContactEmail = contactEmail;
const newHistory: Models.IHistory = {
Id: Math.max(...Array.from(updatedEvent.Histories).map(h => h.Id), 0) + 1,
Message: update,
Created: updateAt,
Status: status!,
Event: updatedEvent
};
updatedEvent.Histories.add(newHistory);
DB.Events[eventIndex] = updatedEvent;
Update();
}
_setUpdate("");
_setStatus(undefined);
_setUpdateAt(new Date());
}, {
manual: true
});
return {
State: {
title,
type,
update,
description,
contactEmail,
status,
start,
end,
updateAt,
},
Actions: {
setTitle,
setType,
setUpdate,
setDescription,
setContactEmail,
setStatus,
setStart,
setEnd,
setUpdateAt,
},
Validation: {
title: valTitle,
type: valType,
update: valUpdate,
description: valDescription,
contactEmail: valContactEmail,
status: valStatus,
start: valStart,
end: valEnd,
updateAt: valUpdateAt,
},
OnSubmit: runAsync,
Loading: loading
}
}