-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSummary.jsx
275 lines (248 loc) · 8.01 KB
/
Summary.jsx
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
import {Form, Formik} from 'formik';
import {useContext, useState} from 'react';
import {FormattedMessage, useIntl} from 'react-intl';
import {createSearchParams, useLocation, useNavigate} from 'react-router';
import {useAsync} from 'react-use';
import {ConfigContext} from 'Context';
import {post} from 'api';
import {CardTitle} from 'components/Card';
import ErrorMessage from 'components/Errors/ErrorMessage';
import FormStepSummary from 'components/FormStepSummary';
import {Literal} from 'components/Literal';
import Loader from 'components/Loader';
import SummaryConfirmation from 'components/SummaryConfirmation';
import {ValidationError} from 'errors';
import useTitle from 'hooks/useTitle';
import {fieldLabel as dateLabel} from '../fields/DateSelect';
import {getLocations, fieldLabel as locationLabel} from '../fields/LocationSelect';
import {amountLabel} from '../fields/Product';
import {getAllProducts, fieldLabel as productLabel} from '../fields/ProductSelect';
import {fieldLabel as timeLabel} from '../fields/TimeSelect';
import {getContactDetailsFields} from '../steps/ContactDetailsStep';
import {useCreateAppointmentContext} from './CreateAppointmentState';
const createAppointment = async (baseUrl, submission, appointmentData, statementValues) => {
const {products, location, date, datetime, ...contactDetails} = appointmentData;
const body = {
submission: submission.url,
products,
location,
date,
datetime,
contactDetails,
...statementValues,
};
const response = await post(`${baseUrl}appointments/appointments`, body);
return response.data;
};
const getErrorsNavigateTo = errors => {
const errorKeys = Object.keys(errors);
if (errorKeys.includes('products')) {
return 'producten';
}
const locationAndTimeKeys = ['date', 'datetime', 'location'];
if (locationAndTimeKeys.some(key => errorKeys.includes(key))) {
return 'kalender';
}
if (errorKeys.includes('contactDetails')) {
return 'contactgegevens';
}
return null;
};
const Summary = () => {
const intl = useIntl();
const {baseUrl} = useContext(ConfigContext);
const {state: routerState} = useLocation();
const navigate = useNavigate();
const {appointmentData, submission, setErrors} = useCreateAppointmentContext();
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState(null);
useTitle(
intl.formatMessage({
description: 'Summary page title',
defaultMessage: 'Check and confirm',
})
);
// throw for unhandled submit errors
if (submitError) throw submitError;
const {products, location, date, datetime, ...contactDetails} = appointmentData;
const productIds = products.map(p => p.productId).sort();
const {
loading,
value = [],
error,
} = useAsync(async () => {
const promises = [
getAllProducts(baseUrl),
getLocations(baseUrl, productIds),
getContactDetailsFields(baseUrl, productIds),
];
return await Promise.all(promises);
}, [baseUrl, JSON.stringify(productIds)]);
if (error) throw error;
const [productList = [], locations = [], contactDetailComponents = []] = value;
// products, as repeating group/editgrid
let productsData = [];
const numProducts = products.length;
products.forEach(({productId, amount}, index) => {
const header = (
<FormattedMessage
description="Appointments: single product label/header"
defaultMessage="Product {number}/{total}"
values={{number: index + 1, total: numProducts}}
/>
);
if (numProducts > 1) {
productsData.push({name: header, value: null, component: {type: 'editgrid'}});
}
productsData.push(
{
name: intl.formatMessage(productLabel),
value: productId,
component: {
type: 'radio',
values: productList.map(({identifier, name}) => ({
value: identifier,
label: name,
})),
},
},
{
name: intl.formatMessage(amountLabel),
value: amount,
component: {type: 'number', decimalLimit: 0},
}
);
});
// location and time data, in the shape that FormStepSummary expects
const locationAndTimeData = [
{
name: intl.formatMessage(locationLabel),
value: location,
component: {
type: 'radio',
values: locations.map(({identifier, name}) => ({value: identifier, label: name})),
},
},
{
name: intl.formatMessage(dateLabel),
value: date,
component: {type: 'date'},
},
{
name: intl.formatMessage(timeLabel),
value: datetime,
component: {type: 'time'},
},
];
// contact details data
const contactDetailsData = contactDetailComponents.map(component => ({
name: component.label,
value: contactDetails[component.key],
component,
}));
/**
* Submit the appointment data to the backend.
*/
const onSubmit = async statementValues => {
setSubmitting(true);
let appointment;
try {
appointment = await createAppointment(baseUrl, submission, appointmentData, statementValues);
} catch (e) {
if (e instanceof ValidationError) {
const {initialErrors, initialTouched} = e.asFormikProps();
const navigateTo = getErrorsNavigateTo(initialErrors);
setErrors({initialErrors, initialTouched});
if (navigateTo) navigate(`../${navigateTo}`);
return;
}
setSubmitError(e);
return;
} finally {
setSubmitting(false);
}
// TODO: store details in sessionStorage instead, to survive hard refreshes
navigate(
{
pathname: '../bevestiging',
search: createSearchParams({
statusUrl: appointment.statusUrl,
}).toString(),
},
{
state: {submission},
}
);
};
const processingError = submitting ? '' : routerState?.errorMessage;
return (
<>
<CardTitle
title={
<FormattedMessage
description="Check overview and confirm"
defaultMessage="Check and confirm"
/>
}
component="h2"
headingType="subtitle"
padded
/>
{processingError && <ErrorMessage>{processingError}</ErrorMessage>}
{loading ? (
<Loader modifiers={['centered']} />
) : (
<Formik
initialValues={{privacyPolicyAccepted: false, statementOfTruthAccepted: false}}
onSubmit={onSubmit}
>
<Form>
{/* Products overview */}
<FormStepSummary
editUrl="../producten"
name={
<FormattedMessage
description="Appointment overview: products step title"
defaultMessage="{numProducts, plural, one {Product} other {Products}}"
values={{numProducts}}
/>
}
data={productsData}
editStepText={<Literal name="changeText" />}
/>
{/* Selected location and time */}
<FormStepSummary
editUrl="../kalender"
name={
<FormattedMessage
description="Appointment overview: location and time step title"
defaultMessage="Location and time"
/>
}
data={locationAndTimeData}
editStepText={<Literal name="changeText" />}
/>
{/* Contact details */}
<FormStepSummary
editUrl="../contactgegevens"
name={
<FormattedMessage
description="Appointment overview: contact details step title"
defaultMessage="Contact details"
/>
}
data={contactDetailsData}
editStepText={<Literal name="changeText" />}
/>
<SummaryConfirmation
submissionAllowed="yes"
onPrevPage={() => navigate('../contactgegevens')}
/>
</Form>
</Formik>
)}
</>
);
};
Summary.propTypes = {};
export default Summary;