generated from cfpb/open-source-project-template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathStep1Form.tsx
325 lines (294 loc) · 11 KB
/
Step1Form.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* eslint-disable jsx-a11y/label-has-associated-control */
import { zodResolver } from '@hookform/resolvers/zod';
import useSblAuth from 'api/useSblAuth';
import { useEffect, useState } from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { Element, scroller } from 'react-scroll';
import { useNavigate } from 'react-router-dom';
import AssociatedFinancialInstitutions from './AssociatedFinancialInstitutions';
import NoDatabaseResultError from './NoDatabaseResultError';
import FormParagraph from 'components/FormParagraph';
import FieldGroup from 'components/FieldGroup';
import InputErrorMessage from 'components/InputErrorMessage';
import { Button, Link, Heading } from 'design-system-react';
import { fiOptions, fiData } from 'pages/ProfileForm/ProfileForm.data';
import type {
InstitutionDetailsApiType,
InstitutionDetailsApiCheckedType,
FinancialInstitutionRS,
ValidationSchema,
} from 'pages/ProfileForm/types';
import {
FormFields as formFields,
validationSchema,
} from 'pages/ProfileForm/types';
import InputEntry from './InputEntry';
import Step1FormErrorHeader from './Step1FormErrorHeader';
import Step1FormHeader from './Step1FormHeader';
import { useQuery } from '@tanstack/react-query';
import useProfileForm from 'store/useProfileForm';
import Step1FormDropdownContainer from './Step1FormDropdownContainer';
import fetchInstitutions from 'api/fetchInstitutions';
import submitUserProfile from 'api/submitUserProfile';
import {
formatUserProfileObject,
formatDataCheckedState,
} from 'pages/ProfileForm/ProfileFormUtils';
function Step1Form(): JSX.Element {
/* Initial- Fetch all institutions */
const auth = useSblAuth();
const email = auth.user?.profile.email;
// eslint-disable-next-line unicorn/prefer-string-slice
const emailDomain = email?.substring(email.lastIndexOf('@') + 1);
const {
isLoading,
isError,
data: afData,
} = useQuery({
queryKey: [`fetch-institutions-${emailDomain}`, emailDomain],
queryFn: async () => fetchInstitutions(auth, emailDomain),
enabled: !!emailDomain,
});
const defaultValues: ValidationSchema = {
firstName: '',
lastName: '',
email: email ?? '',
financialInstitutions: [],
};
const {
register,
handleSubmit,
setValue,
trigger,
getValues,
formState: { errors: formErrors },
} = useForm<ValidationSchema>({
resolver: zodResolver(validationSchema),
defaultValues,
});
const onSubmit: SubmitHandler<ValidationSchema> = data => {
// TODO: decide if real-time input validation or on submit button click validation is better UX
// console.log('data:', data);
};
/* Selected State - Start */
// Associated Financial Institutions state
const [checkedListState, setCheckedListState] = useState<
InstitutionDetailsApiCheckedType[]
>([]);
useEffect(() => {
const dataCheckedState = formatDataCheckedState(afData);
setCheckedListState(dataCheckedState);
}, [afData]);
// Dropdown -- Financial Institutions state
const [selectedFI, setSelectedFI] = useState<FinancialInstitutionRS[]>([]);
/* Selected State - End */
// Formatting: Checkmarking either the Associated Financial Institutions or the Dropdown Financial Institutions, adds to the react-hook-form object
/* Format - Start */
const getFinancialInstitutionsFormData = (
checkedListStateArray: InstitutionDetailsApiCheckedType[],
): InstitutionDetailsApiType[] => {
const newFinancialInstitutions: InstitutionDetailsApiType[] = [];
for (const object of checkedListStateArray) {
if (object.checked) {
const foundObject: InstitutionDetailsApiType = afData?.find(
institutionsObject => object.lei === institutionsObject.lei,
);
newFinancialInstitutions.push(foundObject);
}
}
// TODO: Added multiselected to list of selected institutions
// selectedFI.forEach( (objectRS: FinancialInstitutionRS) => {
// const found = fiData.find(object => object.lei === objectRS.value);
// if (found) {
// newFinancialInstitutions.push(found);
// }
// } );
return newFinancialInstitutions;
};
useEffect(() => {
const checkedFinancialInstitutions =
getFinancialInstitutionsFormData(checkedListState);
setValue('financialInstitutions', checkedFinancialInstitutions);
}, [checkedListState, selectedFI]);
/* Format - End */
const navigate = useNavigate();
const enableMultiselect = useProfileForm(state => state.enableMultiselect);
const isSalesforce = useProfileForm(state => state.isSalesforce);
// 'Clear Form' function
function clearForm(): void {
setValue('firstName', '');
setValue('lastName', '');
setSelectedFI([]);
setCheckedListState([]);
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// Used for smooth scrolling to the Step1FormErrorHeader upon error
const scrollToErrorForm = (): void => {
scroller.scrollTo('step1FormErrorHeader', {
duration: 375,
smooth: true,
offset: -25, // Scrolls to element 25 pixels above the element
});
};
// Post Submission
const onSubmitButtonAction = async (): Promise<void> => {
// TODO: Handle error UX on submission failure or timeout
const userProfileObject = getValues();
const formattedUserProfileObject =
formatUserProfileObject(userProfileObject);
const passesValidation = await trigger();
if (passesValidation) {
const response = await submitUserProfile(
auth,
formattedUserProfileObject,
);
// TODO: workaround regarding UserProfile info not updating until reuath with keycloak
// more investigation needed, see:
// https://github.com/cfpb/sbl-frontend/issues/135
await auth.signinSilent();
window.location.href = '/landing';
// navigate('/landing')
} else {
// on errors scroll to Step1FormErrorHeader
scrollToErrorForm();
}
};
// Based on useQuery states
if (!auth.user?.access_token) return <>Login first!</>;
if (isLoading) return <>Loading Institutions!</>;
if (isError) return <>Error on loading institutions!</>;
return (
<div id='step1form'>
<Step1FormHeader />
<Element name='step1FormErrorHeader' id='step1FormErrorHeader'>
<Step1FormErrorHeader errors={formErrors} />
</Element>
<Heading type='3'>Provide your identifying information</Heading>
<FormParagraph>
Type your first name and last name in the fields below. Your email
address is automatically populated from <Link href='#'>Login.gov</Link>.
</FormParagraph>
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<InputEntry
label={formFields.firstName}
id='firstName'
{...register('firstName')}
errors={formErrors}
isDisabled={false}
/>
<InputEntry
label={formFields.lastName}
id='lastName'
{...register('lastName')}
errors={formErrors}
isDisabled={false}
/>
<InputEntry
label={formFields.email}
id='email'
{...register('email')}
errors={formErrors}
isDisabled
/>
</FieldGroup>
<Element name='financialInstitutions'>
{isSalesforce ? null : (
<>
<div className='mb-9 mt-8'>
<h3>
Select the financial institution you are authorized to file
for
</h3>
<FormParagraph>
If there is a match between your email domain and the email
domain of a financial institution in our system you will see a
list of matches below.{' '}
</FormParagraph>
</div>
<FieldGroup>
<AssociatedFinancialInstitutions
errors={formErrors}
checkedListState={checkedListState}
setCheckedListState={setCheckedListState}
/>
{enableMultiselect ? (
<Step1FormDropdownContainer
error={
formErrors.financialInstitutions
? formErrors.financialInstitutions.message
: ''
}
options={fiOptions}
id='financialInstitutionsMultiselect'
onChange={newSelected => setSelectedFI(newSelected)} // TODO: use useCallback
label=''
isMulti
pillAlign='bottom'
placeholder=''
withCheckbox
showClearAllSelectedButton={false}
isClearable={false}
value={selectedFI}
/>
) : null}
{/* TODO: The below error occurs if the 'Get All Financial Instituions' fetch fails or fetches empty data */}
{formErrors.fiData ? <NoDatabaseResultError /> : null}
</FieldGroup>
{formErrors.financialInstitutions ? (
<div>
<InputErrorMessage>
{formErrors.financialInstitutions.message}
</InputErrorMessage>
</div>
) : null}
</>
)}
{isSalesforce ? (
<>
<div className='mb-9 mt-8'>
<h3>Financial institution associations</h3>
<FormParagraph>
Please provide the name and LEI of the financial institution
you are authorized to file for and submit to our support staff
for processing. In order to access the filing platform you
must have an LEI for your financial institution.{' '}
</FormParagraph>
</div>
<FieldGroup>
<InputEntry
label='Financial institution name'
errors={formErrors}
/>
<InputEntry label='LEI' errors={formErrors} />
<InputEntry label='RSSD ID' errors={formErrors} />
<InputEntry label='Additional details' errors={formErrors} />
</FieldGroup>
</>
) : null}
</Element>
<div className='mt-[30px]'>
<Button
appearance='primary'
// TODO: Route to SBLhelp/Salesforce on no associated LEIs: https://github.com/cfpb/sbl-frontend/issues/99
onClick={onSubmitButtonAction}
label='Submit'
aria-label='Submit User Profile'
size='default'
type='button'
/>
<div className='ml-[15px] inline-block'>
<Button
label='Clear form'
onClick={clearForm}
appearance='warning'
asLink
/>
</div>
</div>
</form>
</div>
);
}
export default Step1Form;