factpulse 1.0.0 → 1.0.8

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 (194) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +3 -3
  3. data/Gemfile.lock +1 -1
  4. data/README.md +73 -119
  5. data/docs/AFNORPDPPADirectoryServiceApi.md +31 -1148
  6. data/docs/BodyAjouterFichierApiV1ChorusProTransversesAjouterFichierPost.md +22 -0
  7. data/docs/BodyCompleterFactureApiV1ChorusProFacturesCompleterPost.md +22 -0
  8. data/docs/BodyListerServicesStructureApiV1ChorusProStructuresIdStructureCppServicesGet.md +20 -0
  9. data/docs/BodyRechercherFacturesDestinataireApiV1ChorusProFacturesRechercherDestinatairePost.md +22 -0
  10. data/docs/BodyRechercherFacturesFournisseurApiV1ChorusProFacturesRechercherFournisseurPost.md +22 -0
  11. data/docs/BodyRecyclerFactureApiV1ChorusProFacturesRecyclerPost.md +22 -0
  12. data/docs/BodyTelechargerGroupeFacturesApiV1ChorusProFacturesTelechargerGroupePost.md +22 -0
  13. data/docs/BodyTraiterFactureRecueApiV1ChorusProFacturesTraiterFactureRecuePost.md +22 -0
  14. data/docs/BodyValideurConsulterFactureApiV1ChorusProFacturesValideurConsulterPost.md +22 -0
  15. data/docs/BodyValideurRechercherFacturesApiV1ChorusProFacturesValideurRechercherPost.md +22 -0
  16. data/docs/BodyValideurTraiterFactureApiV1ChorusProFacturesValideurTraiterPost.md +22 -0
  17. data/docs/ChorusProApi.md +70 -66
  18. data/docs/Destinataire.md +0 -4
  19. data/docs/{MontantAPayer.md → DirectionFlux.md} +2 -2
  20. data/docs/FactureEnrichieInfoInput.md +32 -0
  21. data/docs/{FactureEnrichieInfo.md → FactureEnrichieInfoOutput.md} +2 -2
  22. data/docs/FactureFacturX.md +0 -2
  23. data/docs/FluxResume.md +32 -0
  24. data/docs/Fournisseur.md +0 -2
  25. data/docs/LigneDePoste.md +2 -2
  26. data/docs/LigneDePosteMontantTotalLigneHt.md +15 -0
  27. data/docs/LigneDeTVA.md +2 -2
  28. data/docs/MontantTotal.md +5 -5
  29. data/docs/MontantTotalMontantRemiseGlobaleTtc.md +15 -0
  30. data/docs/{MontantBaseHt.md → Montantapayer.md} +2 -2
  31. data/docs/Montantbaseht.md +15 -0
  32. data/docs/Montanthttotal.md +15 -0
  33. data/docs/Montantttctotal.md +15 -0
  34. data/docs/{ErrorLevel.md → Montanttva.md} +2 -2
  35. data/docs/{ErrorSource.md → Montanttva1.md} +2 -2
  36. data/docs/Montantunitaireht.md +15 -0
  37. data/docs/OptionsProcessing.md +1 -1
  38. data/docs/PDPCredentials.md +24 -0
  39. data/docs/ProcessingEndpointsUnifisApi.md +147 -0
  40. data/docs/{StatutCelery.md → ProfilFlux.md} +2 -2
  41. data/docs/QuotaInfo.md +26 -0
  42. data/docs/ReponseHealthcheckAFNOR.md +22 -0
  43. data/docs/ReponseRechercheFlux.md +24 -0
  44. data/docs/ReponseSoumissionFlux.md +30 -0
  45. data/docs/RequeteRechercheFlux.md +34 -0
  46. data/docs/RequeteSoumissionFlux.md +28 -0
  47. data/docs/SantApi.md +0 -62
  48. data/docs/SignatureLectroniqueApi.md +315 -0
  49. data/docs/SoumettreFactureCompleteResponse.md +1 -1
  50. data/docs/SoumettreFactureRequest.md +3 -3
  51. data/docs/StatutAcquittement.md +15 -0
  52. data/docs/StatutTache.md +2 -2
  53. data/docs/SyntaxeFlux.md +15 -0
  54. data/docs/TraitementFactureApi.md +2 -2
  55. data/docs/TypeFlux.md +15 -0
  56. data/docs/Utilisateur.md +40 -0
  57. data/factpulse.gemspec +2 -2
  58. data/lib/factpulse/api/afnorpdppa_api.rb +1 -1
  59. data/lib/factpulse/api/afnorpdppa_directory_service_api.rb +30 -1014
  60. data/lib/factpulse/api/afnorpdppa_flow_service_api.rb +1 -1
  61. data/lib/factpulse/api/chorus_pro_api.rb +108 -95
  62. data/lib/factpulse/api/processing_endpoints_unifis_api.rb +158 -0
  63. data/lib/factpulse/api/sant_api.rb +1 -58
  64. data/lib/factpulse/api/signature_lectronique_api.rb +333 -0
  65. data/lib/factpulse/api/traitement_facture_api.rb +5 -5
  66. data/lib/factpulse/api/utilisateur_api.rb +1 -1
  67. data/lib/factpulse/api_client.rb +3 -7
  68. data/lib/factpulse/api_error.rb +1 -1
  69. data/lib/factpulse/api_model_base.rb +1 -1
  70. data/lib/factpulse/configuration.rb +1 -1
  71. data/lib/factpulse/models/adresse_electronique.rb +1 -1
  72. data/lib/factpulse/models/adresse_postale.rb +1 -1
  73. data/lib/factpulse/models/body_ajouter_fichier_api_v1_chorus_pro_transverses_ajouter_fichier_post.rb +202 -0
  74. data/lib/factpulse/models/body_completer_facture_api_v1_chorus_pro_factures_completer_post.rb +202 -0
  75. data/lib/factpulse/models/body_lister_services_structure_api_v1_chorus_pro_structures_id_structure_cpp_services_get.rb +174 -0
  76. data/lib/factpulse/models/body_rechercher_factures_destinataire_api_v1_chorus_pro_factures_rechercher_destinataire_post.rb +202 -0
  77. data/lib/factpulse/models/body_rechercher_factures_fournisseur_api_v1_chorus_pro_factures_rechercher_fournisseur_post.rb +202 -0
  78. data/lib/factpulse/models/body_recycler_facture_api_v1_chorus_pro_factures_recycler_post.rb +202 -0
  79. data/lib/factpulse/models/{api_error.rb → body_telecharger_groupe_factures_api_v1_chorus_pro_factures_telecharger_groupe_post.rb} +44 -47
  80. data/lib/factpulse/models/{note.rb → body_traiter_facture_recue_api_v1_chorus_pro_factures_traiter_facture_recue_post.rb} +55 -28
  81. data/lib/factpulse/models/body_valideur_consulter_facture_api_v1_chorus_pro_factures_valideur_consulter_post.rb +202 -0
  82. data/lib/factpulse/models/body_valideur_rechercher_factures_api_v1_chorus_pro_factures_valideur_rechercher_post.rb +202 -0
  83. data/lib/factpulse/models/body_valideur_traiter_facture_api_v1_chorus_pro_factures_valideur_traiter_post.rb +202 -0
  84. data/lib/factpulse/models/cadre_de_facturation.rb +1 -1
  85. data/lib/factpulse/models/categorie_tva.rb +11 -11
  86. data/lib/factpulse/models/certificate_info_response.rb +1 -1
  87. data/lib/factpulse/models/chorus_pro_credentials.rb +1 -1
  88. data/lib/factpulse/models/code_cadre_facturation.rb +1 -1
  89. data/lib/factpulse/models/code_raison_reduction.rb +9 -9
  90. data/lib/factpulse/models/consulter_facture_request.rb +1 -1
  91. data/lib/factpulse/models/consulter_facture_response.rb +1 -1
  92. data/lib/factpulse/models/consulter_structure_request.rb +1 -1
  93. data/lib/factpulse/models/consulter_structure_response.rb +1 -1
  94. data/lib/factpulse/models/credentials_afnor.rb +1 -1
  95. data/lib/factpulse/models/credentials_chorus_pro.rb +1 -1
  96. data/lib/factpulse/models/destinataire.rb +2 -22
  97. data/lib/factpulse/models/destination.rb +1 -1
  98. data/lib/factpulse/models/destination_afnor.rb +1 -1
  99. data/lib/factpulse/models/destination_chorus_pro.rb +1 -1
  100. data/lib/factpulse/models/{statut_celery.rb → direction_flux.rb} +7 -10
  101. data/lib/factpulse/models/donnees_facture_simplifiees.rb +1 -1
  102. data/lib/factpulse/models/facture_enrichie_info_input.rb +315 -0
  103. data/lib/factpulse/models/{facture_enrichie_info.rb → facture_enrichie_info_output.rb} +4 -4
  104. data/lib/factpulse/models/facture_factur_x.rb +2 -13
  105. data/lib/factpulse/models/flux_resume.rb +251 -0
  106. data/lib/factpulse/models/format_sortie.rb +1 -1
  107. data/lib/factpulse/models/fournisseur.rb +2 -12
  108. data/lib/factpulse/models/generate_certificate_request.rb +1 -1
  109. data/lib/factpulse/models/generate_certificate_response.rb +1 -1
  110. data/lib/factpulse/models/http_validation_error.rb +1 -1
  111. data/lib/factpulse/models/information_signature_api.rb +1 -1
  112. data/lib/factpulse/models/ligne_de_poste.rb +4 -3
  113. data/lib/factpulse/models/ligne_de_poste_montant_remise_ht.rb +2 -2
  114. data/lib/factpulse/models/{montant_total_ligne_ht.rb → ligne_de_poste_montant_total_ligne_ht.rb} +3 -3
  115. data/lib/factpulse/models/ligne_de_poste_taux_tva_manuel.rb +2 -2
  116. data/lib/factpulse/models/ligne_de_tva.rb +3 -3
  117. data/lib/factpulse/models/mode_depot.rb +1 -1
  118. data/lib/factpulse/models/mode_paiement.rb +1 -1
  119. data/lib/factpulse/models/montant_ht_total.rb +1 -2
  120. data/lib/factpulse/models/montant_total.rb +7 -6
  121. data/lib/factpulse/models/montant_total_acompte.rb +2 -2
  122. data/lib/factpulse/models/{montant_a_payer.rb → montant_total_montant_remise_globale_ttc.rb} +3 -3
  123. data/lib/factpulse/models/montant_ttc_total.rb +1 -2
  124. data/lib/factpulse/models/montant_tva.rb +1 -2
  125. data/lib/factpulse/models/{montant_tva_total.rb → montantapayer.rb} +3 -3
  126. data/lib/factpulse/models/{montant_tva_ligne.rb → montantbaseht.rb} +3 -3
  127. data/lib/factpulse/models/montanthttotal.rb +104 -0
  128. data/lib/factpulse/models/montantttctotal.rb +104 -0
  129. data/lib/factpulse/models/montanttva.rb +104 -0
  130. data/lib/factpulse/models/montanttva1.rb +104 -0
  131. data/lib/factpulse/models/{montant_unitaire_ht.rb → montantunitaireht.rb} +2 -2
  132. data/lib/factpulse/models/obtenir_id_chorus_pro_request.rb +1 -1
  133. data/lib/factpulse/models/obtenir_id_chorus_pro_response.rb +1 -1
  134. data/lib/factpulse/models/options_processing.rb +16 -2
  135. data/lib/factpulse/models/parametres_signature.rb +1 -1
  136. data/lib/factpulse/models/parametres_structure.rb +1 -1
  137. data/lib/factpulse/models/pdf_factur_x_info.rb +1 -1
  138. data/lib/factpulse/models/pdp_credentials.rb +247 -0
  139. data/lib/factpulse/models/piece_jointe_complementaire.rb +1 -1
  140. data/lib/factpulse/models/profil_api.rb +1 -1
  141. data/lib/factpulse/models/profil_flux.rb +41 -0
  142. data/lib/factpulse/models/quantite.rb +1 -1
  143. data/lib/factpulse/models/quota_info.rb +269 -0
  144. data/lib/factpulse/models/rechercher_services_response.rb +1 -1
  145. data/lib/factpulse/models/rechercher_structure_request.rb +1 -1
  146. data/lib/factpulse/models/rechercher_structure_response.rb +1 -1
  147. data/lib/factpulse/models/references.rb +1 -1
  148. data/lib/factpulse/models/reponse_healthcheck_afnor.rb +220 -0
  149. data/lib/factpulse/models/reponse_recherche_flux.rb +249 -0
  150. data/lib/factpulse/models/reponse_soumission_flux.rb +294 -0
  151. data/lib/factpulse/models/reponse_tache.rb +1 -1
  152. data/lib/factpulse/models/reponse_validation_erreur.rb +1 -1
  153. data/lib/factpulse/models/reponse_validation_succes.rb +1 -1
  154. data/lib/factpulse/models/requete_recherche_flux.rb +306 -0
  155. data/lib/factpulse/models/{validation_error_detail.rb → requete_soumission_flux.rb} +61 -68
  156. data/lib/factpulse/models/resultat_afnor.rb +1 -1
  157. data/lib/factpulse/models/resultat_chorus_pro.rb +1 -1
  158. data/lib/factpulse/models/resultat_validation_pdfapi.rb +1 -1
  159. data/lib/factpulse/models/scheme_id.rb +7 -7
  160. data/lib/factpulse/models/service_structure.rb +1 -1
  161. data/lib/factpulse/models/signature_info.rb +1 -1
  162. data/lib/factpulse/models/soumettre_facture_complete_request.rb +1 -1
  163. data/lib/factpulse/models/soumettre_facture_complete_response.rb +2 -2
  164. data/lib/factpulse/models/soumettre_facture_request.rb +7 -4
  165. data/lib/factpulse/models/soumettre_facture_response.rb +1 -1
  166. data/lib/factpulse/models/{error_level.rb → statut_acquittement.rb} +7 -6
  167. data/lib/factpulse/models/statut_facture.rb +1 -1
  168. data/lib/factpulse/models/statut_tache.rb +5 -30
  169. data/lib/factpulse/models/structure_info.rb +1 -1
  170. data/lib/factpulse/models/{error_source.rb → syntaxe_flux.rb} +10 -13
  171. data/lib/factpulse/models/tauxmanuel.rb +2 -2
  172. data/lib/factpulse/models/type_facture.rb +1 -1
  173. data/lib/factpulse/models/type_flux.rb +43 -0
  174. data/lib/factpulse/models/type_tva.rb +1 -1
  175. data/lib/factpulse/models/unite.rb +1 -1
  176. data/lib/factpulse/models/utilisateur.rb +328 -0
  177. data/lib/factpulse/models/validation_error.rb +1 -1
  178. data/lib/factpulse/models/validation_error_loc_inner.rb +1 -1
  179. data/lib/factpulse/version.rb +2 -2
  180. data/lib/factpulse.rb +39 -15
  181. metadata +79 -42
  182. data/docs/APIError.md +0 -22
  183. data/docs/MontantRemiseGlobaleTtc.md +0 -15
  184. data/docs/MontantTotalLigneHt.md +0 -15
  185. data/docs/MontantTvaLigne.md +0 -15
  186. data/docs/MontantTvaTotal.md +0 -15
  187. data/docs/MontantUnitaireHt.md +0 -15
  188. data/docs/Note.md +0 -20
  189. data/docs/ValidationErrorDetail.md +0 -26
  190. data/lib/factpulse/helpers/client.rb +0 -300
  191. data/lib/factpulse/helpers/exceptions.rb +0 -21
  192. data/lib/factpulse/helpers.rb +0 -13
  193. data/lib/factpulse/models/montant_base_ht.rb +0 -104
  194. data/lib/factpulse/models/montant_remise_globale_ttc.rb +0 -104
