-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreateShiftMain.tsx
308 lines (293 loc) · 12.8 KB
/
CreateShiftMain.tsx
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
import React from 'react';
import moment from "moment";
import { Button, ModalBody, ModalFooter, Box, FormControl, FormLabel, Input, Flex, Select, NumberDecrementStepper, NumberIncrementStepper, NumberInput, NumberInputField, NumberInputStepper, InputRightElement, InputGroup, FormHelperText, Tag, TagLabel, TagCloseButton, Wrap, WrapItem, useToast} from "@chakra-ui/react";
import { CreateShiftFormStepComponentType, CreateShiftFormStepProps, Frequency, ServiceRequestType } from '../../../types/ServiceRequestTypes';
import { capitalizeName, titleCase } from '../../../utils/FormatUtils';
import EARLIEST_SHIFT_TIME from '../../../constants/ServiceRequestConstants';
import { validateEmail } from '../../../utils/ValidationUtils'
import ServiceRequestAPIClient from "../../../APIClients/ServiceRequestAPIClient";
const CreateShiftMain: CreateShiftFormStepComponentType = ({ onSubmit, updateFields, updateErrorFields, data, errors }: CreateShiftFormStepProps): React.ReactElement => {
const { requestName, shiftTime, shiftEndTime, frequency, currentEmail, inviteEmails, requestType } = data;
const { shiftTimeError, shiftEndTimeError } = errors;
const toast = useToast();
const formatDate = (date: Date) => {
return moment(date).format("YYYY-MM-DD");
};
const formatTime = (date: Date) => {
return moment(date).format("HH:mm");
};
const createDateFromTimeAndDate = (timeStr: string, dateStr: string) => {
const date = moment(dateStr);
const time = timeStr.split(':');
return new Date(
date.year(), // year
date.month(), // month
date.date(), // day
parseInt(time[0], 10), // hour
parseInt(time[1], 10), // minute
);
};
const updateShiftTimeErrorFields = (startTime: Date, endTime: Date) => {
const showError = startTime >= endTime;
updateErrorFields({
shiftTimeError: showError ? "Start time should be before end time" : "",
shiftEndTimeError: showError ? "End time should be after start time" : "",
});
};
const handleShiftDateChange = (value: string) => {
const newStartTime = createDateFromTimeAndDate(EARLIEST_SHIFT_TIME, value);
updateFields(
{
shiftTime: newStartTime.toISOString(),
}
);
if (shiftEndTime) {
const endTime = new Date(shiftEndTime);
const newEndTime = new Date(
newStartTime.getFullYear(), // year
newStartTime.getMonth(), // month
newStartTime.getDate(), // day
endTime.getHours(), // hour
endTime.getMinutes(), // minute
);
updateFields(
{
shiftEndTime: newEndTime.toISOString(),
}
);
updateShiftTimeErrorFields(newStartTime, newEndTime);
}
};
const handleShiftTimeChange = (value: string) => {
if (shiftTime) {
const startTime = createDateFromTimeAndDate(value, shiftTime);
updateFields(
{
shiftTime: startTime.toISOString(),
}
);
if (shiftEndTime) {
updateShiftTimeErrorFields(startTime, new Date(shiftEndTime));
}
}
};
const handleShiftEndTimeChange = (value: string) => {
if (shiftTime) {
const endTime = createDateFromTimeAndDate(value, shiftTime);
updateFields(
{
shiftEndTime: endTime.toISOString(),
}
);
updateShiftTimeErrorFields(new Date(shiftTime), endTime);
}
};
const handleAddEmail = async () => {
if (currentEmail && currentEmail.trim()) {
const emailError = validateEmail(currentEmail);
if (emailError) {
toast({
title: "Invalid Email",
description: "Please enter a valid email address.",
status: "error",
position: 'top-right',
duration: 5000,
isClosable: true,
});
return;
}
try {
const user = await ServiceRequestAPIClient.getUserByEmail(currentEmail.trim());
if (user) {
// If user exists in the database, add their full name
const displayName = capitalizeName(`${user.firstName} ${user.lastName}`);
const updatedEmails = [...(inviteEmails || []), displayName];
updateFields({ inviteEmails: updatedEmails, currentEmail: "" });
} else {
// If user doesn't exist, add the email as-is (this part doesn't work right now so I put the logic in the catch block)
const updatedEmails = [...(inviteEmails || []), currentEmail.trim()];
updateFields({ inviteEmails: updatedEmails, currentEmail: "" });
}
} catch (error) {
console.error("User not Found:", error);
// Add the email if there's an error
const updatedEmails = [...(inviteEmails || []), currentEmail.trim()];
updateFields({ inviteEmails: updatedEmails, currentEmail: "" });
}
console.log(inviteEmails);
}
};
const handleRemoveEmail = (index: number) => {
const updatedEmails = (inviteEmails || []).filter((_, i) => i !== index);
updateFields({ inviteEmails: updatedEmails });
};
const isButtonDisabled =
!requestName ||
!shiftTime ||
!shiftEndTime ||
!requestType ||
!!shiftTimeError ||
!!shiftEndTimeError;
return <form onSubmit={onSubmit}>
<ModalBody>
<FormControl isRequired>
<FormLabel>Shift Title</FormLabel>
<Input
placeholder="Enter shift title"
value={requestName}
onChange={event => { updateFields({ requestName: event.target.value }); }}
/>
</FormControl>
<Flex columnGap={3}>
<Box flex="1.5">
<FormControl mt={6} isRequired>
<FormLabel>Date</FormLabel>
<Input
type="date"
value={formatDate(new Date(shiftTime!))}
onChange={event => handleShiftDateChange(event.target.value)}
/>
</FormControl>
</Box>
<Box flex="1">
<FormControl mt={6} isRequired>
<FormLabel>Start Time</FormLabel>
<Input
type="time"
value={shiftTime ? formatTime(new Date(shiftTime)) : ""}
onChange={event => handleShiftTimeChange(event.target.value)}
/>
{shiftTimeError && (
<FormHelperText fontSize="12" textAlign="left" color="red.500">
{shiftTimeError}
</FormHelperText>
)}
</FormControl>
</Box>
<Box flex="1">
<FormControl mt={6} isRequired>
<FormLabel>End Time</FormLabel>
<Input
type="time"
value={shiftEndTime ? formatTime(new Date(shiftEndTime)) : ""}
onChange={event => handleShiftEndTimeChange(event.target.value)}
/>
{shiftEndTimeError && (
<FormHelperText fontSize="12" textAlign="left" color="red.500">
{shiftEndTimeError}
</FormHelperText>
)}
</FormControl>
</Box>
</Flex>
<FormControl mt={6} width="50%">
<FormLabel>Repeat</FormLabel>
<Select
value={frequency ? titleCase(frequency) : ""}
onChange={event => {
updateFields(
{
frequency: event.target.value.toUpperCase() as Frequency,
}
);
}}
>
{
Object.values(Frequency).map((value, index) =>
<option key={index}>
{titleCase(value)}
</option>
)
}
</Select>
</FormControl>
<FormControl mt={6}>
<FormLabel>Invite Others</FormLabel>
<InputGroup>
<Input
value={currentEmail}
onChange={(event) => updateFields({ currentEmail: event.target.value })}
/>
<InputRightElement width="4.5rem">
<Button
color="white"
background="#28214C"
h="1.75rem"
w="3.5rem"
size="sm"
onClick={handleAddEmail}
>
Add
</Button>
</InputRightElement>
</InputGroup>
{inviteEmails && inviteEmails.length > 0 && (
<Wrap mt={4}>
{inviteEmails.map((email, index) => (
<WrapItem key={index}>
<Tag size="md" colorScheme="gray" borderRadius="full">
<TagLabel>{email}</TagLabel>
<TagCloseButton onClick={() => handleRemoveEmail(index)} />
</Tag>
</WrapItem>
))}
</Wrap>
)}
</FormControl>
<Flex columnGap={3}>
{/* <Box flex="1">
<FormControl mt={6} isRequired>
<FormLabel>Volunteers Required</FormLabel>
TODO: Add numVolunteersRequired to schema.prisma
TODO: Determine if we want to set a maximum? Used 10 for now
<NumberInput defaultValue={1} max={10} min={1}>
<NumberInputField />
<NumberInputStepper>
<NumberIncrementStepper />
<NumberDecrementStepper />
</NumberInputStepper>
</NumberInput>
</FormControl>
</Box> */}
<Box flex="1">
<FormControl mt={6} isRequired>
<FormLabel>Shift Type</FormLabel>
<Select
value={requestType ? `${titleCase(requestType)} Shift` : ""}
onChange={event => {
const type = event.target.value.split(' ')[0].toUpperCase();
updateFields(
{
requestType: type as ServiceRequestType,
}
);
}}
>
{
Object.values(ServiceRequestType).map((type, index) =>
<option key={index}>
{titleCase(type)} Shift
</option>
)
}
</Select>
</FormControl>
</Box>
</Flex>
</ModalBody>
<ModalFooter>
<Button
w="30%"
mt={4}
color="white"
background="#28214C"
type="submit"
isDisabled={isButtonDisabled}
>
Next
</Button>
</ModalFooter>
</form>;
};
export default CreateShiftMain;