@terreno/ui 0.31.0 → 56.0.0-beta.2

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 (126) hide show
  1. package/dist/ActionSheet.d.ts +1 -1
  2. package/dist/Avatar.js +1 -4
  3. package/dist/Avatar.js.map +1 -1
  4. package/dist/Box.js +45 -9
  5. package/dist/Box.js.map +1 -1
  6. package/dist/Common.d.ts +21 -0
  7. package/dist/Common.js.map +1 -1
  8. package/dist/ConflictSheet.d.ts +53 -0
  9. package/dist/ConflictSheet.js +132 -0
  10. package/dist/ConflictSheet.js.map +1 -0
  11. package/dist/DateTimeActionSheet.d.ts +2 -1
  12. package/dist/DateTimeField.js +5 -21
  13. package/dist/DateTimeField.js.map +1 -1
  14. package/dist/DecimalRangeActionSheet.d.ts +1 -1
  15. package/dist/EmojiSelector.d.ts +1 -1
  16. package/dist/ErrorPage.d.ts +1 -1
  17. package/dist/HeightActionSheet.d.ts +1 -1
  18. package/dist/Hyperlink.d.ts +2 -1
  19. package/dist/Hyperlink.js +2 -1
  20. package/dist/Hyperlink.js.map +1 -1
  21. package/dist/Image.d.ts +1 -1
  22. package/dist/ImageBackground.d.ts +1 -1
  23. package/dist/MobileAddressAutoComplete.d.ts +1 -1
  24. package/dist/NumberPickerActionSheet.d.ts +1 -1
  25. package/dist/Page.d.ts +5 -4
  26. package/dist/Page.js +0 -2
  27. package/dist/Page.js.map +1 -1
  28. package/dist/PickerSelect.d.ts +1 -1
  29. package/dist/SidebarNavigation.js +1 -1
  30. package/dist/SidebarNavigation.js.map +1 -1
  31. package/dist/SidebarNavigation.native.js +1 -1
  32. package/dist/SidebarNavigation.native.js.map +1 -1
  33. package/dist/SplitPage.d.ts +1 -1
  34. package/dist/SplitPage.js +1 -4
  35. package/dist/SplitPage.js.map +1 -1
  36. package/dist/SplitPage.native.d.ts +1 -1
  37. package/dist/SyncStatusBanner.d.ts +46 -0
  38. package/dist/SyncStatusBanner.js +29 -0
  39. package/dist/SyncStatusBanner.js.map +1 -0
  40. package/dist/Theme.d.ts +1 -1
  41. package/dist/Toast.d.ts +9 -1
  42. package/dist/Toast.js +20 -7
  43. package/dist/Toast.js.map +1 -1
  44. package/dist/ToastNotifications.js +23 -1
  45. package/dist/ToastNotifications.js.map +1 -1
  46. package/dist/UnifiedAddressAutoComplete.d.ts +1 -1
  47. package/dist/Unifier.js +1 -1
  48. package/dist/Unifier.js.map +1 -1
  49. package/dist/conflictFieldDiff.d.ts +14 -0
  50. package/dist/conflictFieldDiff.js +62 -0
  51. package/dist/conflictFieldDiff.js.map +1 -0
  52. package/dist/icons/OfflineIcon.d.ts +1 -1
  53. package/dist/icons/OnlineIcon.d.ts +1 -1
  54. package/dist/icons/OutOfficeIcon.d.ts +1 -1
  55. package/dist/index.d.ts +5 -2
  56. package/dist/index.js +5 -2
  57. package/dist/index.js.map +1 -1
  58. package/dist/pdfHtmlTemplate.d.ts +30 -0
  59. package/dist/pdfHtmlTemplate.js +170 -0
  60. package/dist/pdfHtmlTemplate.js.map +1 -0
  61. package/dist/table/TableTitle.js +1 -3
  62. package/dist/table/TableTitle.js.map +1 -1
  63. package/dist/useAppLaunchOrForeground.d.ts +9 -0
  64. package/dist/useAppLaunchOrForeground.js +27 -0
  65. package/dist/useAppLaunchOrForeground.js.map +1 -0
  66. package/package.json +44 -37
  67. package/src/ActionSheet.test.tsx +123 -136
  68. package/src/Box.test.tsx +68 -30
  69. package/src/Box.tsx +46 -7
  70. package/src/Common.ts +21 -3
  71. package/src/ConflictSheet.test.tsx +461 -0
  72. package/src/ConflictSheet.tsx +399 -0
  73. package/src/ConsentFormScreen.test.tsx +22 -0
  74. package/src/DateTimeField.test.tsx +14 -0
  75. package/src/DateTimeField.tsx +5 -19
  76. package/src/Hyperlink.tsx +1 -1
  77. package/src/Page.tsx +2 -3
  78. package/src/SidebarNavigation.native.tsx +1 -1
  79. package/src/SidebarNavigation.tsx +1 -1
  80. package/src/SyncStatusBanner.test.tsx +204 -0
  81. package/src/SyncStatusBanner.tsx +148 -0
  82. package/src/TerrenoProvider.test.tsx +3 -4
  83. package/src/Toast.test.tsx +60 -0
  84. package/src/Toast.tsx +46 -1
  85. package/src/ToastNotifications.test.tsx +82 -0
  86. package/src/ToastNotifications.tsx +25 -1
  87. package/src/Unifier.ts +1 -1
  88. package/src/WebDropdownMenu.test.tsx +128 -0
  89. package/src/__snapshots__/AiSuggestionBox.test.tsx.snap +0 -3
  90. package/src/__snapshots__/Body.test.tsx.snap +0 -16
  91. package/src/__snapshots__/Box.test.tsx.snap +4 -13
  92. package/src/__snapshots__/Page.test.tsx.snap +0 -84
  93. package/src/__snapshots__/SplitPage.test.tsx.snap +24 -120
  94. package/src/__snapshots__/TapToEdit.test.tsx.snap +5 -16
  95. package/src/__snapshots__/Toast.test.tsx.snap +4 -2
  96. package/src/bunSetup.ts +19 -0
  97. package/src/conflictFieldDiff.test.ts +26 -0
  98. package/src/conflictFieldDiff.ts +78 -0
  99. package/src/index.tsx +5 -2
  100. package/src/login/__snapshots__/LoginScreen.test.tsx.snap +0 -9
  101. package/src/pdfHtmlTemplate.ts +219 -0
  102. package/src/signUp/__snapshots__/OAuthButtons.test.tsx.snap +0 -1
  103. package/src/signUp/__snapshots__/PasswordRequirements.test.tsx.snap +2 -16
  104. package/src/signUp/__snapshots__/SignUpScreen.test.tsx.snap +1 -17
  105. package/src/signUp/__snapshots__/Swiper.test.tsx.snap +0 -1
  106. package/src/table/__snapshots__/Table.test.tsx.snap +22 -87
  107. package/src/table/__snapshots__/TableHeader.test.tsx.snap +10 -50
  108. package/src/table/__snapshots__/TableHeaderCell.test.tsx.snap +10 -84
  109. package/src/table/__snapshots__/TableRow.test.tsx.snap +12 -77
  110. package/src/useAppLaunchOrForeground.test.tsx +54 -0
  111. package/src/useAppLaunchOrForeground.ts +30 -0
  112. package/dist/ConsentHistory.d.ts +0 -9
  113. package/dist/ConsentHistory.js +0 -70
  114. package/dist/ConsentHistory.js.map +0 -1
  115. package/dist/generateConsentHistoryPdf.d.ts +0 -2
  116. package/dist/generateConsentHistoryPdf.js +0 -185
  117. package/dist/generateConsentHistoryPdf.js.map +0 -1
  118. package/dist/useConsentHistory.d.ts +0 -63
  119. package/dist/useConsentHistory.js +0 -40
  120. package/dist/useConsentHistory.js.map +0 -1
  121. package/src/ConsentHistory.test.tsx +0 -224
  122. package/src/ConsentHistory.tsx +0 -249
  123. package/src/generateConsentHistoryPdf.test.ts +0 -253
  124. package/src/generateConsentHistoryPdf.ts +0 -211
  125. package/src/useConsentHistory.test.ts +0 -106
  126. package/src/useConsentHistory.ts +0 -94
