@terreno/admin-frontend 0.31.0 → 57.0.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 (52) hide show
  1. package/dist/AdminShell.d.ts +5 -0
  2. package/dist/AdminShell.js +100 -31
  3. package/dist/AdminShell.js.map +1 -1
  4. package/dist/ConsentHistory.d.ts +9 -0
  5. package/dist/ConsentHistory.js +61 -0
  6. package/dist/ConsentHistory.js.map +1 -0
  7. package/dist/generateConsentHistoryPdf.d.ts +2 -0
  8. package/dist/generateConsentHistoryPdf.js +225 -0
  9. package/dist/generateConsentHistoryPdf.js.map +1 -0
  10. package/dist/generateConsentPdf.js +75 -28
  11. package/dist/generateConsentPdf.js.map +1 -1
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.js +3 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/pdfUtils.d.ts +9 -0
  16. package/dist/pdfUtils.js +25 -0
  17. package/dist/pdfUtils.js.map +1 -0
  18. package/dist/useAdminBackgroundTask.js.map +1 -1
  19. package/dist/useConsentHistory.d.ts +63 -0
  20. package/dist/useConsentHistory.js +40 -0
  21. package/dist/useConsentHistory.js.map +1 -0
  22. package/package.json +11 -9
  23. package/src/AdminModelForm.test.tsx +1 -1
  24. package/src/AdminModelList.test.tsx +1 -1
  25. package/src/AdminModelTable.test.tsx +1 -1
  26. package/src/AdminPrimitiveArrayField.test.tsx +1 -1
  27. package/src/AdminScriptList.test.tsx +1 -1
  28. package/src/AdminShell.test.tsx +191 -0
  29. package/src/AdminShell.tsx +331 -144
  30. package/src/AdminVersionConfig.test.tsx +1 -1
  31. package/src/CheckboxListEditor.test.tsx +1 -1
  32. package/src/ConfigurationScreen.test.tsx +1 -1
  33. package/src/ConsentFormEditor.test.tsx +1 -1
  34. package/src/ConsentFormList.test.tsx +1 -1
  35. package/src/ConsentHistory.test.tsx +161 -0
  36. package/src/ConsentHistory.tsx +251 -0
  37. package/src/ConsentResponseViewer.test.tsx +1 -1
  38. package/src/DocumentStorageBrowser.test.tsx +1 -1
  39. package/src/LocaleContentEditor.test.tsx +1 -1
  40. package/src/generateConsentHistoryPdf.ts +259 -0
  41. package/src/generateConsentPdf.ts +96 -31
  42. package/src/index.tsx +3 -0
  43. package/src/isolated/AdminFieldRenderer.isolated.tsx +1 -1
  44. package/src/isolated/AdminNestedArrayField.isolated.tsx +1 -1
  45. package/src/isolated/AdminObjectPicker.isolated.tsx +1 -1
  46. package/src/isolated/AdminScriptRunModal.isolated.tsx +1 -1
  47. package/src/isolated/DocumentStorageBrowser.isolated.tsx +1 -1
  48. package/src/isolated/generateConsentPdf.isolated.ts +5 -0
  49. package/src/pdfUtils.ts +28 -0
  50. package/src/useAdminBackgroundTask.ts +1 -0
  51. package/src/useConsentHistory.test.ts +106 -0
  52. package/src/useConsentHistory.ts +94 -0
