@redacto.io/consent-sdk-react 9.1.0 → 9.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/.turbo/turbo-build.log +10 -9
  2. package/CHANGELOG.md +12 -0
  3. package/dist/index.js +2 -4
  4. package/dist/index.mjs +2 -4
  5. package/dist/privacy-center.d.mts +56 -2
  6. package/dist/privacy-center.d.ts +56 -2
  7. package/dist/privacy-center.js +4840 -1874
  8. package/dist/privacy-center.mjs +5124 -2158
  9. package/package.json +1 -1
  10. package/src/RedactoNoticeConsent/RedactoNoticeConsent.tsx +2 -4
  11. package/src/RedactoNoticeConsent/api/types.ts +1 -0
  12. package/src/RedactoPrivacyCenter/PrivacyCenterCaseDetailsPage.tsx +3 -1
  13. package/src/RedactoPrivacyCenter/PrivacyCenterHomePage.tsx +3 -0
  14. package/src/RedactoPrivacyCenter/PrivacyCenterMyReceiptPage.tsx +26 -0
  15. package/src/RedactoPrivacyCenter/api/actions.ts +66 -0
  16. package/src/RedactoPrivacyCenter/api/client.ts +79 -0
  17. package/src/RedactoPrivacyCenter/components/CaseDetails/DocumentRequestCard.tsx +19 -13
  18. package/src/RedactoPrivacyCenter/components/CaseDetails/FinalizedTooltipWrapper.tsx +25 -0
  19. package/src/RedactoPrivacyCenter/components/CaseDetails/MessageComposer.tsx +39 -30
  20. package/src/RedactoPrivacyCenter/components/CaseDetails/MessageItem.tsx +2 -0
  21. package/src/RedactoPrivacyCenter/components/CaseDetails/MessagesTab.tsx +10 -3
  22. package/src/RedactoPrivacyCenter/components/CaseDetails/utils.ts +21 -6
  23. package/src/RedactoPrivacyCenter/components/DataRequest/ProductSelectionSection.tsx +222 -0
  24. package/src/RedactoPrivacyCenter/components/DataRequest/PurposeSelectionSection.tsx +12 -0
  25. package/src/RedactoPrivacyCenter/components/Form.tsx +843 -162
  26. package/src/RedactoPrivacyCenter/components/ReceiptsList.tsx +492 -0
  27. package/src/RedactoPrivacyCenter/components/RequestSubmit.tsx +284 -71
  28. package/src/RedactoPrivacyCenter/components/SideMenuBarPC/constants.tsx +6 -1
  29. package/src/RedactoPrivacyCenter/components/groupHelpers.ts +56 -0
  30. package/src/RedactoPrivacyCenter/components/receiptColumns.tsx +203 -0
  31. package/src/RedactoPrivacyCenter/components/types.ts +26 -2
  32. package/src/RedactoPrivacyCenter/context/NavigationContext.tsx +2 -2
  33. package/src/RedactoPrivacyCenter/lib/api.ts +95 -1
  34. package/src/RedactoPrivacyCenter/lib/constants.ts +17 -0
  35. package/src/RedactoPrivacyCenter/lib/types.ts +115 -0
  36. package/src/RedactoPrivacyCenter/locales/as/translation.json +40 -1
  37. package/src/RedactoPrivacyCenter/locales/bho/translation.json +40 -1
  38. package/src/RedactoPrivacyCenter/locales/bn/translation.json +40 -1
  39. package/src/RedactoPrivacyCenter/locales/brx/translation.json +40 -1
  40. package/src/RedactoPrivacyCenter/locales/doi/translation.json +40 -1
  41. package/src/RedactoPrivacyCenter/locales/en/translation.json +46 -1
  42. package/src/RedactoPrivacyCenter/locales/gom/translation.json +40 -1
  43. package/src/RedactoPrivacyCenter/locales/gu/translation.json +40 -1
  44. package/src/RedactoPrivacyCenter/locales/hi/translation.json +40 -1
  45. package/src/RedactoPrivacyCenter/locales/kn/translation.json +40 -1
  46. package/src/RedactoPrivacyCenter/locales/ks/translation.json +40 -1
  47. package/src/RedactoPrivacyCenter/locales/mai/translation.json +40 -1
  48. package/src/RedactoPrivacyCenter/locales/ml/translation.json +40 -1
  49. package/src/RedactoPrivacyCenter/locales/mni-Mtei/translation.json +40 -1
  50. package/src/RedactoPrivacyCenter/locales/mr/translation.json +40 -1
  51. package/src/RedactoPrivacyCenter/locales/ne/translation.json +40 -1
  52. package/src/RedactoPrivacyCenter/locales/or/translation.json +40 -1
  53. package/src/RedactoPrivacyCenter/locales/pa/translation.json +40 -1
  54. package/src/RedactoPrivacyCenter/locales/sa/translation.json +40 -1
  55. package/src/RedactoPrivacyCenter/locales/sat/translation.json +40 -1
  56. package/src/RedactoPrivacyCenter/locales/sd/translation.json +40 -1
  57. package/src/RedactoPrivacyCenter/locales/ta/translation.json +40 -1
  58. package/src/RedactoPrivacyCenter/locales/te/translation.json +40 -1
  59. package/src/RedactoPrivacyCenter/locales/ur/translation.json +40 -1
  60. package/src/RedactoPrivacyCenter/styles/injectStyles.ts +301 -0
  61. package/src/RedactoPrivacyCenter/ui/PCTooltip.tsx +3 -1
  62. package/tests/Form.test.tsx +1170 -0
  63. package/tests/ProductSelectionSection.test.tsx +293 -0
  64. package/tests/RequestSubmit.test.tsx +295 -0
