datakeen-session-react 1.1.202-dev.14 → 1.1.202-dev.16

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 (33) hide show
  1. package/dist/cjs/components/DatakeenSession.js +14 -2
  2. package/dist/cjs/components/session/ContinuedElsewhere.js +9 -5
  3. package/dist/cjs/components/session/ContinuedElsewhereIllustration.js +37 -0
  4. package/dist/cjs/components/session/SessionContent.js +3 -3
  5. package/dist/cjs/hooks/useActiveDevice.js +171 -0
  6. package/dist/cjs/hooks/useRemoteSessionSync.js +32 -12
  7. package/dist/cjs/hooks/useUserInputForm.js +57 -0
  8. package/dist/cjs/i18n/en.json.js +5 -3
  9. package/dist/cjs/i18n/es.json.js +5 -3
  10. package/dist/cjs/i18n/fr.json.js +5 -3
  11. package/dist/cjs/index.css.js +1 -1
  12. package/dist/cjs/services/api.js +4 -1
  13. package/dist/cjs/services/realtime/sessionSyncReducer.js +14 -3
  14. package/dist/cjs/services/sessionCredentials.js +23 -2
  15. package/dist/cjs/services/sessionService.js +35 -0
  16. package/dist/cjs/utils/extractedCopy.js +38 -0
  17. package/dist/esm/components/DatakeenSession.js +14 -2
  18. package/dist/esm/components/session/ContinuedElsewhere.js +10 -6
  19. package/dist/esm/components/session/ContinuedElsewhereIllustration.js +33 -0
  20. package/dist/esm/components/session/SessionContent.js +3 -3
  21. package/dist/esm/hooks/useActiveDevice.js +166 -0
  22. package/dist/esm/hooks/useRemoteSessionSync.js +32 -12
  23. package/dist/esm/hooks/useUserInputForm.js +58 -1
  24. package/dist/esm/i18n/en.json.js +5 -3
  25. package/dist/esm/i18n/es.json.js +5 -3
  26. package/dist/esm/i18n/fr.json.js +5 -3
  27. package/dist/esm/index.css.js +1 -1
  28. package/dist/esm/services/api.js +5 -2
  29. package/dist/esm/services/realtime/sessionSyncReducer.js +14 -4
  30. package/dist/esm/services/sessionCredentials.js +22 -3
  31. package/dist/esm/services/sessionService.js +36 -2
  32. package/dist/esm/utils/extractedCopy.js +36 -0
  33. package/package.json +1 -1