@@ -0,0 +1,259 @@
1
+ import {buildConsentPdfHtml, type PdfTemplateData, sharePdfFromHtml} from "@terreno/ui";
2
+ import {DateTime} from "luxon";
3
+ import {Platform} from "react-native";
4
+
5
+ import {
6
+ CONTENT_WIDTH,
7
+ ensureSpace,
8
+ formatDate,
9
+ MARGIN_LEFT,
10
+ MARGIN_RIGHT,
11
+ PAGE_WIDTH,
12
+ } from "./pdfUtils";
13
+ import type {ConsentHistoryEntry} from "./useConsentHistory";
14
+
15
+ const buildTemplateData = (entry: ConsentHistoryEntry): PdfTemplateData => {
16
+ const formTitle = entry.form?.title ?? "Unknown Form";
17
+ const formSlug = entry.form?.slug ?? "";
18
+ const formType = entry.form?.type ?? "";
19
+ const formVersion = entry.form?.version ?? entry.formVersionSnapshot;
20
+
21
+ const fields: PdfTemplateData["fields"] = [];
22
+ if (formSlug) {
23
+ fields.push({label: "Form Slug:", value: formSlug});
24
+ }
25
+ if (formType) {
26
+ fields.push({label: "Form Type:", value: formType});
27
+ }
28
+ if (formVersion !== undefined) {
29
+ fields.push({label: "Form Version:", value: String(formVersion)});
30
+ }
31
+ fields.push({label: "Decision:", value: entry.agreed ? "Agreed" : "Declined"});
32
+ if (entry.agreedAt) {
33
+ fields.push({label: "Agreed At:", value: formatDate(entry.agreedAt)});
34
+ }
35
+ if (entry.locale) {
36
+ fields.push({label: "Locale:", value: entry.locale});
37
+ }
38
+
39
+ const checkboxEntries =
40
+ entry.checkboxValues && typeof entry.checkboxValues === "object"
41
+ ? Object.entries(entry.checkboxValues)
42
+ : [];
43
+
44
+ const checkboxes = checkboxEntries.map(([index, checked]) => ({
45
+ checked: Boolean(checked),
46
+ label: entry.form?.checkboxes?.[Number(index)]?.label ?? `Checkbox ${index}`,
47
+ }));
48
+
49
+ const auditTrail: PdfTemplateData["fields"] = [];
50
+ if (entry.ipAddress) {
51
+ auditTrail.push({label: "IP Address:", value: entry.ipAddress});
52
+ }
53
+ if (entry.userAgent) {
54
+ auditTrail.push({label: "User Agent:", value: entry.userAgent});
55
+ }
56
+ if (entry.formVersionSnapshot !== undefined) {
57
+ auditTrail.push({label: "Form Version:", value: String(entry.formVersionSnapshot)});
58
+ }
59
+ if (entry.signedAt) {
60
+ auditTrail.push({label: "Signed At:", value: formatDate(entry.signedAt)});
61
+ }
62
+
63
+ return {
64
+ auditTrail: auditTrail.length > 0 ? auditTrail : undefined,
65
+ checkboxes: checkboxes.length > 0 ? checkboxes : undefined,
66
+ contentSnapshot: entry.contentSnapshot,
67
+ fields,
68
+ formTitle,
69
+ responseId: entry._id,
70
+ signature: entry.signature,
71
+ title: "Consent Record",
72
+ };
73
+ };
74
+
75
+ const generatePdfWeb = async (entry: ConsentHistoryEntry): Promise<void> => {
76
+ const {jsPDF: JsPDF} = await import("jspdf");
77
+ const doc = new JsPDF({format: "a4", orientation: "portrait", unit: "mm"});
78
+
79
+ const formTitle = entry.form?.title ?? "Unknown Form";
80
+ const formSlug = entry.form?.slug ?? "";
81
+ const formType = entry.form?.type ?? "";
82
+ const formVersion = entry.form?.version ?? entry.formVersionSnapshot;
83
+
84
+ let y = 20;
85
+
86
+ doc.setFontSize(18);
87
+ doc.setFont("helvetica", "bold");
88
+ doc.text("Consent Record", MARGIN_LEFT, y);
89
+ y += 10;
90
+
91
+ doc.setFontSize(14);
92
+ doc.setFont("helvetica", "normal");
93
+ doc.text(formTitle, MARGIN_LEFT, y);
94
+ y += 10;
95
+
96
+ doc.setDrawColor(200, 200, 200);
97
+ doc.line(MARGIN_LEFT, y, PAGE_WIDTH - MARGIN_RIGHT, y);
98
+ y += 8;
99
+
100
+ const addField = (label: string, value: string) => {
101
+ y = ensureSpace(doc, y, 8);
102
+ doc.setFontSize(9);
103
+ doc.setFont("helvetica", "bold");
104
+ doc.setTextColor(100, 100, 100);
105
+ doc.text(label, MARGIN_LEFT, y);
106
+ doc.setFont("helvetica", "normal");
107
+ doc.setTextColor(0, 0, 0);
108
+ doc.setFontSize(10);
109
+ doc.text(value, MARGIN_LEFT + 45, y);
110
+ y += 6;
111
+ };
112
+
113
+ doc.setFontSize(12);
114
+ doc.setFont("helvetica", "bold");
115
+ doc.setTextColor(0, 0, 0);
116
+ doc.text("Response Details", MARGIN_LEFT, y);
117
+ y += 8;
118
+
119
+ if (formSlug) {
120
+ addField("Form Slug:", formSlug);
121
+ }
122
+ if (formType) {
123
+ addField("Form Type:", formType);
124
+ }
125
+ if (formVersion !== undefined) {
126
+ addField("Form Version:", String(formVersion));
127
+ }
128
+ addField("Decision:", entry.agreed ? "Agreed" : "Declined");
129
+ if (entry.agreedAt) {
130
+ addField("Agreed At:", formatDate(entry.agreedAt));
131
+ }
132
+ if (entry.locale) {
133
+ addField("Locale:", entry.locale);
134
+ }
135
+
136
+ y += 4;
137
+
138
+ const checkboxEntries =
139
+ entry.checkboxValues && typeof entry.checkboxValues === "object"
140
+ ? Object.entries(entry.checkboxValues)
141
+ : [];
142
+
143
+ if (checkboxEntries.length > 0) {
144
+ y = ensureSpace(doc, y, 12 + checkboxEntries.length * 6);
145
+ doc.setFontSize(12);
146
+ doc.setFont("helvetica", "bold");
147
+ doc.setTextColor(0, 0, 0);
148
+ doc.text("Checkbox Responses", MARGIN_LEFT, y);
149
+ y += 8;
150
+
151
+ for (const [index, checked] of checkboxEntries) {
152
+ y = ensureSpace(doc, y, 6);
153
+ doc.setFontSize(10);
154
+ doc.setFont("helvetica", "normal");
155
+ const label = entry.form?.checkboxes?.[Number(index)]?.label;
156
+ const checkmark = checked ? "[x]" : "[ ]";
157
+ doc.text(`${checkmark} ${label ?? `Checkbox ${index}`}`, MARGIN_LEFT + 4, y);
158
+ y += 6;
159
+ }
160
+ y += 4;
161
+ }
162
+
163
+ const hasAuditTrail = entry.ipAddress || entry.userAgent || entry.formVersionSnapshot;
164
+
165
+ if (hasAuditTrail) {
166
+ y = ensureSpace(doc, y, 20);
167
+ doc.setFontSize(12);
168
+ doc.setFont("helvetica", "bold");
169
+ doc.setTextColor(0, 0, 0);
170
+ doc.text("Audit Trail", MARGIN_LEFT, y);
171
+ y += 8;
172
+
173
+ if (entry.ipAddress) {
174
+ addField("IP Address:", entry.ipAddress);
175
+ }
176
+ if (entry.userAgent) {
177
+ addField("User Agent:", entry.userAgent);
178
+ }
179
+ if (entry.formVersionSnapshot !== undefined) {
180
+ addField("Form Version:", String(entry.formVersionSnapshot));
181
+ }
182
+ if (entry.signedAt) {
183
+ addField("Signed At:", formatDate(entry.signedAt));
184
+ }
185
+ y += 4;
186
+ }
187
+
188
+ if (entry.signature) {
189
+ y = ensureSpace(doc, y, 50);
190
+ doc.setFontSize(12);
191
+ doc.setFont("helvetica", "bold");
192
+ doc.setTextColor(0, 0, 0);
193
+ doc.text("Signature", MARGIN_LEFT, y);
194
+ y += 6;
195
+
196
+ try {
197
+ const format = entry.signature.includes("image/png") ? "PNG" : "JPEG";
198
+ doc.addImage(entry.signature, format, MARGIN_LEFT, y, 80, 30);
199
+ y += 34;
200
+ } catch {
201
+ doc.setFontSize(10);
202
+ doc.setFont("helvetica", "italic");
203
+ doc.text("(Signature image could not be embedded)", MARGIN_LEFT, y);
204
+ y += 6;
205
+ }
206
+ y += 4;
207
+ }
208
+
209
+ if (entry.contentSnapshot) {
210
+ y = ensureSpace(doc, y, 20);
211
+ doc.setFontSize(12);
212
+ doc.setFont("helvetica", "bold");
213
+ doc.setTextColor(0, 0, 0);
214
+ doc.text("Content Snapshot", MARGIN_LEFT, y);
215
+ y += 8;
216
+
217
+ doc.setFontSize(9);
218
+ doc.setFont("helvetica", "normal");
219
+ doc.setTextColor(50, 50, 50);
220
+
221
+ const lines = doc.splitTextToSize(entry.contentSnapshot, CONTENT_WIDTH);
222
+ for (const line of lines) {
223
+ y = ensureSpace(doc, y, 5);
224
+ doc.text(line, MARGIN_LEFT, y);
225
+ y += 4;
226
+ }
227
+ }
228
+
229
+ y = ensureSpace(doc, y, 20);
230
+ y += 8;
231
+ doc.setDrawColor(200, 200, 200);
232
+ doc.line(MARGIN_LEFT, y, PAGE_WIDTH - MARGIN_RIGHT, y);
233
+ y += 6;
234
+ doc.setFontSize(8);
235
+ doc.setFont("helvetica", "italic");
236
+ doc.setTextColor(150, 150, 150);
237
+ doc.text(`Generated ${DateTime.now().toLocaleString(DateTime.DATETIME_FULL)}`, MARGIN_LEFT, y);
238
+ if (entry._id) {
239
+ doc.text(`Response ID: ${entry._id}`, PAGE_WIDTH - MARGIN_RIGHT, y, {align: "right"});
240
+ }
241
+
242
+ const filename = `consent-${formSlug || "response"}-${DateTime.now().toFormat("yyyy-MM-dd")}.pdf`;
243
+ doc.save(filename);
244
+ };
245
+
246
+ const generatePdfMobile = async (entry: ConsentHistoryEntry): Promise<void> => {
247
+ const templateData = buildTemplateData(entry);
248
+ const html = buildConsentPdfHtml(templateData);
249
+ const formSlug = entry.form?.slug ?? "response";
250
+ const filename = `consent-${formSlug}-${DateTime.now().toFormat("yyyy-MM-dd")}.pdf`;
251
+ await sharePdfFromHtml({filename, html});
252
+ };
253
+
254
+ export const generateConsentHistoryPdf = async (entry: ConsentHistoryEntry): Promise<void> => {
255
+ if (Platform.OS === "web") {
256
+ return generatePdfWeb(entry);
257
+ }
258
+ return generatePdfMobile(entry);
259
+ };
@@ -1,5 +1,15 @@
1
- import {jsPDF} from "jspdf";
1
+ import {buildConsentPdfHtml, type PdfTemplateData, sharePdfFromHtml} from "@terreno/ui";
2
2
  import {DateTime} from "luxon";
