Class: FactPulse::Helpers::FactPulseClient

Inherits:
Object
  • Object
show all
Defined in:
lib/factpulse/helpers/client.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email:, password:, api_url: nil, client_uid: nil, chorus_credentials: nil, afnor_credentials: nil, polling_interval: nil, polling_timeout: nil, max_retries: nil) ⇒ FactPulseClient

Returns a new instance of FactPulseClient.



84
85
86
87
88
89
90
# File 'lib/factpulse/helpers/client.rb', line 84

def initialize(email:, password:, api_url: nil, client_uid: nil, chorus_credentials: nil, afnor_credentials: nil,
               polling_interval: nil, polling_timeout: nil, max_retries: nil)
  @email, @password = email, password; @api_url = (api_url || 'https://factpulse.fr').chomp('/')
  @client_uid, @polling_interval, @polling_timeout, @max_retries = client_uid, polling_interval || 2000, polling_timeout || 120000, max_retries || 1
  @chorus_credentials, @afnor_credentials = chorus_credentials, afnor_credentials
  @access_token = @refresh_token = @token_expires_at = nil
end

Instance Attribute Details

#afnor_credentials ⇒ Object (readonly)

Returns the value of attribute afnor_credentials.



82
83
84
# File 'lib/factpulse/helpers/client.rb', line 82

def afnor_credentials
  @afnor_credentials
end

#chorus_credentials ⇒ Object (readonly)

Returns the value of attribute chorus_credentials.



82
83
84
# File 'lib/factpulse/helpers/client.rb', line 82

def chorus_credentials
  @chorus_credentials
end

Class Method Details

.format_montant(m) ⇒ Object



128
# File 'lib/factpulse/helpers/client.rb', line 128

def self.format_montant(m); MontantHelpers.montant(m); end

Instance Method Details

#afnor_credentials_for_api ⇒ Object



93
# File 'lib/factpulse/helpers/client.rb', line 93

def afnor_credentials_for_api; @afnor_credentials&.to_h; end

#chorus_credentials_for_api ⇒ Object



92
# File 'lib/factpulse/helpers/client.rb', line 92

def chorus_credentials_for_api; @chorus_credentials&.to_h; end

#ensure_authenticated(force_refresh: false) ⇒ Object



98
99
100
101
102
103
104
105
106
107
# File 'lib/factpulse/helpers/client.rb', line 98

def ensure_authenticated(force_refresh: false)
  now = (Time.now.to_f * 1000).to_i
  if force_refresh || @access_token.nil? || (@token_expires_at && now >= @token_expires_at)
    payload = { 'username' => @email, 'password' => @password }; payload['client_uid'] = @client_uid if @client_uid
    response = http_post(URI("#{@api_url}/api/token/"), payload)
    raise FactPulseAuthError, "Auth failed" unless response.is_a?(Net::HTTPSuccess)
    tokens = JSON.parse(response.body); @access_token, @refresh_token = tokens['access'], tokens['refresh']
    @token_expires_at = now + (28 * 60 * 1000)
  end
end

#generer_facturx(facture_data, pdf_source, profil: 'EN16931', format_sortie: 'pdf', sync: true, timeout: nil) ⇒ String

Génère une facture Factur-X à partir d'un dict/hash et d'un PDF source. Accepte un Hash, un String JSON, ou tout objet avec une méthode to_h/to_hash.

Parameters:

  • facture_data (Hash, String, Object) —

    Données de la facture

  • pdf_source (String, File) —

    Chemin vers le PDF source ou objet File

  • profil (String) (defaults to: 'EN16931') —

    Profil Factur-X (MINIMUM, BASIC, EN16931, EXTENDED)

  • format_sortie (String) (defaults to: 'pdf') —

    Format de sortie (pdf, xml, both)

  • sync (Boolean) (defaults to: true) —

    Mode synchrone (true) ou asynchrone (false)

  • timeout (Integer, nil) (defaults to: nil) —

    Timeout en ms pour le polling

Returns:

  • (String) —

    Contenu binaire du PDF généré



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/factpulse/helpers/client.rb', line 139

