@factpulse/sdk 2.0.11 → 2.0.49

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 (302) hide show
  1. package/.github/SETUP_GITHUB_ACTIONS.md +70 -8
  2. package/.github/workflows/publish-npm.yml +5 -7
  3. package/.openapi-generator/FILES +58 -26
  4. package/CHANGELOG.md +3 -3
  5. package/README.md +165 -116
  6. package/api/afnorpdppaapi.ts +149 -0
  7. package/api/chorus-pro-api.ts +151 -181
  8. package/api/traitement-facture-api.ts +12 -12
  9. package/api/vrification-pdfxmlapi.ts +536 -0
  10. package/api.ts +1 -0
  11. package/dist/api/afnorpdppaapi.d.ts +65 -0
  12. package/dist/api/afnorpdppaapi.js +142 -1
  13. package/dist/api/afnorpdppadirectory-service-api.js +4 -1
  14. package/dist/api/afnorpdppaflow-service-api.js +4 -1
  15. package/dist/api/chorus-pro-api.d.ts +168 -103
  16. package/dist/api/chorus-pro-api.js +155 -160
  17. package/dist/api/sant-api.js +4 -1
  18. package/dist/api/traitement-facture-api.d.ts +12 -12
  19. package/dist/api/traitement-facture-api.js +16 -13
  20. package/dist/api/utilisateur-api.js +4 -1
  21. package/dist/api/vrification-pdfxmlapi.d.ts +237 -0
  22. package/dist/api/vrification-pdfxmlapi.js +514 -0
  23. package/dist/api.d.ts +1 -0
  24. package/dist/api.js +1 -0
  25. package/dist/base.js +4 -1
  26. package/dist/esm/api/afnorpdppaapi.d.ts +65 -0
  27. package/dist/esm/api/afnorpdppaapi.js +139 -1
  28. package/dist/esm/api/chorus-pro-api.d.ts +168 -103
  29. package/dist/esm/api/chorus-pro-api.js +151 -159
  30. package/dist/esm/api/traitement-facture-api.d.ts +12 -12
  31. package/dist/esm/api/traitement-facture-api.js +12 -12
  32. package/dist/esm/api/vrification-pdfxmlapi.d.ts +237 -0
  33. package/dist/esm/api/vrification-pdfxmlapi.js +504 -0
  34. package/dist/esm/api.d.ts +1 -0
  35. package/dist/esm/api.js +1 -0
  36. package/dist/esm/models/{utilisateur.d.ts → apierror.d.ts} +12 -15
  37. package/dist/esm/models/beneficiaire.d.ts +26 -0
  38. package/dist/esm/models/bounding-box-schema.d.ts +44 -0
  39. package/dist/esm/models/cadre-de-facturation.d.ts +3 -1
  40. package/dist/esm/models/champ-verifie-schema.d.ts +42 -0
  41. package/dist/esm/models/code-cadre-facturation.d.ts +3 -0
  42. package/dist/esm/models/code-cadre-facturation.js +3 -0
  43. package/dist/esm/models/destinataire.d.ts +1 -1
  44. package/dist/esm/models/dimension-page-schema.d.ts +24 -0
  45. package/dist/esm/models/{quota-info.d.ts → direction-flux.d.ts} +6 -8
  46. package/dist/esm/models/direction-flux.js +20 -0
  47. package/dist/esm/models/error-level.d.ts +16 -0
  48. package/dist/esm/models/error-level.js +17 -0
  49. package/dist/esm/models/{body-ajouter-fichier-api-v1-chorus-pro-transverses-ajouter-fichier-post.d.ts → error-source.d.ts} +11 -9
  50. package/dist/esm/models/error-source.js +23 -0
  51. package/dist/esm/models/facture-entrante.d.ts +68 -0
  52. package/dist/esm/models/facture-factur-x.d.ts +2 -0
  53. package/dist/esm/models/{body-rechercher-factures-destinataire-api-v1-chorus-pro-factures-rechercher-destinataire-post.d.ts → flux-resume.d.ts} +12 -8
  54. package/dist/esm/models/format-facture.d.ts +20 -0
  55. package/dist/esm/models/format-facture.js +21 -0
  56. package/dist/esm/models/fournisseur-entrant.d.ts +29 -0
  57. package/dist/esm/models/fournisseur.d.ts +1 -1
  58. package/dist/esm/models/index.d.ts +28 -13
  59. package/dist/esm/models/index.js +28 -13
  60. package/dist/esm/models/ligne-de-tva.d.ts +3 -1
  61. package/dist/esm/models/nature-operation.d.ts +31 -0
  62. package/dist/esm/models/nature-operation.js +32 -0
  63. package/dist/esm/models/note-obligatoire-schema.d.ts +34 -0
  64. package/dist/esm/models/note.d.ts +2 -2
  65. package/dist/esm/models/pdpcredentials.d.ts +33 -0
  66. package/dist/esm/models/profil-flux.d.ts +20 -0
  67. package/dist/esm/models/profil-flux.js +21 -0
  68. package/dist/esm/models/{body-completer-facture-api-v1-chorus-pro-factures-completer-post.d.ts → reponse-healthcheck-afnor.d.ts} +16 -8
  69. package/dist/esm/models/reponse-recherche-flux.d.ts +33 -0
  70. package/dist/esm/models/reponse-soumission-flux.d.ts +38 -0
  71. package/dist/esm/models/reponse-verification-succes.d.ts +56 -0
  72. package/dist/esm/models/reponse-verification-succes.js +14 -0
  73. package/dist/esm/models/requete-recherche-flux.d.ts +34 -0
  74. package/dist/esm/models/requete-recherche-flux.js +14 -0
  75. package/dist/esm/models/requete-soumission-flux.d.ts +31 -0
  76. package/dist/esm/models/requete-soumission-flux.js +14 -0
  77. package/dist/esm/models/statut-acquittement.d.ts +20 -0
  78. package/dist/esm/models/statut-acquittement.js +21 -0
  79. package/dist/esm/models/statut-champ-api.d.ts +22 -0
  80. package/dist/esm/models/statut-champ-api.js +23 -0
  81. package/dist/esm/models/syntaxe-flux.d.ts +22 -0
  82. package/dist/esm/models/syntaxe-flux.js +23 -0
  83. package/dist/esm/models/type-document.d.ts +37 -0
  84. package/dist/esm/models/type-document.js +38 -0
  85. package/dist/esm/models/type-facture.d.ts +65 -3
  86. package/dist/esm/models/type-facture.js +65 -3
  87. package/dist/esm/models/type-flux.d.ts +22 -0
  88. package/dist/esm/models/type-flux.js +23 -0
  89. package/dist/esm/models/validation-error-detail.d.ts +32 -0
  90. package/dist/esm/models/validation-error-detail.js +14 -0
  91. package/dist/esm/src/helpers/client.d.ts +265 -0
  92. package/dist/esm/src/helpers/client.js +817 -0
  93. package/dist/esm/src/helpers/exceptions.d.ts +23 -0
  94. package/dist/esm/src/helpers/exceptions.js +27 -0
  95. package/dist/esm/src/helpers/index.d.ts +3 -0
  96. package/dist/esm/src/helpers/index.js +6 -0
  97. package/dist/models/{utilisateur.d.ts → apierror.d.ts} +12 -15
  98. package/dist/models/beneficiaire.d.ts +26 -0
  99. package/dist/models/bounding-box-schema.d.ts +44 -0
  100. package/dist/models/cadre-de-facturation.d.ts +3 -1
  101. package/dist/models/champ-verifie-schema.d.ts +42 -0
  102. package/dist/models/code-cadre-facturation.d.ts +3 -0
  103. package/dist/models/code-cadre-facturation.js +3 -0
  104. package/dist/models/destinataire.d.ts +1 -1
  105. package/dist/models/dimension-page-schema.d.ts +24 -0
  106. package/dist/models/{quota-info.d.ts → direction-flux.d.ts} +6 -8
  107. package/dist/models/direction-flux.js +23 -0
  108. package/dist/models/error-level.d.ts +16 -0
  109. package/dist/models/error-level.js +20 -0
  110. package/dist/models/error-source.d.ts +22 -0
  111. package/dist/models/error-source.js +26 -0
  112. package/dist/models/facture-entrante.d.ts +68 -0
  113. package/dist/models/facture-factur-x.d.ts +2 -0
  114. package/dist/models/flux-resume.d.ts +24 -0
  115. package/dist/models/format-facture.d.ts +20 -0
  116. package/dist/models/format-facture.js +24 -0
  117. package/dist/models/fournisseur-entrant.d.ts +29 -0
  118. package/dist/models/fournisseur.d.ts +1 -1
  119. package/dist/models/index.d.ts +28 -13
  120. package/dist/models/index.js +28 -13
  121. package/dist/models/ligne-de-tva.d.ts +3 -1
  122. package/dist/models/nature-operation.d.ts +31 -0
  123. package/dist/models/nature-operation.js +35 -0
  124. package/dist/models/note-obligatoire-schema.d.ts +34 -0
  125. package/dist/models/note.d.ts +2 -2
  126. package/dist/models/pdpcredentials.d.ts +33 -0
  127. package/dist/models/profil-flux.d.ts +20 -0
  128. package/dist/models/profil-flux.js +24 -0
  129. package/dist/{esm/models/body-recycler-facture-api-v1-chorus-pro-factures-recycler-post.d.ts → models/reponse-healthcheck-afnor.d.ts} +16 -8
  130. package/dist/models/reponse-recherche-flux.d.ts +33 -0
  131. package/dist/models/reponse-soumission-flux.d.ts +38 -0
  132. package/dist/models/reponse-verification-succes.d.ts +56 -0
  133. package/dist/models/reponse-verification-succes.js +15 -0
  134. package/dist/models/requete-recherche-flux.d.ts +34 -0
  135. package/dist/models/requete-recherche-flux.js +15 -0
  136. package/dist/models/requete-soumission-flux.d.ts +31 -0
  137. package/dist/models/requete-soumission-flux.js +15 -0
  138. package/dist/models/statut-acquittement.d.ts +20 -0
  139. package/dist/models/statut-acquittement.js +24 -0
  140. package/dist/models/statut-champ-api.d.ts +22 -0
  141. package/dist/models/statut-champ-api.js +26 -0
  142. package/dist/models/syntaxe-flux.d.ts +22 -0
  143. package/dist/models/syntaxe-flux.js +26 -0
  144. package/dist/models/type-document.d.ts +37 -0
  145. package/dist/models/type-document.js +41 -0
  146. package/dist/models/type-facture.d.ts +65 -3
  147. package/dist/models/type-facture.js +65 -3
  148. package/dist/models/type-flux.d.ts +22 -0
  149. package/dist/models/type-flux.js +26 -0
  150. package/dist/models/validation-error-detail.d.ts +32 -0
  151. package/dist/models/validation-error-detail.js +15 -0
  152. package/dist/src/helpers/client.d.ts +265 -0
  153. package/dist/src/helpers/client.js +866 -0
  154. package/dist/src/helpers/exceptions.d.ts +23 -0
  155. package/dist/src/helpers/exceptions.js +35 -0
  156. package/dist/src/helpers/index.d.ts +3 -0
  157. package/dist/src/helpers/index.js +23 -0
  158. package/docs/AFNORPDPPAApi.md +108 -0
  159. package/docs/APIError.md +25 -0
  160. package/docs/Beneficiaire.md +31 -0
  161. package/docs/BoundingBoxSchema.md +33 -0
  162. package/docs/CadreDeFacturation.md +3 -1
  163. package/docs/ChampVerifieSchema.md +37 -0
  164. package/docs/ChorusProApi.md +54 -69
  165. package/docs/CodeCadreFacturation.md +1 -0
  166. package/docs/DimensionPageSchema.md +23 -0
  167. package/docs/DirectionFlux.md +11 -0
  168. package/docs/ErrorLevel.md +10 -0
  169. package/docs/ErrorSource.md +22 -0
  170. package/docs/FactureEntrante.md +57 -0
  171. package/docs/FactureFacturX.md +2 -0
  172. package/docs/FluxResume.md +35 -0
  173. package/docs/FormatFacture.md +13 -0
  174. package/docs/FournisseurEntrant.md +35 -0
  175. package/docs/LigneDeTVA.md +5 -1
  176. package/docs/NatureOperation.md +35 -0
  177. package/docs/Note.md +4 -4
  178. package/docs/NoteObligatoireSchema.md +33 -0
  179. package/docs/PDPCredentials.md +29 -0
  180. package/docs/ProfilFlux.md +13 -0
  181. package/docs/ReponseHealthcheckAFNOR.md +25 -0
  182. package/docs/ReponseRechercheFlux.md +27 -0
  183. package/docs/ReponseSoumissionFlux.md +33 -0
  184. package/docs/ReponseVerificationSucces.md +39 -0
  185. package/docs/RequeteRechercheFlux.md +37 -0
  186. package/docs/RequeteSoumissionFlux.md +31 -0
  187. package/docs/StatutAcquittement.md +13 -0
  188. package/docs/StatutChampAPI.md +17 -0
  189. package/docs/SyntaxeFlux.md +17 -0
  190. package/docs/TraitementFactureApi.md +3 -3
  191. package/docs/TypeDocument.md +17 -0
  192. package/docs/TypeFacture.md +31 -3
  193. package/docs/TypeFlux.md +17 -0
  194. package/docs/ValidationErrorDetail.md +29 -0
  195. package/docs/VrificationPDFXMLApi.md +335 -0
  196. package/models/{utilisateur.ts → apierror.ts} +12 -15
  197. package/models/beneficiaire.ts +34 -0
  198. package/models/bounding-box-schema.ts +50 -0
  199. package/models/cadre-de-facturation.ts +5 -1
  200. package/models/champ-verifie-schema.ts +54 -0
  201. package/models/code-cadre-facturation.ts +3 -0
  202. package/models/destinataire.ts +1 -1
  203. package/models/dimension-page-schema.ts +30 -0
  204. package/models/{quota-info.ts → direction-flux.ts} +10 -8
  205. package/models/error-level.ts +26 -0
  206. package/models/error-source.ts +32 -0
  207. package/models/facture-entrante.ts +82 -0
  208. package/models/facture-factur-x.ts +4 -0
  209. package/models/flux-resume.ts +30 -0
  210. package/models/format-facture.ts +30 -0
  211. package/models/fournisseur-entrant.ts +39 -0
  212. package/models/fournisseur.ts +1 -1
  213. package/models/index.ts +28 -13
  214. package/models/ligne-de-tva.ts +3 -1
  215. package/models/nature-operation.ts +41 -0
  216. package/models/{body-lister-services-structure-api-v1-chorus-pro-structures-id-structure-cpp-services-get.ts → note-obligatoire-schema.ts} +24 -5
  217. package/models/note.ts +2 -2
  218. package/models/pdpcredentials.ts +39 -0
  219. package/models/profil-flux.ts +30 -0
  220. package/models/reponse-healthcheck-afnor.ts +34 -0
  221. package/models/{body-ajouter-fichier-api-v1-chorus-pro-transverses-ajouter-fichier-post.ts → reponse-recherche-flux.ts} +21 -8
  222. package/models/{body-completer-facture-api-v1-chorus-pro-factures-completer-post.ts → reponse-soumission-flux.ts} +26 -10
  223. package/models/reponse-verification-succes.ts +68 -0
  224. package/models/requete-recherche-flux.ts +48 -0
  225. package/models/{body-rechercher-factures-destinataire-api-v1-chorus-pro-factures-rechercher-destinataire-post.ts → requete-soumission-flux.ts} +23 -6
  226. package/models/statut-acquittement.ts +30 -0
  227. package/models/statut-champ-api.ts +32 -0
  228. package/models/syntaxe-flux.ts +32 -0
  229. package/models/type-document.ts +47 -0
  230. package/models/type-facture.ts +65 -3
  231. package/models/type-flux.ts +32 -0
  232. package/models/validation-error-detail.ts +44 -0
  233. package/package.json +2 -2
  234. package/src/helpers/client.ts +882 -0
  235. package/src/helpers/exceptions.ts +32 -0
  236. package/src/helpers/index.ts +6 -0
  237. package/tsconfig.esm.json +1 -0
  238. package/tsconfig.json +1 -0
  239. package/dist/esm/models/body-lister-services-structure-api-v1-chorus-pro-structures-id-structure-cpp-services-get.d.ts +0 -17
  240. package/dist/esm/models/body-rechercher-factures-fournisseur-api-v1-chorus-pro-factures-rechercher-fournisseur-post.d.ts +0 -20
  241. package/dist/esm/models/body-telecharger-groupe-factures-api-v1-chorus-pro-factures-telecharger-groupe-post.d.ts +0 -20
  242. package/dist/esm/models/body-traiter-facture-recue-api-v1-chorus-pro-factures-traiter-facture-recue-post.d.ts +0 -20
  243. package/dist/esm/models/body-valideur-consulter-facture-api-v1-chorus-pro-factures-valideur-consulter-post.d.ts +0 -20
  244. package/dist/esm/models/body-valideur-rechercher-factures-api-v1-chorus-pro-factures-valideur-rechercher-post.d.ts +0 -20
  245. package/dist/esm/models/body-valideur-traiter-facture-api-v1-chorus-pro-factures-valideur-traiter-post.d.ts +0 -20
  246. package/dist/models/body-ajouter-fichier-api-v1-chorus-pro-transverses-ajouter-fichier-post.d.ts +0 -20
  247. package/dist/models/body-completer-facture-api-v1-chorus-pro-factures-completer-post.d.ts +0 -20
  248. package/dist/models/body-lister-services-structure-api-v1-chorus-pro-structures-id-structure-cpp-services-get.d.ts +0 -17
  249. package/dist/models/body-rechercher-factures-destinataire-api-v1-chorus-pro-factures-rechercher-destinataire-post.d.ts +0 -20
  250. package/dist/models/body-rechercher-factures-fournisseur-api-v1-chorus-pro-factures-rechercher-fournisseur-post.d.ts +0 -20
  251. package/dist/models/body-recycler-facture-api-v1-chorus-pro-factures-recycler-post.d.ts +0 -20
  252. package/dist/models/body-telecharger-groupe-factures-api-v1-chorus-pro-factures-telecharger-groupe-post.d.ts +0 -20
  253. package/dist/models/body-traiter-facture-recue-api-v1-chorus-pro-factures-traiter-facture-recue-post.d.ts +0 -20
  254. package/dist/models/body-valideur-consulter-facture-api-v1-chorus-pro-factures-valideur-consulter-post.d.ts +0 -20
  255. package/dist/models/body-valideur-rechercher-factures-api-v1-chorus-pro-factures-valideur-rechercher-post.d.ts +0 -20
  256. package/dist/models/body-valideur-traiter-facture-api-v1-chorus-pro-factures-valideur-traiter-post.d.ts +0 -20
  257. package/docs/BodyAjouterFichierApiV1ChorusProTransversesAjouterFichierPost.md +0 -24
  258. package/docs/BodyCompleterFactureApiV1ChorusProFacturesCompleterPost.md +0 -24
  259. package/docs/BodyListerServicesStructureApiV1ChorusProStructuresIdStructureCppServicesGet.md +0 -22
  260. package/docs/BodyRechercherFacturesDestinataireApiV1ChorusProFacturesRechercherDestinatairePost.md +0 -24
  261. package/docs/BodyRechercherFacturesFournisseurApiV1ChorusProFacturesRechercherFournisseurPost.md +0 -24
  262. package/docs/BodyRecyclerFactureApiV1ChorusProFacturesRecyclerPost.md +0 -24
  263. package/docs/BodyTelechargerGroupeFacturesApiV1ChorusProFacturesTelechargerGroupePost.md +0 -24
  264. package/docs/BodyTraiterFactureRecueApiV1ChorusProFacturesTraiterFactureRecuePost.md +0 -24
  265. package/docs/BodyValideurConsulterFactureApiV1ChorusProFacturesValideurConsulterPost.md +0 -24
  266. package/docs/BodyValideurRechercherFacturesApiV1ChorusProFacturesValideurRechercherPost.md +0 -24
  267. package/docs/BodyValideurTraiterFactureApiV1ChorusProFacturesValideurTraiterPost.md +0 -24
  268. package/docs/QuotaInfo.md +0 -29
  269. package/docs/Utilisateur.md +0 -43
  270. package/models/body-rechercher-factures-fournisseur-api-v1-chorus-pro-factures-rechercher-fournisseur-post.ts +0 -28
  271. package/models/body-recycler-facture-api-v1-chorus-pro-factures-recycler-post.ts +0 -28
  272. package/models/body-telecharger-groupe-factures-api-v1-chorus-pro-factures-telecharger-groupe-post.ts +0 -28
  273. package/models/body-traiter-facture-recue-api-v1-chorus-pro-factures-traiter-facture-recue-post.ts +0 -28
  274. package/models/body-valideur-consulter-facture-api-v1-chorus-pro-factures-valideur-consulter-post.ts +0 -28
  275. package/models/body-valideur-rechercher-factures-api-v1-chorus-pro-factures-valideur-rechercher-post.ts +0 -28
  276. package/models/body-valideur-traiter-facture-api-v1-chorus-pro-factures-valideur-traiter-post.ts +0 -28
  277. /package/dist/esm/models/{body-ajouter-fichier-api-v1-chorus-pro-transverses-ajouter-fichier-post.js → apierror.js} +0 -0
  278. /package/dist/esm/models/{body-completer-facture-api-v1-chorus-pro-factures-completer-post.js → beneficiaire.js} +0 -0
  279. /package/dist/esm/models/{body-lister-services-structure-api-v1-chorus-pro-structures-id-structure-cpp-services-get.js → bounding-box-schema.js} +0 -0
  280. /package/dist/esm/models/{body-rechercher-factures-destinataire-api-v1-chorus-pro-factures-rechercher-destinataire-post.js → champ-verifie-schema.js} +0 -0
  281. /package/dist/esm/models/{body-rechercher-factures-fournisseur-api-v1-chorus-pro-factures-rechercher-fournisseur-post.js → dimension-page-schema.js} +0 -0
  282. /package/dist/esm/models/{body-recycler-facture-api-v1-chorus-pro-factures-recycler-post.js → facture-entrante.js} +0 -0
  283. /package/dist/esm/models/{body-telecharger-groupe-factures-api-v1-chorus-pro-factures-telecharger-groupe-post.js → flux-resume.js} +0 -0
  284. /package/dist/esm/models/{body-traiter-facture-recue-api-v1-chorus-pro-factures-traiter-facture-recue-post.js → fournisseur-entrant.js} +0 -0
  285. /package/dist/esm/models/{body-valideur-consulter-facture-api-v1-chorus-pro-factures-valideur-consulter-post.js → note-obligatoire-schema.js} +0 -0
  286. /package/dist/esm/models/{body-valideur-rechercher-factures-api-v1-chorus-pro-factures-valideur-rechercher-post.js → pdpcredentials.js} +0 -0
  287. /package/dist/esm/models/{body-valideur-traiter-facture-api-v1-chorus-pro-factures-valideur-traiter-post.js → reponse-healthcheck-afnor.js} +0 -0
  288. /package/dist/esm/models/{quota-info.js → reponse-recherche-flux.js} +0 -0
  289. /package/dist/esm/models/{utilisateur.js → reponse-soumission-flux.js} +0 -0
  290. /package/dist/models/{body-ajouter-fichier-api-v1-chorus-pro-transverses-ajouter-fichier-post.js → apierror.js} +0 -0
  291. /package/dist/models/{body-completer-facture-api-v1-chorus-pro-factures-completer-post.js → beneficiaire.js} +0 -0
  292. /package/dist/models/{body-lister-services-structure-api-v1-chorus-pro-structures-id-structure-cpp-services-get.js → bounding-box-schema.js} +0 -0
  293. /package/dist/models/{body-rechercher-factures-destinataire-api-v1-chorus-pro-factures-rechercher-destinataire-post.js → champ-verifie-schema.js} +0 -0
  294. /package/dist/models/{body-rechercher-factures-fournisseur-api-v1-chorus-pro-factures-rechercher-fournisseur-post.js → dimension-page-schema.js} +0 -0
  295. /package/dist/models/{body-recycler-facture-api-v1-chorus-pro-factures-recycler-post.js → facture-entrante.js} +0 -0
  296. /package/dist/models/{body-telecharger-groupe-factures-api-v1-chorus-pro-factures-telecharger-groupe-post.js → flux-resume.js} +0 -0
  297. /package/dist/models/{body-traiter-facture-recue-api-v1-chorus-pro-factures-traiter-facture-recue-post.js → fournisseur-entrant.js} +0 -0
  298. /package/dist/models/{body-valideur-consulter-facture-api-v1-chorus-pro-factures-valideur-consulter-post.js → note-obligatoire-schema.js} +0 -0
  299. /package/dist/models/{body-valideur-rechercher-factures-api-v1-chorus-pro-factures-valideur-rechercher-post.js → pdpcredentials.js} +0 -0
  300. /package/dist/models/{body-valideur-traiter-facture-api-v1-chorus-pro-factures-valideur-traiter-post.js → reponse-healthcheck-afnor.js} +0 -0
  301. /package/dist/models/{quota-info.js → reponse-recherche-flux.js} +0 -0
  302. /package/dist/models/{utilisateur.js → reponse-soumission-flux.js} +0 -0