@@ -0,0 +1,1170 @@
1
+ import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ // ─── react-i18next stub ──────────────────────────────────────────────────────
5
+ vi.mock('react-i18next', () => {
6
+ const en: Record<string, string> = {
7
+ raiseDataRequest: 'Raise a data request',
8
+ contact: 'Contact',
9
+ contactPlaceholder: 'Enter email',
10
+ requestType: 'Request type',
11
+ requestDetails: 'Request details',
12
+ selectRequestType: 'Select request type',
13
+ supportingDocumentation: 'Supporting documentation',
14
+ confirmCheckBox: 'I confirm the details above are accurate',
15
+ submit: 'Submit',
16
+ cancel: 'Cancel',
17
+ uploadFile: 'Upload file',
18
+ uploadFileButton: 'Browse',
19
+ description: 'Description',
20
+ additionalNote: 'Additional note',
21
+ reasonOptional: 'Reason (optional)',
22
+ timePeriod: 'Time period',
23
+ today: 'Today',
24
+ last7Days: 'Last 7 days',
25
+ last30Days: 'Last 30 days',
26
+ last3Months: 'Last 3 months',
27
+ access: 'access',
28
+ correction: 'correction',
29
+ erasure: 'erasure',
30
+ grievance: 'grievance',
31
+ nomination: 'nomination',
32
+ forProduct: 'For {{productName}}',
33
+ actingOnBehalfOfShort: 'acting on behalf of {{nominator}}',
34
+ selectPurposesForThisProduct: 'Select purposes within this product.',
35
+ selectProductsForRequest:
36
+ 'Select a product for your {{requestType}} request',
37
+ selectProductsForRequestGeneric: 'Select a product to continue',
38
+ nominationChipSuffix: '· {{nominator}}',
39
+ yourData: 'Your data',
40
+ actingOnBehalfOf: 'Acting on behalf of {{nominator}}',
41
+ activePurposes_one: '{{count}} active purpose',
42
+ activePurposes_other: '{{count}} active purposes',
43
+ autoSelected: 'Auto-selected',
44
+ noProductsAvailable: 'No products available',
45
+ noProductsAvailableDescription: 'You have no consents to manage yet.',
46
+ requestSubmittedSuccess: 'Request submitted',
47
+ requestSubmissionFailed: 'Request failed',
48
+ submissionFailed: 'Submission failed',
49
+ whatDataToAccess: 'What data to access',
50
+ whatDataToDelete: 'What data to delete',
51
+ selectAll: 'Select all',
52
+ dataCollected: 'Data collected',
53
+ revokeConsentNo: 'No',
54
+ revokeConsentYes: 'Yes',
55
+ revokeConsentModalTitle: 'Revoke consent?',
56
+ revokeConsentModalQuestion: 'Do you also want to revoke consent?',
57
+ revokeConsentModalPurposesLabel: 'Purposes',
58
+ revokeConsentModalYourPurposes: 'Your purposes',
59
+ revokeConsentModalIfYesLabel: 'If yes:',
60
+ revokeConsentModalIfYesBody: 'Your consent will be revoked.',
61
+ requestSubmittedSuccessfully: 'Request submitted successfully',
62
+ thankYouForSubmittingYourRequest: 'Thanks',
63
+ };
64
+ const interpolate = (template: string, vars?: Record<string, unknown>) =>
65
+ template.replace(/\{\{(\w+)\}\}/g, (_match, key: string) => {
66
+ const value = vars?.[key];
67
+ return value === undefined || value === null ? '' : String(value);
68
+ });
69
+ const t = (key: string, opts?: Record<string, unknown>) => {
70
+ const count = typeof opts?.count === 'number' ? opts.count : undefined;
71
+ const pluralKey =
72
+ count !== undefined
73
+ ? count === 1
74
+ ? `${key}_one`
75
+ : `${key}_other`
76
+ : key;
77
+ const template = en[pluralKey] ?? en[key] ?? key;
78
+ return interpolate(template, opts);
79
+ };
80
+ return {
81
+ useTranslation: () => ({
82
+ t,
83
+ i18n: { language: 'en', on: vi.fn(), off: vi.fn() },
84
+ }),
85
+ };
86
+ });
87
+
88
+ // ─── i18n module stub (used directly by Form.tsx for `on`/`off`) ─────────────
89
+ vi.mock('../src/RedactoPrivacyCenter/lib/i18n', () => ({
90
+ default: {
91
+ language: 'en',
92
+ on: vi.fn(),
93
+ off: vi.fn(),
94
+ },
95
+ }));
96
+
97
+ // ─── API stubs ───────────────────────────────────────────────────────────────
98
+ // `createCaseRequest` (legacy single-case path) and `createCaseRequestUnsafe`
99
+ // (batch path) are both shipped at runtime. We route them through one
100
+ // shared mock so existing tests can keep using `createCaseRequest.mock...`
101
+ // regardless of which code path the Form picks. Tests that need to assert
102
+ // throw-vs-null semantics override the relevant mock individually.
103
+ const createCaseRequest = vi.fn();
104
+ const getFormData = vi.fn();
105
+ vi.mock('../src/RedactoPrivacyCenter/lib/api', () => ({
106
+ createCaseRequest: (...args: unknown[]) => createCaseRequest(...args),
107
+ createCaseRequestUnsafe: (...args: unknown[]) => createCaseRequest(...args),
108
+ getFormData: (...args: unknown[]) => getFormData(...args),
109
+ }));
110
+
111
+ // ─── upload stub ─────────────────────────────────────────────────────────────
112
+ vi.mock('../src/RedactoPrivacyCenter/api/upload', () => ({
113
+ uploadFileWithS2S: vi.fn(),
114
+ }));
115
+
116
+ // ─── tanstack/react-query stub ───────────────────────────────────────────────
117
+ vi.mock('@tanstack/react-query', () => ({
118
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
119
+ }));
120
+
121
+ // ─── Toast stub ──────────────────────────────────────────────────────────────
122
+ vi.mock('../src/RedactoPrivacyCenter/utils/toast', () => ({
123
+ toast: {
124
+ success: vi.fn(),
125
+ error: vi.fn(),
126
+ info: vi.fn(),
127
+ },
128
+ }));
129
+
130
+ // ─── Auth / BaseUrl / Organization context stubs ─────────────────────────────
131
+ // Stable references prevent identity churn from re-firing effects whose deps
132
+ // include context-derived values (auth, consentClient, organization).
133
+ vi.mock('../src/RedactoPrivacyCenter/context/AuthContext', () => {
134
+ const auth = {
135
+ accessToken: 'tok',
136
+ refreshToken: 'rtok',
137
+ onError: () => false,
138
+ updateTokens: () => {},
139
+ };
140
+ return { useAuth: () => auth };
141
+ });
142
+
143
+ vi.mock('../src/RedactoPrivacyCenter/context/BaseUrlContext', () => {
144
+ const base = {
145
+ consentClient: { get: () => Promise.resolve(null), post: () => Promise.resolve(null) },
146
+ baseUrl: 'https://consent.test',
147
+ };
148
+ return { useBaseUrl: () => base };
149
+ });
150
+
151
+ vi.mock('../src/RedactoPrivacyCenter/context/OrganizationContext', () => {
152
+ const org = {
153
+ organization: {
154
+ uuid: 'org-uuid',
155
+ slug: 'acme',
156
+ name: 'Acme',
157
+ workspaces: [{ uuid: 'ws-uuid' }],
158
+ },
159
+ };
160
+ return { useOrganization: () => org };
161
+ });
162
+
163
+ // ─── Optional peer-dep icon libs: stub with concrete named exports.
164
+ // `lucide-react` and `react-icons/*` are peer deps with no entry in the
165
+ // package's own node_modules. Tests don't care about icon glyphs — we
166
+ // stub every name imported by transitively-loaded SDK modules.
167
+ vi.mock('lucide-react', () => {
168
+ const S = () => null;
169
+ return {
170
+ X: S, ChevronDown: S, ChevronDownIcon: S, Check: S, Mail: S, Search: S,
171
+ ArrowUpToLine: S, ArrowLeft: S, Filter: S, Circle: S, Smartphone: S,
172
+ LaptopMinimal: S, ShieldCheck: S, Globe2: S, Menu: S, MessageCircleWarning: S,
173
+ PanelLeftClose: S, PanelLeftOpen: S, LogOut: S, Activity: S, ReceiptText: S,
174
+ };
175
+ });
176
+ vi.mock('react-icons/ai', () => ({ AiOutlineClose: () => null }));
177
+ vi.mock('react-icons/pi', () => {
178
+ const S = () => null;
179
+ return {
180
+ PiUploadBold: S, PiWarningCircleBold: S, PiCaretDownFill: S, PiCaretUpFill: S,
181
+ };
182
+ });
183
+ vi.mock('react-icons/fi', () => {
184
+ const S = () => null;
185
+ return {
186
+ FiAlertCircle: S, FiChevronDown: S, FiChevronUp: S, FiX: S,
187
+ FiDownload: S, FiSearch: S, FiFilter: S,
188
+ };
189
+ });
190
+ vi.mock('react-icons/io5', () => {
191
+ const S = () => null;
192
+ return {
193
+ IoArrowBack: S, IoChevronBackOutline: S, IoAdd: S, IoAttach: S,
194
+ IoDocumentText: S, IoNotificationsOutline: S, IoPersonOutline: S,
195
+ IoRefresh: S, IoRefreshOutline: S, IoSend: S, IoTimeOutline: S,
196
+ IoDocumentOutline: S, IoShieldCheckmarkOutline: S, IoAlertCircleOutline: S,
197
+ IoSettingsOutline: S,
198
+ };
199
+ });
200
+
201
+ // ─── PCSelect stub: replace at module source so the barrel re-export
202
+ // picks up the stub. PCSelect uses lucide-react, which is fragile in
203
+ // tests; stubbing also lets us drive it with a native <select>.
204
+ vi.mock('../src/RedactoPrivacyCenter/ui/PCSelect', () => {
205
+ type Option = { value: string | number; label: string };
206
+ const PCSelect = ({
207
+ options,
208
+ value,
209
+ onChange,
210
+ label,
211
+ disabled,
212
+ }: {
213
+ options: readonly Option[];
214
+ value: Option | null;
215
+ onChange?: (opt: Option | null) => void;
216
+ label?: React.ReactNode;
217
+ disabled?: boolean;
218
+ }) => (
219
+ <label>
220
+ {typeof label === 'string' ? label : null}
221
+ <select
222
+ data-testid="pc-select"
223
+ disabled={disabled}
224
+ value={value ? String(value.value) : ''}
225
+ onChange={(e) => {
226
+ const opt = options.find((o) => String(o.value) === e.target.value);
227
+ onChange?.(opt ?? null);
228
+ }}
229
+ >
230
+ <option value="">--</option>
231
+ {options.map((o) => (
232
+ <option key={String(o.value)} value={String(o.value)}>
233
+ {o.label}
234
+ </option>
235
+ ))}
236
+ </select>
237
+ </label>
238
+ );
239
+ return { PCSelect };
240
+ });
241
+
242
+ // ─── PCModal stub: render inline always when isOpen ──────────────────────────
243
+ vi.mock('../src/RedactoPrivacyCenter/ui/PCModal', () => ({
244
+ PCModal: ({
245
+ isOpen,
246
+ children,
247
+ footer,
248
+ }: {
249
+ isOpen: boolean;
250
+ children?: React.ReactNode;
251
+ footer?: React.ReactNode;
252
+ }) =>
253
+ isOpen ? (
254
+ <div data-testid="pc-modal">
255
+ {children}
256
+ {footer}
257
+ </div>
258
+ ) : null,
259
+ }));
260
+
261
+ // ─── Heavy/optional child stubs we don't want to exercise ────────────────────
262
+ // CorrectionDataSection stub: light enough to render quickly, rich enough
263
+ // for the per-product CORRECTION grouped-flow tests to drive selection
264
+ // and value entry. Mirrors the real component's prop contract: a checkbox
265
+ // per data-element plus two inputs (current / updated) per selected name.
266
+ // Existing tests that don't interact with it still pass — they just see
267
+ // an empty checklist when their request type isn't CORRECTION.
268
+ vi.mock(
269
+ '../src/RedactoPrivacyCenter/components/DataRequest/CorrectionDataSection',
270
+ () => ({
271
+ default: ({
272
+ dataElements,
273
+ selected,
274
+ setSelected,
275
+ correctionValues,
276
+ setCorrectionValues,
277
+ }: {
278
+ dataElements: Array<{ uuid: string; name: string }>;
279
+ selected: string[];
280
+ setSelected: (values: string[]) => void;
281
+ correctionValues: Record<
282
+ string,
283
+ { current: string; updated: string }
284
+ >;
285
+ setCorrectionValues: (
286
+ values: Record<string, { current: string; updated: string }>,
287
+ ) => void;
288
+ }) => (
289
+ <div data-testid="correction-section">
290
+ {dataElements.map((de) => (
291
+ <div key={de.uuid}>
292
+ <label>
293
+ <input
294
+ type="checkbox"
295
+ aria-label={`correction-de-${de.name}`}
296
+ checked={selected.includes(de.name)}
297
+ onChange={(e) =>
298
+ setSelected(
299
+ e.target.checked
300
+ ? [...selected, de.name]
301
+ : selected.filter((n) => n !== de.name),
302
+ )
303
+ }
304
+ />
305
+ {de.name}
306
+ </label>
307
+ {selected.includes(de.name) && (
308
+ <>
309
+ <input
310
+ aria-label={`correction-current-${de.name}`}
311
+ value={correctionValues[de.name]?.current ?? ''}
312
+ onChange={(e) =>
313
+ setCorrectionValues({
314
+ ...correctionValues,
315
+ [de.name]: {
316
+ ...(correctionValues[de.name] ?? {
317
+ current: '',
318
+ updated: '',
319
+ }),
320
+ current: e.target.value,
321
+ },
322
+ })
323
+ }
324
+ />
325
+ <input
326
+ aria-label={`correction-updated-${de.name}`}
327
+ value={correctionValues[de.name]?.updated ?? ''}
328
+ onChange={(e) =>
329
+ setCorrectionValues({
330
+ ...correctionValues,
331
+ [de.name]: {
332
+ ...(correctionValues[de.name] ?? {
333
+ current: '',
334
+ updated: '',
335
+ }),
336
+ updated: e.target.value,
337
+ },
338
+ })
339
+ }
340
+ />
341
+ </>
342
+ )}
343
+ </div>
344
+ ))}
345
+ </div>
346
+ ),
347
+ }),
348
+ );
349
+ vi.mock(
350
+ '../src/RedactoPrivacyCenter/components/DataRequest/GrievanceDataSection',
351
+ () => ({
352
+ default: () => <div data-testid="grievance-section" />,
353
+ }),
354
+ );
355
+ vi.mock(
356
+ '../src/RedactoPrivacyCenter/components/DataRequest/NominationDataSection',
357
+ () => ({
358
+ default: () => <div data-testid="nomination-section" />,
359
+ }),
360
+ );
361
+ vi.mock('../src/RedactoPrivacyCenter/components/RequestSubmit', () => ({
362
+ default: ({
363
+ result,
364
+ onRetry,
365
+ }: {
366
+ result: {
367
+ succeeded: Array<{
368
+ case_id: string;
369
+ product_uuid: string;
370
+ product_name: string;
371
+ group_key: string;
372
+ }>;
373
+ failed: Array<{
374
+ group_key: string;
375
+ product_uuid: string;
376
+ product_name: string;
377
+ error: string;
378
+ }>;
379
+ };
380
+ onRetry?: (groupKey: string) => void;
381
+ }) => (
382
+ <div data-testid="request-submitted">
383
+ <ul data-testid="request-submitted-succeeded">
384
+ {result.succeeded.map((s) => (
385
+ <li key={`${s.group_key}:${s.case_id}`} data-group-key={s.group_key}>
386
+ {s.case_id}
387
+ </li>
388
+ ))}
389
+ </ul>
390
+ <ul data-testid="request-submitted-failed">
391
+ {result.failed.map((f) => (
392
+ <li key={f.group_key} data-group-key={f.group_key}>
393
+ {f.product_name}
394
+ {onRetry !== undefined && (
395
+ <button
396
+ type="button"
397
+ onClick={() => onRetry(f.group_key)}
398
+ aria-label={`retry-${f.group_key}`}
399
+ >
400
+ Retry
401
+ </button>
402
+ )}
403
+ </li>
404
+ ))}
405
+ </ul>
406
+ </div>
407
+ ),
408
+ }));
409
+
410
+ // ─── Imports under test (must come after all vi.mock calls) ──────────────────
411
+ import Form from '../src/RedactoPrivacyCenter/components/Form';
412
+ import {
413
+ RequestTypeEnum,
414
+ type FormData,
415
+ type FormProductGroup,
416
+ } from '../src/RedactoPrivacyCenter/lib/types';
417
+
418
+ const baseDataElement = (uuid: string, name: string) => ({
419
+ uuid,
420
+ name,
421
+ description: '',
422
+ enabled: true,
423
+ required: false,
424
+ given_consent: true,
425
+ selected: true,
426
+ });
427
+
428
+ const basePurpose = (
429
+ uuid: string,
430
+ name: string,
431
+ dataElements = [baseDataElement(`${uuid}-de1`, `${name}-data`)],
432
+ ) => ({
433
+ uuid,
434
+ name,
435
+ description: '',
436
+ industries: '',
437
+ selected: false,
438
+ given_consent: true,
439
+ data_elements: dataElements,
440
+ });
441
+
442
+ /**
443
+ * Build a FormData stub.
444
+ *
445
+ * `formUuid` is the FormDataOut session uuid (a fresh uuid the backend
446
+ * mints per call to `PrivacyCenterSDK._generate_uuid()`) — intentionally
447
+ * distinct from any user / nominator ConsentUser uuid so tests catch
448
+ * the regression where the SDK previously sent this as `data_principal_uuid`
449
+ * on direct cards and the backend rejected it as `invalid_data_principal`.
450
+ */
451
+ const makeFormData = (
452
+ overrides: Partial<FormData> = {},
453
+ formUuid = 'form-session-uuid',
454
+ ): FormData => ({
455
+ uuid: formUuid,
456
+ name: 'Jane Principal',
457
+ contact: 'jane@example.com',
458
+ grievance_options: [],
459
+ purposes: [],
460
+ direct_groups: [],
461
+ nominated_groups: [],
462
+ ...overrides,
463
+ });
464
+
465
+ const makeGroup = (
466
+ overrides: Partial<FormProductGroup> = {},
467
+ ): FormProductGroup => ({
468
+ product_uuid: 'prod-1',
469
+ product_name: 'Acme Loyalty',
470
+ product_description: null,
471
+ nominator: null,
472
+ purposes: [basePurpose('purp-1', 'Marketing')],
473
+ ...overrides,
474
+ });
475
+
476
+ const setupSession = (email = 'jane@example.com') => {
477
+ sessionStorage.setItem('email', email);
478
+ };
479
+
480
+ const pickRequestType = (value: string) => {
481
+ const select = screen.getByTestId('pc-select') as HTMLSelectElement;
482
+ fireEvent.change(select, { target: { value } });
483
+ };
484
+
485
+ const clickProductChip = (groupKey: string) => {
486
+ fireEvent.click(screen.getByTestId(`product-chip-${groupKey}`));
487
+ };
488
+
489
+ describe('Form (P2-SDK-3)', () => {
490
+ beforeEach(() => {
491
+ createCaseRequest.mockReset();
492
+ getFormData.mockReset();
493
+ sessionStorage.clear();
494
+ });
495
+
496
+ afterEach(() => {
497
+ sessionStorage.clear();
498
+ });
499
+
500
+ it('falls back to the legacy flat render when direct_groups is undefined', async () => {
501
+ setupSession();
502
+ // Legacy backend shape: no direct_groups field at all.
503
+ const legacyData = {
504
+ uuid: 'form-session-uuid',
505
+ name: 'Jane',
506
+ contact: 'jane@example.com',
507
+ grievance_options: [],
508
+ purposes: [{ purpose: basePurpose('purp-1', 'Marketing') }],
509
+ } as unknown as FormData;
510
+ getFormData.mockResolvedValue(legacyData);
511
+
512
+ // The Form emits a one-time console.warn when it falls back to the
513
+ // legacy render so customer developers notice their backend hasn't
514
+ // shipped Phase 1. Spy on it so we can both silence and assert.
515
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
516
+
517
+ render(<Form onCreateRequest={vi.fn()} />);
518
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
519
+
520
+ pickRequestType(RequestTypeEnum.ERASURE);
521
+
522
+ // Legacy purpose row should appear; the grouped header must not.
523
+ await waitFor(() => {
524
+ expect(screen.getByText('Marketing')).toBeInTheDocument();
525
+ });
526
+ expect(
527
+ screen.queryByText(/Select a product/i),
528
+ ).not.toBeInTheDocument();
529
+
530
+ expect(warnSpy).toHaveBeenCalledWith(
531
+ expect.stringContaining('Backend response lacks direct_groups'),
532
+ );
533
+ warnSpy.mockRestore();
534
+ });
535
+
536
+ it('renders the product step for DSAR types when direct_groups is present', async () => {
537
+ setupSession();
538
+ const direct = makeGroup({
539
+ product_uuid: 'prod-direct',
540
+ product_name: 'Acme Loyalty',
541
+ });
542
+ const second = makeGroup({
543
+ product_uuid: 'prod-direct-2',
544
+ product_name: 'Acme Rewards',
545
+ purposes: [basePurpose('purp-2', 'Analytics')],
546
+ });
547
+ getFormData.mockResolvedValue(
548
+ makeFormData({ direct_groups: [direct, second] }),
549
+ );
550
+
551
+ render(<Form onCreateRequest={vi.fn()} />);
552
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
553
+
554
+ pickRequestType(RequestTypeEnum.ERASURE);
555
+
556
+ await waitFor(() => {
557
+ expect(screen.getByText('Acme Loyalty')).toBeInTheDocument();
558
+ });
559
+ expect(screen.getByText('Acme Rewards')).toBeInTheDocument();
560
+ expect(
561
+ screen.getByText(/Select a product for your erasure request/i),
562
+ ).toBeInTheDocument();
563
+ });
564
+
565
+ it('skips the product selection step when only one consent group exists', async () => {
566
+ // TECH-3712 UX: when the DP has exactly one consent group total
567
+ // (direct + nominated combined), ProductSelectionSection is friction —
568
+ // step 2 must not render at all. The lone group is auto-selected so
569
+ // step 3 (per-product purpose picker) renders directly.
570
+ setupSession();
571
+ const soleGroup = makeGroup({
572
+ product_uuid: 'prod-sole',
573
+ product_name: 'Acme Loyalty',
574
+ purposes: [basePurpose('purp-sole', 'Marketing')],
575
+ });
576
+ getFormData.mockResolvedValue(
577
+ makeFormData({ direct_groups: [soleGroup], nominated_groups: [] }),
578
+ );
579
+
580
+ render(<Form onCreateRequest={vi.fn()} />);
581
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
582
+
583
+ pickRequestType(RequestTypeEnum.ERASURE);
584
+
585
+ // Per-product card for the sole group should appear without the user
586
+ // touching a product card (auto-selected at Form level).
587
+ await waitFor(() => {
588
+ expect(
589
+ screen.getByTestId('per-product-purposes-prod-sole'),
590
+ ).toBeInTheDocument();
591
+ });
592
+
593
+ // ProductSelectionSection itself must NOT render. The step-2 product
594
+ // chip (data-testid `product-chip-prod-sole`) and the step-2 header
595
+ // ("Select a product...") are both signals it rendered.
596
+ expect(
597
+ screen.queryByTestId('product-chip-prod-sole'),
598
+ ).not.toBeInTheDocument();
599
+ expect(
600
+ screen.queryByText(/Select a product/i),
601
+ ).not.toBeInTheDocument();
602
+
603
+ // Step 3 (per-product purpose picker) is fully wired up: the purpose
604
+ // checkbox is present and tickable.
605
+ await waitFor(() => {
606
+ expect(screen.getByText('Marketing')).toBeInTheDocument();
607
+ });
608
+ const marketingCheckbox = screen
609
+ .getByText('Marketing')
610
+ .closest('label')
611
+ ?.querySelector('input[type="checkbox"]') as HTMLInputElement | null;
612
+ expect(marketingCheckbox).toBeTruthy();
613
+ });
614
+
615
+ it('skips the product step for nomination and grievance', async () => {
616
+ setupSession();
617
+ const direct = makeGroup();
618
+ getFormData.mockResolvedValue(
619
+ makeFormData({
620
+ direct_groups: [direct],
621
+ grievance_options: [
622
+ { value: 'consent_violation', label: 'Consent violation' },
623
+ ],
624
+ }),
625
+ );
626
+
627
+ render(<Form onCreateRequest={vi.fn()} />);
628
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
629
+
630
+ pickRequestType(RequestTypeEnum.GRIEVANCE);
631
+
632
+ await waitFor(() => {
633
+ expect(screen.getByTestId('grievance-section')).toBeInTheDocument();
634
+ });
635
+ expect(
636
+ screen.queryByText(/Select a product/i),
637
+ ).not.toBeInTheDocument();
638
+
639
+ pickRequestType(RequestTypeEnum.NOMINATION);
640
+
641
+ await waitFor(() => {
642
+ expect(screen.getByTestId('nomination-section')).toBeInTheDocument();
643
+ });
644
+ expect(
645
+ screen.queryByText(/Select a product/i),
646
+ ).not.toBeInTheDocument();
647
+ });
648
+
649
+ it('fires one createCaseRequest with correct anchors on single-product erasure submit', async () => {
650
+ setupSession();
651
+ const directGroup = makeGroup({
652
+ product_uuid: 'prod-direct',
653
+ product_name: 'Acme Loyalty',
654
+ purposes: [basePurpose('purp-direct', 'Marketing')],
655
+ });
656
+ const nominatedGroup = makeGroup({
657
+ product_uuid: 'prod-nominated',
658
+ product_name: 'Partner Bank',
659
+ nominator: {
660
+ uuid: 'nominator-uuid',
661
+ org_user_id: 'org-user-1',
662
+ name: 'Alice',
663
+ email: 'alice@example.com',
664
+ },
665
+ purposes: [basePurpose('purp-nominated', 'Analytics')],
666
+ });
667
+ getFormData.mockResolvedValue(
668
+ makeFormData({
669
+ direct_groups: [directGroup],
670
+ nominated_groups: [nominatedGroup],
671
+ }),
672
+ );
673
+ createCaseRequest.mockResolvedValueOnce({
674
+ case_id: 'CASE-1',
675
+ uuid: 'uuid-1',
676
+ });
677
+
678
+ render(<Form onCreateRequest={vi.fn()} />);
679
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
680
+
681
+ pickRequestType(RequestTypeEnum.ERASURE);
682
+
683
+ await waitFor(() =>
684
+ expect(screen.getByText('Acme Loyalty')).toBeInTheDocument(),
685
+ );
686
+ clickProductChip('prod-direct');
687
+
688
+ await waitFor(() => {
689
+ expect(
690
+ screen.getByTestId('per-product-purposes-prod-direct'),
691
+ ).toBeInTheDocument();
692
+ });
693
+
694
+ const marketingCheckbox = screen
695
+ .getByText('Marketing')
696
+ .closest('label')
697
+ ?.querySelector('input[type="checkbox"]') as HTMLInputElement | null;
698
+ expect(marketingCheckbox).toBeTruthy();
699
+ fireEvent.click(marketingCheckbox!);
700
+
701
+ const allCheckboxes = screen.getAllByRole(
702
+ 'checkbox',
703
+ ) as HTMLInputElement[];
704
+ const confirmCheckbox = allCheckboxes.find((c) =>
705
+ c.closest('label')?.textContent?.includes('I confirm'),
706
+ );
707
+ expect(confirmCheckbox).toBeTruthy();
708
+ fireEvent.click(confirmCheckbox!);
709
+
710
+ const submitButton = screen.getByRole('button', { name: /^submit$/i });
711
+ expect(submitButton).not.toBeDisabled();
712
+ await act(async () => {
713
+ fireEvent.click(submitButton);
714
+ });
715
+
716
+ await waitFor(() => {
717
+ expect(createCaseRequest).toHaveBeenCalledTimes(1);
718
+ });
719
+
720
+ const payload = createCaseRequest.mock.calls[0][2];
721
+ expect(payload.product_uuid).toBe('prod-direct');
722
+ expect('data_principal_uuid' in payload).toBe(false);
723
+ expect(payload.uuid).toBe('form-session-uuid');
724
+ expect(payload.request_type).toBe('erasure');
725
+ expect(payload.revoke_consent_on_fulfilment).toBe(false);
726
+
727
+ await waitFor(() => {
728
+ expect(screen.getByTestId('request-submitted')).toBeInTheDocument();
729
+ });
730
+ });
731
+
732
+ it('switches the inline purpose panel when another product chip is selected', async () => {
733
+ setupSession();
734
+ const creditCard = makeGroup({
735
+ product_uuid: 'prod-cc',
736
+ product_name: 'Credit Card',
737
+ purposes: [basePurpose('purp-cc', 'Marketing')],
738
+ });
739
+ const savings = makeGroup({
740
+ product_uuid: 'prod-sav',
741
+ product_name: 'Savings Account',
742
+ purposes: [basePurpose('purp-sav', 'Analytics')],
743
+ });
744
+ getFormData.mockResolvedValue(
745
+ makeFormData({ direct_groups: [creditCard, savings] }),
746
+ );
747
+
748
+ render(<Form onCreateRequest={vi.fn()} />);
749
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
750
+
751
+ pickRequestType(RequestTypeEnum.ERASURE);
752
+
753
+ await waitFor(() =>
754
+ expect(screen.getByText('Credit Card')).toBeInTheDocument(),
755
+ );
756
+ clickProductChip('prod-cc');
757
+
758
+ const ccPanel = await screen.findByTestId('per-product-purposes-prod-cc');
759
+ expect(within(ccPanel).getByText('Credit Card')).toBeInTheDocument();
760
+ expect(within(ccPanel).getByText('Marketing')).toBeInTheDocument();
761
+ expect(
762
+ screen.queryByTestId('per-product-purposes-prod-sav'),
763
+ ).not.toBeInTheDocument();
764
+
765
+ clickProductChip('prod-sav');
766
+
767
+ const savPanel = await screen.findByTestId('per-product-purposes-prod-sav');
768
+ expect(within(savPanel).getByText('Savings Account')).toBeInTheDocument();
769
+ expect(within(savPanel).getByText('Analytics')).toBeInTheDocument();
770
+ expect(
771
+ screen.queryByTestId('per-product-purposes-prod-cc'),
772
+ ).not.toBeInTheDocument();
773
+
774
+ clickProductChip('prod-cc');
775
+ await screen.findByTestId('per-product-purposes-prod-cc');
776
+ expect(screen.getByText('Marketing')).toBeInTheDocument();
777
+ });
778
+
779
+ it('disambiguates direct vs nominated chips on the same product via inline panel header', async () => {
780
+ setupSession();
781
+ const direct = makeGroup({
782
+ product_uuid: 'prod-cc',
783
+ product_name: 'Credit Card',
784
+ purposes: [basePurpose('purp-direct', 'Marketing')],
785
+ });
786
+ const nominated = makeGroup({
787
+ product_uuid: 'prod-cc',
788
+ product_name: 'Credit Card',
789
+ nominator: {
790
+ uuid: 'alice-uuid',
791
+ org_user_id: 'org-user-alice',
792
+ name: 'Alice',
793
+ email: 'alice@example.com',
794
+ },
795
+ purposes: [basePurpose('purp-nominated', 'Analytics')],
796
+ });
797
+ getFormData.mockResolvedValue(
798
+ makeFormData({
799
+ direct_groups: [direct],
800
+ nominated_groups: [nominated],
801
+ }),
802
+ );
803
+
804
+ render(<Form onCreateRequest={vi.fn()} />);
805
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
806
+
807
+ pickRequestType(RequestTypeEnum.ERASURE);
808
+
809
+ await waitFor(() =>
810
+ expect(screen.getByTestId('product-chip-prod-cc')).toBeInTheDocument(),
811
+ );
812
+ clickProductChip('prod-cc');
813
+
814
+ const directPanel = await screen.findByTestId(
815
+ 'per-product-purposes-prod-cc',
816
+ );
817
+ expect(within(directPanel).getByText('Credit Card')).toBeInTheDocument();
818
+ expect(
819
+ within(directPanel).queryByText(/acting on behalf of/i),
820
+ ).not.toBeInTheDocument();
821
+
822
+ clickProductChip('prod-cc:alice-uuid');
823
+
824
+ const nominatedPanel = await screen.findByTestId(
825
+ 'per-product-purposes-prod-cc:alice-uuid',
826
+ );
827
+ expect(within(nominatedPanel).getByText('Credit Card')).toBeInTheDocument();
828
+ expect(
829
+ within(nominatedPanel).getByText(/acting on behalf of Alice/i),
830
+ ).toBeInTheDocument();
831
+ });
832
+
833
+ it('fires one createCaseRequest with per-product correction_data on single-product correction submit', async () => {
834
+ setupSession();
835
+ const loyalty = makeGroup({
836
+ product_uuid: 'prod-loyalty',
837
+ product_name: 'Acme Loyalty',
838
+ purposes: [
839
+ basePurpose('purp-loyalty', 'Marketing', [
840
+ baseDataElement('de-loyalty-email', 'email'),
841
+ ]),
842
+ ],
843
+ });
844
+ const rewards = makeGroup({
845
+ product_uuid: 'prod-rewards',
846
+ product_name: 'Acme Rewards',
847
+ purposes: [
848
+ basePurpose('purp-rewards', 'Analytics', [
849
+ baseDataElement('de-rewards-phone', 'phone'),
850
+ ]),
851
+ ],
852
+ });
853
+ getFormData.mockResolvedValue(
854
+ makeFormData({
855
+ direct_groups: [loyalty, rewards],
856
+ purposes: [
857
+ {
858
+ purpose: basePurpose('purp-loyalty', 'Marketing', [
859
+ baseDataElement('de-loyalty-email', 'email'),
860
+ ]),
861
+ },
862
+ {
863
+ purpose: basePurpose('purp-rewards', 'Analytics', [
864
+ baseDataElement('de-rewards-phone', 'phone'),
865
+ ]),
866
+ },
867
+ ],
868
+ }),
869
+ );
870
+ createCaseRequest.mockResolvedValueOnce({
871
+ case_id: 'CASE-1',
872
+ uuid: 'uuid-1',
873
+ });
874
+
875
+ render(<Form onCreateRequest={vi.fn()} />);
876
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
877
+
878
+ pickRequestType(RequestTypeEnum.CORRECTION);
879
+
880
+ await waitFor(() =>
881
+ expect(screen.getByText('Acme Loyalty')).toBeInTheDocument(),
882
+ );
883
+ clickProductChip('prod-loyalty');
884
+
885
+ const loyaltyPanel = await screen.findByTestId(
886
+ 'per-product-purposes-prod-loyalty',
887
+ );
888
+
889
+ expect(
890
+ within(loyaltyPanel).getByLabelText('correction-de-email'),
891
+ ).toBeInTheDocument();
892
+ expect(
893
+ within(loyaltyPanel).queryByLabelText('correction-de-phone'),
894
+ ).not.toBeInTheDocument();
895
+
896
+ fireEvent.click(within(loyaltyPanel).getByLabelText('correction-de-email'));
897
+ fireEvent.change(
898
+ within(loyaltyPanel).getByLabelText('correction-current-email'),
899
+ { target: { value: 'old@x.com' } },
900
+ );
901
+ fireEvent.change(
902
+ within(loyaltyPanel).getByLabelText('correction-updated-email'),
903
+ { target: { value: 'new@x.com' } },
904
+ );
905
+
906
+ const allCheckboxes = screen.getAllByRole(
907
+ 'checkbox',
908
+ ) as HTMLInputElement[];
909
+ const confirmCheckbox = allCheckboxes.find((c) =>
910
+ c.closest('label')?.textContent?.includes('I confirm'),
911
+ );
912
+ expect(confirmCheckbox).toBeTruthy();
913
+ fireEvent.click(confirmCheckbox!);
914
+
915
+ const submitButton = screen.getByRole('button', { name: /^submit$/i });
916
+ expect(submitButton).not.toBeDisabled();
917
+ await act(async () => {
918
+ fireEvent.click(submitButton);
919
+ });
920
+
921
+ await waitFor(() => {
922
+ expect(createCaseRequest).toHaveBeenCalledTimes(1);
923
+ });
924
+
925
+ const payload = createCaseRequest.mock.calls[0][2];
926
+ expect(payload.product_uuid).toBe('prod-loyalty');
927
+ expect(payload.request_type).toBe('correction');
928
+ expect('data_principal_uuid' in payload).toBe(false);
929
+ expect(payload.request_details.purposes).toEqual([]);
930
+ expect(payload.request_details.correction_data).toEqual([
931
+ { name: 'email', curr_value: 'old@x.com', new_value: 'new@x.com' },
932
+ ]);
933
+
934
+ await waitFor(() => {
935
+ expect(screen.getByTestId('request-submitted')).toBeInTheDocument();
936
+ });
937
+ });
938
+
939
+ it('falls back to the legacy flat CorrectionDataSection when direct_groups is undefined', async () => {
940
+ // TECH-3712 (correction grouped path) regression guard: when the
941
+ // backend hasn't shipped Phase 1 yet (`direct_groups` absent), the
942
+ // CORRECTION render path must drop back to the legacy flat-data-element
943
+ // CorrectionDataSection and the submit must produce a single POST
944
+ // without `product_uuid`.
945
+ setupSession();
946
+ const legacyData = {
947
+ uuid: 'form-session-uuid',
948
+ name: 'Jane',
949
+ contact: 'jane@example.com',
950
+ grievance_options: [],
951
+ purposes: [
952
+ {
953
+ purpose: basePurpose('purp-1', 'Marketing', [
954
+ baseDataElement('de-1', 'email'),
955
+ ]),
956
+ },
957
+ ],
958
+ } as unknown as FormData;
959
+ getFormData.mockResolvedValue(legacyData);
960
+ createCaseRequest.mockResolvedValueOnce({
961
+ case_id: 'CASE-LEGACY',
962
+ uuid: 'uuid-legacy',
963
+ });
964
+
965
+ // Silence the legacy-mode warning emitted by Form.tsx so test output
966
+ // stays focused on the assertions.
967
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
968
+
969
+ render(<Form onCreateRequest={vi.fn()} />);
970
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
971
+
972
+ pickRequestType(RequestTypeEnum.CORRECTION);
973
+
974
+ // The product-step header must NOT appear — legacy fallback skips it.
975
+ expect(
976
+ screen.queryByText(/Select a product/i),
977
+ ).not.toBeInTheDocument();
978
+
979
+ // The legacy flat CorrectionDataSection should render with the
980
+ // backend's flat `purposes` data elements.
981
+ const correctionSection = await screen.findByTestId('correction-section');
982
+ expect(
983
+ within(correctionSection).getByLabelText('correction-de-email'),
984
+ ).toBeInTheDocument();
985
+
986
+ fireEvent.click(
987
+ within(correctionSection).getByLabelText('correction-de-email'),
988
+ );
989
+ fireEvent.change(
990
+ within(correctionSection).getByLabelText('correction-current-email'),
991
+ { target: { value: 'old' } },
992
+ );
993
+ fireEvent.change(
994
+ within(correctionSection).getByLabelText('correction-updated-email'),
995
+ { target: { value: 'new' } },
996
+ );
997
+
998
+ const allCheckboxes = screen.getAllByRole(
999
+ 'checkbox',
1000
+ ) as HTMLInputElement[];
1001
+ const confirmCheckbox = allCheckboxes.find((c) =>
1002
+ c.closest('label')?.textContent?.includes('I confirm'),
1003
+ );
1004
+ expect(confirmCheckbox).toBeTruthy();
1005
+ fireEvent.click(confirmCheckbox!);
1006
+
1007
+ const submitButton = screen.getByRole('button', { name: /^submit$/i });
1008
+ expect(submitButton).not.toBeDisabled();
1009
+ await act(async () => {
1010
+ fireEvent.click(submitButton);
1011
+ });
1012
+
1013
+ await waitFor(() => {
1014
+ expect(createCaseRequest).toHaveBeenCalledTimes(1);
1015
+ });
1016
+
1017
+ // Single POST with no product anchor — the legacy single-case path.
1018
+ const payload = createCaseRequest.mock.calls[0][2];
1019
+ expect(payload.request_type).toBe('correction');
1020
+ expect(payload.product_uuid).toBeUndefined();
1021
+ expect('data_principal_uuid' in payload).toBe(false);
1022
+ expect(payload.request_details.correction_data).toEqual([
1023
+ { name: 'email', curr_value: 'old', new_value: 'new' },
1024
+ ]);
1025
+
1026
+ warnSpy.mockRestore();
1027
+ });
1028
+
1029
+ it('records group_key on successful single-product batch submission', async () => {
1030
+ setupSession();
1031
+ const otherDirect = makeGroup({
1032
+ product_uuid: 'prod-other',
1033
+ product_name: 'Other Product',
1034
+ purposes: [basePurpose('purp-other', 'Other')],
1035
+ });
1036
+ const nominated = makeGroup({
1037
+ product_uuid: 'prod-cc',
1038
+ product_name: 'Credit Card',
1039
+ nominator: {
1040
+ uuid: 'alice-uuid',
1041
+ org_user_id: 'org-user-alice',
1042
+ name: 'Alice',
1043
+ email: 'alice@example.com',
1044
+ },
1045
+ purposes: [basePurpose('purp-nominated', 'Analytics')],
1046
+ });
1047
+ getFormData.mockResolvedValue(
1048
+ makeFormData({
1049
+ direct_groups: [otherDirect],
1050
+ nominated_groups: [nominated],
1051
+ }),
1052
+ );
1053
+ createCaseRequest.mockResolvedValueOnce({
1054
+ case_id: 'CASE-NOMINATED',
1055
+ uuid: 'uuid-nominated',
1056
+ });
1057
+
1058
+ render(<Form onCreateRequest={vi.fn()} />);
1059
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
1060
+
1061
+ pickRequestType(RequestTypeEnum.ERASURE);
1062
+
1063
+ await waitFor(() =>
1064
+ expect(
1065
+ screen.getByTestId('product-chip-prod-cc:alice-uuid'),
1066
+ ).toBeInTheDocument(),
1067
+ );
1068
+ clickProductChip('prod-cc:alice-uuid');
1069
+
1070
+ const nominatedPanel = await screen.findByTestId(
1071
+ 'per-product-purposes-prod-cc:alice-uuid',
1072
+ );
1073
+ fireEvent.click(
1074
+ within(nominatedPanel)
1075
+ .getByText('Analytics')
1076
+ .closest('label')!
1077
+ .querySelector('input[type="checkbox"]')!,
1078
+ );
1079
+
1080
+ const confirmCheckbox = (
1081
+ screen.getAllByRole('checkbox') as HTMLInputElement[]
1082
+ ).find((c) => c.closest('label')?.textContent?.includes('I confirm'));
1083
+ fireEvent.click(confirmCheckbox!);
1084
+
1085
+ await act(async () => {
1086
+ fireEvent.click(screen.getByRole('button', { name: /^submit$/i }));
1087
+ });
1088
+
1089
+ await waitFor(() => {
1090
+ expect(screen.getByTestId('request-submitted')).toBeInTheDocument();
1091
+ });
1092
+
1093
+ const succeededItems = within(
1094
+ screen.getByTestId('request-submitted-succeeded'),
1095
+ ).getAllByRole('listitem');
1096
+ expect(succeededItems).toHaveLength(1);
1097
+ expect(succeededItems[0].getAttribute('data-group-key')).toBe(
1098
+ 'prod-cc:alice-uuid',
1099
+ );
1100
+ });
1101
+
1102
+ it('disables submit when the selected CORRECTION product has incomplete entries', async () => {
1103
+ setupSession();
1104
+ const loyalty = makeGroup({
1105
+ product_uuid: 'prod-loyalty',
1106
+ product_name: 'Acme Loyalty',
1107
+ purposes: [
1108
+ basePurpose('purp-loyalty', 'Marketing', [
1109
+ baseDataElement('de-loyalty-email', 'email'),
1110
+ ]),
1111
+ ],
1112
+ });
1113
+ const rewards = makeGroup({
1114
+ product_uuid: 'prod-rewards',
1115
+ product_name: 'Acme Rewards',
1116
+ purposes: [
1117
+ basePurpose('purp-rewards', 'Analytics', [
1118
+ baseDataElement('de-rewards-phone', 'phone'),
1119
+ ]),
1120
+ ],
1121
+ });
1122
+ getFormData.mockResolvedValue(
1123
+ makeFormData({ direct_groups: [loyalty, rewards] }),
1124
+ );
1125
+
1126
+ render(<Form onCreateRequest={vi.fn()} />);
1127
+ await waitFor(() => expect(getFormData).toHaveBeenCalled());
1128
+
1129
+ pickRequestType(RequestTypeEnum.CORRECTION);
1130
+
1131
+ await waitFor(() =>
1132
+ expect(screen.getByText('Acme Loyalty')).toBeInTheDocument(),
1133
+ );
1134
+ clickProductChip('prod-loyalty');
1135
+
1136
+ const loyaltyPanel = await screen.findByTestId(
1137
+ 'per-product-purposes-prod-loyalty',
1138
+ );
1139
+
1140
+ const allCheckboxes = screen.getAllByRole(
1141
+ 'checkbox',
1142
+ ) as HTMLInputElement[];
1143
+ const confirmCheckbox = allCheckboxes.find((c) =>
1144
+ c.closest('label')?.textContent?.includes('I confirm'),
1145
+ );
1146
+ expect(confirmCheckbox).toBeTruthy();
1147
+ fireEvent.click(confirmCheckbox!);
1148
+
1149
+ const submitButton = screen.getByRole(
1150
+ 'button',
1151
+ { name: /^submit$/i },
1152
+ ) as HTMLButtonElement;
1153
+ expect(submitButton.disabled).toBe(true);
1154
+
1155
+ fireEvent.click(within(loyaltyPanel).getByLabelText('correction-de-email'));
1156
+ fireEvent.change(
1157
+ within(loyaltyPanel).getByLabelText('correction-current-email'),
1158
+ { target: { value: 'old@x.com' } },
1159
+ );
1160
+ fireEvent.change(
1161
+ within(loyaltyPanel).getByLabelText('correction-updated-email'),
1162
+ { target: { value: 'new@x.com' } },
1163
+ );
1164
+
1165
+ expect(
1166
+ (screen.getByRole('button', { name: /^submit$/i }) as HTMLButtonElement)
1167
+ .disabled,
1168
+ ).toBe(false);
1169
+ });
1170
+ });