3
+ import {Platform} from "react-native";
4
+
5
+ import {
6
+ CONTENT_WIDTH,
7
+ ensureSpace,
8
+ formatDate,
9
+ MARGIN_LEFT,
10
+ MARGIN_RIGHT,
11
+ PAGE_WIDTH,
12
+ } from "./pdfUtils";
3
13
 
4
14
  interface ConsentResponseData {
5
15
  _id?: string;
@@ -17,35 +27,7 @@ interface ConsentResponseData {
17
27
  userId?: {_id?: string; email?: string; id?: string; name?: string} | string;
18
28
  }
19
29
 
20
- const PAGE_WIDTH = 210;
21
- const MARGIN_LEFT = 20;
22
- const MARGIN_RIGHT = 20;
23
- const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT;
24
- const PAGE_HEIGHT = 297;
25
- const MARGIN_BOTTOM = 20;
26
-
27
- const formatDate = (value: unknown): string => {
28
- if (!value) {
29
- return "";
30
- }
31
- const dt = DateTime.fromISO(String(value));
32
- if (!dt.isValid) {
33
- return String(value);
34
- }
35
- return dt.toLocaleString(DateTime.DATETIME_FULL);
36
- };
37
-
38
- const ensureSpace = (doc: jsPDF, y: number, needed: number): number => {
39
- if (y + needed > PAGE_HEIGHT - MARGIN_BOTTOM) {
40
- doc.addPage();
41
- return 20;
42
- }
43
- return y;
44
- };
45
-
46
- export const generateConsentPdf = async (response: ConsentResponseData): Promise<void> => {
47
- const doc = new jsPDF({format: "a4", orientation: "portrait", unit: "mm"});
48
-
30
+ const extractResponseFields = (response: ConsentResponseData) => {
49
31
  const formTitle =
50
32
  typeof response.consentFormId === "object"
51
33
  ? (response.consentFormId?.title ?? "Unknown Form")
@@ -71,6 +53,75 @@ export const generateConsentPdf = async (response: ConsentResponseData): Promise
71
53
 
72
54
  const userName = typeof response.userId === "object" ? (response.userId?.name ?? "") : "";
73
55
 
56
+ return {formSlug, formTitle, formType, formVersion, userEmail, userId, userName};
57
+ };
58
+
59
+ const buildTemplateData = (response: ConsentResponseData): PdfTemplateData => {
60
+ const {formTitle, formSlug, formType, formVersion, userId, userEmail, userName} =
61
+ extractResponseFields(response);
62
+
63
+ const fields: PdfTemplateData["fields"] = [];
64
+ if (formSlug) {
65
+ fields.push({label: "Form Slug:", value: formSlug});
66
+ }
67
+ if (formType) {
68
+ fields.push({label: "Form Type:", value: formType});
69
+ }
70
+ if (formVersion !== undefined) {
71
+ fields.push({label: "Form Version:", value: String(formVersion)});
72
+ }
73
+ fields.push({label: "Decision:", value: response.agreed ? "Agreed" : "Declined"});
74
+ if (response.agreedAt) {
75
+ fields.push({label: "Agreed At:", value: formatDate(response.agreedAt)});
76
+ }
77
+ if (response.locale) {
78
+ fields.push({label: "Locale:", value: response.locale});
79
+ }
80
+
81
+ const checkboxEntries =
82
+ response.checkboxValues && typeof response.checkboxValues === "object"
83
+ ? Object.entries(response.checkboxValues)
84
+ : [];
85
+
86
+ const checkboxes = checkboxEntries.map(([index, checked]) => ({
87
+ checked: Boolean(checked),
88
+ label: `Checkbox ${index}`,
89
+ }));
90
+
91
+ const auditTrail: PdfTemplateData["fields"] = [];
92
+ if (response.ipAddress) {
93
+ auditTrail.push({label: "IP Address:", value: response.ipAddress});
94
+ }
95
+ if (response.userAgent) {
96
+ auditTrail.push({label: "User Agent:", value: response.userAgent});
97
+ }
98
+ if (response.formVersionSnapshot !== undefined) {
99
+ auditTrail.push({label: "Form Version:", value: String(response.formVersionSnapshot)});
100
+ }
101
+ if (response.signedAt) {
102
+ auditTrail.push({label: "Signed At:", value: formatDate(response.signedAt)});
103
+ }
104
+
105
+ return {
106
+ auditTrail: auditTrail.length > 0 ? auditTrail : undefined,
107
+ checkboxes: checkboxes.length > 0 ? checkboxes : undefined,
108
+ contentSnapshot: response.contentSnapshot,
109
+ fields,
110
+ formTitle,
111
+ responseId: response._id,
112
+ signature: response.signature,
113
+ title: "Consent Record",
114
+ userInfo: {email: userEmail || undefined, name: userName || undefined, userId},
115
+ };
116
+ };
117
+
118
+ const generatePdfWeb = async (response: ConsentResponseData): Promise<void> => {
119
+ const {jsPDF: JsPDF} = await import("jspdf");
120
+ const doc = new JsPDF({format: "a4", orientation: "portrait", unit: "mm"});
121
+
122
+ const {formTitle, formSlug, formType, formVersion, userId, userEmail, userName} =
123
+ extractResponseFields(response);
124
+
74
125
  let y = 20;
75
126
 
76
127
  // Title
@@ -209,7 +260,6 @@ export const generateConsentPdf = async (response: ConsentResponseData): Promise
209
260
  y += 6;
210
261
 
211
262
  try {
212
- // signature is a base64 data URI (e.g. data:image/png;base64,...)
213
263
  const sigData = response.signature;
214
264
  const format = sigData.includes("image/png") ? "PNG" : "JPEG";
215
265
  doc.addImage(sigData, format, MARGIN_LEFT, y, 80, 30);
@@ -262,3 +312,18 @@ export const generateConsentPdf = async (response: ConsentResponseData): Promise
262
312
  const filename = `consent-${formSlug || "response"}-${userId.slice(-6)}-${DateTime.now().toFormat("yyyy-MM-dd")}.pdf`;
263
313
  doc.save(filename);
264
314
  };
315
+
316
+ const generatePdfMobile = async (response: ConsentResponseData): Promise<void> => {
317
+ const templateData = buildTemplateData(response);
318
+ const html = buildConsentPdfHtml(templateData);
319
+ const {formSlug, userId} = extractResponseFields(response);
320
+ const filename = `consent-${formSlug || "response"}-${userId.slice(-6)}-${DateTime.now().toFormat("yyyy-MM-dd")}.pdf`;
321
+ await sharePdfFromHtml({filename, html});
322
+ };
323
+
324
+ export const generateConsentPdf = async (response: ConsentResponseData): Promise<void> => {
325
+ if (Platform.OS === "web") {
326
+ return generatePdfWeb(response);
327
+ }
328
+ return generatePdfMobile(response);
329
+ };
package/src/index.tsx CHANGED
@@ -18,8 +18,10 @@ export {CheckboxListEditor} from "./CheckboxListEditor";
18
18
  export {ConfigurationScreen} from "./ConfigurationScreen";
19
19
  export {ConsentFormEditor} from "./ConsentFormEditor";
20
20
  export {ConsentFormList} from "./ConsentFormList";
21
+ export {ConsentHistory} from "./ConsentHistory";
21
22
  export {ConsentResponseViewer} from "./ConsentResponseViewer";
22
23
  export {DocumentStorageBrowser} from "./DocumentStorageBrowser";
24
+ export {generateConsentHistoryPdf} from "./generateConsentHistoryPdf";
23
25
  export {LocaleContentEditor} from "./LocaleContentEditor";
24
26
  export type {
25
27
  AdminConfigResponse,
@@ -40,4 +42,5 @@ export {useAdminApi} from "./useAdminApi";
40
42
  export {useAdminConfig} from "./useAdminConfig";
41
43
  export {useAdminScripts} from "./useAdminScripts";
42
44
  export {useConfigurationApi} from "./useConfigurationApi";
45
+ export * from "./useConsentHistory";
43
46
  export {useDocumentStorageApi} from "./useDocumentStorageApi";
@@ -2,8 +2,8 @@
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {describe, expect, it, mock} from "bun:test";
4
4
  import {renderWithTheme} from "@terreno/ui/src/test-utils";
5
+ import {fireEvent} from "@testing-library/react-native";
5
6
  import React from "react";
6
- import {fireEvent} from "../../../ui/node_modules/@testing-library/react-native";
7
7
 
8
8
  mock.module("../AdminNestedArrayField", () => ({
9
9
  AdminNestedArrayField: ({title}: {title: string}) =>
@@ -2,9 +2,9 @@
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {describe, expect, it, mock} from "bun:test";
4
4
  import {renderWithTheme} from "@terreno/ui/src/test-utils";
5
+ import {fireEvent} from "@testing-library/react-native";
5
6
  import React from "react";
6
7
  import type {ReactTestInstance} from "react-test-renderer";
7
- import {fireEvent} from "../../../ui/node_modules/@testing-library/react-native";
8
8
  import type {AdminApi, AdminFieldConfig} from "../types";
9
9
 
10
10
  mock.module("../AdminFieldRendererCore", () => ({
@@ -2,8 +2,8 @@
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {beforeEach, describe, expect, it, mock} from "bun:test";
4
4
  import {renderWithTheme} from "@terreno/ui/src/test-utils";
5
+ import {act, fireEvent} from "@testing-library/react-native";
5
6
  import React from "react";
6
- import {act, fireEvent} from "../../../ui/node_modules/@testing-library/react-native";
7
7
  import {AdminObjectPicker} from "../AdminObjectPicker";
8
8
  import type {AdminApi} from "../types";
9
9
 
@@ -2,9 +2,9 @@
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {beforeEach, describe, expect, it, mock} from "bun:test";
4
4
  import {renderWithTheme} from "@terreno/ui/src/test-utils";
5
+ import {act, fireEvent} from "@testing-library/react-native";
5
6
  import React from "react";
6
7
  import type {ReactTestInstance} from "react-test-renderer";
7
- import {act, fireEvent} from "../../../ui/node_modules/@testing-library/react-native";
8
8
  import type {AdminApi} from "../types";
9
9
 
10
10
  // Mock @terreno/ui so the Modal renders its children inline. The real Modal
@@ -2,10 +2,10 @@
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {beforeEach, describe, expect, it, mock} from "bun:test";
4
4
  import {renderWithTheme} from "@terreno/ui/src/test-utils";
5
+ import {act, fireEvent} from "@testing-library/react-native";
5
6
  import React from "react";
6
7
  import {Platform} from "react-native";
7
8
  import type {ReactTestInstance} from "react-test-renderer";
8
- import {act, fireEvent} from "../../../ui/node_modules/@testing-library/react-native";
9
9
  import type {AdminApi} from "../types";
10
10
 
11
11
  mock.module("react-native-webview", () => ({
@@ -1,4 +1,5 @@
1
1
  import {beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {Platform} from "react-native";
2
3
 
3
4
  interface JsPDFCall {
4
5
  method: string;
@@ -56,6 +57,10 @@ class MockJsPDF {
56
57
 
57
58
  mock.module("jspdf", () => ({jsPDF: MockJsPDF}));
58
59
 
60
+ // These tests assert against the jsPDF drawing calls, which only the web branch of
61
+ // generateConsentPdf makes; the native branch delegates to expo-print instead.
62
+ Platform.OS = "web";
63
+
59
64
  // Single import of the module-under-test so all tests share coverage counters.
60
65
  import {generateConsentPdf} from "../generateConsentPdf";
61
66
 
@@ -0,0 +1,28 @@
1
+ import type {jsPDF} from "jspdf";
2
+ import {DateTime} from "luxon";
3
+
4
+ export const PAGE_WIDTH = 210;
5
+ export const MARGIN_LEFT = 20;
6
+ export const MARGIN_RIGHT = 20;
7
+ export const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT;
8
+ export const PAGE_HEIGHT = 297;
9
+ export const MARGIN_BOTTOM = 20;
10
+
11
+ export const formatDate = (value: unknown): string => {
12
+ if (!value) {
13
+ return "";
14
+ }
15
+ const dt = DateTime.fromISO(String(value));
16
+ if (!dt.isValid) {
17
+ return String(value);
18
+ }
19
+ return dt.toLocaleString(DateTime.DATETIME_FULL);
20
+ };
21
+
22
+ export const ensureSpace = (doc: jsPDF, y: number, needed: number): number => {
23
+ if (y + needed > PAGE_HEIGHT - MARGIN_BOTTOM) {
24
+ doc.addPage();
25
+ return 20;
26
+ }
27
+ return y;
28
+ };
@@ -17,6 +17,7 @@ export const useAdminBackgroundTaskMutation = (
17
17
  api: AdminApi,
18
18
  adminApiRoot: string
19
19
  ): ReturnType<// noExplicitAny: RTK mutation type from dynamic injectEndpoints
20
+ // noExplicitAny: dynamic hook lookup on RTK Query enhanced API
20
21
  // biome-ignore lint/suspicious/noExplicitAny: dynamic hook lookup on RTK Query enhanced API
21
22
  any> => {
22
23
  const enhancedApi = useMemo(() => {
@@ -0,0 +1,106 @@
1
+ import {describe, expect, it, mock} from "bun:test";
2
+ import {renderHook} from "@testing-library/react-native";
3
+
4
+ import type {ConsentHistoryEntry} from "./useConsentHistory";
5
+ import {useConsentHistory} from "./useConsentHistory";
6
+
7
+ type ConsentHistoryApi = Parameters<typeof useConsentHistory>[0];
8
+
9
+ interface MockQueryDef {
10
+ query: () => string;
11
+ providesTags: string[];
12
+ }
13
+
14
+ interface MockInjectOpts {
15
+ endpoints: (build: {query: (def: MockQueryDef) => string}) => Record<string, unknown>;
16
+ }
17
+
18
+ describe("useConsentHistory", () => {
19
+ const buildApi = (queryResult: {data?: unknown; error?: unknown; isLoading?: boolean}) => {
20
+ const refetch = mock(() => {});
21
+ const useGetMyConsentsQuery = mock(() => ({
22
+ data: queryResult.data,
23
+ error: queryResult.error,
24
+ isLoading: queryResult.isLoading ?? false,
25
+ refetch,
26
+ }));
27
+ const api = {
28
+ enhanceEndpoints: mock((opts: {addTagTypes: string[]}) => {
29
+ expect(opts.addTagTypes).toContain("MyConsents");
30
+ return {
31
+ injectEndpoints: mock((injectOpts: MockInjectOpts) => {
32
+ const build = {
33
+ query: mock((def: MockQueryDef) => {
34
+ // Exercise the URL builder so the closure captures `base`
35
+ const url = def.query();
36
+ expect(url).toContain("/consents/my");
37
+ return "my-consents-query";
38
+ }),
39
+ };
40
+ injectOpts.endpoints(build);
41
+ return {useGetMyConsentsQuery};
42
+ }),
43
+ };
44
+ }),
45
+ };
46
+ return {api, refetch};
47
+ };
48
+
49
+ it("returns an array of entries when response is an array", () => {
50
+ const {api} = buildApi({
51
+ data: [{_id: "1", agreed: true} as unknown as ConsentHistoryEntry],
52
+ });
53
+ const {result} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
54
+ expect(Array.isArray(result.current.entries)).toBe(true);
55
+ expect(result.current.entries).toHaveLength(1);
56
+ });
57
+
58
+ it("unwraps .data property when response is object shape", () => {
59
+ const {api} = buildApi({
60
+ data: {data: [{_id: "2", agreed: false} as unknown as ConsentHistoryEntry]},
61
+ });
62
+ const {result} = renderHook(() =>
63
+ useConsentHistory(api as unknown as ConsentHistoryApi, "/api")
64
+ );
65
+ expect(Array.isArray(result.current.entries)).toBe(true);
66
+ expect(result.current.entries).toHaveLength(1);
67
+ });
68
+
69
+ it("returns empty array when no data is present", () => {
70
+ const {api} = buildApi({data: undefined, isLoading: true});
71
+ const {result} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
72
+ expect(result.current.entries).toEqual([]);
73
+ expect(result.current.isLoading).toBe(true);
74
+ });
75
+
76
+ it("surfaces error from the query hook", () => {
77
+ const {api} = buildApi({data: undefined, error: "boom"});
78
+ const {result} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
79
+ expect(result.current.error).toBe("boom");
80
+ });
81
+
82
+ it("injects the my-consents endpoint only once per (api, baseUrl)", () => {
83
+ let injectCallCount = 0;
84
+ const refetch = mock(() => {});
85
+ const useGetMyConsentsQuery = mock(() => ({
86
+ data: undefined,
87
+ error: undefined,
88
+ isLoading: false,
89
+ refetch,
90
+ }));
91
+ const api = {
92
+ enhanceEndpoints: () => ({
93
+ injectEndpoints: () => {
94
+ injectCallCount += 1;
95
+ return {useGetMyConsentsQuery};
96
+ },
97
+ }),
98
+ };
99
+ const {rerender} = renderHook(() => useConsentHistory(api as unknown as ConsentHistoryApi));
100
+ rerender(undefined);
101
+ rerender(undefined);
102
+ // The hook reuses the cached enhanced api after the first render so the
103
+ // dev-mode RTK warning about re-injecting endpoints never fires.
104
+ expect(injectCallCount).toBe(1);
105
+ });
106
+ });