@@ -1,249 +0,0 @@
1
- import {DateTime} from "luxon";
2
- import React, {useCallback, useState} from "react";
3
- import {Image, Pressable} from "react-native";
4
-
5
- import {Badge} from "./Badge";
6
- import {Box} from "./Box";
7
- import {Button} from "./Button";
8
- import {Card} from "./Card";
9
- import {generateConsentHistoryPdf} from "./generateConsentHistoryPdf";
10
- import {Icon} from "./Icon";
11
- import {IconButton} from "./IconButton";
12
- import {MarkdownView} from "./MarkdownView";
13
- import {Page} from "./Page";
14
- import {Spinner} from "./Spinner";
15
- import {Text} from "./Text";
16
- import type {ConsentHistoryEntry} from "./useConsentHistory";
17
- import {useConsentHistory} from "./useConsentHistory";
18
-
19
- interface ConsentHistoryProps {
20
- api: Parameters<typeof useConsentHistory>[0];
21
- baseUrl?: string;
22
- title?: string;
23
- }
24
-
25
- const formatDate = (value: unknown): string => {
26
- if (!value) {
27
- return "";
28
- }
29
- const dt = DateTime.fromISO(String(value));
30
- if (!dt.isValid) {
31
- return String(value);
32
- }
33
- return dt.toLocaleString(DateTime.DATETIME_MED);
34
- };
35
-
36
- const ConsentHistoryItem: React.FC<{entry: ConsentHistoryEntry}> = ({entry}) => {
37
- const [expanded, setExpanded] = useState(false);
38
- const [isDownloading, setIsDownloading] = useState(false);
39
-
40
- const toggle = useCallback(() => {
41
- setExpanded((prev) => !prev);
42
- }, []);
43
-
44
- const handleDownload = useCallback(async () => {
45
- setIsDownloading(true);
46
- try {
47
- await generateConsentHistoryPdf(entry);
48
- } catch (err) {
49
- console.error("Failed to generate PDF", err);
50
- } finally {
51
- setIsDownloading(false);
52
- }
53
- }, [entry]);
54
-
55
- const formTitle = entry.form?.title ?? "Unknown Form";
56
- const formType = entry.form?.type ?? "";
57
-
58
- const checkboxEntries =
59
- entry.checkboxValues && typeof entry.checkboxValues === "object"
60
- ? Object.entries(entry.checkboxValues)
61
- : [];
62
-
63
- return (
64
- <Card padding={0} testID={`consent-history-item-${entry._id}`}>
65
- <Pressable onPress={toggle} testID={`consent-history-item-toggle-${entry._id}`}>
66
- <Box direction="row" gap={3} padding={4}>
67
- <Box flex="grow" gap={1}>
68
- <Box alignItems="center" direction="row" gap={2}>
69
- <Text bold size="md">
70
- {formTitle}
71
- </Text>
72
- {formType ? <Badge status="neutral" value={formType} /> : null}
73
- </Box>
74
- <Box alignItems="center" direction="row" gap={2}>
75
- <Badge
76
- status={entry.agreed ? "success" : "error"}
77
- value={entry.agreed ? "Agreed" : "Declined"}
78
- />
79
- <Text color="secondaryDark" size="sm">
80
- {formatDate(entry.agreedAt)}
81
- </Text>
82
- </Box>
83
- </Box>
84
- <Box alignItems="center" justifyContent="center">
85
- <Icon
86
- color="secondaryDark"
87
- iconName={expanded ? "chevron-up" : "chevron-down"}
88
- size="sm"
89
- />
90
- </Box>
91
- </Box>
92
- </Pressable>
93
-
94
- {expanded && (
95
- <Box gap={3} padding={4} testID={`consent-history-item-details-${entry._id}`}>
96
- <Box alignItems="center" direction="row" justifyContent="between">
97
- <Box color="disabled" flex="grow" height={1} />
98
- <Box marginLeft={2}>
99
- <IconButton
100
- accessibilityLabel="Download PDF"
101
- iconName="download"
102
- loading={isDownloading}
103
- onClick={handleDownload}
104
- testID={`consent-history-download-${entry._id}`}
105
- tooltipText="Download PDF"
106
- />
107
- </Box>
108
- </Box>
109
-
110
- {entry.form?.version !== undefined && (
111
- <Box alignItems="center" direction="row" gap={2}>
112
- <Text color="secondaryDark" size="sm">
113
- Version:
114
- </Text>
115
- <Text size="sm">{entry.form.version}</Text>
116
- </Box>
117
- )}
118
-
119
- {entry.locale && (
120
- <Box alignItems="center" direction="row" gap={2}>
121
- <Text color="secondaryDark" size="sm">
122
- Locale:
123
- </Text>
124
- <Text size="sm">{entry.locale}</Text>
125
- </Box>
126
- )}
127
-
128
- {entry.signedAt && (
129
- <Box alignItems="center" direction="row" gap={2}>
130
- <Text color="secondaryDark" size="sm">
131
- Signed:
132
- </Text>
133
- <Text size="sm">{formatDate(entry.signedAt)}</Text>
134
- </Box>
135
- )}
136
-
137
- {entry.ipAddress && (
138
- <Box alignItems="center" direction="row" gap={2}>
139
- <Text color="secondaryDark" size="sm">
140
- IP Address:
141
- </Text>
142
- <Text size="sm">{entry.ipAddress}</Text>
143
- </Box>
144
- )}
145
-
146
- {checkboxEntries.length > 0 && (
147
- <Box gap={2}>
148
- <Text bold color="secondaryDark" size="sm">
149
- Checkboxes
150
- </Text>
151
- {checkboxEntries.map(([index, checked]) => {
152
- const label = entry.form?.checkboxes?.[Number(index)]?.label;
153
- return (
154
- <Box alignItems="center" direction="row" gap={2} key={index}>
155
- <Badge
156
- status={checked ? "success" : "neutral"}
157
- value={checked ? "Yes" : "No"}
158
- />
159
- <Text size="sm">{label ?? `Checkbox ${index}`}</Text>
160
- </Box>
161
- );
162
- })}
163
- </Box>
164
- )}
165
-
166
- {entry.signature && (
167
- <Box gap={2}>
168
- <Text bold color="secondaryDark" size="sm">
169
- Signature
170
- </Text>
171
- <Box border="default" padding={2} rounding="sm">
172
- <Image
173
- accessibilityLabel="Your signature"
174
- accessible
175
- resizeMode="contain"
176
- source={{uri: entry.signature}}
177
- style={{height: 80, width: "100%"}}
178
- testID={`consent-history-signature-${entry._id}`}
179
- />
180
- </Box>
181
- </Box>
182
- )}
183
-
184
- {entry.contentSnapshot && (
185
- <Box gap={2}>
186
- <Text bold color="secondaryDark" size="sm">
187
- Form Content
188
- </Text>
189
- <Box border="default" padding={3} rounding="sm">
190
- <MarkdownView>{entry.contentSnapshot}</MarkdownView>
191
- </Box>
192
- </Box>
193
- )}
194
- </Box>
195
- )}
196
- </Card>
197
- );
198
- };
199
-
200
- export const ConsentHistory: React.FC<ConsentHistoryProps> = ({
201
- api,
202
- baseUrl,
203
- title = "My Consents",
204
- }) => {
205
- const {entries, isLoading, error, refetch} = useConsentHistory(api, baseUrl);
206
-
207
- if (isLoading) {
208
- return (
209
- <Page maxWidth={800} title={title}>
210
- <Box alignItems="center" justifyContent="center" padding={6}>
211
- <Spinner />
212
- </Box>
213
- </Page>
214
- );
215
- }
216
-
217
- if (error) {
218
- return (
219
- <Page maxWidth={800} title={title}>
220
- <Box alignItems="center" direction="column" gap={3} padding={6}>
221
- <Text color="error" size="lg">
222
- Failed to load consent history
223
- </Text>
224
- <Button onClick={refetch} text="Retry" />
225
- </Box>
226
- </Page>
227
- );
228
- }
229
-
230
- if (entries.length === 0) {
231
- return (
232
- <Page maxWidth={800} title={title}>
233
- <Box alignItems="center" padding={6}>
234
- <Text color="secondaryDark">No consent records found.</Text>
235
- </Box>
236
- </Page>
237
- );
238
- }
239
-
240
- return (
241
- <Page maxWidth={800} scroll title={title}>
242
- <Box gap={3} padding={4} testID="consent-history-list">
243
- {entries.map((entry) => (
244
- <ConsentHistoryItem entry={entry} key={entry._id} />
245
- ))}
246
- </Box>
247
- </Page>
248
- );
249
- };
@@ -1,253 +0,0 @@
1
- import {beforeEach, describe, expect, it, mock} from "bun:test";
2
-
3
- import type {ConsentHistoryEntry} from "./useConsentHistory";
4
-
5
- interface PdfCall {
6
- args: unknown[];
7
- method: string;
8
- }
9
-
10
- interface MockDoc {
11
- calls: PdfCall[];
12
- savedFilename?: string;
13
- }
14
-
15
- let docs: MockDoc[] = [];
16
- let addImageShouldThrow = false;
17
-
18
- class MockJsPdf {
19
- calls: PdfCall[] = [];
20
- savedFilename?: string;
21
-
22
- constructor(..._args: unknown[]) {
23
- docs.push(this as unknown as MockDoc);
24
- }
25
-
26
- private record(method: string, args: unknown[]): void {
27
- this.calls.push({args, method});
28
- }
29
-
30
- setFontSize(...args: unknown[]): void {
31
- this.record("setFontSize", args);
32
- }
33
-
34
- setFont(...args: unknown[]): void {
35
- this.record("setFont", args);
36
- }
37
-
38
- setDrawColor(...args: unknown[]): void {
39
- this.record("setDrawColor", args);
40
- }
41
-
42
- setTextColor(...args: unknown[]): void {
43
- this.record("setTextColor", args);
44
- }
45
-
46
- text(...args: unknown[]): void {
47
- this.record("text", args);
48
- }
49
-
50
- line(...args: unknown[]): void {
51
- this.record("line", args);
52
- }
53
-
54
- addPage(...args: unknown[]): void {
55
- this.record("addPage", args);
56
- }
57
-
58
- addImage(...args: unknown[]): void {
59
- this.record("addImage", args);
60
- if (addImageShouldThrow) {
61
- throw new Error("cannot embed image");
62
- }
63
- }
64
-
65
- splitTextToSize(textValue: string, ..._rest: unknown[]): string[] {
66
- this.record("splitTextToSize", [textValue]);
67
- return String(textValue).split("\n");
68
- }
69
-
70
- save(...args: unknown[]): void {
71
- this.record("save", args);
72
- this.savedFilename = String(args[0]);
73
- }
74
- }
75
-
76
- mock.module("jspdf", () => ({jsPDF: MockJsPdf}));
77
-
78
- const {generateConsentHistoryPdf} = await import("./generateConsentHistoryPdf");
79
-
80
- const lastDoc = (): MockDoc => docs[docs.length - 1]!;
81
-
82
- const textStrings = (doc: MockDoc): string[] =>
83
- doc.calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
84
-
85
- const wasCalled = (doc: MockDoc, method: string): boolean =>
86
- doc.calls.some((c) => c.method === method);
87
-
88
- const baseEntry: ConsentHistoryEntry = {
89
- _id: "response-1",
90
- agreed: true,
91
- agreedAt: "2024-01-15T10:30:00.000Z",
92
- form: {
93
- captureSignature: true,
94
- checkboxes: [
95
- {label: "I agree to the terms", required: true},
96
- {label: "I consent to data use", required: false},
97
- ],
98
- slug: "privacy-policy",
99
- title: "Privacy Policy",
100
- type: "consent",
101
- version: 3,
102
- },
103
- };
104
-
105
- describe("generateConsentHistoryPdf", () => {
106
- beforeEach(() => {
107
- docs = [];
108
- addImageShouldThrow = false;
109
- });
110
-
111
- it("renders a complete consent record with every section", async () => {
112
- const entry: ConsentHistoryEntry = {
113
- ...baseEntry,
114
- checkboxValues: {"0": true, "1": false, "2": true},
115
- contentSnapshot: "First line of the snapshot\nSecond line of the snapshot",
116
- formVersionSnapshot: 3,
117
- ipAddress: "203.0.113.7",
118
- locale: "en-US",
119
- signature: "data:image/png;base64,AAAA",
120
- signedAt: "2024-01-15T10:31:00.000Z",
121
- userAgent: "Mozilla/5.0",
122
- };
123
-
124
- await generateConsentHistoryPdf(entry);
125
-
126
- const doc = lastDoc();
127
- const texts = textStrings(doc);
128
- expect(texts).toContain("Consent Record");
129
- expect(texts).toContain("Privacy Policy");
130
- expect(texts).toContain("Response Details");
131
- expect(texts).toContain("Checkbox Responses");
132
- expect(texts).toContain("Audit Trail");
133
- expect(texts).toContain("Signature");
134
- expect(texts).toContain("Content Snapshot");
135
- // Known checkbox labels render with their check state.
136
- expect(texts).toContain("[x] I agree to the terms");
137
- expect(texts).toContain("[ ] I consent to data use");
138
- // Unknown checkbox index falls back to a generated label.
139
- expect(texts).toContain("[x] Checkbox 2");
140
- // Agreed decision.
141
- expect(texts.some((t) => t === "Agreed")).toBe(true);
142
- // Snapshot lines are split and rendered individually.
143
- expect(texts).toContain("First line of the snapshot");
144
- expect(texts).toContain("Second line of the snapshot");
145
- // Image embedded as PNG.
146
- const image = doc.calls.find((c) => c.method === "addImage");
147
- expect(image?.args[1]).toBe("PNG");
148
- // Footer includes the response id.
149
- expect(texts.some((t) => t.includes("Response ID: response-1"))).toBe(true);
150
- // Saved with a slug-based filename.
151
- expect(doc.savedFilename).toContain("consent-privacy-policy-");
152
- expect(doc.savedFilename?.endsWith(".pdf")).toBe(true);
153
- });
154
-
155
- it("handles a minimal declined entry with no optional sections", async () => {
156
- const entry: ConsentHistoryEntry = {
157
- _id: "",
158
- agreed: false,
159
- agreedAt: "",
160
- form: null,
161
- };
162
-
163
- await generateConsentHistoryPdf(entry);
164
-
165
- const doc = lastDoc();
166
- const texts = textStrings(doc);
167
- expect(texts).toContain("Unknown Form");
168
- expect(texts.some((t) => t === "Declined")).toBe(true);
169
- expect(texts).not.toContain("Checkbox Responses");
170
- expect(texts).not.toContain("Audit Trail");
171
- expect(texts).not.toContain("Signature");
172
- expect(texts).not.toContain("Content Snapshot");
173
- expect(wasCalled(doc, "addImage")).toBe(false);
174
- // No _id means no response-id footer line.
175
- expect(texts.some((t) => t.includes("Response ID:"))).toBe(false);
176
- // Falls back to "response" in the filename when there is no slug.
177
- expect(doc.savedFilename).toContain("consent-response-");
178
- });
179
-
180
- it("embeds a JPEG signature when the data URI is not PNG", async () => {
181
- const entry: ConsentHistoryEntry = {
182
- ...baseEntry,
183
- signature: "data:image/jpeg;base64,BBBB",
184
- };
185
-
186
- await generateConsentHistoryPdf(entry);
187
-
188
- const doc = lastDoc();
189
- const image = doc.calls.find((c) => c.method === "addImage");
190
- expect(image?.args[1]).toBe("JPEG");
191
- });
192
-
193
- it("falls back to a placeholder when the signature image cannot be embedded", async () => {
194
- addImageShouldThrow = true;
195
- const entry: ConsentHistoryEntry = {
196
- ...baseEntry,
197
- signature: "data:image/png;base64,CCCC",
198
- };
199
-
200
- await generateConsentHistoryPdf(entry);
201
-
202
- const doc = lastDoc();
203
- const texts = textStrings(doc);
204
- expect(texts).toContain("(Signature image could not be embedded)");
205
- });
206
-
207
- it("adds pages when content overflows the page height", async () => {
208
- const manyLines = Array.from({length: 200}, (_v, i) => `Line ${i}`).join("\n");
209
- const entry: ConsentHistoryEntry = {
210
- ...baseEntry,
211
- contentSnapshot: manyLines,
212
- };
213
-
214
- await generateConsentHistoryPdf(entry);
215
-
216
- const doc = lastDoc();
217
- expect(wasCalled(doc, "addPage")).toBe(true);
218
- });
219
-
220
- it("uses the audit-trail form version when the form has no version", async () => {
221
- const entry: ConsentHistoryEntry = {
222
- _id: "id-2",
223
- agreed: true,
224
- agreedAt: "2024-01-15T10:30:00.000Z",
225
- form: null,
226
- formVersionSnapshot: 7,
227
- };
228
-
229
- await generateConsentHistoryPdf(entry);
230
-
231
- const doc = lastDoc();
232
- const texts = textStrings(doc);
233
- // formVersion resolves from formVersionSnapshot in Response Details...
234
- expect(texts).toContain("Audit Trail");
235
- // ...and the snapshot version shows up as a value.
236
- expect(texts.some((t) => t === "7")).toBe(true);
237
- });
238
-
239
- it("renders raw invalid dates and skips empty dates via formatDate", async () => {
240
- const entry: ConsentHistoryEntry = {
241
- ...baseEntry,
242
- agreedAt: "not-a-real-date",
243
- signedAt: "",
244
- };
245
-
246
- await generateConsentHistoryPdf(entry);
247
-
248
- const doc = lastDoc();
249
- const texts = textStrings(doc);
250
- // Invalid date string is passed through unchanged.
251
- expect(texts).toContain("not-a-real-date");
252
- });
253
- });
@@ -1,211 +0,0 @@
1
- import {jsPDF} from "jspdf";
2
- import {DateTime} from "luxon";
3
-
4
- import type {ConsentHistoryEntry} from "./useConsentHistory";
5
-
6
- const PAGE_WIDTH = 210;
7
- const MARGIN_LEFT = 20;
8
- const MARGIN_RIGHT = 20;
9
- const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT;
10
- const PAGE_HEIGHT = 297;
11
- const MARGIN_BOTTOM = 20;
12
-
13
- const formatDate = (value: unknown): string => {
14
- if (!value) {
15
- return "";
16
- }
17
- const dt = DateTime.fromISO(String(value));
18
- if (!dt.isValid) {
19
- return String(value);
20
- }
21
- return dt.toLocaleString(DateTime.DATETIME_FULL);
22
- };
23
-
24
- const ensureSpace = (doc: jsPDF, y: number, needed: number): number => {
25
- if (y + needed > PAGE_HEIGHT - MARGIN_BOTTOM) {
26
- doc.addPage();
27
- return 20;
28
- }
29
- return y;
30
- };
31
-
32
- export const generateConsentHistoryPdf = async (entry: ConsentHistoryEntry): Promise<void> => {
33
- const doc = new jsPDF({format: "a4", orientation: "portrait", unit: "mm"});
34
-
35
- const formTitle = entry.form?.title ?? "Unknown Form";
36
- const formSlug = entry.form?.slug ?? "";
37
- const formType = entry.form?.type ?? "";
38
- const formVersion = entry.form?.version ?? entry.formVersionSnapshot;
39
-
40
- let y = 20;
41
-
42
- // Title
43
- doc.setFontSize(18);
44
- doc.setFont("helvetica", "bold");
45
- doc.text("Consent Record", MARGIN_LEFT, y);
46
- y += 10;
47
-
48
- // Form title
49
- doc.setFontSize(14);
50
- doc.setFont("helvetica", "normal");
51
- doc.text(formTitle, MARGIN_LEFT, y);
52
- y += 10;
53
-
54
- // Separator
55
- doc.setDrawColor(200, 200, 200);
56
- doc.line(MARGIN_LEFT, y, PAGE_WIDTH - MARGIN_RIGHT, y);
57
- y += 8;
58
-
59
- // Helper to add a labeled field
60
- const addField = (label: string, value: string) => {
61
- y = ensureSpace(doc, y, 8);
62
- doc.setFontSize(9);
63
- doc.setFont("helvetica", "bold");
64
- doc.setTextColor(100, 100, 100);
65
- doc.text(label, MARGIN_LEFT, y);
66
- doc.setFont("helvetica", "normal");
67
- doc.setTextColor(0, 0, 0);
68
- doc.setFontSize(10);
69
- doc.text(value, MARGIN_LEFT + 45, y);
70
- y += 6;
71
- };
72
-
73
- // Response Details
74
- doc.setFontSize(12);
75
- doc.setFont("helvetica", "bold");
76
- doc.setTextColor(0, 0, 0);
77
- doc.text("Response Details", MARGIN_LEFT, y);
78
- y += 8;
79
-
80
- if (formSlug) {
81
- addField("Form Slug:", formSlug);
82
- }
83
- if (formType) {
84
- addField("Form Type:", formType);
85
- }
86
- if (formVersion !== undefined) {
87
- addField("Form Version:", String(formVersion));
88
- }
89
- addField("Decision:", entry.agreed ? "Agreed" : "Declined");
90
- if (entry.agreedAt) {
91
- addField("Agreed At:", formatDate(entry.agreedAt));
92
- }
93
- if (entry.locale) {
94
- addField("Locale:", entry.locale);
95
- }
96
-
97
- y += 4;
98
-
99
- // Checkbox Values
100
- const checkboxEntries =
101
- entry.checkboxValues && typeof entry.checkboxValues === "object"
102
- ? Object.entries(entry.checkboxValues)
103
- : [];
104
-
105
- if (checkboxEntries.length > 0) {
106
- y = ensureSpace(doc, y, 12 + checkboxEntries.length * 6);
107
- doc.setFontSize(12);
108
- doc.setFont("helvetica", "bold");
109
- doc.setTextColor(0, 0, 0);
110
- doc.text("Checkbox Responses", MARGIN_LEFT, y);
111
- y += 8;
112
-
113
- for (const [index, checked] of checkboxEntries) {
114
- y = ensureSpace(doc, y, 6);
115
- doc.setFontSize(10);
116
- doc.setFont("helvetica", "normal");
117
- const label = entry.form?.checkboxes?.[Number(index)]?.label;
118
- const checkmark = checked ? "[x]" : "[ ]";
119
- doc.text(`${checkmark} ${label ?? `Checkbox ${index}`}`, MARGIN_LEFT + 4, y);
120
- y += 6;
121
- }
122
- y += 4;
123
- }
124
-
125
- // Audit Trail
126
- const hasAuditTrail = entry.ipAddress || entry.userAgent || entry.formVersionSnapshot;
127
-
128
- if (hasAuditTrail) {
129
- y = ensureSpace(doc, y, 20);
130
- doc.setFontSize(12);
131
- doc.setFont("helvetica", "bold");
132
- doc.setTextColor(0, 0, 0);
133
- doc.text("Audit Trail", MARGIN_LEFT, y);
134
- y += 8;
135
-
136
- if (entry.ipAddress) {
137
- addField("IP Address:", entry.ipAddress);
138
- }
139
- if (entry.userAgent) {
140
- addField("User Agent:", entry.userAgent);
141
- }
142
- if (entry.formVersionSnapshot !== undefined) {
143
- addField("Form Version:", String(entry.formVersionSnapshot));
144
- }
145
- if (entry.signedAt) {
146
- addField("Signed At:", formatDate(entry.signedAt));
147
- }
148
- y += 4;
149
- }
150
-
151
- // Signature
152
- if (entry.signature) {
153
- y = ensureSpace(doc, y, 50);
154
- doc.setFontSize(12);
155
- doc.setFont("helvetica", "bold");
156
- doc.setTextColor(0, 0, 0);
157
- doc.text("Signature", MARGIN_LEFT, y);
158
- y += 6;
159
-
160
- try {
161
- const format = entry.signature.includes("image/png") ? "PNG" : "JPEG";
162
- doc.addImage(entry.signature, format, MARGIN_LEFT, y, 80, 30);
163
- y += 34;
164
- } catch {
165
- doc.setFontSize(10);
166
- doc.setFont("helvetica", "italic");
167
- doc.text("(Signature image could not be embedded)", MARGIN_LEFT, y);
168
- y += 6;
169
- }
170
- y += 4;
171
- }
172
-
173
- // Content Snapshot
174
- if (entry.contentSnapshot) {
175
- y = ensureSpace(doc, y, 20);
176
- doc.setFontSize(12);
177
- doc.setFont("helvetica", "bold");
178
- doc.setTextColor(0, 0, 0);
179
- doc.text("Content Snapshot", MARGIN_LEFT, y);
180
- y += 8;
181
-
182
- doc.setFontSize(9);
183
- doc.setFont("helvetica", "normal");
184
- doc.setTextColor(50, 50, 50);
185
-
186
- const lines = doc.splitTextToSize(entry.contentSnapshot, CONTENT_WIDTH);
187
- for (const line of lines) {
188
- y = ensureSpace(doc, y, 5);
189
- doc.text(line, MARGIN_LEFT, y);
190
- y += 4;
191
- }
192
- }
193
-
194
- // Footer
195
- y = ensureSpace(doc, y, 20);
196
- y += 8;
197
- doc.setDrawColor(200, 200, 200);
198
- doc.line(MARGIN_LEFT, y, PAGE_WIDTH - MARGIN_RIGHT, y);
199
- y += 6;
200
- doc.setFontSize(8);
201
- doc.setFont("helvetica", "italic");
202
- doc.setTextColor(150, 150, 150);
203
- doc.text(`Generated ${DateTime.now().toLocaleString(DateTime.DATETIME_FULL)}`, MARGIN_LEFT, y);
204
- if (entry._id) {
205
- doc.text(`Response ID: ${entry._id}`, PAGE_WIDTH - MARGIN_RIGHT, y, {align: "right"});
206
- }
207
-
208
- // Download
209
- const filename = `consent-${formSlug || "response"}-${DateTime.now().toFormat("yyyy-MM-dd")}.pdf`;
210
- doc.save(filename);
211
- };