@@ -0,0 +1,817 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import axios from 'axios';
11
+ import FormData from 'form-data';
12
+ import * as fs from 'fs';
13
+ import * as path from 'path';
14
+ import { FactPulseAuthError, FactPulsePollingTimeout, FactPulseValidationError } from './exceptions';
15
+ /** Convertit une valeur en string de montant pour l'API. */
16
+ export function montant(value) {
17
+ if (value === null || value === undefined)
18
+ return '0.00';
19
+ if (typeof value === 'number')
20
+ return value.toFixed(2);
21
+ if (typeof value === 'string')
22
+ return value;
23
+ return '0.00';
24
+ }
25
+ /** Crée un objet MontantTotal simplifié. */
26
+ export function montantTotal(ht, tva, ttc, aPayer, options) {
27
+ const result = {
28
+ montantHtTotal: montant(ht), montantTva: montant(tva),
29
+ montantTtcTotal: montant(ttc), montantAPayer: montant(aPayer),
30
+ };
31
+ if ((options === null || options === void 0 ? void 0 : options.remiseTtc) !== undefined)
32
+ result.montantRemiseGlobaleTtc = montant(options.remiseTtc);
33
+ if ((options === null || options === void 0 ? void 0 : options.motifRemise) !== undefined)
34
+ result.motifRemiseGlobaleTtc = options.motifRemise;
35
+ if ((options === null || options === void 0 ? void 0 : options.acompte) !== undefined)
36
+ result.acompte = montant(options.acompte);
37
+ return result;
38
+ }
39
+ /** Crée une ligne de poste (aligné sur LigneDePoste de models.py).
40
+ * Pour le taux TVA: soit tauxTva (code ex: "TVA20") soit tauxTvaManuel (valeur ex: 20.00) */
41
+ export function ligneDePoste(numero, denomination, quantite, montantUnitaireHt, montantTotalLigneHt, options) {
42
+ var _a, _b, _c;
43
+ const result = {
44
+ numero, denomination, quantite: montant(quantite), montantUnitaireHt: montant(montantUnitaireHt),
45
+ montantTotalLigneHt: montant(montantTotalLigneHt),
46
+ categorieTva: (_a = options === null || options === void 0 ? void 0 : options.categorieTva) !== null && _a !== void 0 ? _a : 'S', unite: (_b = options === null || options === void 0 ? void 0 : options.unite) !== null && _b !== void 0 ? _b : 'FORFAIT',
47
+ };
48
+ // Soit tauxTva (code) soit tauxTvaManuel (valeur)
49
+ if (options === null || options === void 0 ? void 0 : options.tauxTva)
50
+ result.tauxTva = options.tauxTva;
51
+ else
52
+ result.tauxTvaManuel = montant((_c = options === null || options === void 0 ? void 0 : options.tauxTvaManuel) !== null && _c !== void 0 ? _c : '20.00');
53
+ if (options === null || options === void 0 ? void 0 : options.reference)
54
+ result.reference = options.reference;
55
+ if ((options === null || options === void 0 ? void 0 : options.montantRemiseHt) !== undefined)
56
+ result.montantRemiseHt = montant(options.montantRemiseHt);
57
+ if (options === null || options === void 0 ? void 0 : options.codeRaisonReduction)
58
+ result.codeRaisonReduction = options.codeRaisonReduction;
59
+ if (options === null || options === void 0 ? void 0 : options.raisonReduction)
60
+ result.raisonReduction = options.raisonReduction;
61
+ if (options === null || options === void 0 ? void 0 : options.dateDebutPeriode)
62
+ result.dateDebutPeriode = options.dateDebutPeriode;
63
+ if (options === null || options === void 0 ? void 0 : options.dateFinPeriode)
64
+ result.dateFinPeriode = options.dateFinPeriode;
65
+ return result;
66
+ }
67
+ /** Crée une ligne de TVA (aligné sur LigneDeTVA de models.py).
68
+ * Pour le taux: soit taux (code ex: "TVA20") soit tauxManuel (valeur ex: 20.00) */
69
+ export function ligneDeTva(montantBaseHt, montantTva, options) {
70
+ var _a, _b;
71
+ const result = {
72
+ montantBaseHt: montant(montantBaseHt), montantTva: montant(montantTva), categorie: (_a = options === null || options === void 0 ? void 0 : options.categorie) !== null && _a !== void 0 ? _a : 'S',
73
+ };
74
+ // Soit taux (code) soit tauxManuel (valeur)
75
+ if (options === null || options === void 0 ? void 0 : options.taux)
76
+ result.taux = options.taux;
77
+ else
78
+ result.tauxManuel = montant((_b = options === null || options === void 0 ? void 0 : options.tauxManuel) !== null && _b !== void 0 ? _b : '20.00');
79
+ return result;
80
+ }
81
+ /** Crée une adresse postale pour l'API FactPulse. */
82
+ export function adressePostale(ligne1, codePostal, ville, options) {
83
+ var _a;
84
+ const result = { ligneUn: ligne1, codePostal, nomVille: ville, paysCodeIso: (_a = options === null || options === void 0 ? void 0 : options.pays) !== null && _a !== void 0 ? _a : 'FR' };
85
+ if (options === null || options === void 0 ? void 0 : options.ligne2)
86
+ result.ligneDeux = options.ligne2;
87
+ if (options === null || options === void 0 ? void 0 : options.ligne3)
88
+ result.ligneTrois = options.ligne3;
89
+ return result;
90
+ }
91
+ /** Crée une adresse électronique pour l'API FactPulse. schemeId: "0009"=SIREN, "0225"=SIRET */
92
+ export function adresseElectronique(identifiant, schemeId = '0009') {
93
+ return { identifiant, schemeId };
94
+ }
95
+ /** Calcule le numéro TVA intracommunautaire français depuis un SIREN. */
96
+ function calculerTvaIntra(siren) {
97
+ if (siren.length !== 9 || !/^\d+$/.test(siren))
98
+ return null;
99
+ const cle = (12 + 3 * (parseInt(siren, 10) % 97)) % 97;
100
+ return `FR${cle.toString().padStart(2, '0')}${siren}`;
101
+ }
102
+ /** Crée un fournisseur (émetteur) avec auto-calcul SIREN, TVA intracommunautaire et adresses. */
103
+ export function fournisseur(nom, siret, adresseLigne1, codePostal, ville, options) {
104
+ var _a, _b, _c;
105
+ const opts = options !== null && options !== void 0 ? options : {};
106
+ const siren = (_a = opts.siren) !== null && _a !== void 0 ? _a : (siret.length === 14 ? siret.slice(0, 9) : undefined);
107
+ const numeroTvaIntra = (_b = opts.numeroTvaIntra) !== null && _b !== void 0 ? _b : (siren ? calculerTvaIntra(siren) : null);
108
+ const result = {
109
+ nom, idFournisseur: (_c = opts.idFournisseur) !== null && _c !== void 0 ? _c : 0, siret,
110
+ adresseElectronique: adresseElectronique(siret, '0225'),
111
+ adressePostale: adressePostale(adresseLigne1, codePostal, ville, { pays: opts.pays, ligne2: opts.adresseLigne2 }),
112
+ };
113
+ if (siren)
114
+ result.siren = siren;
115
+ if (numeroTvaIntra)
116
+ result.numeroTvaIntra = numeroTvaIntra;
117
+ if (opts.iban)
118
+ result.iban = opts.iban;
119
+ if (opts.codeService)
120
+ result.idServiceFournisseur = opts.codeService;
121
+ if (opts.codeCoordonnesBancaires)
122
+ result.codeCoordonnesBancairesFournisseur = opts.codeCoordonnesBancaires;
123
+ return result;
124
+ }
125
+ /** Crée un destinataire (client) avec auto-calcul SIREN et adresses. */
126
+ export function destinataire(nom, siret, adresseLigne1, codePostal, ville, options) {
127
+ var _a;
128
+ const opts = options !== null && options !== void 0 ? options : {};
129
+ const siren = (_a = opts.siren) !== null && _a !== void 0 ? _a : (siret.length === 14 ? siret.slice(0, 9) : undefined);
130
+ const result = {
131
+ nom, siret,
132
+ adresseElectronique: adresseElectronique(siret, '0225'),
133
+ adressePostale: adressePostale(adresseLigne1, codePostal, ville, { pays: opts.pays, ligne2: opts.adresseLigne2 }),
134
+ };
135
+ if (siren)
136
+ result.siren = siren;
137
+ if (opts.codeServiceExecutant)
138
+ result.codeServiceExecutant = opts.codeServiceExecutant;
139
+ return result;
140
+ }
141
+ /**
142
+ * Crée un bénéficiaire (factor) pour l'affacturage.
143
+ *
144
+ * Le bénéficiaire (BG-10 / PayeeTradeParty) est utilisé lorsque le paiement
145
+ * doit être effectué à un tiers différent du fournisseur, typiquement un
146
+ * factor (société d'affacturage).
147
+ *
148
+ * Pour les factures affacturées, il faut aussi:
149
+ * - Utiliser un type de document affacturé (393, 396, 501, 502, 472, 473)
150
+ * - Ajouter une note ACC avec la mention de subrogation
151
+ * - L'IBAN du bénéficiaire sera utilisé pour le paiement
152
+ *
153
+ * @param nom Raison sociale du factor (BT-59)
154
+ * @param options Options: siret (BT-60), siren (BT-61), iban, bic
155
+ * @returns Dict prêt à être utilisé dans une facture affacturée
156
+ *
157
+ * @example
158
+ * const factor = beneficiaire('FACTOR SAS', {
159
+ * siret: '30000000700033',
160
+ * iban: 'FR76 3000 4000 0500 0012 3456 789',
161
+ * });
162
+ */
163
+ export function beneficiaire(nom, options) {
164
+ var _a;
165
+ const opts = options !== null && options !== void 0 ? options : {};
166
+ // Auto-calcul SIREN depuis SIRET
167
+ const siren = (_a = opts.siren) !== null && _a !== void 0 ? _a : (opts.siret && opts.siret.length === 14 ? opts.siret.slice(0, 9) : undefined);
168
+ const result = { nom };
169
+ if (opts.siret)
170
+ result.siret = opts.siret;
171
+ if (siren)
172
+ result.siren = siren;
173
+ if (opts.iban)
174
+ result.iban = opts.iban;
175
+ if (opts.bic)
176
+ result.bic = opts.bic;
177
+ return result;
178
+ }
179
+ // =============================================================================
180
+ // Client principal
181
+ // =============================================================================
182
+ const DEFAULT_API_URL = 'https://factpulse.fr';
183
+ const DEFAULT_POLLING_INTERVAL = 2000;
184
+ const DEFAULT_POLLING_TIMEOUT = 120000;
185
+ const DEFAULT_MAX_RETRIES = 1;
186
+ export class FactPulseClient {
187
+ constructor(config) {
188
+ var _a;
189
+ this.accessToken = null;
190
+ this.refreshToken = null;
191
+ this.tokenExpiresAt = null;
192
+ this.config = {
193
+ email: config.email, password: config.password,
194
+ apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ''),
195
+ clientUid: config.clientUid || '',
196
+ chorusCredentials: config.chorusCredentials,
197
+ afnorCredentials: config.afnorCredentials,
198
+ pollingInterval: config.pollingInterval || DEFAULT_POLLING_INTERVAL,
199
+ pollingTimeout: config.pollingTimeout || DEFAULT_POLLING_TIMEOUT,
200
+ maxRetries: (_a = config.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_MAX_RETRIES,
201
+ };
202
+ this.chorusCredentials = config.chorusCredentials;
203
+ this.afnorCredentials = config.afnorCredentials;
204
+ this.httpClient = axios.create({ timeout: 30000, headers: { 'Content-Type': 'application/json' } });
205
+ }
206
+ getChorusCredentialsForApi() {
207
+ var _a;
208
+ if (!this.chorusCredentials)
209
+ return undefined;
210
+ return {
211
+ piste_client_id: this.chorusCredentials.pisteClientId,
212
+ piste_client_secret: this.chorusCredentials.pisteClientSecret,
213
+ chorus_pro_login: this.chorusCredentials.chorusProLogin,
214
+ chorus_pro_password: this.chorusCredentials.chorusProPassword,
215
+ sandbox: (_a = this.chorusCredentials.sandbox) !== null && _a !== void 0 ? _a : true,
216
+ };
217
+ }
218
+ getAfnorCredentialsForApi() {
219
+ if (!this.afnorCredentials)
220
+ return undefined;
221
+ return {
222
+ client_id: this.afnorCredentials.clientId,
223
+ client_secret: this.afnorCredentials.clientSecret,
224
+ flow_service_url: this.afnorCredentials.flowServiceUrl,
225
+ };
226
+ }
227
+ // Alias plus courts
228
+ getChorusProCredentials() { return this.getChorusCredentialsForApi(); }
229
+ getAfnorCredentials() { return this.getAfnorCredentialsForApi(); }
230
+ obtainToken() {
231
+ return __awaiter(this, void 0, void 0, function* () {
232
+ var _a, _b;
233
+ const payload = { username: this.config.email, password: this.config.password };
234
+ if (this.config.clientUid)
235
+ payload.client_uid = this.config.clientUid;
236
+ try {
237
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/token/`, payload);
238
+ return response.data;
239
+ }
240
+ catch (error) {
241
+ const axiosError = error;
242
+ throw new FactPulseAuthError(`Impossible d'obtenir le token JWT: ${((_b = (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.detail) || axiosError.message}`);
243
+ }
244
+ });
245
+ }
246
+ ensureAuthenticated() {
247
+ return __awaiter(this, arguments, void 0, function* (forceRefresh = false) {
248
+ const now = Date.now();
249
+ if (forceRefresh || !this.accessToken || (this.tokenExpiresAt && now >= this.tokenExpiresAt)) {
250
+ const tokens = yield this.obtainToken();
251
+ this.accessToken = tokens.access;
252
+ this.refreshToken = tokens.refresh;
253
+ this.tokenExpiresAt = now + 28 * 60 * 1000;
254
+ }
255
+ });
256
+ }
257
+ resetAuth() { this.accessToken = this.refreshToken = null; this.tokenExpiresAt = null; }
258
+ pollTask(taskId, timeout, interval) {
259
+ return __awaiter(this, void 0, void 0, function* () {
260
+ var _a;
261
+ const timeoutMs = timeout !== null && timeout !== void 0 ? timeout : this.config.pollingTimeout;
262
+ const intervalMs = interval !== null && interval !== void 0 ? interval : this.config.pollingInterval;
263
+ const startTime = Date.now();
264
+ let currentInterval = intervalMs;
265
+ while (true) {
266
+ if (Date.now() - startTime > timeoutMs)
267
+ throw new FactPulsePollingTimeout(taskId, timeoutMs);
268
+ yield this.ensureAuthenticated();
269
+ try {
270
+ const response = yield this.httpClient.get(`${this.config.apiUrl}/api/v1/traitement/taches/${taskId}/statut`, {
271
+ headers: { Authorization: `Bearer ${this.accessToken}` },
272
+ });
273
+ const { statut, resultat } = response.data;
274
+ if (statut === 'SUCCESS')
275
+ return resultat || {};
276
+ if (statut === 'FAILURE') {
277
+ // Format AFNOR: errorMessage, details
278
+ const result = resultat;
279
+ const errors = Array.isArray(result === null || result === void 0 ? void 0 : result.details) ? result.details.filter((e) => typeof e === 'object' && e !== null) : [];
280
+ throw new FactPulseValidationError(`La tâche ${taskId} a échoué: ${(result === null || result === void 0 ? void 0 : result.errorMessage) || 'Erreur inconnue'}`, errors);
281
+ }
282
+ yield new Promise(resolve => setTimeout(resolve, currentInterval));
283
+ currentInterval = Math.min(currentInterval * 1.5, 10000);
284
+ }
285
+ catch (error) {
286
+ if (error instanceof FactPulseValidationError || error instanceof FactPulsePollingTimeout)
287
+ throw error;
288
+ const axiosError = error;
289
+ if (((_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status) === 401) {
290
+ this.resetAuth();
291
+ continue;
292
+ }
293
+ throw new FactPulseValidationError(`Erreur API: ${axiosError.message}`);
294
+ }
295
+ }
296
+ });
297
+ }
298
+ genererFacturx(factureData_1, pdfPath_1) {
299
+ return __awaiter(this, arguments, void 0, function* (factureData, pdfPath, profil = 'EN16931', formatSortie = 'pdf', sync = true, timeout) {
300
+ var _a, _b, _c, _d;
301
+ const jsonData = typeof factureData === 'string' ? factureData : JSON.stringify(factureData);
302
+ let taskId = null;
303
+ for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
304
+ yield this.ensureAuthenticated();
305
+ const form = new FormData();
306
+ form.append('donnees_facture', jsonData);
307
+ form.append('profil', profil);
308
+ form.append('format_sortie', formatSortie);
309
+ form.append('source_pdf', fs.createReadStream(pdfPath), { filename: path.basename(pdfPath), contentType: 'application/pdf' });
310
+ try {
311
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/traitement/generer-facture`, form, {
312
+ headers: Object.assign(Object.assign({}, form.getHeaders()), { Authorization: `Bearer ${this.accessToken}` }), timeout: 60000,
313
+ });
314
+ taskId = response.data.id_tache;
315
+ break;
316
+ }
317
+ catch (error) {
318
+ const axiosError = error;
319
+ if (((_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status) === 401 && attempt < this.config.maxRetries) {
320
+ this.resetAuth();
321
+ continue;
322
+ }
323
+ // Extraire les détails d'erreur du corps de la réponse
324
+ const responseData = (_b = axiosError.response) === null || _b === void 0 ? void 0 : _b.data;
325
+ let errorMsg = `Erreur API (${((_c = axiosError.response) === null || _c === void 0 ? void 0 : _c.status) || 'unknown'}): ${axiosError.message}`;
326
+ const errors = [];
327
+ if (responseData) {
328
+ // Format FastAPI/Pydantic: {"detail": [{"loc": [...], "msg": "...", "type": "..."}]}
329
+ if (Array.isArray(responseData.detail)) {
330
+ errorMsg = 'Erreur de validation';
331
+ for (const err of responseData.detail) {
332
+ if (typeof err === 'object' && err !== null) {
333
+ const loc = err.loc || [];
334
+ errors.push({
335
+ level: 'ERROR',
336
+ item: loc.map(String).join(' -> '),
337
+ reason: err.msg || String(err),
338
+ source: 'validation',
339
+ code: err.type,
340
+ });
341
+ }
342
+ }
343
+ }
344
+ else if (typeof responseData.detail === 'string') {
345
+ errorMsg = responseData.detail;
346
+ }
347
+ else if (responseData.errorMessage) {
348
+ errorMsg = responseData.errorMessage;
349
+ }
350
+ }
351
+ console.error(`Erreur API ${(_d = axiosError.response) === null || _d === void 0 ? void 0 : _d.status}:`, responseData);
352
+ throw new FactPulseValidationError(errorMsg, errors);
353
+ }
354
+ }
355
+ if (!taskId)
356
+ throw new FactPulseValidationError("Pas d'ID de tâche");
357
+ if (!sync)
358
+ return taskId;
359
+ const result = yield this.pollTask(taskId, timeout);
360
+ if (result.contenu_b64)
361
+ return Buffer.from(result.contenu_b64, 'base64');
362
+ throw new FactPulseValidationError('Pas de contenu');
363
+ });
364
+ }
365
+ static formatMontant(m) {
366
+ if (m === null || m === undefined)
367
+ return '0.00';
368
+ if (typeof m === 'number')
369
+ return m.toFixed(2);
370
+ if (typeof m === 'string')
371
+ return m;
372
+ return '0.00';
373
+ }
374
+ // =========================================================================
375
+ // AFNOR - Authentication et helpers internes
376
+ // =========================================================================
377
+ /**
378
+ * Recupere les credentials AFNOR (mode stored ou zero-trust).
379
+ * Mode zero-trust: Retourne les afnorCredentials fournis au constructeur.
380
+ * Mode stored: Recupere les credentials via GET /api/v1/afnor/credentials.
381
+ */
382
+ getAfnorCredentialsInternal() {
383
+ return __awaiter(this, void 0, void 0, function* () {
384
+ var _a, _b;
385
+ // Mode zero-trust : credentials fournis au constructeur
386
+ if (this.afnorCredentials) {
387
+ return this.afnorCredentials;
388
+ }
389
+ // Mode stored : recuperer les credentials via l'API
390
+ yield this.ensureAuthenticated();
391
+ try {
392
+ const response = yield this.httpClient.get(`${this.config.apiUrl}/api/v1/afnor/credentials`, {
393
+ headers: { Authorization: `Bearer ${this.accessToken}` },
394
+ });
395
+ const creds = response.data;
396
+ return {
397
+ flowServiceUrl: creds.flow_service_url,
398
+ tokenUrl: creds.token_url,
399
+ clientId: creds.client_id,
400
+ clientSecret: creds.client_secret,
401
+ directoryServiceUrl: creds.directory_service_url,
402
+ };
403
+ }
404
+ catch (error) {
405
+ const axiosError = error;
406
+ if (((_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status) === 400) {
407
+ const detail = (_b = axiosError.response.data) === null || _b === void 0 ? void 0 : _b.detail;
408
+ if (typeof detail === 'object' && (detail === null || detail === void 0 ? void 0 : detail.error) === 'NO_CLIENT_UID') {
409
+ throw new FactPulseAuthError("Aucun client_uid dans le JWT. Pour utiliser les endpoints AFNOR, soit:\n" +
410
+ "1. Generez un token avec un client_uid (mode stored)\n" +
411
+ "2. Fournissez AFNORCredentials au constructeur du client (mode zero-trust)");
412
+ }
413
+ }
414
+ throw new FactPulseAuthError(`Echec recuperation credentials AFNOR: ${axiosError.message}`);
415
+ }
416
+ });
417
+ }
418
+ /**
419
+ * Obtient le token OAuth2 AFNOR et l'URL de la PDP.
420
+ * Cette methode:
421
+ * 1. Recupere les credentials AFNOR (mode stored ou zero-trust)
422
+ * 2. Fait l'OAuth AFNOR pour obtenir un token
423
+ * 3. Retourne le token et l'URL de la PDP
424
+ */
425
+ getAfnorTokenAndUrl() {
426
+ return __awaiter(this, void 0, void 0, function* () {
427
+ // Etape 1: Obtenir les credentials AFNOR
428
+ const credentials = yield this.getAfnorCredentialsInternal();
429
+ // Etape 2: Faire l'OAuth AFNOR via le proxy FactPulse
430
+ const oauthData = new URLSearchParams({
431
+ grant_type: 'client_credentials',
432
+ client_id: credentials.clientId,
433
+ client_secret: credentials.clientSecret,
434
+ });
435
+ try {
436
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/afnor/oauth/token`, oauthData.toString(), {
437
+ headers: {
438
+ 'Content-Type': 'application/x-www-form-urlencoded',
439
+ 'X-PDP-Token-URL': credentials.tokenUrl,
440
+ },
441
+ });
442
+ const tokenData = response.data;
443
+ if (!tokenData.access_token) {
444
+ throw new FactPulseAuthError('Reponse OAuth2 AFNOR invalide: access_token manquant');
445
+ }
446
+ return {
447
+ token: tokenData.access_token,
448
+ pdpBaseUrl: credentials.flowServiceUrl,
449
+ };
450
+ }
451
+ catch (error) {
452
+ const axiosError = error;
453
+ throw new FactPulseAuthError(`Echec OAuth2 AFNOR: ${axiosError.message}`);
454
+ }
455
+ });
456
+ }
457
+ /**
458
+ * Effectue une requete vers l'API AFNOR avec gestion d'auth et d'erreurs.
459
+ * IMPORTANT: Cette methode utilise le token OAuth AFNOR, PAS le JWT FactPulse!
460
+ */
461
+ makeAfnorRequest(method, endpoint, options) {
462
+ return __awaiter(this, void 0, void 0, function* () {
463
+ var _a, _b, _c, _d;
464
+ // Obtenir le token AFNOR et l'URL de la PDP
465
+ const { token: afnorToken, pdpBaseUrl } = yield this.getAfnorTokenAndUrl();
466
+ const url = `${this.config.apiUrl}/api/v1/afnor${endpoint}`;
467
+ // TOUJOURS utiliser le token AFNOR + header X-PDP-Base-URL
468
+ const headers = {
469
+ 'Authorization': `Bearer ${afnorToken}`,
470
+ 'X-PDP-Base-URL': pdpBaseUrl,
471
+ };
472
+ try {
473
+ let response;
474
+ if (options === null || options === void 0 ? void 0 : options.files) {
475
+ response = yield this.httpClient.request({
476
+ method,
477
+ url,
478
+ data: options.files,
479
+ headers: Object.assign(Object.assign({}, options.files.getHeaders()), headers),
480
+ params: options === null || options === void 0 ? void 0 : options.params,
481
+ timeout: 60000,
482
+ });
483
+ }
484
+ else {
485
+ response = yield this.httpClient.request({
486
+ method,
487
+ url,
488
+ data: options === null || options === void 0 ? void 0 : options.data,
489
+ headers: Object.assign(Object.assign({}, headers), { 'Content-Type': 'application/json' }),
490
+ params: options === null || options === void 0 ? void 0 : options.params,
491
+ timeout: 30000,
492
+ });
493
+ }
494
+ return response.data;
495
+ }
496
+ catch (error) {
497
+ const axiosError = error;
498
+ const errorMsg = ((_b = (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.errorMessage) ||
499
+ ((_d = (_c = axiosError.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.detail) ||
500
+ axiosError.message;
501
+ throw new FactPulseValidationError(`Erreur AFNOR: ${errorMsg}`);
502
+ }
503
+ });
504
+ }
505
+ // ==================== AFNOR Directory ====================
506
+ rechercherSiretAfnor(siret) {
507
+ return __awaiter(this, void 0, void 0, function* () {
508
+ return this.makeAfnorRequest('GET', `/directory/siret/${siret}`);
509
+ });
510
+ }
511
+ rechercherSirenAfnor(siren) {
512
+ return __awaiter(this, void 0, void 0, function* () {
513
+ return this.makeAfnorRequest('GET', `/directory/siren/${siren}`);
514
+ });
515
+ }
516
+ listerCodesRoutageAfnor(siren) {
517
+ return __awaiter(this, void 0, void 0, function* () {
518
+ return this.makeAfnorRequest('GET', `/directory/siren/${siren}/routing-codes`);
519
+ });
520
+ }
521
+ // ==================== AFNOR Flow ====================
522
+ /**
523
+ * Soumet une facture a une PDP via l'API AFNOR.
524
+ * L'authentification utilise le token OAuth AFNOR (obtenu automatiquement),
525
+ * soit via les credentials stockes (mode stored), soit via les afnorCredentials
526
+ * fournis au constructeur (mode zero-trust).
527
+ *
528
+ * @param pdfBuffer Buffer du PDF Factur-X a soumettre
529
+ * @param flowName Nom du flux (ex: "Facture FAC-2025-001")
530
+ * @param options Options: trackingId, flowSyntax (CII/UBL), flowProfile
531
+ */
532
+ soumettreFactureAfnor(pdfBuffer_1, flowName_1) {
533
+ return __awaiter(this, arguments, void 0, function* (pdfBuffer, flowName, options = {}) {
534
+ const { trackingId, flowSyntax = 'CII', flowProfile = 'EN16931' } = options;
535
+ // Calculer SHA-256
536
+ const crypto = require('crypto');
537
+ const sha256 = crypto.createHash('sha256').update(pdfBuffer).digest('hex');
538
+ // Preparer flowInfo
539
+ const flowInfo = { name: flowName, flowSyntax, flowProfile, sha256 };
540
+ if (trackingId)
541
+ flowInfo.trackingId = trackingId;
542
+ const form = new FormData();
543
+ form.append('file', pdfBuffer, { filename: 'facture.pdf', contentType: 'application/pdf' });
544
+ form.append('flowInfo', JSON.stringify(flowInfo), { contentType: 'application/json' });
545
+ return this.makeAfnorRequest('POST', '/flow/v1/flows', { files: form });
546
+ });
547
+ }
548
+ rechercherFluxAfnor() {
549
+ return __awaiter(this, arguments, void 0, function* (criteria = {}) {
550
+ var _a, _b;
551
+ const searchBody = {
552
+ offset: (_a = criteria.offset) !== null && _a !== void 0 ? _a : 0,
553
+ limit: (_b = criteria.limit) !== null && _b !== void 0 ? _b : 25,
554
+ where: {},
555
+ };
556
+ if (criteria.trackingId)
557
+ searchBody.where.trackingId = criteria.trackingId;
558
+ if (criteria.status)
559
+ searchBody.where.status = criteria.status;
560
+ return this.makeAfnorRequest('POST', '/flow/v1/flows/search', { data: searchBody });
561
+ });
562
+ }
563
+ telechargerFluxAfnor(flowId) {
564
+ return __awaiter(this, void 0, void 0, function* () {
565
+ // Pour le telechargement, on doit gerer le type de reponse differemment
566
+ const { token: afnorToken, pdpBaseUrl } = yield this.getAfnorTokenAndUrl();
567
+ const url = `${this.config.apiUrl}/api/v1/afnor/flow/v1/flows/${flowId}`;
568
+ const response = yield this.httpClient.get(url, {
569
+ headers: {
570
+ 'Authorization': `Bearer ${afnorToken}`,
571
+ 'X-PDP-Base-URL': pdpBaseUrl,
572
+ },
573
+ responseType: 'arraybuffer',
574
+ });
575
+ return Buffer.from(response.data);
576
+ });
577
+ }
578
+ /**
579
+ * Récupère les métadonnées JSON d'un flux entrant (facture fournisseur).
580
+ * Télécharge un flux entrant depuis la PDP AFNOR et extrait les métadonnées
581
+ * de la facture vers un format JSON unifié. Supporte Factur-X, CII et UBL.
582
+ *
583
+ * Note: Cet endpoint utilise l'authentification JWT FactPulse (pas OAuth AFNOR).
584
+ * Le serveur FactPulse se charge d'appeler la PDP avec les credentials stockés.
585
+ *
586
+ * @param flowId Identifiant du flux (UUID)
587
+ * @param includeDocument Si true, inclut le document original encodé en base64
588
+ * @returns Métadonnées de la facture (fournisseur, montants, dates, etc.)
589
+ *
590
+ * @example
591
+ * const facture = await client.obtenirFactureEntranteAfnor("550e8400-...");
592
+ * console.log(`Fournisseur: ${facture.fournisseur.nom}`);
593
+ * console.log(`Montant TTC: ${facture.montant_ttc} ${facture.devise}`);
594
+ */
595
+ obtenirFactureEntranteAfnor(flowId_1) {
596
+ return __awaiter(this, arguments, void 0, function* (flowId, includeDocument = false) {
597
+ var _a, _b;
598
+ yield this.ensureAuthenticated();
599
+ const url = `${this.config.apiUrl}/api/v1/afnor/flux-entrants/${flowId}`;
600
+ const params = {};
601
+ if (includeDocument) {
602
+ params.include_document = 'true';
603
+ }
604
+ try {
605
+ const response = yield this.httpClient.get(url, {
606
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
607
+ params: Object.keys(params).length > 0 ? params : undefined,
608
+ timeout: 60000,
609
+ });
610
+ return response.data;
611
+ }
612
+ catch (error) {
613
+ const axiosError = error;
614
+ throw new FactPulseValidationError(`Erreur flux entrant: ${((_b = (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.detail) || axiosError.message}`);
615
+ }
616
+ });
617
+ }
618
+ healthcheckAfnor() {
619
+ return __awaiter(this, void 0, void 0, function* () {
620
+ return this.makeAfnorRequest('GET', '/flow/v1/healthcheck');
621
+ });
622
+ }
623
+ // ==================== Chorus Pro ====================
624
+ rechercherStructureChorus(criteria) {
625
+ return __awaiter(this, void 0, void 0, function* () {
626
+ yield this.ensureAuthenticated();
627
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/chorus-pro/structures/rechercher`, criteria, {
628
+ headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json' },
629
+ });
630
+ return response.data;
631
+ });
632
+ }
633
+ consulterStructureChorus(idStructureCpp) {
634
+ return __awaiter(this, void 0, void 0, function* () {
635
+ yield this.ensureAuthenticated();
636
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/chorus-pro/structures/consulter`, { id_structure_cpp: idStructureCpp }, {
637
+ headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json' },
638
+ });
639
+ return response.data;
640
+ });
641
+ }
642
+ /**
643
+ * Liste les services d'une structure Chorus Pro.
644
+ * @param idStructureCpp ID Chorus Pro de la structure
645
+ * @returns Objet avec listeServices, total, codeRetour, libelle
646
+ */
647
+ listerServicesStructureChorus(idStructureCpp) {
648
+ return __awaiter(this, void 0, void 0, function* () {
649
+ yield this.ensureAuthenticated();
650
+ const response = yield this.httpClient.get(`${this.config.apiUrl}/api/v1/chorus-pro/structures/${idStructureCpp}/services`, {
651
+ headers: { Authorization: `Bearer ${this.accessToken}` },
652
+ });
653
+ return response.data;
654
+ });
655
+ }
656
+ obtenirIdChorusDepuisSiret(siret) {
657
+ return __awaiter(this, void 0, void 0, function* () {
658
+ const results = yield this.rechercherStructureChorus({ identifiant_structure: siret, type_identifiant: 'SIRET' });
659
+ if (results.length > 0 && results[0].id_structure_cpp)
660
+ return results[0].id_structure_cpp;
661
+ return null;
662
+ });
663
+ }
664
+ soumettreFactureChorus(factureData) {
665
+ return __awaiter(this, void 0, void 0, function* () {
666
+ yield this.ensureAuthenticated();
667
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/chorus/factures/soumettre`, factureData, {
668
+ headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json' },
669
+ });
670
+ return response.data;
671
+ });
672
+ }
673
+ consulterFactureChorus(identifiantFactureCpp) {
674
+ return __awaiter(this, void 0, void 0, function* () {
675
+ yield this.ensureAuthenticated();
676
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/chorus/factures/consulter`, { identifiant_facture_cpp: identifiantFactureCpp }, {
677
+ headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json' },
678
+ });
679
+ return response.data;
680
+ });
681
+ }
682
+ // ==================== Validation ====================
683
+ /**
684
+ * Valide un PDF Factur-X.
685
+ * @param pdfBuffer - Contenu du PDF en Buffer
686
+ * @param options - Options de validation
687
+ * @param options.profil - Profil Factur-X (MINIMUM, BASIC, EN16931, EXTENDED). Si non spécifié, auto-détecté.
688
+ * @param options.useVerapdf - Active la validation stricte PDF/A avec VeraPDF (défaut: false)
689
+ */
690
+ validerPdfFacturx(pdfBuffer_1) {
691
+ return __awaiter(this, arguments, void 0, function* (pdfBuffer, options = {}) {
692
+ var _a;
693
+ yield this.ensureAuthenticated();
694
+ const form = new FormData();
695
+ form.append('fichier_pdf', pdfBuffer, { filename: 'facture.pdf', contentType: 'application/pdf' });
696
+ if (options.profil) {
697
+ form.append('profil', options.profil);
698
+ }
699
+ form.append('use_verapdf', String((_a = options.useVerapdf) !== null && _a !== void 0 ? _a : false));
700
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/traitement/valider-pdf-facturx`, form, {
701
+ headers: Object.assign(Object.assign({}, form.getHeaders()), { Authorization: `Bearer ${this.accessToken}` }),
702
+ });
703
+ return response.data;
704
+ });
705
+ }
706
+ validerXmlFacturx(xmlContent_1) {
707
+ return __awaiter(this, arguments, void 0, function* (xmlContent, profil = 'EN16931') {
708
+ yield this.ensureAuthenticated();
709
+ const form = new FormData();
710
+ form.append('fichier_xml', Buffer.from(xmlContent, 'utf-8'), { filename: 'facture.xml', contentType: 'application/xml' });
711
+ form.append('profil', profil);
712
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/traitement/valider-xml`, form, {
713
+ headers: Object.assign(Object.assign({}, form.getHeaders()), { Authorization: `Bearer ${this.accessToken}` }),
714
+ });
715
+ return response.data;
716
+ });
717
+ }
718
+ validerSignaturePdf(pdfBuffer) {
719
+ return __awaiter(this, void 0, void 0, function* () {
720
+ yield this.ensureAuthenticated();
721
+ const form = new FormData();
722
+ form.append('fichier_pdf', pdfBuffer, { filename: 'document.pdf', contentType: 'application/pdf' });
723
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/traitement/valider-signature-pdf`, form, {
724
+ headers: Object.assign(Object.assign({}, form.getHeaders()), { Authorization: `Bearer ${this.accessToken}` }),
725
+ });
726
+ return response.data;
727
+ });
728
+ }
729
+ // ==================== Signature ====================
730
+ /**
731
+ * Signe un PDF avec le certificat configuré côté serveur (via client_uid du JWT).
732
+ * Le certificat doit être préalablement configuré dans Django Admin.
733
+ */
734
+ signerPdf(pdfBuffer_1) {
735
+ return __awaiter(this, arguments, void 0, function* (pdfBuffer, options = {}) {
736
+ yield this.ensureAuthenticated();
737
+ const form = new FormData();
738
+ form.append('fichier_pdf', pdfBuffer, { filename: 'document.pdf', contentType: 'application/pdf' });
739
+ if (options.raison)
740
+ form.append('raison', options.raison);
741
+ if (options.localisation)
742
+ form.append('localisation', options.localisation);
743
+ if (options.contact)
744
+ form.append('contact', options.contact);
745
+ if (options.usePadesLt !== undefined)
746
+ form.append('use_pades_lt', String(options.usePadesLt));
747
+ if (options.useTimestamp !== undefined)
748
+ form.append('use_timestamp', String(options.useTimestamp));
749
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/traitement/signer-pdf`, form, {
750
+ headers: Object.assign(Object.assign({}, form.getHeaders()), { Authorization: `Bearer ${this.accessToken}` }),
751
+ });
752
+ // L'API retourne du JSON avec pdf_signe_base64
753
+ const data = response.data;
754
+ if (data.pdf_signe_base64) {
755
+ return Buffer.from(data.pdf_signe_base64, 'base64');
756
+ }
757
+ throw new Error('Réponse de signature invalide');
758
+ });
759
+ }
760
+ /**
761
+ * Génère un certificat de test (NON PRODUCTION).
762
+ * Le certificat doit ensuite être configuré dans Django Admin.
763
+ */
764
+ genererCertificatTest() {
765
+ return __awaiter(this, arguments, void 0, function* (options = {}) {
766
+ yield this.ensureAuthenticated();
767
+ const response = yield this.httpClient.post(`${this.config.apiUrl}/api/v1/traitement/generer-certificat-test`, {
768
+ cn: options.cn || 'Test Organisation',
769
+ organisation: options.organisation || 'Test Organisation',
770
+ email: options.email || 'test@example.com',
771
+ duree_jours: options.dureeJours || 365,
772
+ taille_cle: options.tailleClé || 2048,
773
+ }, {
774
+ headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json' },
775
+ });
776
+ return response.data;
777
+ });
778
+ }
779
+ // ==================== Workflow complet ====================
780
+ /**
781
+ * Workflow complet : génération + validation + signature + soumission AFNOR.
782
+ * Note: La signature utilise le certificat configuré côté serveur (via client_uid du JWT).
783
+ * @param factureData Données de la facture
784
+ * @param pdfPath Chemin vers le PDF source
785
+ * @param options Options du workflow
786
+ * @returns Résultat avec pdfBuffer, validation, signature et afnor
787
+ */
788
+ genererFacturxComplet(factureData_1, pdfPath_1) {
789
+ return __awaiter(this, arguments, void 0, function* (factureData, pdfPath, options = {}) {
790
+ const { profil = 'EN16931', valider = true, signer = false, soumettreAfnor = false, afnorFlowName, afnorTrackingId, timeout, } = options;
791
+ const result = { pdfBuffer: Buffer.alloc(0) };
792
+ // 1. Génération
793
+ const pdfBuffer = yield this.genererFacturx(factureData, pdfPath, profil, 'pdf', true, timeout);
794
+ result.pdfBuffer = pdfBuffer;
795
+ // 2. Validation
796
+ if (valider) {
797
+ const validation = yield this.validerPdfFacturx(pdfBuffer, { profil });
798
+ result.validation = validation;
799
+ }
800
+ // 3. Signature (utilise le certificat configuré côté serveur)
801
+ if (signer) {
802
+ const signedPdf = yield this.signerPdf(result.pdfBuffer);
803
+ result.pdfBuffer = signedPdf;
804
+ result.signature = { signe: true };
805
+ }
806
+ // 4. Soumission AFNOR
807
+ if (soumettreAfnor) {
808
+ const numeroFacture = (factureData.numeroFacture || factureData.numero_facture || 'FACTURE');
809
+ const flowName = afnorFlowName || `Facture ${numeroFacture}`;
810
+ const trackingId = afnorTrackingId || numeroFacture;
811
+ const afnorResult = yield this.soumettreFactureAfnor(result.pdfBuffer, flowName, { trackingId });
812
+ result.afnor = afnorResult;
813
+ }
814
+ return result;
815
+ });
816
+ }
817
+ }