def generer_facturx(facture_data, pdf_source, profil: 'EN16931', format_sortie: 'pdf', sync: true, timeout: nil)
  # Conversion des données en JSON string
  json_data = case facture_data
              when String then facture_data
              when Hash then JSON.generate(facture_data)
              else
                if facture_data.respond_to?(:to_h)
                  JSON.generate(facture_data.to_h)
                elsif facture_data.respond_to?(:to_hash)
                  JSON.generate(facture_data.to_hash)
                else
                  raise FactPulseValidationError.new("Type de données non supporté: #{facture_data.class}")
                end
              end

  # Lecture du PDF source
  pdf_content = case pdf_source
                when String then File.binread(pdf_source)
                when File then pdf_source.read
                else
                  if pdf_source.respond_to?(:read)
                    pdf_source.read
                  else
                    raise FactPulseValidationError.new("Type de PDF non supporté: #{pdf_source.class}")
                  end
                end
  pdf_filename = pdf_source.is_a?(String) ? File.basename(pdf_source) : 'facture.pdf'

  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/traitement/generer-facture")

  # Construire la requête multipart
  boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
  body = []

  # Champ donnees_facture
  body << "--#{boundary}\r\n"
  body << "Content-Disposition: form-data; name=\"donnees_facture\"\r\n\r\n"
  body << "#{json_data}\r\n"

  # Champ profil
  body << "--#{boundary}\r\n"
  body << "Content-Disposition: form-data; name=\"profil\"\r\n\r\n"
  body << "#{profil}\r\n"

  # Champ format_sortie
  body << "--#{boundary}\r\n"
  body << "Content-Disposition: form-data; name=\"format_sortie\"\r\n\r\n"
  body << "#{format_sortie}\r\n"

  # Champ source_pdf (fichier)
  body << "--#{boundary}\r\n"
  body << "Content-Disposition: form-data; name=\"source_pdf\"; filename=\"#{pdf_filename}\"\r\n"
  body << "Content-Type: application/pdf\r\n\r\n"
  body << pdf_content
  body << "\r\n"

  body << "--#{boundary}--\r\n"
  body_str = body.join

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'
  http.read_timeout = 120

  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = "Bearer #{@access_token}"
  request['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
  request.body = body_str

  response = http.request(request)

  if response.code == '401'
    reset_auth
    ensure_authenticated
    request['Authorization'] = "Bearer #{@access_token}"
    response = http.request(request)
  end

  unless response.is_a?(Net::HTTPSuccess)
    error_data = JSON.parse(response.body) rescue { 'detail' => response.body }
    raise FactPulseValidationError.new("Erreur API: #{error_data['detail'] || response.body}")
  end

  data = JSON.parse(response.body)

  if sync && data['id_tache']
    result = poll_task(data['id_tache'], timeout: timeout)
    if result['contenu_b64']
      require 'base64'
      return Base64.decode64(result['contenu_b64'])
    elsif result['contenu_xml']
      return result['contenu_xml']
    end
    raise FactPulseValidationError.new("Résultat inattendu: #{result.keys.join(', ')}")
  end

  data
end

#get_afnor_credentials ⇒ Object



96
# File 'lib/factpulse/helpers/client.rb', line 96

def get_afnor_credentials; afnor_credentials_for_api; end

#get_chorus_pro_credentials ⇒ Object

Alias plus courts



95
# File 'lib/factpulse/helpers/client.rb', line 95

def get_chorus_pro_credentials; chorus_credentials_for_api; end

#poll_task(task_id, timeout: nil, interval: nil) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/factpulse/helpers/client.rb', line 111

def poll_task(task_id, timeout: nil, interval: nil)
  timeout_ms, interval_ms = timeout || @polling_timeout, interval || @polling_interval
  start_time, current_interval = (Time.now.to_f * 1000).to_i, interval_ms.to_f
  loop do
    raise FactPulsePollingTimeout.new(task_id, timeout_ms) if (Time.now.to_f * 1000).to_i - start_time > timeout_ms
    ensure_authenticated; response = http_get(URI("#{@api_url}/api/v1/traitement/taches/#{task_id}/statut"))
    reset_auth and next if response.code == '401'
    data = JSON.parse(response.body)
    return data['resultat'] || {} if data['statut'] == 'SUCCESS'
    if data['statut'] == 'FAILURE'
      r = data['resultat'] || {}
      raise FactPulseValidationError.new("Task #{task_id} failed: #{r['message_erreur'] || '?'}", (r['erreurs'] || []).map { |e| ValidationErrorDetail.from_hash(e) })
    end
    sleep(current_interval / 1000.0); current_interval = [current_interval * 1.5, 10000].min
  end
end

#reset_auth ⇒ Object



109
# File 'lib/factpulse/helpers/client.rb', line 109

def reset_auth; @access_token = @refresh_token = @token_expires_at = nil; end