@@ -1,300 +0,0 @@
1
- # frozen_string_literal: true
2
- require 'net/http'; require 'json'; require 'base64'; require 'uri'; require 'securerandom'
3
-
4
- module FactPulse
5
- module Helpers
6
- # Credentials Chorus Pro pour le mode Zero-Trust.
7
- # Ces credentials sont passés dans chaque requête et ne sont jamais stockés côté serveur.
8
- class ChorusProCredentials
9
- attr_reader :piste_client_id, :piste_client_secret, :chorus_pro_login, :chorus_pro_password, :sandbox
10
- def initialize(piste_client_id:, piste_client_secret:, chorus_pro_login:, chorus_pro_password:, sandbox: true)
11
- @piste_client_id, @piste_client_secret = piste_client_id, piste_client_secret
12
- @chorus_pro_login, @chorus_pro_password, @sandbox = chorus_pro_login, chorus_pro_password, sandbox
13
- end
14
- def to_h
15
- { 'piste_client_id' => @piste_client_id, 'piste_client_secret' => @piste_client_secret,
16
- 'chorus_pro_login' => @chorus_pro_login, 'chorus_pro_password' => @chorus_pro_password, 'sandbox' => @sandbox }
17
- end
18
- end
19
-
20
- # Credentials AFNOR PDP pour le mode Zero-Trust.
21
- # L'API FactPulse utilise ces credentials pour s'authentifier auprès de la PDP AFNOR.
22
- class AFNORCredentials
23
- attr_reader :flow_service_url, :token_url, :client_id, :client_secret, :directory_service_url
24
- def initialize(flow_service_url:, token_url:, client_id:, client_secret:, directory_service_url: nil)
25
- @flow_service_url, @token_url = flow_service_url, token_url
26
- @client_id, @client_secret, @directory_service_url = client_id, client_secret, directory_service_url
27
- end
28
- def to_h
29
- result = { 'flow_service_url' => @flow_service_url, 'token_url' => @token_url,
30
- 'client_id' => @client_id, 'client_secret' => @client_secret }
31
- result['directory_service_url'] = @directory_service_url if @directory_service_url
32
- result
33
- end
34
- end
35
-
36
- # Helpers pour créer des montants totaux simplifiés.
37
- module MontantHelpers
38
- def self.montant(value)
39
- return '0.00' if value.nil?
40
- return format('%.2f', value) if value.is_a?(Numeric)
41
- value.is_a?(String) ? value : '0.00'
42
- end
43
-
44
- def self.montant_total(ht, tva, ttc, a_payer, remise_ttc: nil, motif_remise: nil, acompte: nil)
45
- result = {
46
- 'montantHtTotal' => montant(ht), 'montantTva' => montant(tva),
47
- 'montantTtcTotal' => montant(ttc), 'montantAPayer' => montant(a_payer)
48
- }
49
- result['montantRemiseGlobaleTtc'] = montant(remise_ttc) if remise_ttc
50
- result['motifRemiseGlobaleTtc'] = motif_remise if motif_remise
51
- result['acompte'] = montant(acompte) if acompte
52
- result
53
- end
54
-
55
- # Crée une ligne de poste (aligné sur LigneDePoste de models.py).
56
- def self.ligne_de_poste(numero, denomination, quantite, montant_unitaire_ht, montant_total_ligne_ht,
57
- taux_tva: '20.00', categorie_tva: 'S', unite: 'FORFAIT', **options)
58
- result = {
59
- 'numero' => numero, 'denomination' => denomination,
60
- 'quantite' => montant(quantite), 'montantUnitaireHt' => montant(montant_unitaire_ht),
61
- 'montantTotalLigneHt' => montant(montant_total_ligne_ht), 'tauxTva' => montant(taux_tva),
62
- 'categorieTva' => categorie_tva, 'unite' => unite
63
- }
64
- result['reference'] = options[:reference] if options[:reference]
65
- result['montantRemiseHt'] = montant(options[:montant_remise_ht]) if options[:montant_remise_ht]
66
- result['codeRaisonReduction'] = options[:code_raison_reduction] if options[:code_raison_reduction]
67
- result['raisonReduction'] = options[:raison_reduction] if options[:raison_reduction]
68
- result['dateDebutPeriode'] = options[:date_debut_periode] if options[:date_debut_periode]
69
- result['dateFinPeriode'] = options[:date_fin_periode] if options[:date_fin_periode]
70
- result
71
- end
72
-
73
- # Crée une ligne de TVA (aligné sur LigneDeTVA de models.py).
74
- def self.ligne_de_tva(taux_manuel, montant_base_ht, montant_tva, categorie: 'S')
75
- {
76
- 'tauxManuel' => montant(taux_manuel), 'montantBaseHt' => montant(montant_base_ht),
77
- 'montantTva' => montant(montant_tva), 'categorie' => categorie
78
- }
79
- end
80
-
81
- # Crée une adresse postale pour l'API FactPulse.
82
- def self.adresse_postale(ligne1, code_postal, ville, pays: 'FR', ligne2: nil, ligne3: nil)
83
- result = { 'ligneUn' => ligne1, 'codePostal' => code_postal, 'nomVille' => ville, 'paysCodeIso' => pays }
84
- result['ligneDeux'] = ligne2 if ligne2
85
- result['ligneTrois'] = ligne3 if ligne3
86
- result
87
- end
88
-
89
- # Crée une adresse électronique. scheme_id: "0009"=SIREN, "0225"=SIRET
90
- def self.adresse_electronique(identifiant, scheme_id: '0009')
91
- { 'identifiant' => identifiant, 'schemeId' => scheme_id }
92
- end
93
-
94
- # Calcule le numéro TVA intracommunautaire français depuis un SIREN.
95
- def self.calculer_tva_intra(siren)
96
- return nil if siren.nil? || siren.length != 9 || !siren.match?(/^\d+$/)
97
- cle = (12 + 3 * (siren.to_i % 97)) % 97
98
- format('FR%02d%s', cle, siren)
99
- end
100
-
101
- # Crée un fournisseur (émetteur) avec auto-calcul SIREN, TVA intracommunautaire et adresses.
102
- def self.fournisseur(nom, siret, adresse_ligne1, code_postal, ville, **options)
103
- siren = options[:siren] || (siret.length == 14 ? siret[0, 9] : nil)
104
- numero_tva_intra = options[:numero_tva_intra] || (siren ? calculer_tva_intra(siren) : nil)
105
- result = {
106
- 'nom' => nom, 'idFournisseur' => options[:id_fournisseur] || 0, 'siret' => siret,
107
- 'adresseElectronique' => adresse_electronique(siret, scheme_id: '0225'),
108
- 'adressePostale' => adresse_postale(adresse_ligne1, code_postal, ville, pays: options[:pays] || 'FR', ligne2: options[:adresse_ligne2])
109
- }
110
- result['siren'] = siren if siren
111
- result['numeroTvaIntra'] = numero_tva_intra if numero_tva_intra
112
- result['iban'] = options[:iban] if options[:iban]
113
- result['idServiceFournisseur'] = options[:code_service] if options[:code_service]
114
- result['codeCoordonnesBancairesFournisseur'] = options[:code_coordonnees_bancaires] if options[:code_coordonnees_bancaires]
115
- result
116
- end
117
-
118
- # Crée un destinataire (client) avec auto-calcul SIREN et adresses.
119
- def self.destinataire(nom, siret, adresse_ligne1, code_postal, ville, **options)
120
- siren = options[:siren] || (siret.length == 14 ? siret[0, 9] : nil)
121
- result = {
122
- 'nom' => nom, 'siret' => siret,
123
- 'adresseElectronique' => adresse_electronique(siret, scheme_id: '0225'),
124
- 'adressePostale' => adresse_postale(adresse_ligne1, code_postal, ville, pays: options[:pays] || 'FR', ligne2: options[:adresse_ligne2])
125
- }
126
- result['siren'] = siren if siren
127
- result['codeServiceExecutant'] = options[:code_service_executant] if options[:code_service_executant]
128
- result
129
- end
130
- end
131
-
132
- class FactPulseClient
133
- attr_reader :chorus_credentials, :afnor_credentials
134
-
135
- def initialize(email:, password:, api_url: nil, client_uid: nil, chorus_credentials: nil, afnor_credentials: nil,
136
- polling_interval: nil, polling_timeout: nil, max_retries: nil)
137
- @email, @password = email, password; @api_url = (api_url || 'https://factpulse.fr').chomp('/')
138
- @client_uid, @polling_interval, @polling_timeout, @max_retries = client_uid, polling_interval || 2000, polling_timeout || 120000, max_retries || 1
139
- @chorus_credentials, @afnor_credentials = chorus_credentials, afnor_credentials
140
- @access_token = @refresh_token = @token_expires_at = nil
141
- end
142
-
143
- def chorus_credentials_for_api; @chorus_credentials&.to_h; end
144
- def afnor_credentials_for_api; @afnor_credentials&.to_h; end
145
- # Alias plus courts
146
- def get_chorus_pro_credentials; chorus_credentials_for_api; end
147
- def get_afnor_credentials; afnor_credentials_for_api; end
148
-
149
- def ensure_authenticated(force_refresh: false)
150
- now = (Time.now.to_f * 1000).to_i
151
- if force_refresh || @access_token.nil? || (@token_expires_at && now >= @token_expires_at)
152
- payload = { 'username' => @email, 'password' => @password }; payload['client_uid'] = @client_uid if @client_uid
153
- response = http_post(URI("#{@api_url}/api/token/"), payload)
154
- raise FactPulseAuthError, "Auth failed" unless response.is_a?(Net::HTTPSuccess)
155
- tokens = JSON.parse(response.body); @access_token, @refresh_token = tokens['access'], tokens['refresh']
156
- @token_expires_at = now + (28 * 60 * 1000)
157
- end
158
- end
159
-
160
- def reset_auth; @access_token = @refresh_token = @token_expires_at = nil; end
161
-
162
- def poll_task(task_id, timeout: nil, interval: nil)
163
- timeout_ms, interval_ms = timeout || @polling_timeout, interval || @polling_interval
164
- start_time, current_interval = (Time.now.to_f * 1000).to_i, interval_ms.to_f
165
- loop do
166
- raise FactPulsePollingTimeout.new(task_id, timeout_ms) if (Time.now.to_f * 1000).to_i - start_time > timeout_ms
167
- ensure_authenticated; response = http_get(URI("#{@api_url}/api/v1/traitement/taches/#{task_id}/statut"))
168
- reset_auth and next if response.code == '401'
169
- data = JSON.parse(response.body)
170
- return data['resultat'] || {} if data['statut'] == 'SUCCESS'
171
- if data['statut'] == 'FAILURE'
172
- r = data['resultat'] || {}
173
- raise FactPulseValidationError.new("Task #{task_id} failed: #{r['message_erreur'] || '?'}", (r['erreurs'] || []).map { |e| ValidationErrorDetail.from_hash(e) })
174
- end
175
- sleep(current_interval / 1000.0); current_interval = [current_interval * 1.5, 10000].min
176
- end
177
- end
178
-
179
- def self.format_montant(m); MontantHelpers.montant(m); end
180
-
181
- # Génère une facture Factur-X à partir d'un dict/hash et d'un PDF source.
182
- # Accepte un Hash, un String JSON, ou tout objet avec une méthode to_h/to_hash.
183
- # @param facture_data [Hash, String, Object] Données de la facture
184
- # @param pdf_source [String, File] Chemin vers le PDF source ou objet File
185
- # @param profil [String] Profil Factur-X (MINIMUM, BASIC, EN16931, EXTENDED)
186
- # @param format_sortie [String] Format de sortie (pdf, xml, both)
187
- # @param sync [Boolean] Mode synchrone (true) ou asynchrone (false)
188
- # @param timeout [Integer, nil] Timeout en ms pour le polling
189
- # @return [String] Contenu binaire du PDF généré
190
- def generer_facturx(facture_data, pdf_source, profil: 'EN16931', format_sortie: 'pdf', sync: true, timeout: nil)
191
- # Conversion des données en JSON string
192
- json_data = case facture_data
193
- when String then facture_data
194
- when Hash then JSON.generate(facture_data)
195
- else
196
- if facture_data.respond_to?(:to_h)
197
- JSON.generate(facture_data.to_h)
198
- elsif facture_data.respond_to?(:to_hash)
199
- JSON.generate(facture_data.to_hash)
200
- else
201
- raise FactPulseValidationError.new("Type de données non supporté: #{facture_data.class}")
202
- end
203
- end
204
-
205
- # Lecture du PDF source
206
- pdf_content = case pdf_source
207
- when String then File.binread(pdf_source)
208
- when File then pdf_source.read
209
- else
210
- if pdf_source.respond_to?(:read)
211
- pdf_source.read
212
- else
213
- raise FactPulseValidationError.new("Type de PDF non supporté: #{pdf_source.class}")
214
- end
215
- end
216
- pdf_filename = pdf_source.is_a?(String) ? File.basename(pdf_source) : 'facture.pdf'
217
-
218
- ensure_authenticated
219
- uri = URI("#{@api_url}/api/v1/traitement/generer-facture")
220
-
221
- # Construire la requête multipart
222
- boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
223
- body = []
224
-
225
- # Champ donnees_facture
226
- body << "--#{boundary}\r\n"
227
- body << "Content-Disposition: form-data; name=\"donnees_facture\"\r\n\r\n"
228
- body << "#{json_data}\r\n"
229
-
230
- # Champ profil
231
- body << "--#{boundary}\r\n"
232
- body << "Content-Disposition: form-data; name=\"profil\"\r\n\r\n"
233
- body << "#{profil}\r\n"
234
-
235
- # Champ format_sortie
236
- body << "--#{boundary}\r\n"
237
- body << "Content-Disposition: form-data; name=\"format_sortie\"\r\n\r\n"
238
- body << "#{format_sortie}\r\n"
239
-
240
- # Champ source_pdf (fichier)
241
- body << "--#{boundary}\r\n"
242
- body << "Content-Disposition: form-data; name=\"source_pdf\"; filename=\"#{pdf_filename}\"\r\n"
243
- body << "Content-Type: application/pdf\r\n\r\n"
244
- body << pdf_content
245
- body << "\r\n"
246
-
247
- body << "--#{boundary}--\r\n"
248
- body_str = body.join
249
-
250
- http = Net::HTTP.new(uri.host, uri.port)
251
- http.use_ssl = uri.scheme == 'https'
252
- http.read_timeout = 120
253
-
254
- request = Net::HTTP::Post.new(uri)
255
- request['Authorization'] = "Bearer #{@access_token}"
256
- request['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
257
- request.body = body_str
258
-
259
- response = http.request(request)
260
-
261
- if response.code == '401'
262
- reset_auth
263
- ensure_authenticated
264
- request['Authorization'] = "Bearer #{@access_token}"
265
- response = http.request(request)
266
- end
267
-
268
- unless response.is_a?(Net::HTTPSuccess)
269
- error_data = JSON.parse(response.body) rescue { 'detail' => response.body }
270
- raise FactPulseValidationError.new("Erreur API: #{error_data['detail'] || response.body}")
271
- end
272
-
273
- data = JSON.parse(response.body)
274
-
275
- if sync && data['id_tache']
276
- result = poll_task(data['id_tache'], timeout: timeout)
277
- if result['contenu_b64']
278
- require 'base64'
279
- return Base64.decode64(result['contenu_b64'])
280
- elsif result['contenu_xml']
281
- return result['contenu_xml']
282
- end
283
- raise FactPulseValidationError.new("Résultat inattendu: #{result.keys.join(', ')}")
284
- end
285
-
286
- data
287
- end
288
-
289
- private
290
- def http_post(uri, payload)
291
- Net::HTTP.new(uri.host, uri.port).tap { |h| h.use_ssl = uri.scheme == 'https'; h.read_timeout = 30 }
292
- .request(Net::HTTP::Post.new(uri).tap { |r| r['Content-Type'] = 'application/json'; r.body = JSON.generate(payload) })
293
- end
294
- def http_get(uri)
295
- Net::HTTP.new(uri.host, uri.port).tap { |h| h.use_ssl = uri.scheme == 'https'; h.read_timeout = 30 }
296
- .request(Net::HTTP::Get.new(uri).tap { |r| r['Authorization'] = "Bearer #{@access_token}" })
297
- end
298
- end
299
- end
300
- end
@@ -1,21 +0,0 @@
1
- # frozen_string_literal: true
2
- module FactPulse
3
- module Helpers
4
- class FactPulseError < StandardError; end
5
- class FactPulseAuthError < FactPulseError; end
6
- class FactPulsePollingTimeout < FactPulseError
7
- attr_reader :task_id, :timeout
8
- def initialize(task_id, timeout); @task_id, @timeout = task_id, timeout; super("Timeout (#{timeout}ms) pour #{task_id}"); end
9
- end
10
- class ValidationErrorDetail
11
- attr_accessor :level, :item, :reason, :source, :code
12
- def initialize(level: '', item: '', reason: '', source: nil, code: nil); @level, @item, @reason, @source, @code = level, item, reason, source, code; end
13
- def to_s; "[#{@item.to_s.empty? ? 'unknown' : @item}] #{@reason.to_s.empty? ? 'Unknown error' : @reason}"; end
14
- def self.from_hash(h); new(level: h['level']||'', item: h['item']||'', reason: h['reason']||'', source: h['source'], code: h['code']); end
15
- end
16
- class FactPulseValidationError < FactPulseError
17
- attr_reader :errors
18
- def initialize(msg, errors = []); @errors = errors; super(errors.empty? ? msg : "#{msg}\n\nDétails:\n#{errors.map{|e| " - #{e}"}.join("\n")}"); end
19
- end
20
- end
21
- end
@@ -1,13 +0,0 @@
1
- # frozen_string_literal: true
2
- require_relative 'helpers/exceptions'
3
- require_relative 'helpers/client'
4
- module FactPulse
5
- module Helpers
6
- def self.create_client(**opts); FactPulseClient.new(**opts); end
7
- def self.format_montant(m); MontantHelpers.montant(m); end
8
- def self.montant(m); MontantHelpers.montant(m); end
9
- def self.montant_total(*args, **kwargs); MontantHelpers.montant_total(*args, **kwargs); end
10
- def self.ligne_de_poste(*args, **kwargs); MontantHelpers.ligne_de_poste(*args, **kwargs); end
11
- def self.ligne_de_tva(*args, **kwargs); MontantHelpers.ligne_de_tva(*args, **kwargs); end
12
- end
13
- end
@@ -1,104 +0,0 @@
1
- =begin
2
- #API REST FactPulse
3
-
4
- # API REST pour la facturation électronique en France : Factur-X, AFNOR PDP/PA, signatures électroniques. ## 🎯 Fonctionnalités principales ### 📄 Génération de factures Factur-X - **Formats** : XML seul ou PDF/A-3 avec XML embarqué - **Profils** : MINIMUM, BASIC, EN16931, EXTENDED - **Normes** : EN 16931 (directive UE 2014/55), ISO 19005-3 (PDF/A-3), CII (UN/CEFACT) - **🆕 Format simplifié** : Génération à partir de SIRET + auto-enrichissement (API Chorus Pro + Recherche Entreprises) ### ✅ Validation et conformité - **Validation XML** : Schematron (45 à 210+ règles selon profil) - **Validation PDF** : PDF/A-3, métadonnées XMP Factur-X, signatures électroniques - **VeraPDF** : Validation stricte PDF/A (146+ règles ISO 19005-3) - **Traitement asynchrone** : Support Celery pour validations lourdes (VeraPDF) ### 📡 Intégration AFNOR PDP/PA (XP Z12-013) - **Soumission de flux** : Envoi de factures vers Plateformes de Dématérialisation Partenaires - **Recherche de flux** : Consultation des factures soumises - **Téléchargement** : Récupération des PDF/A-3 avec XML - **Directory Service** : Recherche d'entreprises (SIREN/SIRET) - **Multi-client** : Support de plusieurs configs PDP par utilisateur (stored credentials ou zero-storage) ### ✍️ Signature électronique PDF - **Standards** : PAdES-B-B, PAdES-B-T (horodatage RFC 3161), PAdES-B-LT (archivage long terme) - **Niveaux eIDAS** : SES (auto-signé), AdES (CA commerciale), QES (PSCO) - **Validation** : Vérification intégrité cryptographique et certificats - **Génération de certificats** : Certificats X.509 auto-signés pour tests ### 🔄 Traitement asynchrone - **Celery** : Génération, validation et signature asynchrones - **Polling** : Suivi d'état via `/taches/{id_tache}/statut` - **Pas de timeout** : Idéal pour gros fichiers ou validations lourdes ## 🔒 Authentification Toutes les requêtes nécessitent un **token JWT** dans le header Authorization : ``` Authorization: Bearer YOUR_JWT_TOKEN ``` ### Comment obtenir un token JWT ? #### 🔑 Méthode 1 : API `/api/token/` (Recommandée) **URL :** `https://www.factpulse.fr/api/token/` Cette méthode est **recommandée** pour l'intégration dans vos applications et workflows CI/CD. **Prérequis :** Avoir défini un mot de passe sur votre compte **Pour les utilisateurs inscrits via email/password :** - Vous avez déjà un mot de passe, utilisez-le directement **Pour les utilisateurs inscrits via OAuth (Google/GitHub) :** - Vous devez d'abord définir un mot de passe sur : https://www.factpulse.fr/accounts/password/set/ - Une fois le mot de passe créé, vous pourrez utiliser l'API **Exemple de requête :** ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\" }' ``` **Paramètre optionnel `client_uid` :** Pour sélectionner les credentials d'un client spécifique (PA/PDP, Chorus Pro, certificats de signature), ajoutez `client_uid` : ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\", \"client_uid\": \"550e8400-e29b-41d4-a716-446655440000\" }' ``` Le `client_uid` sera inclus dans le JWT et permettra à l'API d'utiliser automatiquement : - Les credentials AFNOR/PDP configurés pour ce client - Les credentials Chorus Pro configurés pour ce client - Les certificats de signature électronique configurés pour ce client **Réponse :** ```json { \"access\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\", // Token d'accès (validité: 30 min) \"refresh\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\" // Token de rafraîchissement (validité: 7 jours) } ``` **Avantages :** - ✅ Automatisation complète (CI/CD, scripts) - ✅ Gestion programmatique des tokens - ✅ Support du refresh token pour renouveler automatiquement l'accès - ✅ Intégration facile dans n'importe quel langage/outil #### 🖥️ Méthode 2 : Génération via Dashboard (Alternative) **URL :** https://www.factpulse.fr/dashboard/ Cette méthode convient pour des tests rapides ou une utilisation occasionnelle via l'interface graphique. **Fonctionnement :** - Connectez-vous au dashboard - Utilisez les boutons \"Generate Test Token\" ou \"Generate Production Token\" - Fonctionne pour **tous** les utilisateurs (OAuth et email/password), sans nécessiter de mot de passe **Types de tokens :** - **Token Test** : Validité 24h, quota 1000 appels/jour (gratuit) - **Token Production** : Validité 7 jours, quota selon votre forfait **Avantages :** - ✅ Rapide pour tester l'API - ✅ Aucun mot de passe requis - ✅ Interface visuelle simple **Inconvénients :** - ❌ Nécessite une action manuelle - ❌ Pas de refresh token - ❌ Moins adapté pour l'automatisation ### 📚 Documentation complète Pour plus d'informations sur l'authentification et l'utilisation de l'API : https://www.factpulse.fr/documentation-api/
5
-
6
- The version of the OpenAPI document: 1.0.0
7
-
8
- Generated by: https://openapi-generator.tech
9
- Generator version: 7.18.0-SNAPSHOT
10
-
11
- =end
12
-
13
- require 'date'
14
- require 'time'
15
-
16
- module FactPulse
17
- # Montant de la base HT pour cette ligne de TVA. (Accepte number, string ou integer)
18
- module MontantBaseHt
19
- class << self
20
- # List of class defined in anyOf (OpenAPI v3)
21
- def openapi_any_of
22
- [
23
- :'Float',
24
- :'String'
25
- ]
26
- end
27
-
28
- # Builds the object
29
- # @param [Mixed] Data to be matched against the list of anyOf items
30
- # @return [Object] Returns the model or the data itself
31
- def build(data)
32
- # Go through the list of anyOf items and attempt to identify the appropriate one.
33
- # Note:
34
- # - No advanced validation of types in some cases (e.g. "x: { type: string }" will happily match { x: 123 })
35
- # due to the way the deserialization is made in the base_object template (it just casts without verifying).
36
- # - TODO: scalar values are de facto behaving as if they were nullable.
37
- # - TODO: logging when debugging is set.
38
- openapi_any_of.each do |klass|
39
- begin
40
- next if klass == :AnyType # "nullable: true"
41
- return find_and_cast_into_type(klass, data)
42
- rescue # rescue all errors so we keep iterating even if the current item lookup raises
43
- end
44
- end
45
-
46
- openapi_any_of.include?(:AnyType) ? data : nil
47
- end
48
-
49
- private
50
-
51
- SchemaMismatchError = Class.new(StandardError)
52
-
53
- # Note: 'File' is missing here because in the regular case we get the data _after_ a call to JSON.parse.
54
- def find_and_cast_into_type(klass, data)
55
- return if data.nil?
56
-
57
- case klass.to_s
58
- when 'Boolean'
59
- return data if data.instance_of?(TrueClass) || data.instance_of?(FalseClass)
60
- when 'Float'
61
- return data if data.instance_of?(Float)
62
- when 'Integer'
63
- return data if data.instance_of?(Integer)
64
- when 'Time'
65
- return Time.parse(data)
66
- when 'Date'
67
- return Date.iso8601(data)
68
- when 'String'
69
- return data if data.instance_of?(String)
70
- when 'Object' # "type: object"
71
- return data if data.instance_of?(Hash)
72
- when /\AArray<(?<sub_type>.+)>\z/ # "type: array"
73
- if data.instance_of?(Array)
74
- sub_type = Regexp.last_match[:sub_type]
75
- return data.map { |item| find_and_cast_into_type(sub_type, item) }
76
- end
77
- when /\AHash<String, (?<sub_type>.+)>\z/ # "type: object" with "additionalProperties: { ... }"
78
- if data.instance_of?(Hash) && data.keys.all? { |k| k.instance_of?(Symbol) || k.instance_of?(String) }
79
- sub_type = Regexp.last_match[:sub_type]
80
- return data.each_with_object({}) { |(k, v), hsh| hsh[k] = find_and_cast_into_type(sub_type, v) }
81
- end
82
- else # model
83
- const = FactPulse.const_get(klass)
84
- if const
85
- if const.respond_to?(:openapi_any_of) # nested anyOf model
86
- model = const.build(data)
87
- return model if model
88
- else
89
- # raise if data contains keys that are not known to the model
90
- raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty?
91
- model = const.build_from_hash(data)
92
- return model if model
93
- end
94
- end
95
- end
96
-
97
- raise # if no match by now, raise
98
- rescue
99
- raise SchemaMismatchError, "#{data} doesn't match the #{klass} type"
100
- end
101
- end
102
- end
103
-
104
- end
@@ -1,104 +0,0 @@
1
- =begin
2
- #API REST FactPulse
3
-
4
- # API REST pour la facturation électronique en France : Factur-X, AFNOR PDP/PA, signatures électroniques. ## 🎯 Fonctionnalités principales ### 📄 Génération de factures Factur-X - **Formats** : XML seul ou PDF/A-3 avec XML embarqué - **Profils** : MINIMUM, BASIC, EN16931, EXTENDED - **Normes** : EN 16931 (directive UE 2014/55), ISO 19005-3 (PDF/A-3), CII (UN/CEFACT) - **🆕 Format simplifié** : Génération à partir de SIRET + auto-enrichissement (API Chorus Pro + Recherche Entreprises) ### ✅ Validation et conformité - **Validation XML** : Schematron (45 à 210+ règles selon profil) - **Validation PDF** : PDF/A-3, métadonnées XMP Factur-X, signatures électroniques - **VeraPDF** : Validation stricte PDF/A (146+ règles ISO 19005-3) - **Traitement asynchrone** : Support Celery pour validations lourdes (VeraPDF) ### 📡 Intégration AFNOR PDP/PA (XP Z12-013) - **Soumission de flux** : Envoi de factures vers Plateformes de Dématérialisation Partenaires - **Recherche de flux** : Consultation des factures soumises - **Téléchargement** : Récupération des PDF/A-3 avec XML - **Directory Service** : Recherche d'entreprises (SIREN/SIRET) - **Multi-client** : Support de plusieurs configs PDP par utilisateur (stored credentials ou zero-storage) ### ✍️ Signature électronique PDF - **Standards** : PAdES-B-B, PAdES-B-T (horodatage RFC 3161), PAdES-B-LT (archivage long terme) - **Niveaux eIDAS** : SES (auto-signé), AdES (CA commerciale), QES (PSCO) - **Validation** : Vérification intégrité cryptographique et certificats - **Génération de certificats** : Certificats X.509 auto-signés pour tests ### 🔄 Traitement asynchrone - **Celery** : Génération, validation et signature asynchrones - **Polling** : Suivi d'état via `/taches/{id_tache}/statut` - **Pas de timeout** : Idéal pour gros fichiers ou validations lourdes ## 🔒 Authentification Toutes les requêtes nécessitent un **token JWT** dans le header Authorization : ``` Authorization: Bearer YOUR_JWT_TOKEN ``` ### Comment obtenir un token JWT ? #### 🔑 Méthode 1 : API `/api/token/` (Recommandée) **URL :** `https://www.factpulse.fr/api/token/` Cette méthode est **recommandée** pour l'intégration dans vos applications et workflows CI/CD. **Prérequis :** Avoir défini un mot de passe sur votre compte **Pour les utilisateurs inscrits via email/password :** - Vous avez déjà un mot de passe, utilisez-le directement **Pour les utilisateurs inscrits via OAuth (Google/GitHub) :** - Vous devez d'abord définir un mot de passe sur : https://www.factpulse.fr/accounts/password/set/ - Une fois le mot de passe créé, vous pourrez utiliser l'API **Exemple de requête :** ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\" }' ``` **Paramètre optionnel `client_uid` :** Pour sélectionner les credentials d'un client spécifique (PA/PDP, Chorus Pro, certificats de signature), ajoutez `client_uid` : ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\", \"client_uid\": \"550e8400-e29b-41d4-a716-446655440000\" }' ``` Le `client_uid` sera inclus dans le JWT et permettra à l'API d'utiliser automatiquement : - Les credentials AFNOR/PDP configurés pour ce client - Les credentials Chorus Pro configurés pour ce client - Les certificats de signature électronique configurés pour ce client **Réponse :** ```json { \"access\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\", // Token d'accès (validité: 30 min) \"refresh\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\" // Token de rafraîchissement (validité: 7 jours) } ``` **Avantages :** - ✅ Automatisation complète (CI/CD, scripts) - ✅ Gestion programmatique des tokens - ✅ Support du refresh token pour renouveler automatiquement l'accès - ✅ Intégration facile dans n'importe quel langage/outil #### 🖥️ Méthode 2 : Génération via Dashboard (Alternative) **URL :** https://www.factpulse.fr/dashboard/ Cette méthode convient pour des tests rapides ou une utilisation occasionnelle via l'interface graphique. **Fonctionnement :** - Connectez-vous au dashboard - Utilisez les boutons \"Generate Test Token\" ou \"Generate Production Token\" - Fonctionne pour **tous** les utilisateurs (OAuth et email/password), sans nécessiter de mot de passe **Types de tokens :** - **Token Test** : Validité 24h, quota 1000 appels/jour (gratuit) - **Token Production** : Validité 7 jours, quota selon votre forfait **Avantages :** - ✅ Rapide pour tester l'API - ✅ Aucun mot de passe requis - ✅ Interface visuelle simple **Inconvénients :** - ❌ Nécessite une action manuelle - ❌ Pas de refresh token - ❌ Moins adapté pour l'automatisation ### 📚 Documentation complète Pour plus d'informations sur l'authentification et l'utilisation de l'API : https://www.factpulse.fr/documentation-api/
5
-
6
- The version of the OpenAPI document: 1.0.0
7
-
8
- Generated by: https://openapi-generator.tech
9
- Generator version: 7.18.0-SNAPSHOT
10
-
11
- =end
12
-
13
- require 'date'
14
- require 'time'
15
-
16
- module FactPulse
17
- # Montant de la remise globale TTC. (Accepte number, string ou integer)
18
- module MontantRemiseGlobaleTtc
19
- class << self
20
- # List of class defined in anyOf (OpenAPI v3)
21
- def openapi_any_of
22
- [
23
- :'Float',
24
- :'String'
25
- ]
26
- end
27
-
28
- # Builds the object
29
- # @param [Mixed] Data to be matched against the list of anyOf items
30
- # @return [Object] Returns the model or the data itself
31
- def build(data)
32
- # Go through the list of anyOf items and attempt to identify the appropriate one.
33
- # Note:
34
- # - No advanced validation of types in some cases (e.g. "x: { type: string }" will happily match { x: 123 })
35
- # due to the way the deserialization is made in the base_object template (it just casts without verifying).
36
- # - TODO: scalar values are de facto behaving as if they were nullable.
37
- # - TODO: logging when debugging is set.
38
- openapi_any_of.each do |klass|
39
- begin
40
- next if klass == :AnyType # "nullable: true"
41
- return find_and_cast_into_type(klass, data)
42
- rescue # rescue all errors so we keep iterating even if the current item lookup raises
43
- end
44
- end
45
-
46
- openapi_any_of.include?(:AnyType) ? data : nil
47
- end
48
-
49
- private
50
-
51
- SchemaMismatchError = Class.new(StandardError)
52
-
53
- # Note: 'File' is missing here because in the regular case we get the data _after_ a call to JSON.parse.
54
- def find_and_cast_into_type(klass, data)
55
- return if data.nil?
56
-
57
- case klass.to_s
58
- when 'Boolean'
59
- return data if data.instance_of?(TrueClass) || data.instance_of?(FalseClass)
60
- when 'Float'
61
- return data if data.instance_of?(Float)
62
- when 'Integer'
63
- return data if data.instance_of?(Integer)
64
- when 'Time'
65
- return Time.parse(data)
66
- when 'Date'
67
- return Date.iso8601(data)
68
- when 'String'
69
- return data if data.instance_of?(String)
70
- when 'Object' # "type: object"
71
- return data if data.instance_of?(Hash)
72
- when /\AArray<(?<sub_type>.+)>\z/ # "type: array"
73
- if data.instance_of?(Array)
74
- sub_type = Regexp.last_match[:sub_type]
75
- return data.map { |item| find_and_cast_into_type(sub_type, item) }
76
- end
77
- when /\AHash<String, (?<sub_type>.+)>\z/ # "type: object" with "additionalProperties: { ... }"
78
- if data.instance_of?(Hash) && data.keys.all? { |k| k.instance_of?(Symbol) || k.instance_of?(String) }
79
- sub_type = Regexp.last_match[:sub_type]
80
- return data.each_with_object({}) { |(k, v), hsh| hsh[k] = find_and_cast_into_type(sub_type, v) }
81
- end
82
- else # model
83
- const = FactPulse.const_get(klass)
84
- if const
85
- if const.respond_to?(:openapi_any_of) # nested anyOf model
86
- model = const.build(data)
87
- return model if model
88
- else
89
- # raise if data contains keys that are not known to the model
90
- raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty?
91
- model = const.build_from_hash(data)
92
- return model if model
93
- end
94
- end
95
- end
96
-
97
- raise # if no match by now, raise
98
- rescue
99
- raise SchemaMismatchError, "#{data} doesn't match the #{klass} type"
100
- end
101
- end
102
- end
103
-
104
- end