@@ -0,0 +1,166 @@
1
+ import { __awaiter, __generator } from '../node_modules/tslib/tslib.es6.js';
2
+ import { useRef, useState, useCallback, useEffect } from 'react';
3
+ import { getOrderedJourneySteps, claimActiveDevice } from '../services/sessionService.js';
4
+ import { setSessionDeviceId } from '../services/sessionCredentials.js';
5
+ import { STANDBY_NODE_TYPES } from '../services/realtime/sessionSyncReducer.js';
6
+
7
+ /** Nouvel essai de prise de main tant qu'une analyse tourne sur l'autre appareil. */
8
+ var CONTROL_RETRY_MS = 5000;
9
+ /** UUID v4 aléatoire propre à cet onglet (ni PII ni secret). */
10
+ function createDeviceId() {
11
+ var cryptoApi = typeof globalThis !== "undefined" ? globalThis.crypto : undefined;
12
+ if (cryptoApi === null || cryptoApi === void 0 ? void 0 : cryptoApi.randomUUID)
13
+ return cryptoApi.randomUUID();
14
+ var bytes = new Uint8Array(16);
15
+ if (cryptoApi === null || cryptoApi === void 0 ? void 0 : cryptoApi.getRandomValues)
16
+ cryptoApi.getRandomValues(bytes);
17
+ else
18
+ for (var index = 0; index < 16; index += 1)
19
+ bytes[index] = Math.floor(Math.random() * 256);
20
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
21
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
22
+ var hex = Array.from(bytes, function (byte) { return byte.toString(16).padStart(2, "0"); }).join("");
23
+ return "".concat(hex.slice(0, 8), "-").concat(hex.slice(8, 12), "-").concat(hex.slice(12, 16), "-").concat(hex.slice(16, 20), "-").concat(hex.slice(20));
24
+ }
25
+ var DEVICE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
26
+ /**
27
+ * Identifiant conservé pour cet onglet et cette session (sessionStorage) : un rechargement
28
+ * garde la main au lieu de se prendre pour « un autre appareil ». Repli en mémoire.
29
+ */
30
+ function tabDeviceId(sessionId) {
31
+ var key = "datakeen:deviceId:".concat(sessionId);
32
+ try {
33
+ var stored = window.sessionStorage.getItem(key);
34
+ if (stored && DEVICE_ID_PATTERN.test(stored))
35
+ return stored;
36
+ var created = createDeviceId();
37
+ window.sessionStorage.setItem(key, created);
38
+ return created;
39
+ }
40
+ catch (_a) {
41
+ return createDeviceId();
42
+ }
43
+ }
44
+ /**
45
+ * APP3-2030 — un seul appareil à la fois sur un nœud de capture/upload (selfie, signature,
46
+ * contrôle d'identité, collecte de documents).
47
+ *
48
+ * - Affiché en actif ici : on le déclare au serveur (prise de main automatique), sauf si le
49
+ * serveur indique qu'un autre appareil le tient déjà : on passe alors en attente.
50
+ * - Un autre appareil le reprend (`session.device.claimed`) : on passe en attente.
51
+ * - « Continuer sur cet appareil » : prise de main explicite ; si une analyse lancée ailleurs
52
+ * n'est pas revenue, on l'indique et on réessaie jusqu'à sa fin.
53
+ */
54
+ function useActiveDevice(_a) {
55
+ var _this = this;
56
+ var sessionId = _a.sessionId, enabled = _a.enabled, template = _a.template, step = _a.step, standbyStep = _a.standbyStep, setStandbyStep = _a.setStandbyStep;
57
+ var deviceId = useRef(tabDeviceId(sessionId)).current;
58
+ // `undefined` : pas encore connu (snapshot non reçu) — on ne prend pas la main à l'aveugle.
59
+ var _b = useState(undefined), holder = _b[0], setHolder = _b[1];
60
+ var _c = useState(false), resumeBlocked = _c[0], setResumeBlocked = _c[1];
61
+ // Analyse en cours d'après le serveur (diffusée) : l'écran d'attente l'indique sans clic.
62
+ var _d = useState(false), controlInProgress = _d[0], setControlInProgress = _d[1];
63
+ var resumeIntent = useRef(null);
64
+ var claimInFlight = useRef(false);
65
+ var node = template && Number.isInteger(step) && step >= 1 ? getOrderedJourneySteps(template)[step - 1] : undefined;
66
+ var nodeId = node && STANDBY_NODE_TYPES.has(node.type) ? node.id : null;
67
+ var claim = useCallback(function (targetNodeId, targetStep, explicit) { return __awaiter(_this, void 0, void 0, function () {
68
+ var result;
69
+ return __generator(this, function (_a) {
70
+ switch (_a.label) {
71
+ case 0:
72
+ if (claimInFlight.current)
73
+ return [2 /*return*/];
74
+ claimInFlight.current = true;
75
+ _a.label = 1;
76
+ case 1:
77
+ _a.trys.push([1, , 3, 4]);
78
+ return [4 /*yield*/, claimActiveDevice(sessionId, deviceId, targetNodeId, explicit)];
79
+ case 2:
80
+ result = _a.sent();
81
+ if (result === "claimed") {
82
+ setHolder({ deviceId: deviceId, nodeId: targetNodeId });
83
+ if (explicit && resumeIntent.current === targetStep) {
84
+ resumeIntent.current = null;
85
+ setResumeBlocked(false);
86
+ setStandbyStep(null);
87
+ }
88
+ }
89
+ else if (result === "control-in-progress") {
90
+ if (explicit)
91
+ setResumeBlocked(true);
92
+ else
93
+ setStandbyStep(targetStep);
94
+ }
95
+ else if (explicit && resumeIntent.current === targetStep) {
96
+ // Serveur injoignable : on ne bloque pas l'usager, il poursuit ici.
97
+ resumeIntent.current = null;
98
+ setResumeBlocked(false);
99
+ setStandbyStep(null);
100
+ }
101
+ return [3 /*break*/, 4];
102
+ case 3:
103
+ claimInFlight.current = false;
104
+ return [7 /*endfinally*/];
105
+ case 4: return [2 /*return*/];
106
+ }
107
+ });
108
+ }); }, [sessionId, deviceId, setStandbyStep]);
109
+ // L'identifiant part avec les requêtes de la session (X-Device-Id) : lancer une analyse
110
+ // fait de cet appareil l'appareil actif côté serveur.
111
+ useEffect(function () {
112
+ setSessionDeviceId(sessionId, deviceId);
113
+ return function () { return setSessionDeviceId(sessionId); };
114
+ }, [sessionId, deviceId]);
115
+ // Prise de main automatique, ou mise en attente si un autre appareil tient le nœud.
116
+ useEffect(function () {
117
+ if (!enabled || !nodeId || holder === undefined || standbyStep === step)
118
+ return;
119
+ if (holder && holder.deviceId !== deviceId && holder.nodeId === nodeId) {
120
+ setStandbyStep(step);
121
+ return;
122
+ }
123
+ if (!holder || holder.deviceId !== deviceId || holder.nodeId !== nodeId)
124
+ void claim(nodeId, step, false);
125
+ }, [enabled, nodeId, step, holder, standbyStep, deviceId, claim, setStandbyStep]);
126
+ // L'autre appareil a avancé : la demande de reprise ne vaut plus.
127
+ useEffect(function () {
128
+ if (resumeIntent.current !== null && resumeIntent.current !== step) {
129
+ resumeIntent.current = null;
130
+ setResumeBlocked(false);
131
+ }
132
+ }, [step]);
133
+ // Fin d'analyse annoncée (vrai → faux) : la reprise demandée part tout de suite.
134
+ var wasInProgress = useRef(controlInProgress);
135
+ useEffect(function () {
136
+ var ended = wasInProgress.current && !controlInProgress;
137
+ wasInProgress.current = controlInProgress;
138
+ if (ended && resumeBlocked && nodeId && resumeIntent.current === step)
139
+ void claim(nodeId, step, true);
140
+ }, [controlInProgress, resumeBlocked, nodeId, step, claim]);
141
+ // Analyse en cours ailleurs : nouvel essai régulier jusqu'à sa fin (filet si un événement se perd).
142
+ useEffect(function () {
143
+ if (!resumeBlocked || !nodeId)
144
+ return undefined;
145
+ var timer = setInterval(function () {
146
+ if (resumeIntent.current === step)
147
+ void claim(nodeId, step, true);
148
+ }, CONTROL_RETRY_MS);
149
+ return function () { return clearInterval(timer); };
150
+ }, [resumeBlocked, nodeId, step, claim]);
151
+ var resume = useCallback(function () {
152
+ if (controlInProgress && enabled && nodeId)
153
+ return;
154
+ if (!enabled || !nodeId) {
155
+ setStandbyStep(null);
156
+ return;
157
+ }
158
+ resumeIntent.current = step;
159
+ void claim(nodeId, step, true);
160
+ }, [enabled, nodeId, step, claim, setStandbyStep, controlInProgress]);
161
+ // Bouton grisé tant qu'une analyse tourne, que la reprise ait été demandée ou non.
162
+ var waitingForControl = resumeBlocked || (controlInProgress && standbyStep === step);
163
+ return { deviceId: deviceId, resume: resume, waitingForControl: waitingForControl, setHolder: setHolder, setControlInProgress: setControlInProgress };
164
+ }
165
+
166
+ export { CONTROL_RETRY_MS, createDeviceId, tabDeviceId, useActiveDevice };
@@ -21,13 +21,33 @@ function useRemoteSessionSync(options) {
21
21
  var queue = useRef(Promise.resolve());
22
22
  var disposed = useRef(false);
23
23
  var process = useCallback(function (event) { return __awaiter(_this, void 0, void 0, function () {
24
- var current, decision, _a, fresh, error_1, session, error_2;
25
- return __generator(this, function (_b) {
26
- switch (_b.label) {
24
+ var current, _a, activeDeviceId, activeDeviceNodeId, controlInProgress, decision, _b, fresh, error_1, session, error_2;
25
+ var _c, _d, _e, _f;
26
+ return __generator(this, function (_g) {
27
+ switch (_g.label) {
27
28
  case 0:
28
29
  current = optionsRef.current;
29
30
  if (disposed.current || !current.template)
30
31
  return [2 /*return*/];
32
+ // Appareil actif : appliqué hors de `decideRemoteSync`, qui ne gère que la navigation.
33
+ if (event.type === "session.device.claimed") {
34
+ if (lastRevision.current !== null && event.revision <= lastRevision.current)
35
+ return [2 /*return*/];
36
+ lastRevision.current = event.revision;
37
+ (_c = current.onActiveDevice) === null || _c === void 0 ? void 0 : _c.call(current, { deviceId: event.data.deviceId, nodeId: event.data.nodeId });
38
+ return [2 /*return*/];
39
+ }
40
+ if (event.type === "session.control.updated") {
41
+ if (lastRevision.current !== null && event.revision < lastRevision.current)
42
+ return [2 /*return*/];
43
+ (_d = current.onControlInProgress) === null || _d === void 0 ? void 0 : _d.call(current, event.data.inProgress === true);
44
+ return [2 /*return*/];
45
+ }
46
+ if (event.type === "session.snapshot" && (lastRevision.current === null || event.revision > lastRevision.current)) {
47
+ _a = event.data, activeDeviceId = _a.activeDeviceId, activeDeviceNodeId = _a.activeDeviceNodeId, controlInProgress = _a.controlInProgress;
48
+ (_e = current.onActiveDevice) === null || _e === void 0 ? void 0 : _e.call(current, activeDeviceId && activeDeviceNodeId ? { deviceId: activeDeviceId, nodeId: activeDeviceNodeId } : null);
49
+ (_f = current.onControlInProgress) === null || _f === void 0 ? void 0 : _f.call(current, controlInProgress === true);
50
+ }
31
51
  decision = decideRemoteSync({
32
52
  lastRevision: lastRevision.current,
33
53
  step: current.step,
@@ -52,8 +72,8 @@ function useRemoteSessionSync(options) {
52
72
  lastRevision.current = event.revision;
53
73
  if (deferred.current && deferred.current.revision <= event.revision)
54
74
  deferred.current = null;
55
- _a = decision.action;
56
- switch (_a) {
75
+ _b = decision.action;
76
+ switch (_b) {
57
77
  case "navigate": return [3 /*break*/, 1];
58
78
  case "finish": return [3 /*break*/, 5];
59
79
  case "expire": return [3 /*break*/, 10];
@@ -62,17 +82,17 @@ function useRemoteSessionSync(options) {
62
82
  }
63
83
  return [3 /*break*/, 12];
64
84
  case 1:
65
- _b.trys.push([1, 3, , 4]);
85
+ _g.trys.push([1, 3, , 4]);
66
86
  return [4 /*yield*/, fetchSessionById(current.sessionId)];
67
87
  case 2:
68
- fresh = _b.sent();
88
+ fresh = _g.sent();
69
89
  if (disposed.current)
70
90
  return [2 /*return*/];
71
91
  if (fresh)
72
92
  optionsRef.current.onSessionRefreshed(fresh);
73
93
  return [3 /*break*/, 4];
74
94
  case 3:
75
- error_1 = _b.sent();
95
+ error_1 = _g.sent();
76
96
  console.error("Failed to reload the session before a remote navigation:", error_1);
77
97
  return [3 /*break*/, 4];
78
98
  case 4:
@@ -82,17 +102,17 @@ function useRemoteSessionSync(options) {
82
102
  return [3 /*break*/, 13];
83
103
  case 5:
84
104
  current.applyRemoteFinish();
85
- _b.label = 6;
105
+ _g.label = 6;
86
106
  case 6:
87
- _b.trys.push([6, 8, , 9]);
107
+ _g.trys.push([6, 8, , 9]);
88
108
  return [4 /*yield*/, fetchSessionById(current.sessionId)];
89
109
  case 7:
90
- session = _b.sent();
110
+ session = _g.sent();
91
111
  if (session && !disposed.current)
92
112
  optionsRef.current.onFinished(session);
93
113
  return [3 /*break*/, 9];
94
114
  case 8:
95
- error_2 = _b.sent();
115
+ error_2 = _g.sent();
96
116
  console.error("Failed to reload the finished session:", error_2);
97
117
  return [3 /*break*/, 9];
98
118
  case 9: return [3 /*break*/, 13];
@@ -1,4 +1,4 @@
1
- import { __assign, __rest, __awaiter, __generator } from '../node_modules/tslib/tslib.es6.js';
1
+ import { __assign, __spreadArray, __rest, __awaiter, __generator } from '../node_modules/tslib/tslib.es6.js';
2
2
  import { useMemo, useState, useRef, useEffect } from 'react';
3
3
  import { DEFAULT_FIELDS, FALLBACK_ADDRESS_SUGGESTIONS, GEOCODING_AUTOCOMPLETE_ENDPOINT } from '../constants/userInputForm.js';
4
4
  import { API_BASE_URL } from '../config/env.js';
@@ -12,6 +12,7 @@ import { DEFAULT_DATE_DISPLAY_FORMAT } from '../types/session.js';
12
12
  import { useI18n } from './useI18n.js';
13
13
  import { logFormValidated } from '../services/auditTrailService.js';
14
14
  import { fetchSessionById } from '../services/sessionService.js';
15
+ import { extractedRootTarget } from '../utils/extractedCopy.js';
15
16
 
16
17
  var useUserInputForm = function (_a) {
17
18
  var stepObject = _a.stepObject, setUserInput = _a.setUserInput, initialUserInput = _a.initialUserInput, node = _a.node, template = _a.template, contactInfo = _a.contactInfo, setContactInfo = _a.setContactInfo, onContinueCallback = _a.onContinueCallback, sessionId = _a.sessionId;
@@ -322,6 +323,62 @@ var useUserInputForm = function (_a) {
322
323
  cancelled = true;
323
324
  };
324
325
  }, []); // Une seule relecture à l'ouverture du nœud.
326
+ // APP3-2142 — même principe pour la collecte de documents : le serveur pré-remplit à la
327
+ // racine les champs de formulaire standard reportés depuis un document (ex. raison sociale
328
+ // du KBIS). On relit la session à l'ouverture si un de ces champs manque en mémoire, et on
329
+ // ne complète que les clés vides.
330
+ useEffect(function () {
331
+ var _a;
332
+ if (!sessionId || informationType === "custom")
333
+ return;
334
+ var targets = new Set(((_a = template === null || template === void 0 ? void 0 : template.nodes) !== null && _a !== void 0 ? _a : [])
335
+ .filter(function (n) { return n.type === "document-collection"; })
336
+ .flatMap(function (n) { var _a; return ((_a = n.extractedToUserInput) !== null && _a !== void 0 ? _a : []).map(function (rule) { return extractedRootTarget(rule.field); }); })
337
+ .filter(function (target) { return !!target; }));
338
+ var missing = __spreadArray([], targets, true).filter(function (key) { return !(initialUserInput === null || initialUserInput === void 0 ? void 0 : initialUserInput[key]); });
339
+ if (!missing.length)
340
+ return;
341
+ var cancelled = false;
342
+ fetchSessionById(sessionId)
343
+ .then(function (fresh) {
344
+ var _a;
345
+ var server = ((_a = fresh === null || fresh === void 0 ? void 0 : fresh.userInput) !== null && _a !== void 0 ? _a : {});
346
+ var fill = missing.filter(function (key) { return typeof server[key] === "string" && server[key]; });
347
+ if (cancelled || !fill.length)
348
+ return;
349
+ setUserInput(function (prev) {
350
+ var next = __assign({}, prev);
351
+ for (var _i = 0, fill_2 = fill; _i < fill_2.length; _i++) {
352
+ var key = fill_2[_i];
353
+ if (!next[key])
354
+ next[key] = server[key];
355
+ }
356
+ return next;
357
+ });
358
+ setForm(function (prev) {
359
+ var next = __assign({}, prev);
360
+ for (var _i = 0, fill_3 = fill; _i < fill_3.length; _i++) {
361
+ var key = fill_3[_i];
362
+ if (key === "birthDate") {
363
+ if (!prev.birthDate && !prev.day && !prev.month && !prev.year) {
364
+ next.birthDate = server.birthDate;
365
+ Object.assign(next, parseBirthDate(next.birthDate));
366
+ }
367
+ }
368
+ else if (key in prev && !next[key]) {
369
+ next[key] = server[key];
370
+ }
371
+ }
372
+ return next;
373
+ });
374
+ })
375
+ .catch(function (error) {
376
+ console.warn("[UserInputForm] Champs extraits reportés indisponibles", error);
377
+ });
378
+ return function () {
379
+ cancelled = true;
380
+ };
381
+ }, []); // Une seule relecture à l'ouverture du nœud.
325
382
  // Re-synchronise customFormData depuis initialUserInput quand on (ré)affiche un
326
383
  // nœud DIFFÉRENT sur une instance réutilisée (retour arrière sans remount).
327
384
  // Le champ form standard a déjà son propre effet de re-sync ci-dessus ; le
@@ -910,9 +910,11 @@ var session = {
910
910
  description: "This session has been closed and can no longer be continued."
911
911
  },
912
912
  continued_elsewhere: {
913
- title: "Journey continued on another device",
914
- description: "This step is in progress on another device. You can continue it here if you prefer.",
915
- resume: "Continue on this device"
913
+ title: "Step in progress on another device",
914
+ description: "You can continue it here.",
915
+ resume: "Continue on this device",
916
+ control_in_progress: "An analysis is running on the other device. You can continue here once it is done.",
917
+ waiting: "Analysis in progress…"
916
918
  },
917
919
  end: {
918
920
  button_redirecting: "Redirecting...",
@@ -910,9 +910,11 @@ var session = {
910
910
  description: "Esta sesión se ha cerrado y ya no se puede continuar."
911
911
  },
912
912
  continued_elsewhere: {
913
- title: "Recorrido continuado en otro dispositivo",
914
- description: "Este paso está en curso en otro dispositivo. Puede continuarlo aquí si lo prefiere.",
915
- resume: "Continuar en este dispositivo"
913
+ title: "Paso en curso en otro dispositivo",
914
+ description: "Puede continuarlo aquí.",
915
+ resume: "Continuar en este dispositivo",
916
+ control_in_progress: "Hay un análisis en curso en el otro dispositivo. Podrá continuar aquí cuando termine.",
917
+ waiting: "Análisis en curso…"
916
918
  },
917
919
  end: {
918
920
  button_redirecting: "Redirigiendo...",
@@ -910,9 +910,11 @@ var session = {
910
910
  description: "Cette session a été clôturée et ne peut plus être poursuivie."
911
911
  },
912
912
  continued_elsewhere: {
913
- title: "Parcours poursuivi sur un autre appareil",
914
- description: "Cette étape est en cours sur un autre appareil. Vous pouvez la poursuivre ici si vous le souhaitez.",
915
- resume: "Continuer sur cet appareil"
913
+ title: "Étape en cours sur un autre appareil",
914
+ description: "Vous pouvez la reprendre ici.",
915
+ resume: "Continuer sur cet appareil",
916
+ control_in_progress: "Une analyse est en cours sur l'autre appareil. Vous pourrez reprendre ici une fois terminée.",
917
+ waiting: "Analyse en cours…"
916
918
  },
917
919
  end: {
918
920
  button_redirecting: "Redirection...",