@transfergratis/react-native-sdk 0.1.24 → 0.1.25

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 (149) hide show
  1. package/android/build/intermediates/aapt_friendly_merged_manifests/debug/processDebugManifest/aapt/AndroidManifest.xml +12 -5
  2. package/android/build/intermediates/aar_main_jar/debug/syncDebugLibJars/classes.jar +0 -0
  3. package/android/build/intermediates/annotations_typedef_file/debug/extractDebugAnnotations/typedefs.txt +0 -0
  4. package/android/build/intermediates/incremental/debug/packageDebugResources/compile-file-map.properties +1 -1
  5. package/android/build/intermediates/incremental/debug-mergeJavaRes/merge-state +0 -0
  6. package/android/build/intermediates/manifest_merge_blame_file/debug/processDebugManifest/manifest-merger-blame-debug-report.txt +61 -59
  7. package/android/build/intermediates/merged_java_res/debug/mergeDebugJavaResource/feature-transfergratis-react-native-sdk.jar +0 -0
  8. package/android/build/intermediates/merged_manifest/debug/processDebugManifest/AndroidManifest.xml +12 -5
  9. package/android/build/kotlin/compileDebugKotlin/cacheable/last-build.bin +0 -0
  10. package/android/build/kotlin/compileDebugKotlin/local-state/build-history.bin +0 -0
  11. package/android/build/outputs/aar/transfergratis-react-native-sdk-debug.aar +0 -0
  12. package/android/build/outputs/logs/manifest-merger-debug-report.txt +26 -34
  13. package/android/src/main/AndroidManifest.xml +10 -7
  14. package/build/components/KYCElements/AdditionalDocumentsTemplate.d.ts +12 -0
  15. package/build/components/KYCElements/AdditionalDocumentsTemplate.d.ts.map +1 -0
  16. package/build/components/KYCElements/AdditionalDocumentsTemplate.js +283 -0
  17. package/build/components/KYCElements/AdditionalDocumentsTemplate.js.map +1 -0
  18. package/build/components/KYCElements/EmailVerificationTemplate.d.ts +12 -0
  19. package/build/components/KYCElements/EmailVerificationTemplate.d.ts.map +1 -0
  20. package/build/components/KYCElements/EmailVerificationTemplate.js +193 -0
  21. package/build/components/KYCElements/EmailVerificationTemplate.js.map +1 -0
  22. package/build/components/KYCElements/IDCardCapture.d.ts.map +1 -1
  23. package/build/components/KYCElements/IDCardCapture.js +180 -7
  24. package/build/components/KYCElements/IDCardCapture.js.map +1 -1
  25. package/build/components/KYCElements/OrientationVideoCapture.d.ts +2 -0
  26. package/build/components/KYCElements/OrientationVideoCapture.d.ts.map +1 -1
  27. package/build/components/KYCElements/OrientationVideoCapture.js +2 -2
  28. package/build/components/KYCElements/OrientationVideoCapture.js.map +1 -1
  29. package/build/components/KYCElements/OrientationVideoCaptureEnhanced.d.ts +2 -0
  30. package/build/components/KYCElements/OrientationVideoCaptureEnhanced.d.ts.map +1 -1
  31. package/build/components/KYCElements/OrientationVideoCaptureEnhanced.js +2 -2
  32. package/build/components/KYCElements/OrientationVideoCaptureEnhanced.js.map +1 -1
  33. package/build/components/KYCElements/OrientationVideoCaptureFinal.d.ts +2 -0
  34. package/build/components/KYCElements/OrientationVideoCaptureFinal.d.ts.map +1 -1
  35. package/build/components/KYCElements/OrientationVideoCaptureFinal.js +2 -2
  36. package/build/components/KYCElements/OrientationVideoCaptureFinal.js.map +1 -1
  37. package/build/components/KYCElements/PersonalInformationTemplate.d.ts +12 -0
  38. package/build/components/KYCElements/PersonalInformationTemplate.d.ts.map +1 -0
  39. package/build/components/KYCElements/PersonalInformationTemplate.js +120 -0
  40. package/build/components/KYCElements/PersonalInformationTemplate.js.map +1 -0
  41. package/build/components/KYCElements/PhoneVerificationTemplate.d.ts +12 -0
  42. package/build/components/KYCElements/PhoneVerificationTemplate.d.ts.map +1 -0
  43. package/build/components/KYCElements/PhoneVerificationTemplate.js +185 -0
  44. package/build/components/KYCElements/PhoneVerificationTemplate.js.map +1 -0
  45. package/build/components/KYCElements/SelfieCaptureTemplate.d.ts.map +1 -1
  46. package/build/components/KYCElements/SelfieCaptureTemplate.js +7 -3
  47. package/build/components/KYCElements/SelfieCaptureTemplate.js.map +1 -1
  48. package/build/components/TemplateKYCExample.d.ts +4 -0
  49. package/build/components/TemplateKYCExample.d.ts.map +1 -1
  50. package/build/components/TemplateKYCExample.js +7 -30
  51. package/build/components/TemplateKYCExample.js.map +1 -1
  52. package/build/components/TemplateKYCFlowRefactored.d.ts +4 -0
  53. package/build/components/TemplateKYCFlowRefactored.d.ts.map +1 -1
  54. package/build/components/TemplateKYCFlowRefactored.js +14 -2
  55. package/build/components/TemplateKYCFlowRefactored.js.map +1 -1
  56. package/build/config/KYCConfig.d.ts +14 -0
  57. package/build/config/KYCConfig.d.ts.map +1 -0
  58. package/build/config/KYCConfig.js +26 -0
  59. package/build/config/KYCConfig.js.map +1 -0
  60. package/build/config/allowedDomains.d.ts.map +1 -1
  61. package/build/config/allowedDomains.js +4 -19
  62. package/build/config/allowedDomains.js.map +1 -1
  63. package/build/hooks/useOrientationVideo.d.ts +2 -1
  64. package/build/hooks/useOrientationVideo.d.ts.map +1 -1
  65. package/build/hooks/useOrientationVideo.js +3 -3
  66. package/build/hooks/useOrientationVideo.js.map +1 -1
  67. package/build/hooks/useTemplateKYCFlow.d.ts +6 -1
  68. package/build/hooks/useTemplateKYCFlow.d.ts.map +1 -1
  69. package/build/hooks/useTemplateKYCFlow.js +286 -23
  70. package/build/hooks/useTemplateKYCFlow.js.map +1 -1
  71. package/build/i18n/en/index.d.ts +40 -0
  72. package/build/i18n/en/index.d.ts.map +1 -1
  73. package/build/i18n/en/index.js +41 -1
  74. package/build/i18n/en/index.js.map +1 -1
  75. package/build/i18n/fr/index.d.ts +26 -0
  76. package/build/i18n/fr/index.d.ts.map +1 -1
  77. package/build/i18n/fr/index.js +27 -1
  78. package/build/i18n/fr/index.js.map +1 -1
  79. package/build/index.d.ts +1 -0
  80. package/build/index.d.ts.map +1 -1
  81. package/build/index.js +2 -0
  82. package/build/index.js.map +1 -1
  83. package/build/modules/api/CardAuthentification.d.ts +24 -3
  84. package/build/modules/api/CardAuthentification.d.ts.map +1 -1
  85. package/build/modules/api/CardAuthentification.js +68 -10
  86. package/build/modules/api/CardAuthentification.js.map +1 -1
  87. package/build/modules/api/KYCService.d.ts +7 -7
  88. package/build/modules/api/KYCService.d.ts.map +1 -1
  89. package/build/modules/api/KYCService.js +101 -37
  90. package/build/modules/api/KYCService.js.map +1 -1
  91. package/build/modules/api/SelfieVerification.d.ts +3 -1
  92. package/build/modules/api/SelfieVerification.d.ts.map +1 -1
  93. package/build/modules/api/SelfieVerification.js +17 -1
  94. package/build/modules/api/SelfieVerification.js.map +1 -1
  95. package/build/modules/api/TemplateService.d.ts +0 -1
  96. package/build/modules/api/TemplateService.d.ts.map +1 -1
  97. package/build/modules/api/TemplateService.js +3 -3
  98. package/build/modules/api/TemplateService.js.map +1 -1
  99. package/build/types/KYC.types.d.ts +124 -3
  100. package/build/types/KYC.types.d.ts.map +1 -1
  101. package/build/types/KYC.types.js.map +1 -1
  102. package/build/types/env.types.d.ts +13 -0
  103. package/build/types/env.types.d.ts.map +1 -0
  104. package/build/types/env.types.js +2 -0
  105. package/build/types/env.types.js.map +1 -0
  106. package/build/utils/deviceDetection.d.ts +6 -0
  107. package/build/utils/deviceDetection.d.ts.map +1 -0
  108. package/build/utils/deviceDetection.js +12 -0
  109. package/build/utils/deviceDetection.js.map +1 -0
  110. package/build/utils/platformAlert.d.ts.map +1 -1
  111. package/build/utils/platformAlert.js.map +1 -1
  112. package/build/utils/template-transformer.d.ts.map +1 -1
  113. package/build/utils/template-transformer.js +12 -0
  114. package/build/utils/template-transformer.js.map +1 -1
  115. package/build/web/WebKYCEntry.d.ts.map +1 -1
  116. package/build/web/WebKYCEntry.js +82 -38
  117. package/build/web/WebKYCEntry.js.map +1 -1
  118. package/package.json +1 -1
  119. package/plugin/build/withVisionCamera.js +3 -4
  120. package/plugin/src/withVisionCamera.js +3 -4
  121. package/plugin/src/withVisionCamera.ts +3 -4
  122. package/src/components/KYCElements/AdditionalDocumentsTemplate.tsx +346 -0
  123. package/src/components/KYCElements/EmailVerificationTemplate.tsx +264 -0
  124. package/src/components/KYCElements/IDCardCapture.tsx +216 -15
  125. package/src/components/KYCElements/OrientationVideoCapture.tsx +4 -1
  126. package/src/components/KYCElements/OrientationVideoCaptureEnhanced.tsx +4 -1
  127. package/src/components/KYCElements/OrientationVideoCaptureFinal.tsx +4 -1
  128. package/src/components/KYCElements/PersonalInformationTemplate.tsx +158 -0
  129. package/src/components/KYCElements/PhoneVerificationTemplate.tsx +253 -0
  130. package/src/components/KYCElements/SelfieCaptureTemplate.tsx +6 -3
  131. package/src/components/TemplateKYCExample.tsx +31 -46
  132. package/src/components/TemplateKYCFlowRefactored.tsx +27 -1
  133. package/src/config/KYCConfig.ts +34 -0
  134. package/src/config/allowedDomains.ts +7 -26
  135. package/src/hooks/useOrientationVideo.ts +5 -4
  136. package/src/hooks/useTemplateKYCFlow.tsx +314 -21
  137. package/src/i18n/en/index.ts +43 -2
  138. package/src/i18n/fr/index.ts +28 -1
  139. package/src/index.ts +3 -0
  140. package/src/modules/api/CardAuthentification.ts +75 -10
  141. package/src/modules/api/KYCService.ts +117 -37
  142. package/src/modules/api/SelfieVerification.ts +25 -3
  143. package/src/modules/api/TemplateService.ts +4 -4
  144. package/src/types/KYC.types.ts +146 -3
  145. package/src/types/env.types.ts +13 -0
  146. package/src/utils/deviceDetection.ts +11 -0
  147. package/src/utils/platformAlert.ts +1 -0
  148. package/src/utils/template-transformer.ts +20 -8
  149. package/src/web/WebKYCEntry.tsx +112 -61
