-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathContributeDataModal.tsx
More file actions
276 lines (257 loc) · 8.17 KB
/
ContributeDataModal.tsx
File metadata and controls
276 lines (257 loc) · 8.17 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
import React, { useState } from 'react';
import { Button, Form, Input, Modal, Typography, notification } from 'antd';
import { z } from 'zod';
import ReCAPTCHA from 'react-google-recaptcha';
import { useCreateFeedbackTicket, useAuthenticatedUser } from '@client/hooks';
import { DateInput } from '@client/datafiles';
const formSchema = z.object({
name: z.string().min(1, 'Required'),
email: z.string().email('Invalid Email').min(1, 'Required'),
dateOfHazard: z.string().min(1, 'Required'),
eventTitle: z.string().min(1, 'Required'),
url: z.string().url('Invalid URL').min(1, 'Required'),
latitude: z.coerce
.number({
required_error: 'Required',
invalid_type_error: 'Latitude must be a number',
})
.min(-90, 'Latitude must be between -90 and 90')
.max(90, 'Latitude must be between -90 and 90'),
longitude: z.coerce
.number({
required_error: 'Required',
invalid_type_error: 'Longitude must be a number',
})
.min(-180, 'Longitude must be between -180 and 180')
.max(180, 'Longitude must be between -180 and 180'),
body: z.string().min(10, 'Description must be at least 10 characters'),
recaptchaResponse: z
.string()
.min(1, 'Please complete the reCAPTCHA')
.optional(),
});
type FormValues = z.infer<typeof formSchema>;
export const ContributeDataModal: React.FC = () => {
const { user } = useAuthenticatedUser();
const [isModalOpen, setIsModalOpen] = useState(false);
const [form] = Form.useForm<FormValues>();
const { Link } = Typography;
const recaptchaSiteKey =
(window as any).__RECAPTCHA_ENTERPRISE_SITE_KEY || '';
const isAuthenticated = !!user;
const showModal = () => setIsModalOpen(true);
const handleClose = () => {
form.resetFields();
setIsModalOpen(false);
};
const { mutate } = useCreateFeedbackTicket(
'RECON-PORTAL',
'Data Contribution for DesignSafe Recon Portal'
);
const [notifApi, contextHolder] = notification.useNotification();
const handleSubmit = (values: FormValues) => {
// Putting all extra fields in body so they're included in ticket, hook doesn't handle these extra fields
const formattedBody = `
${values.body}
--- Additional Information ---
Date of Hazard Event: ${values.dateOfHazard || ''}
Event Title: ${values.eventTitle}
URL to Data: ${values.url}
Latitude: ${values.latitude}
Longitude: ${values.longitude}
`.trim();
mutate(
{
formData: {
name: values.name,
email: values.email,
body: formattedBody,
projectId: 'RECON-PORTAL',
title: 'Data Contribution',
...(values.recaptchaResponse && {
recaptchaToken: values.recaptchaResponse,
}), // Only include recaptcha if present
},
},
{
onSuccess: () => {
form.resetFields();
handleClose();
notifApi.open({
type: 'success',
message: '',
description:
'Your data contribution was successfully submitted. Our team will contact you shortly to help load your data.',
placement: 'bottomLeft',
});
},
onError: () => {
notifApi.open({
type: 'error',
message: 'Error',
description: 'Submission failed, please try again.',
placement: 'bottomLeft',
});
},
}
);
};
const validateField = (fieldName: keyof FormValues) => {
return async (_: any, value: any) => {
// Handle reCAPTCHA separately
if (fieldName === 'recaptchaResponse') {
if (isAuthenticated) {
return Promise.resolve(); // Skip for logged-in users
}
// Require for unauthenticated users
if (!value || value.trim() === '') {
return Promise.reject('Please complete the reCAPTCHA');
}
return Promise.resolve();
}
const fieldSchema = formSchema.shape[fieldName];
try {
await fieldSchema.parseAsync(value);
} catch (error) {
if (error instanceof z.ZodError) {
return Promise.reject(error.errors[0]?.message);
}
return Promise.reject('Validation failed');
}
};
};
return (
<>
{contextHolder}
<Link onClick={showModal}>Email us to Contribute your Data</Link>
<Modal
destroyOnHidden
open={isModalOpen}
onCancel={handleClose}
width={900}
title={<h2>Contribute Your Data</h2>}
footer={null}
>
<Form
form={form}
layout="vertical"
onFinish={handleSubmit}
style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}
>
<Form.Item
label="Full Name"
name="name"
rules={[{ validator: validateField('name') }]}
initialValue={
user ? `${user?.firstName} ${user?.lastName}` : undefined
}
required
>
<Input disabled={!!user} />
</Form.Item>
<Form.Item
label="Email"
name="email"
rules={[{ validator: validateField('email') }]}
initialValue={user ? user.email : undefined}
required
>
<Input type="email" disabled={!!user} />
</Form.Item>
<Form.Item
label="Date of Hazard Event"
name="dateOfHazard"
rules={[{ validator: validateField('dateOfHazard') }]}
required
>
<DateInput />
</Form.Item>
<Form.Item
label="Event Title"
name="eventTitle"
rules={[{ validator: validateField('eventTitle') }]}
required
>
<Input />
</Form.Item>
<Form.Item
label="URL to Data"
name="url"
rules={[{ validator: validateField('url') }]}
required
>
<Input />
</Form.Item>
<Form.Item
label="Latitude"
name="latitude"
rules={[{ validator: validateField('latitude') }]}
required
>
<Input
type="number"
onChange={(e) => {
const num = Number(e.target.value);
form.setFieldValue(
'latitude',
e.target.value === '' || isNaN(num) ? undefined : num
);
}}
/>
</Form.Item>
<Form.Item
label="Longitude"
name="longitude"
rules={[{ validator: validateField('longitude') }]}
required
>
<Input
type="number"
onChange={(e) => {
const num = Number(e.target.value);
form.setFieldValue(
'longitude',
e.target.value === '' || isNaN(num) ? undefined : num
);
}}
/>
</Form.Item>
<Form.Item
label="Brief Description"
name="body"
rules={[{ validator: validateField('body') }]}
required
>
<Input.TextArea autoSize={{ minRows: 4 }} />
</Form.Item>
{!isAuthenticated && (
<Form.Item
name="recaptchaResponse"
rules={[{ validator: validateField('recaptchaResponse') }]}
required
>
{recaptchaSiteKey ? (
<ReCAPTCHA
sitekey={recaptchaSiteKey}
onChange={(value) =>
form.setFieldValue('recaptchaResponse', value || '')
}
onExpired={() => form.setFieldValue('recaptchaResponse', '')}
/>
) : (
<div style={{ color: 'red' }}>
RECAPTCHA site key not set yet
</div>
)}
</Form.Item>
)}
<Form.Item>
<Button type="primary" style={{ float: 'right' }} htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</Modal>
</>
);
};