factpulse 1.0.0
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +28 -0
- data/Gemfile +9 -0
- data/Gemfile.lock +74 -0
- data/LICENSE +21 -0
- data/README.md +207 -0
- data/Rakefile +10 -0
- data/docs/AFNORPDPPAApi.md +69 -0
- data/docs/AFNORPDPPADirectoryServiceApi.md +1313 -0
- data/docs/AFNORPDPPAFlowServiceApi.md +258 -0
- data/docs/APIError.md +22 -0
- data/docs/AdresseElectronique.md +20 -0
- data/docs/AdressePostale.md +26 -0
- data/docs/CadreDeFacturation.md +22 -0
- data/docs/CategorieTVA.md +15 -0
- data/docs/CertificateInfoResponse.md +40 -0
- data/docs/ChorusProApi.md +1125 -0
- data/docs/ChorusProCredentials.md +26 -0
- data/docs/CodeCadreFacturation.md +15 -0
- data/docs/CodeRaisonReduction.md +15 -0
- data/docs/ConsulterFactureRequest.md +20 -0
- data/docs/ConsulterFactureResponse.md +34 -0
- data/docs/ConsulterStructureRequest.md +22 -0
- data/docs/ConsulterStructureResponse.md +34 -0
- data/docs/CredentialsAFNOR.md +22 -0
- data/docs/CredentialsChorusPro.md +26 -0
- data/docs/Destinataire.md +28 -0
- data/docs/Destination.md +79 -0
- data/docs/DestinationAFNOR.md +24 -0
- data/docs/DestinationChorusPro.md +20 -0
- data/docs/DonneesFactureSimplifiees.md +34 -0
- data/docs/ErrorLevel.md +15 -0
- data/docs/ErrorSource.md +15 -0
- data/docs/FactureEnrichieInfo.md +32 -0
- data/docs/FactureFacturX.md +46 -0
- data/docs/FormatSortie.md +15 -0
- data/docs/Fournisseur.md +36 -0
- data/docs/GenerateCertificateRequest.md +38 -0
- data/docs/GenerateCertificateResponse.md +32 -0
- data/docs/HTTPValidationError.md +18 -0
- data/docs/InformationSignatureAPI.md +28 -0
- data/docs/LigneDePoste.md +46 -0
- data/docs/LigneDePosteMontantRemiseHt.md +15 -0
- data/docs/LigneDePosteTauxTvaManuel.md +15 -0
- data/docs/LigneDeTVA.md +26 -0
- data/docs/ModeDepot.md +15 -0
- data/docs/ModePaiement.md +15 -0
- data/docs/MontantAPayer.md +15 -0
- data/docs/MontantBaseHt.md +15 -0
- data/docs/MontantHtTotal.md +15 -0
- data/docs/MontantRemiseGlobaleTtc.md +15 -0
- data/docs/MontantTotal.md +30 -0
- data/docs/MontantTotalAcompte.md +15 -0
- data/docs/MontantTotalLigneHt.md +15 -0
- data/docs/MontantTtcTotal.md +15 -0
- data/docs/MontantTva.md +15 -0
- data/docs/MontantTvaLigne.md +15 -0
- data/docs/MontantTvaTotal.md +15 -0
- data/docs/MontantUnitaireHt.md +15 -0
- data/docs/Note.md +20 -0
- data/docs/ObtenirIdChorusProRequest.md +22 -0
- data/docs/ObtenirIdChorusProResponse.md +24 -0
- data/docs/OptionsProcessing.md +24 -0
- data/docs/PDFFacturXInfo.md +22 -0
- data/docs/ParametresSignature.md +34 -0
- data/docs/ParametresStructure.md +22 -0
- data/docs/PieceJointeComplementaire.md +26 -0
- data/docs/ProfilAPI.md +15 -0
- data/docs/Quantite.md +15 -0
- data/docs/RechercherServicesResponse.md +24 -0
- data/docs/RechercherStructureRequest.md +26 -0
- data/docs/RechercherStructureResponse.md +24 -0
- data/docs/References.md +32 -0
- data/docs/ReponseTache.md +18 -0
- data/docs/ReponseValidationErreur.md +18 -0
- data/docs/ReponseValidationSucces.md +18 -0
- data/docs/ResultatAFNOR.md +26 -0
- data/docs/ResultatChorusPro.md +22 -0
- data/docs/ResultatValidationPDFAPI.md +62 -0
- data/docs/SantApi.md +131 -0
- data/docs/SchemeID.md +15 -0
- data/docs/ServiceStructure.md +24 -0
- data/docs/SignatureInfo.md +22 -0
- data/docs/SoumettreFactureCompleteRequest.md +26 -0
- data/docs/SoumettreFactureCompleteResponse.md +34 -0
- data/docs/SoumettreFactureRequest.md +46 -0
- data/docs/SoumettreFactureResponse.md +24 -0
- data/docs/StatutCelery.md +15 -0
- data/docs/StatutFacture.md +22 -0
- data/docs/StatutTache.md +22 -0
- data/docs/StructureInfo.md +26 -0
- data/docs/Tauxmanuel.md +15 -0
- data/docs/TraitementFactureApi.md +831 -0
- data/docs/TypeFacture.md +15 -0
- data/docs/TypeTVA.md +15 -0
- data/docs/Unite.md +15 -0
- data/docs/UtilisateurApi.md +74 -0
- data/docs/ValidationError.md +22 -0
- data/docs/ValidationErrorDetail.md +26 -0
- data/docs/ValidationErrorLocInner.md +15 -0
- data/factpulse.gemspec +39 -0
- data/git_push.sh +57 -0
- data/lib/factpulse/api/afnorpdppa_api.rb +79 -0
- data/lib/factpulse/api/afnorpdppa_directory_service_api.rb +1183 -0
- data/lib/factpulse/api/afnorpdppa_flow_service_api.rb +256 -0
- data/lib/factpulse/api/chorus_pro_api.rb +1103 -0
- data/lib/factpulse/api/sant_api.rb +136 -0
- data/lib/factpulse/api/traitement_facture_api.rb +835 -0
- data/lib/factpulse/api/utilisateur_api.rb +79 -0
- data/lib/factpulse/api_client.rb +397 -0
- data/lib/factpulse/api_error.rb +58 -0
- data/lib/factpulse/api_model_base.rb +88 -0
- data/lib/factpulse/configuration.rb +308 -0
- data/lib/factpulse/helpers/client.rb +300 -0
- data/lib/factpulse/helpers/exceptions.rb +21 -0
- data/lib/factpulse/helpers.rb +13 -0
- data/lib/factpulse/models/adresse_electronique.rb +196 -0
- data/lib/factpulse/models/adresse_postale.rb +189 -0
- data/lib/factpulse/models/api_error.rb +205 -0
- data/lib/factpulse/models/cadre_de_facturation.rb +207 -0
- data/lib/factpulse/models/categorie_tva.rb +47 -0
- data/lib/factpulse/models/certificate_info_response.rb +446 -0
- data/lib/factpulse/models/chorus_pro_credentials.rb +259 -0
- data/lib/factpulse/models/code_cadre_facturation.rb +42 -0
- data/lib/factpulse/models/code_raison_reduction.rb +45 -0
- data/lib/factpulse/models/consulter_facture_request.rb +176 -0
- data/lib/factpulse/models/consulter_facture_response.rb +261 -0
- data/lib/factpulse/models/consulter_structure_request.rb +188 -0
- data/lib/factpulse/models/consulter_structure_response.rb +261 -0
- data/lib/factpulse/models/credentials_afnor.rb +169 -0
- data/lib/factpulse/models/credentials_chorus_pro.rb +191 -0
- data/lib/factpulse/models/destinataire.rb +215 -0
- data/lib/factpulse/models/destination.rb +56 -0
- data/lib/factpulse/models/destination_afnor.rb +228 -0
- data/lib/factpulse/models/destination_chorus_pro.rb +194 -0
- data/lib/factpulse/models/donnees_facture_simplifiees.rb +342 -0
- data/lib/factpulse/models/error_level.rb +40 -0
- data/lib/factpulse/models/error_source.rb +46 -0
- data/lib/factpulse/models/facture_enrichie_info.rb +348 -0
- data/lib/factpulse/models/facture_factur_x.rb +443 -0
- data/lib/factpulse/models/format_sortie.rb +40 -0
- data/lib/factpulse/models/fournisseur.rb +271 -0
- data/lib/factpulse/models/generate_certificate_request.rb +323 -0
- data/lib/factpulse/models/generate_certificate_response.rb +254 -0
- data/lib/factpulse/models/http_validation_error.rb +149 -0
- data/lib/factpulse/models/information_signature_api.rb +216 -0
- data/lib/factpulse/models/ligne_de_poste.rb +390 -0
- data/lib/factpulse/models/ligne_de_poste_montant_remise_ht.rb +104 -0
- data/lib/factpulse/models/ligne_de_poste_taux_tva_manuel.rb +104 -0
- data/lib/factpulse/models/ligne_de_tva.rb +242 -0
- data/lib/factpulse/models/mode_depot.rb +41 -0
- data/lib/factpulse/models/mode_paiement.rb +44 -0
- data/lib/factpulse/models/montant_a_payer.rb +104 -0
- data/lib/factpulse/models/montant_base_ht.rb +104 -0
- data/lib/factpulse/models/montant_ht_total.rb +104 -0
- data/lib/factpulse/models/montant_remise_globale_ttc.rb +104 -0
- data/lib/factpulse/models/montant_total.rb +272 -0
- data/lib/factpulse/models/montant_total_acompte.rb +104 -0
- data/lib/factpulse/models/montant_total_ligne_ht.rb +104 -0
- data/lib/factpulse/models/montant_ttc_total.rb +104 -0
- data/lib/factpulse/models/montant_tva.rb +104 -0
- data/lib/factpulse/models/montant_tva_ligne.rb +104 -0
- data/lib/factpulse/models/montant_tva_total.rb +104 -0
- data/lib/factpulse/models/montant_unitaire_ht.rb +104 -0
- data/lib/factpulse/models/note.rb +175 -0
- data/lib/factpulse/models/obtenir_id_chorus_pro_request.rb +188 -0
- data/lib/factpulse/models/obtenir_id_chorus_pro_response.rb +230 -0
- data/lib/factpulse/models/options_processing.rb +207 -0
- data/lib/factpulse/models/parametres_signature.rb +235 -0
- data/lib/factpulse/models/parametres_structure.rb +175 -0
- data/lib/factpulse/models/pdf_factur_x_info.rb +205 -0
- data/lib/factpulse/models/piece_jointe_complementaire.rb +269 -0
- data/lib/factpulse/models/profil_api.rb +42 -0
- data/lib/factpulse/models/quantite.rb +104 -0
- data/lib/factpulse/models/rechercher_services_response.rb +214 -0
- data/lib/factpulse/models/rechercher_structure_request.rb +191 -0
- data/lib/factpulse/models/rechercher_structure_response.rb +216 -0
- data/lib/factpulse/models/references.rb +290 -0
- data/lib/factpulse/models/reponse_tache.rb +165 -0
- data/lib/factpulse/models/reponse_validation_erreur.rb +167 -0
- data/lib/factpulse/models/reponse_validation_succes.rb +165 -0
- data/lib/factpulse/models/resultat_afnor.rb +240 -0
- data/lib/factpulse/models/resultat_chorus_pro.rb +186 -0
- data/lib/factpulse/models/resultat_validation_pdfapi.rb +523 -0
- data/lib/factpulse/models/scheme_id.rb +43 -0
- data/lib/factpulse/models/service_structure.rb +247 -0
- data/lib/factpulse/models/signature_info.rb +186 -0
- data/lib/factpulse/models/soumettre_facture_complete_request.rb +239 -0
- data/lib/factpulse/models/soumettre_facture_complete_response.rb +355 -0
- data/lib/factpulse/models/soumettre_facture_request.rb +388 -0
- data/lib/factpulse/models/soumettre_facture_response.rb +213 -0
- data/lib/factpulse/models/statut_celery.rb +43 -0
- data/lib/factpulse/models/statut_facture.rb +203 -0
- data/lib/factpulse/models/statut_tache.rb +226 -0
- data/lib/factpulse/models/structure_info.rb +274 -0
- data/lib/factpulse/models/tauxmanuel.rb +104 -0
- data/lib/factpulse/models/type_facture.rb +40 -0
- data/lib/factpulse/models/type_tva.rb +42 -0
- data/lib/factpulse/models/unite.rb +44 -0
- data/lib/factpulse/models/validation_error.rb +218 -0
- data/lib/factpulse/models/validation_error_detail.rb +245 -0
- data/lib/factpulse/models/validation_error_loc_inner.rb +103 -0
- data/lib/factpulse/version.rb +15 -0
- data/lib/factpulse.rb +133 -0
- metadata +345 -0
|
@@ -0,0 +1,308 @@
|
|
|
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
|
+
module FactPulse
|
|
14
|
+
class Configuration
|
|
15
|
+
# Defines url scheme
|
|
16
|
+
attr_accessor :scheme
|
|
17
|
+
|
|
18
|
+
# Defines url host
|
|
19
|
+
attr_accessor :host
|
|
20
|
+
|
|
21
|
+
# Defines url base path
|
|
22
|
+
attr_accessor :base_path
|
|
23
|
+
|
|
24
|
+
# Define server configuration index
|
|
25
|
+
attr_accessor :server_index
|
|
26
|
+
|
|
27
|
+
# Define server operation configuration index
|
|
28
|
+
attr_accessor :server_operation_index
|
|
29
|
+
|
|
30
|
+
# Default server variables
|
|
31
|
+
attr_accessor :server_variables
|
|
32
|
+
|
|
33
|
+
# Default server operation variables
|
|
34
|
+
attr_accessor :server_operation_variables
|
|
35
|
+
|
|
36
|
+
# Defines API keys used with API Key authentications.
|
|
37
|
+
#
|
|
38
|
+
# @return [Hash] key: parameter name, value: parameter value (API key)
|
|
39
|
+
#
|
|
40
|
+
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
|
|
41
|
+
# config.api_key['api_key'] = 'xxx'
|
|
42
|
+
attr_accessor :api_key
|
|
43
|
+
|
|
44
|
+
# Defines API key prefixes used with API Key authentications.
|
|
45
|
+
#
|
|
46
|
+
# @return [Hash] key: parameter name, value: API key prefix
|
|
47
|
+
#
|
|
48
|
+
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
|
|
49
|
+
# config.api_key_prefix['api_key'] = 'Token'
|
|
50
|
+
attr_accessor :api_key_prefix
|
|
51
|
+
|
|
52
|
+
# Defines the username used with HTTP basic authentication.
|
|
53
|
+
#
|
|
54
|
+
# @return [String]
|
|
55
|
+
attr_accessor :username
|
|
56
|
+
|
|
57
|
+
# Defines the password used with HTTP basic authentication.
|
|
58
|
+
#
|
|
59
|
+
# @return [String]
|
|
60
|
+
attr_accessor :password
|
|
61
|
+
|
|
62
|
+
# Defines the access token (Bearer) used with OAuth2.
|
|
63
|
+
attr_accessor :access_token
|
|
64
|
+
|
|
65
|
+
# Defines a Proc used to fetch or refresh access tokens (Bearer) used with OAuth2.
|
|
66
|
+
# Overrides the access_token if set
|
|
67
|
+
# @return [Proc]
|
|
68
|
+
attr_accessor :access_token_getter
|
|
69
|
+
|
|
70
|
+
# Set this to return data as binary instead of downloading a temp file. When enabled (set to true)
|
|
71
|
+
# HTTP responses with return type `File` will be returned as a stream of binary data.
|
|
72
|
+
# Default to false.
|
|
73
|
+
attr_accessor :return_binary_data
|
|
74
|
+
|
|
75
|
+
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
|
|
76
|
+
# details will be logged with `logger.debug` (see the `logger` attribute).
|
|
77
|
+
# Default to false.
|
|
78
|
+
#
|
|
79
|
+
# @return [true, false]
|
|
80
|
+
attr_accessor :debugging
|
|
81
|
+
|
|
82
|
+
# Set this to ignore operation servers for the API client. This is useful when you need to
|
|
83
|
+
# send requests to a different server than the one specified in the OpenAPI document.
|
|
84
|
+
# Will default to the base url defined in the spec but can be overridden by setting
|
|
85
|
+
# `scheme`, `host`, `base_path` directly.
|
|
86
|
+
# Default to false.
|
|
87
|
+
# @return [true, false]
|
|
88
|
+
attr_accessor :ignore_operation_servers
|
|
89
|
+
|
|
90
|
+
# Defines the logger used for debugging.
|
|
91
|
+
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
|
|
92
|
+
#
|
|
93
|
+
# @return [#debug]
|
|
94
|
+
attr_accessor :logger
|
|
95
|
+
|
|
96
|
+
# Defines the temporary folder to store downloaded files
|
|
97
|
+
# (for API endpoints that have file response).
|
|
98
|
+
# Default to use `Tempfile`.
|
|
99
|
+
#
|
|
100
|
+
# @return [String]
|
|
101
|
+
attr_accessor :temp_folder_path
|
|
102
|
+
|
|
103
|
+
# The time limit for HTTP request in seconds.
|
|
104
|
+
# Default to 0 (never times out).
|
|
105
|
+
attr_accessor :timeout
|
|
106
|
+
|
|
107
|
+
# Set this to false to skip client side validation in the operation.
|
|
108
|
+
# Default to true.
|
|
109
|
+
# @return [true, false]
|
|
110
|
+
attr_accessor :client_side_validation
|
|
111
|
+
|
|
112
|
+
### TLS/SSL setting
|
|
113
|
+
# Set this to false to skip verifying SSL certificate when calling API from https server.
|
|
114
|
+
# Default to true.
|
|
115
|
+
#
|
|
116
|
+
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
|
|
117
|
+
#
|
|
118
|
+
# @return [true, false]
|
|
119
|
+
attr_accessor :verify_ssl
|
|
120
|
+
|
|
121
|
+
### TLS/SSL setting
|
|
122
|
+
# Set this to false to skip verifying SSL host name
|
|
123
|
+
# Default to true.
|
|
124
|
+
#
|
|
125
|
+
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
|
|
126
|
+
#
|
|
127
|
+
# @return [true, false]
|
|
128
|
+
attr_accessor :verify_ssl_host
|
|
129
|
+
|
|
130
|
+
### TLS/SSL setting
|
|
131
|
+
# Set this to customize the certificate file to verify the peer.
|
|
132
|
+
#
|
|
133
|
+
# @return [String] the path to the certificate file
|
|
134
|
+
#
|
|
135
|
+
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
|
|
136
|
+
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
|
|
137
|
+
attr_accessor :ssl_ca_cert
|
|
138
|
+
|
|
139
|
+
### TLS/SSL setting
|
|
140
|
+
# Client certificate file (for client certificate)
|
|
141
|
+
attr_accessor :cert_file
|
|
142
|
+
|
|
143
|
+
### TLS/SSL setting
|
|
144
|
+
# Client private key file (for client certificate)
|
|
145
|
+
attr_accessor :key_file
|
|
146
|
+
|
|
147
|
+
# Set this to customize parameters encoding of array parameter with multi collectionFormat.
|
|
148
|
+
# Default to nil.
|
|
149
|
+
#
|
|
150
|
+
# @see The params_encoding option of Ethon. Related source code:
|
|
151
|
+
# https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
|
|
152
|
+
attr_accessor :params_encoding
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
attr_accessor :inject_format
|
|
156
|
+
|
|
157
|
+
attr_accessor :force_ending_format
|
|
158
|
+
|
|
159
|
+
def initialize
|
|
160
|
+
@scheme = 'http'
|
|
161
|
+
@host = 'localhost'
|
|
162
|
+
@base_path = ''
|
|
163
|
+
@server_index = nil
|
|
164
|
+
@server_operation_index = {}
|
|
165
|
+
@server_variables = {}
|
|
166
|
+
@server_operation_variables = {}
|
|
167
|
+
@api_key = {}
|
|
168
|
+
@api_key_prefix = {}
|
|
169
|
+
@client_side_validation = true
|
|
170
|
+
@verify_ssl = true
|
|
171
|
+
@verify_ssl_host = true
|
|
172
|
+
@cert_file = nil
|
|
173
|
+
@key_file = nil
|
|
174
|
+
@timeout = 0
|
|
175
|
+
@params_encoding = nil
|
|
176
|
+
@debugging = false
|
|
177
|
+
@ignore_operation_servers = false
|
|
178
|
+
@inject_format = false
|
|
179
|
+
@force_ending_format = false
|
|
180
|
+
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
|
|
181
|
+
|
|
182
|
+
yield(self) if block_given?
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# The default Configuration object.
|
|
186
|
+
def self.default
|
|
187
|
+
@@default ||= Configuration.new
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def configure
|
|
191
|
+
yield(self) if block_given?
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def scheme=(scheme)
|
|
195
|
+
# remove :// from scheme
|
|
196
|
+
@scheme = scheme.sub(/:\/\//, '')
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def host=(host)
|
|
200
|
+
# remove http(s):// and anything after a slash
|
|
201
|
+
@host = host.sub(/https?:\/\//, '').split('/').first
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def base_path=(base_path)
|
|
205
|
+
# Add leading and trailing slashes to base_path
|
|
206
|
+
@base_path = "/#{base_path}".gsub(/\/+/, '/')
|
|
207
|
+
@base_path = '' if @base_path == '/'
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# Returns base URL for specified operation based on server settings
|
|
211
|
+
def base_url(operation = nil)
|
|
212
|
+
return "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') if ignore_operation_servers
|
|
213
|
+
if operation_server_settings.key?(operation) then
|
|
214
|
+
index = server_operation_index.fetch(operation, server_index)
|
|
215
|
+
server_url(index.nil? ? 0 : index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation])
|
|
216
|
+
else
|
|
217
|
+
server_index.nil? ? "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') : server_url(server_index, server_variables, nil)
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# Gets API key (with prefix if set).
|
|
222
|
+
# @param [String] param_name the parameter name of API key auth
|
|
223
|
+
def api_key_with_prefix(param_name, param_alias = nil)
|
|
224
|
+
key = @api_key[param_name]
|
|
225
|
+
key = @api_key.fetch(param_alias, key) unless param_alias.nil?
|
|
226
|
+
if @api_key_prefix[param_name]
|
|
227
|
+
"#{@api_key_prefix[param_name]} #{key}"
|
|
228
|
+
else
|
|
229
|
+
key
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
# Gets access_token using access_token_getter or uses the static access_token
|
|
234
|
+
def access_token_with_refresh
|
|
235
|
+
return access_token if access_token_getter.nil?
|
|
236
|
+
access_token_getter.call
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# Gets Basic Auth token string
|
|
240
|
+
def basic_auth_token
|
|
241
|
+
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# Returns Auth Settings hash for api client.
|
|
245
|
+
def auth_settings
|
|
246
|
+
{
|
|
247
|
+
'HTTPBearer' =>
|
|
248
|
+
{
|
|
249
|
+
type: 'bearer',
|
|
250
|
+
in: 'header',
|
|
251
|
+
key: 'Authorization',
|
|
252
|
+
value: "Bearer #{access_token_with_refresh}"
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
# Returns an array of Server setting
|
|
258
|
+
def server_settings
|
|
259
|
+
[
|
|
260
|
+
{
|
|
261
|
+
url: "",
|
|
262
|
+
description: "No description provided",
|
|
263
|
+
}
|
|
264
|
+
]
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
def operation_server_settings
|
|
268
|
+
{
|
|
269
|
+
}
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
# Returns URL based on server settings
|
|
273
|
+
#
|
|
274
|
+
# @param index array index of the server settings
|
|
275
|
+
# @param variables hash of variable and the corresponding value
|
|
276
|
+
def server_url(index, variables = {}, servers = nil)
|
|
277
|
+
servers = server_settings if servers == nil
|
|
278
|
+
|
|
279
|
+
# check array index out of bound
|
|
280
|
+
if (index.nil? || index < 0 || index >= servers.size)
|
|
281
|
+
fail ArgumentError, "Invalid index #{index} when selecting the server. Must not be nil and must be less than #{servers.size}"
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
server = servers[index]
|
|
285
|
+
url = server[:url]
|
|
286
|
+
|
|
287
|
+
return url unless server.key? :variables
|
|
288
|
+
|
|
289
|
+
# go through variable and assign a value
|
|
290
|
+
server[:variables].each do |name, variable|
|
|
291
|
+
if variables.key?(name)
|
|
292
|
+
if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name]))
|
|
293
|
+
url.gsub! "{" + name.to_s + "}", variables[name]
|
|
294
|
+
else
|
|
295
|
+
fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}."
|
|
296
|
+
end
|
|
297
|
+
else
|
|
298
|
+
# use default value
|
|
299
|
+
url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value]
|
|
300
|
+
end
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
url
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
end
|
|
308
|
+
end
|
|
@@ -0,0 +1,300 @@
|
|
|
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
|
|
@@ -0,0 +1,21 @@
|
|
|
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
|
|
@@ -0,0 +1,13 @@
|
|
|
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
|