@@ -3,8 +3,8 @@ import kycService, { authentification, truncateFields } from '../modules/api/KYC
3
3
  import useI18n from './useI18n';
4
4
  import { logger } from '../utils/logger';
5
5
  const TemplateKYCFlowContext = createContext(undefined);
6
- export const TemplateKYCFlowProvider = ({ children, template, onComplete, onError, onCancel, initialLanguage = 'en', apiKey, }) => {
7
- const hookResult = useTemplateKYCFlow(template, onComplete, onError, onCancel, initialLanguage, apiKey);
6
+ export const TemplateKYCFlowProvider = ({ children, template, onComplete, onError, onCancel, initialLanguage = 'en', apiKey, env = 'PRODUCTION', existingSessionId, }) => {
7
+ const hookResult = useTemplateKYCFlow(template, onComplete, onError, onCancel, initialLanguage, apiKey, env, existingSessionId);
8
8
  return (<TemplateKYCFlowContext.Provider value={hookResult}>
9
9
  {children}
10
10
  </TemplateKYCFlowContext.Provider>);
@@ -17,7 +17,7 @@ export const useTemplateKYCFlowContext = () => {
17
17
  }
18
18
  return context;
19
19
  };
20
- export const useTemplateKYCFlow = (template, onComplete, onError, onCancel, initialLanguage = 'en', apiKey) => {
20
+ export const useTemplateKYCFlow = (template, onComplete, onError, onCancel, initialLanguage = 'en', apiKey, env = 'PRODUCTION', existingSessionId, initialStep) => {
21
21
  const { setLocale } = useI18n();
22
22
  useEffect(() => {
23
23
  setLocale(initialLanguage);
@@ -71,28 +71,270 @@ export const useTemplateKYCFlow = (template, onComplete, onError, onCancel, init
71
71
  const templateWithReview = useMemo(() => ensureReviewSubmitStep(template), [template, ensureReviewSubmitStep, apiKey]);
72
72
  const templateWithReviewAndVerification = useMemo(() => ensureVerificationProgressStep(templateWithReview), [templateWithReview, ensureVerificationProgressStep, apiKey]);
73
73
  // État initial du flux
74
- const buildInitialState = () => ({
75
- template: templateWithReviewAndVerification,
76
- currentComponentIndex: 0,
77
- completedComponents: [],
78
- componentData: {},
79
- errors: {},
80
- isProcessing: false,
81
- currentLanguage: initialLanguage,
82
- showCustomStepper: true,
83
- session: {
84
- session_id: '',
85
- token: '',
86
- isInitialized: false,
74
+ const buildInitialState = () => {
75
+ // Valider initialStep pour s'assurer qu'il est dans les limites du template
76
+ let validInitialStep = 0;
77
+ let completedComponents = [];
78
+ logger.log('buildInitialState called', { initialStep, existingSessionId });
79
+ if (initialStep !== undefined && initialStep >= 0) {
80
+ const maxIndex = templateWithReviewAndVerification.components.length - 1;
81
+ const requestedStep = Math.min(initialStep, maxIndex);
82
+ const requestedComponent = templateWithReviewAndVerification.components[requestedStep];
83
+ logger.log('Processing initialStep', {
84
+ initialStep,
85
+ requestedStep,
86
+ maxIndex,
87
+ componentType: requestedComponent?.type,
88
+ componentId: requestedComponent?.id
89
+ });
90
+ // Si on reprend à l'étape id_card, on peut rester à id_card si on a une session existante
91
+ // car les données de country_selection peuvent être chargées depuis la session
92
+ if (requestedComponent?.type === 'id_card') {
93
+ // Si on a une session existante, on peut rester à id_card et charger les données
94
+ if (existingSessionId) {
95
+ logger.log('id_card with existing session - staying at id_card');
96
+ validInitialStep = requestedStep;
97
+ // Marquer les composants précédents comme complétés
98
+ if (validInitialStep > 0) {
99
+ completedComponents = templateWithReviewAndVerification.components
100
+ .slice(0, validInitialStep)
101
+ .map(component => component.id);
102
+ }
103
+ }
104
+ else {
105
+ // Si pas de session, revenir à country_selection pour refaire le choix
106
+ const countrySelectionIndex = templateWithReviewAndVerification.components.findIndex(c => c.type === 'country_selection');
107
+ logger.log('id_card without session - going back to country_selection', { countrySelectionIndex });
108
+ if (countrySelectionIndex >= 0) {
109
+ validInitialStep = countrySelectionIndex;
110
+ // Marquer les composants avant country_selection comme complétés
111
+ if (countrySelectionIndex > 0) {
112
+ completedComponents = templateWithReviewAndVerification.components
113
+ .slice(0, countrySelectionIndex)
114
+ .map(component => component.id);
115
+ }
116
+ }
117
+ else {
118
+ // Si pas de country_selection, commencer au début
119
+ validInitialStep = 0;
120
+ }
121
+ }
122
+ }
123
+ else if (requestedComponent?.type === 'review_submit') {
124
+ // Si on reprend au review_submit, on ne marque pas les composants précédents
125
+ // pour permettre à l'utilisateur de revenir en arrière et vérifier/modifier les données
126
+ validInitialStep = requestedStep;
127
+ // Ne pas marquer les composants précédents comme complétés
128
+ completedComponents = [];
129
+ }
130
+ else {
131
+ // Pour les autres composants (selfie, etc.), commencer directement à l'étape demandée
132
+ validInitialStep = requestedStep;
133
+ // Marquer tous les composants précédents comme complétés
134
+ // Cela permet à l'utilisateur de continuer sans refaire les étapes précédentes
135
+ if (validInitialStep > 0) {
136
+ completedComponents = templateWithReviewAndVerification.components
137
+ .slice(0, validInitialStep)
138
+ .map(component => component.id);
139
+ }
140
+ }
141
+ logger.log('Final initial state', {
142
+ validInitialStep,
143
+ completedComponentsCount: completedComponents.length,
144
+ componentAtStep: templateWithReviewAndVerification.components[validInitialStep]?.type
145
+ });
146
+ }
147
+ return {
148
+ template: templateWithReviewAndVerification,
149
+ currentComponentIndex: validInitialStep,
150
+ completedComponents: completedComponents,
151
+ componentData: {},
152
+ errors: {},
87
153
  isProcessing: false,
88
- error: null,
89
- },
90
- verification: {
91
- status: 'idle',
92
- },
93
- });
154
+ currentLanguage: initialLanguage,
155
+ showCustomStepper: true,
156
+ session: {
157
+ session_id: existingSessionId || '',
158
+ token: '',
159
+ isInitialized: false,
160
+ isProcessing: false,
161
+ error: null,
162
+ },
163
+ verification: {
164
+ status: 'idle',
165
+ },
166
+ };
167
+ };
94
168
  // État du flux
95
169
  const [state, setState] = useState(() => buildInitialState());
170
+ // Fonction utilitaire pour convertir base64 en data URI pour l'affichage
171
+ const base64ToDataUri = useCallback((base64, mimeType = 'image/jpeg') => {
172
+ // Si c'est déjà une data URI, retourner tel quel
173
+ if (base64.startsWith('data:')) {
174
+ return base64;
175
+ }
176
+ // Sinon, créer une data URI
177
+ return `data:${mimeType};base64,${base64}`;
178
+ }, []);
179
+ // Charger les données de session si on reprend une session existante
180
+ useEffect(() => {
181
+ const loadSessionData = async () => {
182
+ // Ne charger que si on a une session existante
183
+ if (!existingSessionId) {
184
+ logger.log('No existingSessionId, skipping data load');
185
+ return;
186
+ }
187
+ // Si initialStep n'est pas défini ou est 0, on ne charge pas (début de session)
188
+ if (initialStep === undefined || initialStep === 0) {
189
+ logger.log('initialStep is 0 or undefined, skipping data load');
190
+ return;
191
+ }
192
+ // Attendre que la session soit initialisée
193
+ if (!state.session.isInitialized || !state.session.session_id) {
194
+ logger.log('Session not initialized yet, waiting...', {
195
+ isInitialized: state.session.isInitialized,
196
+ sessionId: state.session.session_id
197
+ });
198
+ return;
199
+ }
200
+ try {
201
+ logger.log('Loading session data for resume:', { sessionId: existingSessionId, step: initialStep });
202
+ const result = await kycService.getVerificationResult(state.session.session_id);
203
+ const sessionData = result[state.session.session_id]?.data;
204
+ if (sessionData) {
205
+ // Restaurer les données des composants depuis la session
206
+ // Utiliser 'as any' car VerificationResult peut avoir des propriétés dynamiques
207
+ const data = sessionData;
208
+ const restoredComponentData = {};
209
+ // Parcourir les composants jusqu'à l'étape initiale (incluse) pour restaurer leurs données
210
+ // Utiliser initialStep + 1 pour inclure le composant à l'étape initialStep
211
+ templateWithReviewAndVerification.components
212
+ .slice(0, initialStep + 1)
213
+ .forEach((component) => {
214
+ // Essayer de restaurer les données selon le type de composant
215
+ if (component.type === 'id_card' || component.type === 'file_upload') {
216
+ // Les documents peuvent être dans différentes structures
217
+ let documents = null;
218
+ // Chercher dans différentes structures possibles
219
+ if (data.documents) {
220
+ documents = data.documents;
221
+ }
222
+ else if (data.user_data?.documents) {
223
+ documents = data.user_data.documents;
224
+ }
225
+ else if (data.document_images) {
226
+ documents = data.document_images;
227
+ }
228
+ if (documents) {
229
+ // Convertir les images base64 en format utilisable
230
+ const restoredDocuments = {};
231
+ Object.keys(documents).forEach((key) => {
232
+ const doc = documents[key];
233
+ if (typeof doc === 'object' && doc !== null) {
234
+ // Si on a un fichier base64, créer une structure avec dir et file
235
+ if (doc.file || doc.base64) {
236
+ const base64Data = doc.file || doc.base64;
237
+ restoredDocuments[key] = {
238
+ dir: base64ToDataUri(base64Data), // Utiliser data URI pour l'affichage
239
+ file: base64Data, // Garder le base64 pour l'envoi
240
+ mrz: doc.mrz || '',
241
+ templatePath: doc.templatePath || '',
242
+ };
243
+ }
244
+ else {
245
+ // Sinon, garder la structure originale
246
+ restoredDocuments[key] = doc;
247
+ }
248
+ }
249
+ else if (typeof doc === 'string') {
250
+ // Si c'est directement une string base64
251
+ restoredDocuments[key] = {
252
+ dir: base64ToDataUri(doc),
253
+ file: doc,
254
+ mrz: '',
255
+ templatePath: '',
256
+ };
257
+ }
258
+ });
259
+ if (Object.keys(restoredDocuments).length > 0) {
260
+ restoredComponentData[component.id] = restoredDocuments;
261
+ }
262
+ }
263
+ }
264
+ else if (component.type === 'selfie') {
265
+ // Les selfies peuvent être dans sessionData.selfie_info
266
+ if (data.selfie_info) {
267
+ const selfieData = {};
268
+ const selfieInfo = data.selfie_info;
269
+ // Si selfie_info contient une image
270
+ if (selfieInfo.image) {
271
+ const base64Image = selfieInfo.image;
272
+ selfieData['front'] = {
273
+ dir: base64ToDataUri(base64Image),
274
+ file: base64Image,
275
+ };
276
+ }
277
+ // Si on a plusieurs orientations
278
+ if (selfieInfo.orientations) {
279
+ Object.keys(selfieInfo.orientations).forEach((orientation) => {
280
+ const img = selfieInfo.orientations[orientation];
281
+ if (img) {
282
+ selfieData[orientation] = {
283
+ dir: base64ToDataUri(img),
284
+ file: img,
285
+ };
286
+ }
287
+ });
288
+ }
289
+ if (Object.keys(selfieData).length > 0) {
290
+ restoredComponentData[component.id] = selfieData;
291
+ }
292
+ }
293
+ }
294
+ else if (component.type === 'country_selection') {
295
+ // Les données de sélection de pays peuvent être dans metadata
296
+ if (data.metadata || data.user_data) {
297
+ restoredComponentData[component.id] = {
298
+ ...(data.metadata || {}),
299
+ ...(data.user_data || {}),
300
+ };
301
+ }
302
+ }
303
+ else if (component.type === 'location') {
304
+ // Les données de localisation peuvent être dans metadata
305
+ if (data.metadata?.location || data.user_data?.location) {
306
+ restoredComponentData[component.id] = {
307
+ ...(data.metadata?.location || {}),
308
+ ...(data.user_data?.location || {}),
309
+ };
310
+ }
311
+ }
312
+ });
313
+ // Mettre à jour l'état avec les données restaurées
314
+ if (Object.keys(restoredComponentData).length > 0) {
315
+ logger.log('Session data restored - components:', Object.keys(restoredComponentData));
316
+ logger.log('Session data restored - sample data:', truncateFields(restoredComponentData));
317
+ setState(prev => ({
318
+ ...prev,
319
+ componentData: {
320
+ ...prev.componentData,
321
+ ...restoredComponentData,
322
+ },
323
+ }));
324
+ logger.log('Component data updated in state');
325
+ }
326
+ else {
327
+ logger.log('No component data to restore from session');
328
+ }
329
+ }
330
+ }
331
+ catch (error) {
332
+ logger.error('Error loading session data:', truncateFields(error));
333
+ // Ne pas bloquer le flux si le chargement échoue
334
+ }
335
+ };
336
+ loadSessionData();
337
+ }, [existingSessionId, initialStep, state.session.isInitialized, state.session.session_id, templateWithReviewAndVerification.components, base64ToDataUri]);
96
338
  const mapComponentTypeToAction = useCallback((type) => {
97
339
  switch (type) {
98
340
  case 'id_card':
@@ -223,7 +465,17 @@ export const useTemplateKYCFlow = (template, onComplete, onError, onCancel, init
223
465
  logger.log('Initializing session');
224
466
  const token = apiKey ? undefined : await authentification();
225
467
  console.log('token in initializeSession', { token, apiKey });
226
- const session = await kycService.newSession({ token, apiKey });
468
+ // Check if we already have a session ID from URL params (passed via state or prop)
469
+ let session;
470
+ const existingSessionId = state.session.session_id; // This might be set from initial props if we add logic for it
471
+ if (existingSessionId && existingSessionId.length > 0) {
472
+ logger.log('Resuming existing session:', existingSessionId);
473
+ // Verify existence/validity if needed, for now trust the ID and just fetch/use it
474
+ session = { session_id: existingSessionId };
475
+ }
476
+ else {
477
+ session = await kycService.newSession({ token, apiKey });
478
+ }
227
479
  // Align backend flow from step 0 with initialize_session
228
480
  try {
229
481
  const templateId = chooseTemplateId(templateWithReviewAndVerification);
@@ -294,6 +546,16 @@ export const useTemplateKYCFlow = (template, onComplete, onError, onCancel, init
294
546
  case 'welcome':
295
547
  // Welcome is valid once user has given consent (componentData is set when they click Get Started)
296
548
  return componentData && componentData.consentGiven !== false;
549
+ case 'email_verification':
550
+ return componentData && componentData.verified === true;
551
+ case 'phone_verification':
552
+ return componentData && componentData.verified === true;
553
+ case 'personal_information':
554
+ return componentData && Object.keys(componentData).length > 0;
555
+ case 'additional_documents':
556
+ // Optional by default in template config, but if required we should check based on config
557
+ // For now, return true or check length if present
558
+ return true;
297
559
  case 'review_submit':
298
560
  return true;
299
561
  default:
@@ -551,6 +813,7 @@ export const useTemplateKYCFlow = (template, onComplete, onError, onCancel, init
551
813
  isComplete,
552
814
  getLocalizedText,
553
815
  initializeSession,
816
+ env,
554
817
  };
555
818
  };
556
819
  //# sourceMappingURL=useTemplateKYCFlow.js.map
@@ -1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AW,CAAC,CAAC,IAAa,EAAE,EAAE;YAC/C,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAChB,GAAG,IAAI;gBACP,iBAAiB,EAAE,IAAI;aACxB,CAAC,CAAC,CAAC;QACN,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;QAEZ,oBAAoB,EAAE,WAAW,CAAC,CAAC,iBAAiB,EAAE,EAAE;YACtD,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAChB,GAAG,IAAI;gBACP,YAAY,EAAE,iBAAiB;aAChC,CAAC,CAAC,CAAC;QACN,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;KACb,CAAC;IAEF,OAAO;QACL,KAAK;QACL,OAAO;QACP,gBAAgB;QAChB,QAAQ;QACR,SAAS;QACT,aAAa;QACb,UAAU;QACV,gBAAgB;QAChB,iBAAiB;KAClB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useState, useCallback, useMemo, createContext, useContext, ReactNode, useEffect } from 'react';\nimport { KYCTemplate, TemplateState, TemplateActions, UseTemplateReturn, TemplateComponent, GovernmentDocumentType, VerificationState } from '../types/KYC.types';\nimport kycService, { authentification, truncateFields } from '../modules/api/KYCService';\nimport useI18n from './useI18n';\nimport { logger } from '../utils/logger';\n\n// Context pour le provider\ninterface TemplateKYCFlowContextType {\n state: TemplateState;\n actions: TemplateActions;\n currentComponent: any;\n progress: number;\n canGoNext: boolean;\n canGoPrevious: boolean;\n isComplete: boolean;\n getLocalizedText: (text: { en: string; fr: string;[key: string]: string }) => string;\n initializeSession: () => Promise<void>;\n}\n\nconst TemplateKYCFlowContext = createContext<TemplateKYCFlowContextType | undefined>(undefined);\n\n// Provider component\ninterface TemplateKYCFlowProviderProps {\n children: ReactNode;\n template: KYCTemplate;\n onComplete?: (data: VerificationState) => void;\n onError?: (error: string) => void;\n onCancel?: () => void;\n initialLanguage?: string;\n apiKey?: string;\n}\n\nexport const TemplateKYCFlowProvider: React.FC<TemplateKYCFlowProviderProps> = ({\n children,\n template,\n onComplete,\n onError,\n onCancel,\n initialLanguage = 'en',\n apiKey,\n}) => {\n const hookResult = useTemplateKYCFlow(template, onComplete, onError, onCancel, initialLanguage, apiKey);\n\n return (\n <TemplateKYCFlowContext.Provider value={hookResult}>\n {children}\n </TemplateKYCFlowContext.Provider>\n );\n};\n\n// Hook pour utiliser le context\nexport const useTemplateKYCFlowContext = (): TemplateKYCFlowContextType => {\n const context = useContext(TemplateKYCFlowContext);\n if (!context) {\n throw new Error('useTemplateKYCFlowContext must be used within a TemplateKYCFlowProvider');\n }\n return context;\n};\n\nexport const useTemplateKYCFlow = (\n template: KYCTemplate,\n onComplete?: (data: VerificationState) => void,\n onError?: (error: string) => void,\n onCancel?: () => void,\n initialLanguage: string = 'en',\n apiKey?: string,\n): UseTemplateReturn => {\n\n const { setLocale } = useI18n();\n\n useEffect(() => {\n setLocale(initialLanguage);\n }, [initialLanguage, apiKey]);\n\n // Helpers to align SDK steps with backend actions/templates\n const isUiOnlyStep = useCallback((type: TemplateComponent['type']) => {\n return type === 'verification_progress';\n }, [apiKey]);\n\n\n\n const ensureReviewSubmitStep = useCallback((tpl: KYCTemplate): KYCTemplate => {\n const hasReview = tpl.components.some(c => c.type === 'review_submit');\n if (hasReview) return tpl;\n\n const lastOrder = tpl.components.reduce((acc, c) => Math.max(acc, c.order ?? 0), 0);\n const lastId = tpl.components.reduce((acc, c) => Math.max(acc, c.id), 0);\n\n const reviewComponent: TemplateComponent = {\n id: lastId + 1,\n type: 'review_submit',\n order: lastOrder + 1,\n labels: { en: 'Review & Submit', fr: 'Revoir & Soumettre' },\n instructions: { en: 'Confirm and submit', fr: 'Confirmer et soumettre' },\n ui: { buttonText: { en: 'Complete Verification', fr: 'Terminer la vérification' } },\n // @ts-ignore - config unused for review component\n config: {},\n } as TemplateComponent;\n\n return {\n ...tpl,\n components: [...tpl.components, reviewComponent],\n };\n }, [apiKey]);\n\n const ensureVerificationProgressStep = useCallback((tpl: KYCTemplate): KYCTemplate => {\n const hasVerification = tpl.components.some(c => c.type === 'verification_progress');\n if (hasVerification) return tpl;\n\n const lastOrder = tpl.components.reduce((acc, c) => Math.max(acc, c.order ?? 0), 0);\n const lastId = tpl.components.reduce((acc, c) => Math.max(acc, c.id), 0);\n\n const verificationComponent: TemplateComponent = {\n id: lastId + 2,\n type: 'verification_progress',\n order: lastOrder + 2,\n labels: { en: 'Verification', fr: 'Vérification' },\n instructions: { en: 'We\\'re reviewing your documents', fr: 'Nous analysons vos documents' },\n ui: { buttonText: { en: '', fr: '' } },\n // @ts-ignore - config unused for progress component\n config: {},\n } as TemplateComponent;\n\n return {\n ...tpl,\n components: [...tpl.components, verificationComponent],\n };\n }, [apiKey]);\n\n const templateWithReview = useMemo(() => ensureReviewSubmitStep(template), [template, ensureReviewSubmitStep, apiKey]);\n const templateWithReviewAndVerification = useMemo(() => ensureVerificationProgressStep(templateWithReview), [templateWithReview, ensureVerificationProgressStep, apiKey]);\n\n // État initial du flux\n const buildInitialState = (): TemplateState => ({\n template: templateWithReviewAndVerification,\n currentComponentIndex: 0,\n completedComponents: [],\n componentData: {},\n errors: {},\n isProcessing: false,\n currentLanguage: initialLanguage,\n showCustomStepper: true,\n session: {\n session_id: '',\n token: '',\n isInitialized: false,\n isProcessing: false,\n error: null,\n },\n verification: {\n status: 'idle',\n },\n });\n\n // État du flux\n const [state, setState] = useState<TemplateState>(() => buildInitialState());\n const mapComponentTypeToAction = useCallback((type: TemplateComponent['type']): string | null => {\n switch (type) {\n case 'id_card':\n case 'file_upload':\n return 'document_upload';\n case 'selfie':\n return 'selfie_capture';\n case 'location':\n return 'location_permission';\n case 'review_submit':\n return 'final_submit';\n case 'country_selection':\n // No direct backend action; pack into metadata of next actionable step\n return null;\n case 'welcome':\n // UI-only step, no backend action needed\n return null;\n case 'initialization':\n return 'initialize_session';\n case 'verification_progress':\n return null; // UI-only\n default:\n return null;\n }\n }, []);\n\n const chooseTemplateId = useCallback((tpl: KYCTemplate): string => {\n const types = tpl.components.map(c => c.type);\n const hasLocation = types.includes('location');\n const hasSelfie = types.includes('selfie');\n const hasIdDoc = types.includes('id_card') || types.includes('file_upload');\n // Simple heuristic to map to backend examples\n if (hasLocation && hasSelfie && hasIdDoc) return 'enhanced_id';\n if (hasSelfie && hasIdDoc) return 'standard_passport';\n return 'standard_passport';\n }, [apiKey]);\n\n\n const computeServerStepIndex = useCallback((tpl: KYCTemplate, upToIndex: number): number => {\n // Count actionable steps before the current component (exclude UI-only and country_selection)\n const actionable = tpl.components\n .slice(0, upToIndex)\n .filter(c => !isUiOnlyStep(c.type) && mapComponentTypeToAction(c.type) !== null);\n return actionable.length; // 0-based\n }, [isUiOnlyStep, mapComponentTypeToAction, apiKey]);\n\n // Build backend-friendly payloads per action\n const buildPayloadForComponent = useCallback((action: string | null, component: TemplateComponent, rawData: any, templateId: string, step: number) => {\n console.log('apiKey in buildPayloadForComponent', apiKey);\n\n const base = { template_id: templateId || null, templateId: templateId || null, step: component.order, permissionGranted: true } as any;\n if (!action) {\n return base;\n }\n // Document upload expects an array of documents with base64 and metadata\n if (action === 'document_upload') {\n const documents: Record<string, any> = {};\n if (rawData && typeof rawData === 'object') {\n Object.keys(rawData).forEach((key) => {\n documents[key] = rawData[key];\n });\n }\n return {\n ...base,\n documents,\n };\n }\n\n if (action === 'selfie_capture') {\n const documents: Record<string, any> = {};\n if (rawData && typeof rawData === 'object') {\n\n Object.keys(rawData).forEach((key) => {\n documents[key] = rawData[key];\n });\n }\n const idCardID = Object.keys(state.componentData).find((c: string) => c === \"1\");\n if (idCardID) {\n const _idCardData = state.componentData[idCardID];\n const documentType = _idCardData?.documentType;\n // Map national_id to identity_card for selfie capture\n const mappedDocumentType = documentType === 'national_id' ? 'identity_card' : (documentType as GovernmentDocumentType || 'identity_card');\n return { ...base, documents, country: _idCardData?.country || '', documentType: mappedDocumentType };\n }\n return { ...base, documents };\n }\n\n if (action === 'location_permission') {\n return { ...base, ...({ metadata: rawData || {} }), ...({ permissionGranted: true, }) };\n }\n\n // Default: wrap as metadata\n return { ...base, metadata: { ...(rawData || {}) } };\n }, [state.componentData, apiKey]);\n // Ensure the template contains a final review step\n\n // console.log('apiKey in useTemplateKYCFlow', apiKey);\n\n\n // Composant actuel\n const currentComponent = useMemo(() => {\n return state.template.components[state.currentComponentIndex] || null;\n }, [state.template.components, state.currentComponentIndex, apiKey]);\n\n // Progression du flux\n const progress = useMemo(() => {\n return state.template.components.length > 0\n ? ((state.currentComponentIndex + 1) / state.template.components.length) * 100\n : 0;\n }, [state.currentComponentIndex, state.template.components.length, apiKey]);\n\n // Vérifications de navigation\n const canGoNext = useMemo(() => {\n return state.currentComponentIndex < state.template.components.length - 1;\n }, [state.currentComponentIndex, state.template.components.length, apiKey]);\n\n const canGoPrevious = useMemo(() => {\n return state.currentComponentIndex > 0;\n }, [state.currentComponentIndex, apiKey]);\n\n const isComplete = useMemo(() => {\n const atReview = state.template.components[state.currentComponentIndex]?.type === 'review_submit';\n const nonReviewCount = state.template.components.filter(c => c.type !== 'review_submit').length;\n const completedNonReview = state.completedComponents.length >= nonReviewCount;\n return atReview && completedNonReview;\n }, [state.currentComponentIndex, state.completedComponents.length, state.template.components, apiKey]);\n\n // Fonction pour obtenir le texte localisé\n const getLocalizedText = useCallback((text: { en: string; fr: string;[key: string]: string }): string => {\n return text[state.currentLanguage] || text.en || '';\n }, [state.currentLanguage, apiKey]);\n\n const initializeSession = useCallback(async () => {\n try {\n setState(prev => ({\n ...prev,\n session: {\n ...prev.session,\n isInitialized: false,\n isProcessing: true,\n error: null,\n },\n }));\n logger.log('Initializing session');\n\n const token = apiKey ? undefined : await authentification();\n console.log('token in initializeSession', { token, apiKey },);\n const session = await kycService.newSession({token,apiKey});\n\n // Align backend flow from step 0 with initialize_session\n try {\n const templateId = chooseTemplateId(templateWithReviewAndVerification);\n await kycService.verificationSession({\n session_id: session.session_id,\n step: 0,\n data: { template_id: templateId, metadata: { language: initialLanguage } },\n templateId: templateId,\n token: token,\n action: 'initialize_session',\n apiKey: apiKey,\n });\n } catch (e) {\n logger.error('Error initializing session:', JSON.stringify(e, null, 2));\n // Non-fatal: we will surface errors via state below if needed\n }\n\n setState(prev => ({\n ...prev,\n session: {\n ...prev.session,\n session_id: session.session_id,\n token: token,\n isInitialized: true,\n isProcessing: false,\n error: null,\n }\n }));\n } catch (error) {\n\n logger.error('Error initializing session:', JSON.stringify(error, null, 2));\n setState(prev => ({\n ...prev,\n session: {\n ...prev.session,\n isInitialized: false,\n isProcessing: false,\n error: \"Erreur lors de l'initialisation de la session\",\n },\n }));\n }\n }, [apiKey]);\n // Validation d'un composant\n const validateComponent = useCallback((componentId: number): boolean => {\n const component = state.template.components.find(c => c.id === componentId);\n if (!component) return false;\n\n const componentData = state.componentData[componentId];\n\n switch (component.type) {\n case 'id_card':\n // Vérifier si au moins un côté a été capturé\n return componentData && Object.keys(componentData).length > 0;\n\n case 'selfie':\n // Vérifier si toutes les orientations ont été capturées\n const config = component.config as any;\n const orientations = config.orientations || ['front'];\n return componentData && orientations.every((orientation: string) => componentData[orientation]);\n\n case 'file_upload':\n // Vérifier si un fichier a été uploadé\n return componentData && componentData.file;\n\n case 'location':\n // Vérifier si la localisation a été obtenue\n return componentData && componentData.latitude && componentData.longitude;\n\n case 'country_selection':\n // Vérifier si un pays a été sélectionné\n logger.log(\"componentData\", truncateFields(componentData), componentId);\n\n return componentData && componentData.code && componentData.regionMapping;\n\n case 'welcome':\n // Welcome is valid once user has given consent (componentData is set when they click Get Started)\n return componentData && componentData.consentGiven !== false;\n\n case 'review_submit':\n return true;\n default:\n return false;\n }\n }, [state.template.components, state.componentData, apiKey]);\n\n // Actions du flux\n const actions: TemplateActions = {\n // Initialiser le template\n initializeTemplate: useCallback((newTemplate: KYCTemplate) => {\n const withReview = ensureReviewSubmitStep(newTemplate);\n const withVerification = ensureVerificationProgressStep(withReview);\n setState(prev => ({\n ...prev,\n template: withVerification,\n currentComponentIndex: 0,\n completedComponents: [],\n componentData: {},\n errors: {},\n isProcessing: false,\n verification: { status: 'idle', result: undefined },\n }));\n }, [ensureReviewSubmitStep, ensureVerificationProgressStep, apiKey]),\n\n // Passer au composant suivant\n nextComponent: useCallback(async () => {\n if (!canGoNext) return;\n\n const currentComp = state.template.components[state.currentComponentIndex];\n if (!currentComp) return;\n\n // Prevent multiple simultaneous calls\n setState(prev => {\n if (prev.isProcessing) {\n return prev;\n }\n return {\n ...prev,\n isProcessing: true,\n };\n });\n // Valider le composant actuel\n if (!validateComponent(currentComp.id)) {\n setState(prev => ({\n ...prev,\n isProcessing: false,\n errors: {\n ...prev.errors,\n [currentComp.id]: state.currentLanguage === \"en\" ? \"please complete this step before move on\" : \" 'Veuillez compléter cette étape avant de continuer'\"\n }\n }));\n return;\n\n }\n\n try {\n const component = state.template.components.find(c => c.id === currentComp.id);\n if (!component) {\n setState(prev => ({\n ...prev,\n isProcessing: false,\n }));\n return;\n }\n if (component.type === 'review_submit') {\n // Move to verification screen and mark verification in progress\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex + 1,\n completedComponents: [...prev.completedComponents, currentComp.id],\n isProcessing: false,\n verification: { status: 'in_progress' },\n errors: {\n ...prev.errors,\n [currentComp.id]: ''\n }\n }));\n return;\n }\n // Determine backend action and step index\n const action = mapComponentTypeToAction(component.type);\n const templateId = chooseTemplateId(state.template);\n const serverStep = computeServerStepIndex(state.template, state.currentComponentIndex);\n\n // Optionally send initialize_session at step 0 before first actionable action\n if (serverStep === 0) {\n try {\n // await kycService.verificationSession({\n // sessionId: state.session.session_id,\n // step: 0,\n // data: { template_id: templateId, metadata: { language: state.currentLanguage } },\n // templateId: templateId,\n // token: state.session.token,\n // action: 'initialize_session'\n // });\n } catch (e) {\n // if init fails, surface error below in the main call handling\n }\n }\n\n // Skip UI-only and data-only steps that have no backend action\n if (!action) {\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex + 1,\n completedComponents: [...prev.completedComponents, currentComp.id],\n isProcessing: false,\n errors: {\n ...prev.errors,\n [currentComp.id]: ''\n }\n }));\n return;\n }\n\n const step = serverStep === 0 && action !== 'initialize_session' ? 1 : serverStep;\n // Build payload data per action\n const payloadData = buildPayloadForComponent(action, component, state.componentData[currentComp.id], templateId, step);\n console.log('payloadData', action, apiKey);\n\n await kycService.verificationSession({\n session_id: state.session.session_id,\n step: step,\n data: payloadData,\n templateId: templateId,\n token: state.session.token,\n action: action,\n apiKey: apiKey ?? \"-\",\n });\n logger.log(\"currentComp state\", truncateFields(state));\n // Marquer comme complété et passer au suivant\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex + 1,\n completedComponents: [...prev.completedComponents, currentComp.id],\n isProcessing: false,\n ...(action === \"location_permission\" ? { permissionGranted: true } : {}),\n errors: {\n ...prev.errors,\n [currentComp.id]: ''\n }\n }));\n\n } catch (error) {\n logger.error('Error in nextComponent:', error);\n setState(prev => ({\n ...prev,\n isProcessing: false,\n errors: {\n ...prev.errors,\n [currentComp.id]: 'Erreur lors de la validation du composant'\n }\n }));\n }\n\n }, [canGoNext, state.currentComponentIndex, state.template.components, validateComponent, apiKey, state.session.session_id, state.session.token, buildPayloadForComponent, mapComponentTypeToAction, chooseTemplateId, state.currentLanguage]),\n\n // Retourner au composant précédent\n previousComponent: useCallback(() => {\n if (!canGoPrevious) return;\n\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex - 1,\n }));\n }, [canGoPrevious, apiKey]),\n\n // Aller à un composant spécifique\n goToComponent: useCallback((componentId: number) => {\n const componentIndex = state.template.components.findIndex(c => c.id === componentId);\n if (componentIndex !== -1) {\n setState(prev => ({\n ...prev,\n currentComponentIndex: componentIndex,\n }));\n }\n }, [state.template.components, apiKey]),\n\n // Mettre à jour les données d'un composant\n updateComponentData: useCallback((componentId: number, data: any) => {\n logger.log(\"updateComponentData\", componentId, JSON.stringify(truncateFields(data), null, 2));\n\n setState(prev => ({\n ...prev,\n componentData: {\n ...prev.componentData,\n [componentId]: data\n },\n errors: {\n ...prev.errors,\n [componentId]: ''\n }\n }));\n\n }, [apiKey]),\n\n // Valider un composant\n validateComponent: useCallback((componentId: number) => {\n return validateComponent(componentId);\n }, [validateComponent, apiKey]),\n // complet verification\n submitVerification: useCallback(async () => {\n setState(prev => ({ ...prev, isProcessing: true }));\n try {\n onComplete?.(state.verification);\n\n } catch (error) {\n setState(prev => ({ ...prev, isProcessing: false }));\n }\n }, [state.session.session_id, state.verification, onComplete, apiKey]),\n\n // Soumettre le template complet\n submitTemplate: useCallback(async () => {\n // Allow submission when on the review step and all previous steps are valid\n const atReview = state.template.components[state.currentComponentIndex]?.type === 'review_submit';\n const allValid = state.template.components\n .filter(c => c.type !== 'review_submit')\n .every(comp => validateComponent(comp.id));\n if (!(atReview && allValid)) {\n onError?.('Le flux KYC n\\'est pas encore terminé');\n return;\n }\n\n setState(prev => ({ ...prev, isProcessing: true }));\n\n try {\n // Vérifier que tous les composants (hors review) sont validés\n if (!allValid) throw new Error('Certaines étapes ne sont pas complètes');\n\n // Appeler le callback de completion\n // onComplete?.(state.componentData);\n\n setState(prev => ({ ...prev, isProcessing: false }));\n } catch (error) {\n setState(prev => ({ ...prev, isProcessing: false }));\n onError?.(error instanceof Error ? error.message : 'Erreur lors de la soumission');\n }\n }, [state.template.components, state.verification, state.currentComponentIndex, validateComponent, state.componentData, onComplete, onError, apiKey]),\n\n // Réinitialiser le template\n resetTemplate: useCallback(() => {\n setState(buildInitialState());\n }, [buildInitialState, apiKey]),\n\n // Changer la langue\n setLanguage: useCallback((language: string) => {\n setState(prev => ({\n ...prev,\n currentLanguage: language,\n }));\n }, [apiKey]),\n\n // Afficher le stepper personnalisé\n showCustomStepper: useCallback((show: boolean) => {\n setState(prev => ({\n ...prev,\n showCustomStepper: show,\n }));\n }, [apiKey]),\n\n setVerificationState: useCallback((verificationState) => {\n setState(prev => ({\n ...prev,\n verification: verificationState,\n }));\n }, [apiKey]),\n };\n\n return {\n state,\n actions,\n currentComponent,\n progress,\n canGoNext,\n canGoPrevious,\n isComplete,\n getLocalizedText,\n initializeSession,\n };\n}; "]}
1
+ {"version":3,"file":"useTemplateKYCFlow.js","sourceRoot":"","sources":["../../src/hooks/useTemplateKYCFlow.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,EAAE,UAAU,EAAa,SAAS,EAAE,MAAM,OAAO,CAAC;AAG/G,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,OAAO,MAAM,WAAW,CAAC;AAChC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAgBzC,MAAM,sBAAsB,GAAG,aAAa,CAAyC,SAAS,CAAC,CAAC;AAgBhG,MAAM,CAAC,MAAM,uBAAuB,GAA2C,CAAC,EAC9E,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,OAAO,EACP,QAAQ,EACR,eAAe,GAAG,IAAI,EACtB,MAAM,EACN,GAAG,GAAG,YAAY,EAClB,iBAAiB,GAClB,EAAE,EAAE;IACH,MAAM,UAAU,GAAG,kBAAkB,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,EAAE,GAAG,EAAE,iBAAiB,CAAC,CAAC;IAEhI,OAAO,CACL,CAAC,sBAAsB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC,CACjD;MAAA,CAAC,QAAQ,CACX;IAAA,EAAE,sBAAsB,CAAC,QAAQ,CAAC,CACnC,CAAC;AACJ,CAAC,CAAC;AAEF,gCAAgC;AAChC,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAA+B,EAAE;IACxE,MAAM,OAAO,GAAG,UAAU,CAAC,sBAAsB,CAAC,CAAC;IACnD,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;IAC7F,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AAoB,EAAE,WAAW,CAAC,CAAC,iBAAiB,EAAE,EAAE;YACtD,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAChB,GAAG,IAAI;gBACP,YAAY,EAAE,iBAAiB;aAChC,CAAC,CAAC,CAAC;QACN,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;KACb,CAAC;IAEF,OAAO;QACL,KAAK;QACL,OAAO;QACP,gBAAgB;QAChB,QAAQ;QACR,SAAS;QACT,aAAa;QACb,UAAU;QACV,gBAAgB;QAChB,iBAAiB;QACjB,GAAG;KACJ,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import React, { useState, useCallback, useMemo, createContext, useContext, ReactNode, useEffect } from 'react';\nimport { KYCTemplate, TemplateState, TemplateActions, UseTemplateReturn, TemplateComponent, GovernmentDocumentType, VerificationState } from '../types/KYC.types';\nimport { KycEnvironment } from '../types/env.types';\nimport kycService, { authentification, truncateFields } from '../modules/api/KYCService';\nimport useI18n from './useI18n';\nimport { logger } from '../utils/logger';\n\n// Context pour le provider\ninterface TemplateKYCFlowContextType {\n state: TemplateState;\n actions: TemplateActions;\n currentComponent: any;\n progress: number;\n canGoNext: boolean;\n canGoPrevious: boolean;\n isComplete: boolean;\n getLocalizedText: (text: { en: string; fr: string;[key: string]: string }) => string;\n initializeSession: () => Promise<void>;\n env: KycEnvironment;\n}\n\nconst TemplateKYCFlowContext = createContext<TemplateKYCFlowContextType | undefined>(undefined);\n\n// Provider component\ninterface TemplateKYCFlowProviderProps {\n children: ReactNode;\n template: KYCTemplate;\n onComplete?: (data: VerificationState) => void;\n onError?: (error: string) => void;\n onCancel?: () => void;\n initialLanguage?: string;\n apiKey?: string;\n env?: KycEnvironment;\n existingSessionId?: string;\n initialStep?: number;\n}\n\nexport const TemplateKYCFlowProvider: React.FC<TemplateKYCFlowProviderProps> = ({\n children,\n template,\n onComplete,\n onError,\n onCancel,\n initialLanguage = 'en',\n apiKey,\n env = 'PRODUCTION',\n existingSessionId,\n}) => {\n const hookResult = useTemplateKYCFlow(template, onComplete, onError, onCancel, initialLanguage, apiKey, env, existingSessionId);\n\n return (\n <TemplateKYCFlowContext.Provider value={hookResult}>\n {children}\n </TemplateKYCFlowContext.Provider>\n );\n};\n\n// Hook pour utiliser le context\nexport const useTemplateKYCFlowContext = (): TemplateKYCFlowContextType => {\n const context = useContext(TemplateKYCFlowContext);\n if (!context) {\n throw new Error('useTemplateKYCFlowContext must be used within a TemplateKYCFlowProvider');\n }\n return context;\n};\n\nexport const useTemplateKYCFlow = (\n template: KYCTemplate,\n onComplete?: (data: VerificationState) => void,\n onError?: (error: string) => void,\n onCancel?: () => void,\n initialLanguage: string = 'en',\n apiKey?: string,\n env: KycEnvironment = 'PRODUCTION',\n existingSessionId?: string,\n initialStep?: number,\n): UseTemplateReturn => {\n\n const { setLocale } = useI18n();\n\n useEffect(() => {\n setLocale(initialLanguage);\n }, [initialLanguage, apiKey]);\n\n // Helpers to align SDK steps with backend actions/templates\n const isUiOnlyStep = useCallback((type: TemplateComponent['type']) => {\n return type === 'verification_progress';\n }, [apiKey]);\n\n\n\n const ensureReviewSubmitStep = useCallback((tpl: KYCTemplate): KYCTemplate => {\n const hasReview = tpl.components.some(c => c.type === 'review_submit');\n if (hasReview) return tpl;\n\n const lastOrder = tpl.components.reduce((acc, c) => Math.max(acc, c.order ?? 0), 0);\n const lastId = tpl.components.reduce((acc, c) => Math.max(acc, c.id), 0);\n\n const reviewComponent: TemplateComponent = {\n id: lastId + 1,\n type: 'review_submit',\n order: lastOrder + 1,\n labels: { en: 'Review & Submit', fr: 'Revoir & Soumettre' },\n instructions: { en: 'Confirm and submit', fr: 'Confirmer et soumettre' },\n ui: { buttonText: { en: 'Complete Verification', fr: 'Terminer la vérification' } },\n // @ts-ignore - config unused for review component\n config: {},\n } as TemplateComponent;\n\n return {\n ...tpl,\n components: [...tpl.components, reviewComponent],\n };\n }, [apiKey]);\n\n const ensureVerificationProgressStep = useCallback((tpl: KYCTemplate): KYCTemplate => {\n const hasVerification = tpl.components.some(c => c.type === 'verification_progress');\n if (hasVerification) return tpl;\n\n const lastOrder = tpl.components.reduce((acc, c) => Math.max(acc, c.order ?? 0), 0);\n const lastId = tpl.components.reduce((acc, c) => Math.max(acc, c.id), 0);\n\n const verificationComponent: TemplateComponent = {\n id: lastId + 2,\n type: 'verification_progress',\n order: lastOrder + 2,\n labels: { en: 'Verification', fr: 'Vérification' },\n instructions: { en: 'We\\'re reviewing your documents', fr: 'Nous analysons vos documents' },\n ui: { buttonText: { en: '', fr: '' } },\n // @ts-ignore - config unused for progress component\n config: {},\n } as TemplateComponent;\n\n return {\n ...tpl,\n components: [...tpl.components, verificationComponent],\n };\n }, [apiKey]);\n\n const templateWithReview = useMemo(() => ensureReviewSubmitStep(template), [template, ensureReviewSubmitStep, apiKey]);\n const templateWithReviewAndVerification = useMemo(() => ensureVerificationProgressStep(templateWithReview), [templateWithReview, ensureVerificationProgressStep, apiKey]);\n\n // État initial du flux\n const buildInitialState = (): TemplateState => {\n // Valider initialStep pour s'assurer qu'il est dans les limites du template\n let validInitialStep = 0;\n let completedComponents: number[] = [];\n \n logger.log('buildInitialState called', { initialStep, existingSessionId });\n \n if (initialStep !== undefined && initialStep >= 0) {\n const maxIndex = templateWithReviewAndVerification.components.length - 1;\n const requestedStep = Math.min(initialStep, maxIndex);\n const requestedComponent = templateWithReviewAndVerification.components[requestedStep];\n \n logger.log('Processing initialStep', {\n initialStep,\n requestedStep,\n maxIndex,\n componentType: requestedComponent?.type,\n componentId: requestedComponent?.id\n });\n \n // Si on reprend à l'étape id_card, on peut rester à id_card si on a une session existante\n // car les données de country_selection peuvent être chargées depuis la session\n if (requestedComponent?.type === 'id_card') {\n // Si on a une session existante, on peut rester à id_card et charger les données\n if (existingSessionId) {\n logger.log('id_card with existing session - staying at id_card');\n validInitialStep = requestedStep;\n // Marquer les composants précédents comme complétés\n if (validInitialStep > 0) {\n completedComponents = templateWithReviewAndVerification.components\n .slice(0, validInitialStep)\n .map(component => component.id);\n }\n } else {\n // Si pas de session, revenir à country_selection pour refaire le choix\n const countrySelectionIndex = templateWithReviewAndVerification.components.findIndex(\n c => c.type === 'country_selection'\n );\n \n logger.log('id_card without session - going back to country_selection', { countrySelectionIndex });\n \n if (countrySelectionIndex >= 0) {\n validInitialStep = countrySelectionIndex;\n // Marquer les composants avant country_selection comme complétés\n if (countrySelectionIndex > 0) {\n completedComponents = templateWithReviewAndVerification.components\n .slice(0, countrySelectionIndex)\n .map(component => component.id);\n }\n } else {\n // Si pas de country_selection, commencer au début\n validInitialStep = 0;\n }\n }\n } else if (requestedComponent?.type === 'review_submit') {\n // Si on reprend au review_submit, on ne marque pas les composants précédents\n // pour permettre à l'utilisateur de revenir en arrière et vérifier/modifier les données\n validInitialStep = requestedStep;\n // Ne pas marquer les composants précédents comme complétés\n completedComponents = [];\n } else {\n // Pour les autres composants (selfie, etc.), commencer directement à l'étape demandée\n validInitialStep = requestedStep;\n \n // Marquer tous les composants précédents comme complétés\n // Cela permet à l'utilisateur de continuer sans refaire les étapes précédentes\n if (validInitialStep > 0) {\n completedComponents = templateWithReviewAndVerification.components\n .slice(0, validInitialStep)\n .map(component => component.id);\n }\n }\n \n logger.log('Final initial state', {\n validInitialStep,\n completedComponentsCount: completedComponents.length,\n componentAtStep: templateWithReviewAndVerification.components[validInitialStep]?.type\n });\n }\n \n return {\n template: templateWithReviewAndVerification,\n currentComponentIndex: validInitialStep,\n completedComponents: completedComponents,\n componentData: {},\n errors: {},\n isProcessing: false,\n currentLanguage: initialLanguage,\n showCustomStepper: true,\n session: {\n session_id: existingSessionId || '',\n token: '',\n isInitialized: false,\n isProcessing: false,\n error: null,\n },\n verification: {\n status: 'idle',\n },\n };\n };\n\n // État du flux\n const [state, setState] = useState<TemplateState>(() => buildInitialState());\n \n // Fonction utilitaire pour convertir base64 en data URI pour l'affichage\n const base64ToDataUri = useCallback((base64: string, mimeType: string = 'image/jpeg'): string => {\n // Si c'est déjà une data URI, retourner tel quel\n if (base64.startsWith('data:')) {\n return base64;\n }\n // Sinon, créer une data URI\n return `data:${mimeType};base64,${base64}`;\n }, []);\n\n // Charger les données de session si on reprend une session existante\n useEffect(() => {\n const loadSessionData = async () => {\n // Ne charger que si on a une session existante\n if (!existingSessionId) {\n logger.log('No existingSessionId, skipping data load');\n return;\n }\n\n // Si initialStep n'est pas défini ou est 0, on ne charge pas (début de session)\n if (initialStep === undefined || initialStep === 0) {\n logger.log('initialStep is 0 or undefined, skipping data load');\n return;\n }\n\n // Attendre que la session soit initialisée\n if (!state.session.isInitialized || !state.session.session_id) {\n logger.log('Session not initialized yet, waiting...', {\n isInitialized: state.session.isInitialized,\n sessionId: state.session.session_id\n });\n return;\n }\n\n try {\n logger.log('Loading session data for resume:', { sessionId: existingSessionId, step: initialStep });\n const result = await kycService.getVerificationResult(state.session.session_id);\n const sessionData = result[state.session.session_id]?.data;\n\n if (sessionData) {\n // Restaurer les données des composants depuis la session\n // Utiliser 'as any' car VerificationResult peut avoir des propriétés dynamiques\n const data: any = sessionData;\n const restoredComponentData: Record<number, any> = {};\n\n // Parcourir les composants jusqu'à l'étape initiale (incluse) pour restaurer leurs données\n // Utiliser initialStep + 1 pour inclure le composant à l'étape initialStep\n templateWithReviewAndVerification.components\n .slice(0, initialStep + 1)\n .forEach((component) => {\n // Essayer de restaurer les données selon le type de composant\n if (component.type === 'id_card' || component.type === 'file_upload') {\n // Les documents peuvent être dans différentes structures\n let documents: any = null;\n \n // Chercher dans différentes structures possibles\n if (data.documents) {\n documents = data.documents;\n } else if (data.user_data?.documents) {\n documents = data.user_data.documents;\n } else if (data.document_images) {\n documents = data.document_images;\n }\n\n if (documents) {\n // Convertir les images base64 en format utilisable\n const restoredDocuments: Record<string, any> = {};\n \n Object.keys(documents).forEach((key) => {\n const doc = documents[key];\n if (typeof doc === 'object' && doc !== null) {\n // Si on a un fichier base64, créer une structure avec dir et file\n if (doc.file || doc.base64) {\n const base64Data = doc.file || doc.base64;\n restoredDocuments[key] = {\n dir: base64ToDataUri(base64Data), // Utiliser data URI pour l'affichage\n file: base64Data, // Garder le base64 pour l'envoi\n mrz: doc.mrz || '',\n templatePath: doc.templatePath || '',\n };\n } else {\n // Sinon, garder la structure originale\n restoredDocuments[key] = doc;\n }\n } else if (typeof doc === 'string') {\n // Si c'est directement une string base64\n restoredDocuments[key] = {\n dir: base64ToDataUri(doc),\n file: doc,\n mrz: '',\n templatePath: '',\n };\n }\n });\n\n if (Object.keys(restoredDocuments).length > 0) {\n restoredComponentData[component.id] = restoredDocuments;\n }\n }\n } else if (component.type === 'selfie') {\n // Les selfies peuvent être dans sessionData.selfie_info\n if (data.selfie_info) {\n const selfieData: Record<string, any> = {};\n const selfieInfo: any = data.selfie_info;\n \n // Si selfie_info contient une image\n if (selfieInfo.image) {\n const base64Image = selfieInfo.image;\n selfieData['front'] = {\n dir: base64ToDataUri(base64Image),\n file: base64Image,\n };\n }\n \n // Si on a plusieurs orientations\n if (selfieInfo.orientations) {\n Object.keys(selfieInfo.orientations).forEach((orientation) => {\n const img = selfieInfo.orientations[orientation];\n if (img) {\n selfieData[orientation] = {\n dir: base64ToDataUri(img),\n file: img,\n };\n }\n });\n }\n\n if (Object.keys(selfieData).length > 0) {\n restoredComponentData[component.id] = selfieData;\n }\n }\n } else if (component.type === 'country_selection') {\n // Les données de sélection de pays peuvent être dans metadata\n if (data.metadata || data.user_data) {\n restoredComponentData[component.id] = {\n ...(data.metadata || {}),\n ...(data.user_data || {}),\n };\n }\n } else if (component.type === 'location') {\n // Les données de localisation peuvent être dans metadata\n if (data.metadata?.location || data.user_data?.location) {\n restoredComponentData[component.id] = {\n ...(data.metadata?.location || {}),\n ...(data.user_data?.location || {}),\n };\n }\n }\n });\n\n // Mettre à jour l'état avec les données restaurées\n if (Object.keys(restoredComponentData).length > 0) {\n logger.log('Session data restored - components:', Object.keys(restoredComponentData));\n logger.log('Session data restored - sample data:', truncateFields(restoredComponentData));\n setState(prev => ({\n ...prev,\n componentData: {\n ...prev.componentData,\n ...restoredComponentData,\n },\n }));\n logger.log('Component data updated in state');\n } else {\n logger.log('No component data to restore from session');\n }\n }\n } catch (error) {\n logger.error('Error loading session data:', truncateFields(error));\n // Ne pas bloquer le flux si le chargement échoue\n }\n };\n\n loadSessionData();\n }, [existingSessionId, initialStep, state.session.isInitialized, state.session.session_id, templateWithReviewAndVerification.components, base64ToDataUri]);\n\n const mapComponentTypeToAction = useCallback((type: TemplateComponent['type']): string | null => {\n switch (type) {\n case 'id_card':\n case 'file_upload':\n return 'document_upload';\n case 'selfie':\n return 'selfie_capture';\n case 'location':\n return 'location_permission';\n case 'review_submit':\n return 'final_submit';\n case 'country_selection':\n // No direct backend action; pack into metadata of next actionable step\n return null;\n case 'welcome':\n // UI-only step, no backend action needed\n return null;\n case 'initialization':\n return 'initialize_session';\n case 'verification_progress':\n return null; // UI-only\n default:\n return null;\n }\n }, []);\n\n const chooseTemplateId = useCallback((tpl: KYCTemplate): string => {\n const types = tpl.components.map(c => c.type);\n const hasLocation = types.includes('location');\n const hasSelfie = types.includes('selfie');\n const hasIdDoc = types.includes('id_card') || types.includes('file_upload');\n // Simple heuristic to map to backend examples\n if (hasLocation && hasSelfie && hasIdDoc) return 'enhanced_id';\n if (hasSelfie && hasIdDoc) return 'standard_passport';\n return 'standard_passport';\n }, [apiKey]);\n\n\n const computeServerStepIndex = useCallback((tpl: KYCTemplate, upToIndex: number): number => {\n // Count actionable steps before the current component (exclude UI-only and country_selection)\n const actionable = tpl.components\n .slice(0, upToIndex)\n .filter(c => !isUiOnlyStep(c.type) && mapComponentTypeToAction(c.type) !== null);\n return actionable.length; // 0-based\n }, [isUiOnlyStep, mapComponentTypeToAction, apiKey]);\n\n // Build backend-friendly payloads per action\n const buildPayloadForComponent = useCallback((action: string | null, component: TemplateComponent, rawData: any, templateId: string, step: number) => {\n console.log('apiKey in buildPayloadForComponent', apiKey);\n\n const base = { template_id: templateId || null, templateId: templateId || null, step: component.order, permissionGranted: true } as any;\n if (!action) {\n return base;\n }\n // Document upload expects an array of documents with base64 and metadata\n if (action === 'document_upload') {\n const documents: Record<string, any> = {};\n if (rawData && typeof rawData === 'object') {\n Object.keys(rawData).forEach((key) => {\n documents[key] = rawData[key];\n });\n }\n return {\n ...base,\n documents,\n };\n }\n\n if (action === 'selfie_capture') {\n const documents: Record<string, any> = {};\n if (rawData && typeof rawData === 'object') {\n\n Object.keys(rawData).forEach((key) => {\n documents[key] = rawData[key];\n });\n }\n const idCardID = Object.keys(state.componentData).find((c: string) => c === \"1\");\n if (idCardID) {\n const _idCardData = state.componentData[idCardID];\n const documentType = _idCardData?.documentType;\n // Map national_id to identity_card for selfie capture\n const mappedDocumentType = documentType === 'national_id' ? 'identity_card' : (documentType as GovernmentDocumentType || 'identity_card');\n return { ...base, documents, country: _idCardData?.country || '', documentType: mappedDocumentType };\n }\n return { ...base, documents };\n }\n\n if (action === 'location_permission') {\n return { ...base, ...({ metadata: rawData || {} }), ...({ permissionGranted: true, }) };\n }\n\n // Default: wrap as metadata\n return { ...base, metadata: { ...(rawData || {}) } };\n }, [state.componentData, apiKey]);\n // Ensure the template contains a final review step\n\n // console.log('apiKey in useTemplateKYCFlow', apiKey);\n\n\n // Composant actuel\n const currentComponent = useMemo(() => {\n return state.template.components[state.currentComponentIndex] || null;\n }, [state.template.components, state.currentComponentIndex, apiKey]);\n\n // Progression du flux\n const progress = useMemo(() => {\n return state.template.components.length > 0\n ? ((state.currentComponentIndex + 1) / state.template.components.length) * 100\n : 0;\n }, [state.currentComponentIndex, state.template.components.length, apiKey]);\n\n // Vérifications de navigation\n const canGoNext = useMemo(() => {\n return state.currentComponentIndex < state.template.components.length - 1;\n }, [state.currentComponentIndex, state.template.components.length, apiKey]);\n\n const canGoPrevious = useMemo(() => {\n return state.currentComponentIndex > 0;\n }, [state.currentComponentIndex, apiKey]);\n\n const isComplete = useMemo(() => {\n const atReview = state.template.components[state.currentComponentIndex]?.type === 'review_submit';\n const nonReviewCount = state.template.components.filter(c => c.type !== 'review_submit').length;\n const completedNonReview = state.completedComponents.length >= nonReviewCount;\n return atReview && completedNonReview;\n }, [state.currentComponentIndex, state.completedComponents.length, state.template.components, apiKey]);\n\n // Fonction pour obtenir le texte localisé\n const getLocalizedText = useCallback((text: { en: string; fr: string;[key: string]: string }): string => {\n return text[state.currentLanguage] || text.en || '';\n }, [state.currentLanguage, apiKey]);\n\n const initializeSession = useCallback(async () => {\n try {\n setState(prev => ({\n ...prev,\n session: {\n ...prev.session,\n isInitialized: false,\n isProcessing: true,\n error: null,\n },\n }));\n logger.log('Initializing session');\n\n const token = apiKey ? undefined : await authentification();\n console.log('token in initializeSession', { token, apiKey },);\n\n // Check if we already have a session ID from URL params (passed via state or prop)\n let session;\n const existingSessionId = state.session.session_id; // This might be set from initial props if we add logic for it\n\n if (existingSessionId && existingSessionId.length > 0) {\n logger.log('Resuming existing session:', existingSessionId);\n // Verify existence/validity if needed, for now trust the ID and just fetch/use it\n session = { session_id: existingSessionId };\n } else {\n session = await kycService.newSession({ token, apiKey });\n }\n\n // Align backend flow from step 0 with initialize_session\n try {\n const templateId = chooseTemplateId(templateWithReviewAndVerification);\n await kycService.verificationSession({\n session_id: session.session_id,\n step: 0,\n data: { template_id: templateId, metadata: { language: initialLanguage } },\n templateId: templateId,\n token: token,\n action: 'initialize_session',\n apiKey: apiKey,\n });\n } catch (e) {\n logger.error('Error initializing session:', JSON.stringify(e, null, 2));\n // Non-fatal: we will surface errors via state below if needed\n }\n\n setState(prev => ({\n ...prev,\n session: {\n ...prev.session,\n session_id: session.session_id,\n token: token,\n isInitialized: true,\n isProcessing: false,\n error: null,\n }\n }));\n } catch (error) {\n\n logger.error('Error initializing session:', JSON.stringify(error, null, 2));\n setState(prev => ({\n ...prev,\n session: {\n ...prev.session,\n isInitialized: false,\n isProcessing: false,\n error: \"Erreur lors de l'initialisation de la session\",\n },\n }));\n }\n }, [apiKey]);\n // Validation d'un composant\n const validateComponent = useCallback((componentId: number): boolean => {\n const component = state.template.components.find(c => c.id === componentId);\n if (!component) return false;\n\n const componentData = state.componentData[componentId];\n\n switch (component.type) {\n case 'id_card':\n // Vérifier si au moins un côté a été capturé\n return componentData && Object.keys(componentData).length > 0;\n\n case 'selfie':\n // Vérifier si toutes les orientations ont été capturées\n const config = component.config as any;\n const orientations = config.orientations || ['front'];\n return componentData && orientations.every((orientation: string) => componentData[orientation]);\n\n case 'file_upload':\n // Vérifier si un fichier a été uploadé\n return componentData && componentData.file;\n\n case 'location':\n // Vérifier si la localisation a été obtenue\n return componentData && componentData.latitude && componentData.longitude;\n\n case 'country_selection':\n // Vérifier si un pays a été sélectionné\n logger.log(\"componentData\", truncateFields(componentData), componentId);\n\n return componentData && componentData.code && componentData.regionMapping;\n\n case 'welcome':\n // Welcome is valid once user has given consent (componentData is set when they click Get Started)\n return componentData && componentData.consentGiven !== false;\n\n case 'email_verification':\n return componentData && componentData.verified === true;\n\n case 'phone_verification':\n return componentData && componentData.verified === true;\n\n case 'personal_information':\n return componentData && Object.keys(componentData).length > 0;\n\n case 'additional_documents':\n // Optional by default in template config, but if required we should check based on config\n // For now, return true or check length if present\n return true;\n\n case 'review_submit':\n return true;\n default:\n return false;\n }\n }, [state.template.components, state.componentData, apiKey]);\n\n // Actions du flux\n const actions: TemplateActions = {\n // Initialiser le template\n initializeTemplate: useCallback((newTemplate: KYCTemplate) => {\n const withReview = ensureReviewSubmitStep(newTemplate);\n const withVerification = ensureVerificationProgressStep(withReview);\n setState(prev => ({\n ...prev,\n template: withVerification,\n currentComponentIndex: 0,\n completedComponents: [],\n componentData: {},\n errors: {},\n isProcessing: false,\n verification: { status: 'idle', result: undefined },\n }));\n }, [ensureReviewSubmitStep, ensureVerificationProgressStep, apiKey]),\n\n // Passer au composant suivant\n nextComponent: useCallback(async () => {\n if (!canGoNext) return;\n\n const currentComp = state.template.components[state.currentComponentIndex];\n if (!currentComp) return;\n\n // Prevent multiple simultaneous calls\n setState(prev => {\n if (prev.isProcessing) {\n return prev;\n }\n return {\n ...prev,\n isProcessing: true,\n };\n });\n // Valider le composant actuel\n if (!validateComponent(currentComp.id)) {\n setState(prev => ({\n ...prev,\n isProcessing: false,\n errors: {\n ...prev.errors,\n [currentComp.id]: state.currentLanguage === \"en\" ? \"please complete this step before move on\" : \" 'Veuillez compléter cette étape avant de continuer'\"\n }\n }));\n return;\n\n }\n\n try {\n const component = state.template.components.find(c => c.id === currentComp.id);\n if (!component) {\n setState(prev => ({\n ...prev,\n isProcessing: false,\n }));\n return;\n }\n if (component.type === 'review_submit') {\n // Move to verification screen and mark verification in progress\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex + 1,\n completedComponents: [...prev.completedComponents, currentComp.id],\n isProcessing: false,\n verification: { status: 'in_progress' },\n errors: {\n ...prev.errors,\n [currentComp.id]: ''\n }\n }));\n return;\n }\n // Determine backend action and step index\n const action = mapComponentTypeToAction(component.type);\n const templateId = chooseTemplateId(state.template);\n const serverStep = computeServerStepIndex(state.template, state.currentComponentIndex);\n\n // Optionally send initialize_session at step 0 before first actionable action\n if (serverStep === 0) {\n try {\n // await kycService.verificationSession({\n // sessionId: state.session.session_id,\n // step: 0,\n // data: { template_id: templateId, metadata: { language: state.currentLanguage } },\n // templateId: templateId,\n // token: state.session.token,\n // action: 'initialize_session'\n // });\n } catch (e) {\n // if init fails, surface error below in the main call handling\n }\n }\n\n // Skip UI-only and data-only steps that have no backend action\n if (!action) {\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex + 1,\n completedComponents: [...prev.completedComponents, currentComp.id],\n isProcessing: false,\n errors: {\n ...prev.errors,\n [currentComp.id]: ''\n }\n }));\n return;\n }\n\n const step = serverStep === 0 && action !== 'initialize_session' ? 1 : serverStep;\n // Build payload data per action\n const payloadData = buildPayloadForComponent(action, component, state.componentData[currentComp.id], templateId, step);\n console.log('payloadData', action, apiKey);\n\n await kycService.verificationSession({\n session_id: state.session.session_id,\n step: step,\n data: payloadData,\n templateId: templateId,\n token: state.session.token,\n action: action,\n apiKey: apiKey ?? \"-\",\n });\n logger.log(\"currentComp state\", truncateFields(state));\n // Marquer comme complété et passer au suivant\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex + 1,\n completedComponents: [...prev.completedComponents, currentComp.id],\n isProcessing: false,\n ...(action === \"location_permission\" ? { permissionGranted: true } : {}),\n errors: {\n ...prev.errors,\n [currentComp.id]: ''\n }\n }));\n\n } catch (error) {\n logger.error('Error in nextComponent:', error);\n setState(prev => ({\n ...prev,\n isProcessing: false,\n errors: {\n ...prev.errors,\n [currentComp.id]: 'Erreur lors de la validation du composant'\n }\n }));\n }\n\n }, [canGoNext, state.currentComponentIndex, state.template.components, validateComponent, apiKey, state.session.session_id, state.session.token, buildPayloadForComponent, mapComponentTypeToAction, chooseTemplateId, state.currentLanguage]),\n\n // Retourner au composant précédent\n previousComponent: useCallback(() => {\n if (!canGoPrevious) return;\n\n setState(prev => ({\n ...prev,\n currentComponentIndex: prev.currentComponentIndex - 1,\n }));\n }, [canGoPrevious, apiKey]),\n\n // Aller à un composant spécifique\n goToComponent: useCallback((componentId: number) => {\n const componentIndex = state.template.components.findIndex(c => c.id === componentId);\n if (componentIndex !== -1) {\n setState(prev => ({\n ...prev,\n currentComponentIndex: componentIndex,\n }));\n }\n }, [state.template.components, apiKey]),\n\n // Mettre à jour les données d'un composant\n updateComponentData: useCallback((componentId: number, data: any) => {\n logger.log(\"updateComponentData\", componentId, JSON.stringify(truncateFields(data), null, 2));\n\n setState(prev => ({\n ...prev,\n componentData: {\n ...prev.componentData,\n [componentId]: data\n },\n errors: {\n ...prev.errors,\n [componentId]: ''\n }\n }));\n\n }, [apiKey]),\n\n // Valider un composant\n validateComponent: useCallback((componentId: number) => {\n return validateComponent(componentId);\n }, [validateComponent, apiKey]),\n // complet verification\n submitVerification: useCallback(async () => {\n setState(prev => ({ ...prev, isProcessing: true }));\n try {\n onComplete?.(state.verification);\n\n } catch (error) {\n setState(prev => ({ ...prev, isProcessing: false }));\n }\n }, [state.session.session_id, state.verification, onComplete, apiKey]),\n\n // Soumettre le template complet\n submitTemplate: useCallback(async () => {\n // Allow submission when on the review step and all previous steps are valid\n const atReview = state.template.components[state.currentComponentIndex]?.type === 'review_submit';\n const allValid = state.template.components\n .filter(c => c.type !== 'review_submit')\n .every(comp => validateComponent(comp.id));\n if (!(atReview && allValid)) {\n onError?.('Le flux KYC n\\'est pas encore terminé');\n return;\n }\n\n setState(prev => ({ ...prev, isProcessing: true }));\n\n try {\n // Vérifier que tous les composants (hors review) sont validés\n if (!allValid) throw new Error('Certaines étapes ne sont pas complètes');\n\n // Appeler le callback de completion\n // onComplete?.(state.componentData);\n\n setState(prev => ({ ...prev, isProcessing: false }));\n } catch (error) {\n setState(prev => ({ ...prev, isProcessing: false }));\n onError?.(error instanceof Error ? error.message : 'Erreur lors de la soumission');\n }\n }, [state.template.components, state.verification, state.currentComponentIndex, validateComponent, state.componentData, onComplete, onError, apiKey]),\n\n // Réinitialiser le template\n resetTemplate: useCallback(() => {\n setState(buildInitialState());\n }, [buildInitialState, apiKey]),\n\n // Changer la langue\n setLanguage: useCallback((language: string) => {\n setState(prev => ({\n ...prev,\n currentLanguage: language,\n }));\n }, [apiKey]),\n\n // Afficher le stepper personnalisé\n showCustomStepper: useCallback((show: boolean) => {\n setState(prev => ({\n ...prev,\n showCustomStepper: show,\n }));\n }, [apiKey]),\n\n setVerificationState: useCallback((verificationState) => {\n setState(prev => ({\n ...prev,\n verification: verificationState,\n }));\n }, [apiKey]),\n };\n\n return {\n state,\n actions,\n currentComponent,\n progress,\n canGoNext,\n canGoPrevious,\n isComplete,\n getLocalizedText,\n initializeSession,\n env,\n };\n}; "]}