Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 | 71x 381x 381x 381x 381x 381x 381x 381x 5x 381x 5x 5x 5x 1x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 3x 3x 3x 381x 381x 334x 334x 334x 1x 1x | import { ReactNode, useMemo } from "react"; import { Banner, Button, UserPrompt, SimplePageContainer, BreadCrumbs, Form, LoadingSpinner, SectionCard, FormField, banner, userPrompt, FAQFooter, PreSubmissionMessage, optionCrumbsFromPath, ActionFormDescription, RequiredFieldDescription, RequiredIndicator, } from "@/components"; import { DefaultValues, FieldPath, useForm, UseFormReturn } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Navigate, useLocation, useNavigate, useParams } from "react-router"; import { getFormOrigin } from "@/utils"; import { CheckDocumentFunction, documentPoller } from "@/utils/Poller/documentPoller"; import { API } from "aws-amplify"; import { Authority, CognitoUserAttributes } from "shared-types"; import { ActionFormAttachments, AttachmentsOptions } from "./ActionFormAttachments"; import { getAttachments } from "./actionForm.utilities"; import { isStateUser } from "shared-utils"; import { useGetUser } from "@/api"; import { AdditionalInformation } from "./AdditionalInformation"; import { useMutation } from "@tanstack/react-query"; import { queryClient } from "@/router"; type EnforceSchemaProps<Shape extends z.ZodRawShape> = z.ZodObject< Shape & { attachments?: z.ZodObject<{ [Key in keyof Shape]: z.ZodObject<{ label: z.ZodDefault<z.ZodString>; files: z.ZodArray<z.ZodTypeAny, "many"> | z.ZodOptional<z.ZodArray<z.ZodTypeAny, "many">>; }>; }>; }, "strip", z.ZodTypeAny >; export type SchemaWithEnforcableProps<Shape extends z.ZodRawShape = z.ZodRawShape> = | z.ZodEffects<EnforceSchemaProps<Shape>> | EnforceSchemaProps<Shape>; // Utility type to handle Zod schema with or without a transform type InferUntransformedSchema<T> = T extends z.ZodEffects<infer U> ? U : T; type ActionFormProps<Schema extends SchemaWithEnforcableProps> = { schema: Schema; defaultValues?: DefaultValues<z.infer<InferUntransformedSchema<Schema>>>; title: string; fields: (form: UseFormReturn<z.infer<InferUntransformedSchema<Schema>>>) => ReactNode; bannerPostSubmission?: Omit<Banner, "pathnameToDisplayOn">; promptPreSubmission?: Omit<UserPrompt, "onAccept">; promptOnLeavingForm?: Omit<UserPrompt, "onAccept">; attachments?: AttachmentsOptions; additionalInformation?: | { required: boolean; title: string; label: string; } | false; documentPollerArgs: { property: (keyof z.TypeOf<Schema> & string) | ((values: z.TypeOf<Schema>) => string); documentChecker: CheckDocumentFunction; }; conditionsDeterminingUserAccess?: ((user: CognitoUserAttributes | null) => boolean)[]; breadcrumbText: string; formDescription?: string; preSubmissionMessage?: string; showPreSubmissionMessage?: boolean; areFieldsRequired?: boolean; }; export const ActionForm = <Schema extends SchemaWithEnforcableProps>({ schema, defaultValues = {} as DefaultValues<z.TypeOf<InferUntransformedSchema<Schema>>>, title, fields: Fields, bannerPostSubmission = { header: "Package submitted", body: "Your submission has been received.", variant: "success", }, promptOnLeavingForm = { header: "Stop form submission?", body: "All information you've entered on this form will be lost if you leave this page.", acceptButtonText: "Yes, leave form", cancelButtonText: "Return to form", areButtonsReversed: true, }, promptPreSubmission, documentPollerArgs, attachments, conditionsDeterminingUserAccess = [isStateUser], breadcrumbText, formDescription = `Once you submit this form, a confirmation email is sent to you and to CMS. CMS will use this content to review your package, and you will not be able to edit this form. If CMS needs any additional information, they will follow up by email.`, preSubmissionMessage, additionalInformation = { required: false, label: "Add anything else you would like to share with CMS.", title: "Additional Information", }, showPreSubmissionMessage = true, areFieldsRequired = true, }: ActionFormProps<Schema>) => { const { id, authority } = useParams<{ id: string; authority: Authority; type: string; }>(); const { pathname } = useLocation(); const navigate = useNavigate(); const { data: userObj, isLoading: isUserLoading } = useGetUser(); const breadcrumbs = optionCrumbsFromPath(pathname, authority, id); const form = useForm<z.TypeOf<Schema>>({ resolver: zodResolver(schema), mode: "onChange", defaultValues: { ...defaultValues, }, }); const { mutateAsync } = useMutation({ mutationFn: (formData: z.TypeOf<Schema>) => API.post("os", "/submit", { body: formData, }), }); const onSubmit = form.handleSubmit(async (formData) => { try { try { await mutateAsync(formData); } catch (error) { throw Error(`Error submitting form: ${error?.message || error}`); } const { documentChecker, property } = documentPollerArgs; const documentPollerId = typeof property === "function" ? property(formData) : formData[property]; try { const poller = documentPoller(documentPollerId, documentChecker); await poller.startPollingData(); } catch (error) { throw Error(`${error?.message || error}`); } const formOrigins = getFormOrigin({ authority, id }); banner({ ...bannerPostSubmission, pathnameToDisplayOn: formOrigins.pathname, }); // Prevent stale data from displaying on formOrigins page await queryClient.invalidateQueries({ queryKey: ["record"] }); navigate(formOrigins); } catch (error) { console.error(error); banner({ header: "An unexpected error has occurred:", body: error instanceof Error ? error.message : String(error), variant: "destructive", pathnameToDisplayOn: window.location.pathname, }); window.scrollTo(0, 0); } }); const attachmentsFromSchema = useMemo(() => getAttachments(schema), [schema]); if (isUserLoading === true) { return <LoadingSpinner />; } const doesUserHaveAccessToForm = conditionsDeterminingUserAccess.some((condition) => condition(userObj?.user || null), ); if (!userObj || doesUserHaveAccessToForm === false) { return <Navigate to="/" replace />; } return ( <SimplePageContainer> <BreadCrumbs options={[ ...breadcrumbs, { to: pathname, displayText: breadcrumbText, order: breadcrumbs.length, }, ]} /> {form.formState.isSubmitting && <LoadingSpinner />} <Form {...form}> <form onSubmit={onSubmit} className="my-6 space-y-8 mx-auto justify-center flex flex-col"> <SectionCard testId="detail-section" title={title}> <div> {areFieldsRequired && <RequiredFieldDescription />} <ActionFormDescription boldReminder={areFieldsRequired}> {formDescription} </ActionFormDescription> </div> <Fields {...form} /> </SectionCard> {attachmentsFromSchema.length > 0 && ( <ActionFormAttachments attachmentsFromSchema={attachmentsFromSchema} {...attachments} /> )} {additionalInformation && ( <SectionCard testId="additional-info" title={ <> {additionalInformation.title}{" "} {additionalInformation.required && <RequiredIndicator />} </> } > <FormField control={form.control} name={"additionalInformation" as FieldPath<z.TypeOf<Schema>>} render={({ field }) => ( <AdditionalInformation label={additionalInformation.label} field={field} /> )} /> </SectionCard> )} {showPreSubmissionMessage && ( <PreSubmissionMessage hasProgressLossReminder={areFieldsRequired} preSubmissionMessage={preSubmissionMessage} /> )} <section className="flex justify-end gap-2 p-4 ml-auto"> <Button className="px-12" type={promptPreSubmission ? "button" : "submit"} onClick={ promptPreSubmission ? () => userPrompt({ ...promptPreSubmission, onAccept: onSubmit }) : undefined } disabled={form.formState.isValid === false} data-testid="submit-action-form" > Submit </Button> <Button className="px-12" onClick={() => userPrompt({ ...promptOnLeavingForm, onAccept: () => { const origin = getFormOrigin({ id, authority }); navigate(origin); }, }) } variant="outline" type="reset" data-testid="cancel-action-form" > Cancel </Button> </section> </form> </Form> <FAQFooter /> </SimplePageContainer> ); }; |