summaryrefslogtreecommitdiff
path: root/client/src/components/RsvpForm.tsx
blob: fd7bcd55ed9630caa16b7825c79b2e836e3eed63 (plain)
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
import React from 'react';
import { useRef } from 'react';
import { useOutletContext } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
  Button,
  FormControl,
  FormControlLabel,
  FormLabel,
  Grid,
  Paper,
  Radio,
  RadioGroup,
  TextField,
} from '@mui/material';
import MailIcon from '@mui/icons-material/Mail';
import { useForm, Controller, useFieldArray } from 'react-hook-form';
import { useUpdateGuestMutation } from '../slices/api/guestSlice';
import { isFetchBaseQueryError } from '../error';
import Status from './Status';
import { open } from '../slices/snackbarSlice';
import type { Data } from '../error';
import type { Guest } from '../models';

function RsvpForm() {
  const dispatch = useDispatch();
  const [updateGuest] = useUpdateGuestMutation();
  const guest: Guest = useOutletContext();
  const previousPartySize = useRef((guest.partySize ?? 1) - 1);

  const {
    register,
    handleSubmit,
    control,
    watch,
    formState: { errors },
  } = useForm<Guest>({
    defaultValues: {
      id: guest.id,
      firstName: guest.firstName,
      lastName: guest.lastName,
      attendance: guest.attendance,
      email: guest.email,
      message: guest.message,
      partySize: guest.partySize,
      partyList: guest.partyList,
    },
  });

  const onSubmit = async (data: Guest) => {
    try {
      await updateGuest({ ...data }).unwrap();
      dispatch(
        open({
          message: 'RSVP updated',
          severity: 'success',
        })
      );
    } catch (error) {
      if (isFetchBaseQueryError(error)) {
        dispatch(
          open({
            message: (error.data as Data).message,
            severity: 'error',
          })
        );
      } else {
        dispatch(
          open({
            message: 'RSVP failed',
            severity: 'error',
          })
        );
      }
    }
  };

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'partyList',
  });

  const handleParty = () => {
    const partySize = Number(watch('partySize')) - 1;
    if (
      partySize > previousPartySize.current &&
      partySize > 0 &&
      partySize < 10
    ) {
      append(
        new Array(partySize - previousPartySize.current).fill({
          firstName: '',
          lastName: '',
        })
      );
      previousPartySize.current = partySize;
    } else if (partySize < previousPartySize.current && partySize >= 0) {
      remove(
        [...Array(previousPartySize.current - partySize).keys()].map(
          (_, i) => partySize - 1 + i
        )
      );
      previousPartySize.current = partySize;
    }
  };

  return (
    <form
      style={{
        height: '100%',
        width: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'start',
      }}
      noValidate
      onSubmit={handleSubmit(onSubmit)}
    >
      <Paper
        elevation={3}
        sx={{
          '&:hover': { boxShadow: 5 },
          width: { xs: '90%', md: 600 },
          display: 'flex',
          justifyContent: 'center',
          px: 2,
          pb: 2,
          mt: { xs: 10, md: 16 },
        }}
      >
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <p>
              Please RSVP for the wedding by March 10, 2025. The ceremony will
              commence at 4:30 pm on April 26 in Divine Shepherd. The reception
              will follow at 6 pm in A Venue on the Ridge.
            </p>
          </Grid>
          <Grid item xs={12}>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <FormControl>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <FormLabel
                    sx={{ mr: 2 }}
                    error={!!errors.attendance}
                    required
                  >
                    Attendance
                  </FormLabel>
                  <Controller
                    name="attendance"
                    control={control}
                    rules={{ required: true }}
                    render={({ field }) => (
                      <RadioGroup {...field} row>
                        <FormControlLabel
                          value="accept"
                          control={<Radio />}
                          label="Accept"
                        />
                        <FormControlLabel
                          value="decline"
                          control={<Radio />}
                          label="Decline"
                        />
                      </RadioGroup>
                    )}
                  />
                </div>
              </FormControl>
            </div>
          </Grid>
          <Grid item xs={8}>
            <TextField
              label="Email"
              type="email"
              variant="outlined"
              fullWidth
              error={!!errors.email}
              helperText={errors.email?.message}
              required
              {...register('email', {
                setValueAs: (value: string) => value.trim(),
                required: 'This field is required',
                pattern: {
                  value: /\S+@\S+\.\S+/,
                  message: 'Please enter a valid email address',
                },
              })}
            />
          </Grid>
          <Grid item xs={4}>
            <TextField
              label="Party Size"
              type="number"
              variant="outlined"
              fullWidth
              onWheel={(event) => {
                event.currentTarget.blur();
              }}
              error={!!errors.partySize}
              helperText={errors.partySize?.message}
              required
              {...register('partySize', {
                valueAsNumber: true,
                onChange: handleParty,
                required: 'This field is required',
                min: { value: 1, message: 'Please enter a positive integer' },
                max: {
                  value: 9,
                  message: 'Please enter an integer less than 10',
                },
              })}
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              label="Message to the couple"
              variant="outlined"
              fullWidth
              multiline
              rows={3}
              {...register('message')}
            />
          </Grid>
          {fields.map((field, index) => {
            return (
              <Grid
                container
                item
                columnSpacing={2}
                rowSpacing={{ xs: 1 }}
                key={field.id}
              >
                <Grid item xs={6}>
                  <TextField
                    label="First Name"
                    variant="outlined"
                    fullWidth
                    error={!!errors.partyList?.[index]?.firstName}
                    helperText={errors.partyList?.[index]?.firstName?.message}
                    required
                    {...register(`partyList.${index}.firstName`, {
                      setValueAs: (value: string) => value.trim(),
                      required: 'This field is required',
                    })}
                  />
                </Grid>
                <Grid item xs={6}>
                  <TextField
                    label="Last Name"
                    variant="outlined"
                    fullWidth
                    error={!!errors.partyList?.[index]?.lastName}
                    helperText={errors.partyList?.[index]?.lastName?.message}
                    required
                    {...register(`partyList.${index}.lastName`, {
                      setValueAs: (value: string) => value.trim(),
                      required: 'This field is required',
                    })}
                  />
                </Grid>
              </Grid>
            );
          })}
          <Grid item xs={12}>
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
              }}
            >
              <Button type="submit" variant="contained" endIcon={<MailIcon />}>
                RSVP
              </Button>
            </div>
          </Grid>
          <Status />
        </Grid>
      </Paper>
    </form>
  );
}

export default RsvpForm;