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.



168
169
170
171
172
173
174
# File 'lib/factpulse/helpers/client.rb', line 168

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_credentialsObject (readonly)

Returns the value of attribute afnor_credentials.



166
167
168
# File 'lib/factpulse/helpers/client.rb', line 166

def afnor_credentials
  @afnor_credentials
end

#chorus_credentialsObject (readonly)

Returns the value of attribute chorus_credentials.



166
167
168
# File 'lib/factpulse/helpers/client.rb', line 166

def chorus_credentials
  @chorus_credentials
end

Class Method Details

.format_amount(m) ⇒ Object



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

def self.format_amount(m); AmountHelpers.amount(m); end

Instance Method Details

#afnor_credentials_for_apiObject



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

def afnor_credentials_for_api; @afnor_credentials&.to_h; end

#chorus_credentials_for_apiObject



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

def chorus_credentials_for_api; @chorus_credentials&.to_h; end

#consulter_facture_chorus(identifiant_facture_cpp) ⇒ Object

Gets the status of a Chorus Pro invoice.



540
541
542
# File 'lib/factpulse/helpers/client.rb', line 540

def consulter_facture_chorus(identifiant_facture_cpp)
  make_chorus_request('POST', '/factures/consulter', { 'identifiant_facture_cpp' => identifiant_facture_cpp })
end

#consulter_structure_chorus(id_structure_cpp) ⇒ Object

Gets the details of a Chorus Pro structure.



520
521
522
# File 'lib/factpulse/helpers/client.rb', line 520

def consulter_structure_chorus(id_structure_cpp)
  make_chorus_request('POST', '/structures/consulter', { 'id_structure_cpp' => id_structure_cpp })
end

#download_flow_afnor(flow_id) ⇒ Object

Downloads the PDF file of an AFNOR flow.



421
422
423
424
# File 'lib/factpulse/helpers/client.rb', line 421

def download_flow_afnor(flow_id)
  result = make_afnor_request('GET', "/flow/v1/flows/#{flow_id}")
  result['_raw'] || ''
end

#ensure_authenticated(force_refresh: false) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/factpulse/helpers/client.rb', line 182

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

#generate_complete_facturx(invoice, pdf_source_path, **options) ⇒ Object

Generates a complete Factur-X PDF with optional validation, signature and submission.



655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/factpulse/helpers/client.rb', line 655

def generate_complete_facturx(invoice, pdf_source_path, **options)
  profile = options[:profile] || 'EN16931'
  validate = options.fetch(:validate, true)
  sign = options.fetch(:sign, false)
  submit_afnor = options.fetch(:submit_afnor, false)
  timeout = options[:timeout] || 120000

  result = {}

  # 1. Generation
  pdf_bytes = generate_facturx(invoice, pdf_source_path, profile: profile, output_format: 'pdf', sync: true, timeout: timeout)
  result[:pdf_bytes] = pdf_bytes

  # Create a temporary file for subsequent operations
  temp_file = Tempfile.new(['facturx_', '.pdf'])
  begin
    temp_file.binmode
    temp_file.write(pdf_bytes)
    temp_file.flush

    # 2. Validation
    if validate
      validation = validate_facturx_pdf(temp_file.path, profile: profile)
      result[:validation] = validation
      unless validation['is_compliant']
        if options[:output_path]
          File.binwrite(options[:output_path], pdf_bytes)
          result[:pdf_path] = options[:output_path]
        end
        return result
      end
    end

    # 3. Signature
    if sign
      pdf_bytes = sign_pdf(temp_file.path, **options)
      result[:pdf_bytes] = pdf_bytes
      result[:signature] = { 'signed' => true }
      temp_file.rewind
      temp_file.write(pdf_bytes)
      temp_file.flush
    end

    # 4. AFNOR submission
    if submit_afnor
      invoice_number = invoice['invoiceNumber'] || invoice['invoice_number'] || 'INVOICE'
      flow_name = options[:afnor_flow_name] || "Invoice #{invoice_number}"
      tracking_id = options[:afnor_tracking_id] || invoice_number
      afnor_result = submit_invoice_afnor(temp_file.path, flow_name, tracking_id: tracking_id)
      result[:afnor] = afnor_result
    end

    # Final save
    if options[:output_path]
      File.binwrite(options[:output_path], pdf_bytes)
      result[:pdf_path] = options[:output_path]
    end
  ensure
    temp_file.close
    temp_file.unlink
  end

  result
end

#generate_facturx(invoice_data, pdf_source, profile: 'EN16931', output_format: 'pdf', sync: true, timeout: nil) ⇒ Object

Generates a Factur-X invoice from a dict/hash and a source PDF.



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/factpulse/helpers/client.rb', line 216

def generate_facturx(invoice_data, pdf_source, profile: 'EN16931', output_format: 'pdf', sync: true, timeout: nil)
  # Convert data to JSON string
  json_data = case invoice_data
              when String then invoice_data
              when Hash then JSON.generate(invoice_data)
              else
                if invoice_data.respond_to?(:to_h)
                  JSON.generate(invoice_data.to_h)
                elsif invoice_data.respond_to?(:to_hash)
                  JSON.generate(invoice_data.to_hash)
                else
                  raise FactPulseValidationError.new("Unsupported data type: #{invoice_data.class}")
                end
              end

  # Read source PDF
  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("Unsupported PDF type: #{pdf_source.class}")
                  end
                end
  pdf_filename = pdf_source.is_a?(String) ? File.basename(pdf_source) : 'invoice.pdf'

  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/processing/generate-invoice")

  # Build multipart request
  boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
  body = build_multipart_body(boundary, [
    { name: 'invoice_data', content: json_data },
    { name: 'profile', content: profile },
    { name: 'output_format', content: output_format },
    { name: 'source_pdf', content: pdf_content, filename: pdf_filename, content_type: 'application/pdf' }
  ])

  response = http_multipart_post(uri, body, boundary)

  if response.code == '401'
    reset_auth; ensure_authenticated; response = http_multipart_post(uri, body, boundary)
  end

  unless response.is_a?(Net::HTTPSuccess)
    # Extract error details from response body
    error_msg = "API Error (#{response.code})"
    errors = []

    begin
      error_data = JSON.parse(response.body)
      # Format FastAPI/Pydantic: {"detail": [{"loc": [...], "msg": "...", "type": "..."}]}
      if error_data['detail'].is_a?(Array)
        error_msg = 'Validation error'
        error_data['detail'].each do |err|
          next unless err.is_a?(Hash)
          loc = (err['loc'] || []).map(&:to_s).join(' -> ')
          errors << ValidationErrorDetail.new(
            level: 'ERROR',
            item: loc,
            reason: err['msg'] || err.to_s,
            source: 'validation',
            code: err['type']
          )
        end
      elsif error_data['detail'].is_a?(String)
        error_msg = error_data['detail']
      elsif error_data['errorMessage']
        error_msg = error_data['errorMessage']
      end
    rescue JSON::ParserError
      error_msg = "API Error (#{response.code}): #{response.body}"
    end

    warn "API Error #{response.code}: #{response.body}"
    raise FactPulseValidationError.new(error_msg, errors)
  end

  data = JSON.parse(response.body)

  if sync && data['task_id']
    result = poll_task(data['task_id'], timeout: timeout)
    if result['contenu_b64']
      return Base64.decode64(result['contenu_b64'])
    elsif result['contenu_xml']
      return result['contenu_xml']
    end
    raise FactPulseValidationError.new("Unexpected result: #{result.keys.join(', ')}")
  end

  data
end

#generate_test_certificate(**options) ⇒ Object

Generates a test certificate (NOT FOR PRODUCTION).



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/factpulse/helpers/client.rb', line 634

def generate_test_certificate(**options)
  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/processing/generate-test-certificate")
  body = {
    'cn' => options[:cn] || 'Test Organisation',
    'organisation' => options[:organisation] || 'Test Organisation',
    'email' => options[:email] || '[email protected]',
    'validity_days' => options[:validity_days] || 365,
    'key_size' => options[:key_size] || 2048
  }

  response = http_post_json(uri, body)
  raise FactPulseValidationError.new("Error: #{response.code}") unless response.is_a?(Net::HTTPSuccess)
  JSON.parse(response.body) rescue {}
end

#get_afnor_credentialsObject



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

def get_afnor_credentials; afnor_credentials_for_api; end

#get_chorus_pro_credentialsObject

Shorter aliases



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

def get_chorus_pro_credentials; chorus_credentials_for_api; end

#get_incoming_invoice_afnor(flow_id, include_document: false) ⇒ Hash

Retrieves JSON metadata of an incoming flow (supplier invoice). Downloads an incoming flow from the AFNOR PDP and extracts invoice metadata into a unified JSON format. Supports Factur-X, CII and UBL.

Note: This endpoint uses FactPulse JWT authentication (not AFNOR OAuth). The FactPulse server handles calling the PDP with stored credentials.

Examples:

invoice = client.get_incoming_invoice_afnor("550e8400-...")
puts "Supplier: #{invoice['supplier']['name']}"
puts "Total incl. tax: #{invoice['total_incl_tax']} #{invoice['currency']}"

Parameters:

  • flow_id (String)

    Flow identifier (UUID)

  • include_document (Boolean) (defaults to: false)

    If true, includes the document in base64

Returns:

  • (Hash)

    Invoice metadata (supplier, amounts, dates, etc.)

Raises:



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/factpulse/helpers/client.rb', line 441

def get_incoming_invoice_afnor(flow_id, include_document: false)
  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/afnor/incoming-flows/#{flow_id}")
  uri.query = "include_document=true" if include_document

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

  request = Net::HTTP::Get.new(uri)
  request['Authorization'] = "Bearer #{@access_token}"

  response = http.request(request)
  raise FactPulseValidationError.new("Incoming flow error: #{response.code}") unless response.is_a?(Net::HTTPSuccess)
  JSON.parse(response.body) rescue {}
end

#healthcheck_afnorObject

Checks the availability of the AFNOR Flow Service.



459
460
461
# File 'lib/factpulse/helpers/client.rb', line 459

def healthcheck_afnor
  make_afnor_request('GET', '/flow/v1/healthcheck')
end

#list_routing_codes_afnor(siren) ⇒ Object

Lists available routing codes for a SIREN.



476
477
478
# File 'lib/factpulse/helpers/client.rb', line 476

def list_routing_codes_afnor(siren)
  make_afnor_request('GET', "/directory/siren/#{siren}/routing-codes")
end

#lister_services_structure_chorus(id_structure_cpp) ⇒ Object

Lists the services of a Chorus Pro structure.



530
531
532
# File 'lib/factpulse/helpers/client.rb', line 530

def lister_services_structure_chorus(id_structure_cpp)
  make_chorus_request('GET', "/structures/#{id_structure_cpp}/services")
end

#obtenir_id_chorus_depuis_siret(siret, type_identifiant: 'SIRET') ⇒ Object

Gets the Chorus Pro ID of a structure from its SIRET.



525
526
527
# File 'lib/factpulse/helpers/client.rb', line 525

def obtenir_id_chorus_depuis_siret(siret, type_identifiant: 'SIRET')
  make_chorus_request('POST', '/structures/obtenir-id-depuis-siret', { 'siret' => siret, 'type_identifiant' => type_identifiant })
end

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



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/factpulse/helpers/client.rb', line 195

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/processing/tasks/#{task_id}/status"))
    reset_auth and next if response.code == '401'
    data = JSON.parse(response.body)
    return data['resultat'] || {} if data['statut'] == 'SUCCESS'
    if data['statut'] == 'FAILURE'
      # Format AFNOR: errorMessage, details
      r = data['resultat'] || {}
      raise FactPulseValidationError.new("Task #{task_id} failed: #{r['errorMessage'] || '?'}", (r['details'] || []).map { |e| ValidationErrorDetail.from_hash(e) })
    end
    sleep(current_interval / 1000.0); current_interval = [current_interval * 1.5, 10000].min
  end
end

#rechercher_structure_chorus(identifiant_structure: nil, raison_sociale: nil, type_identifiant: 'SIRET', restreindre_privees: true) ⇒ Object

Searches for structures on Chorus Pro.



510
511
512
513
514
515
516
517
# File 'lib/factpulse/helpers/client.rb', line 510

def rechercher_structure_chorus(identifiant_structure: nil, raison_sociale: nil, type_identifiant: 'SIRET', restreindre_privees: true)
  body = { 'restreindre_structures_privees' => restreindre_privees }
  body['identifiant_structure'] = identifiant_structure if identifiant_structure
  body['raison_sociale_structure'] = raison_sociale if raison_sociale
  body['type_identifiant_structure'] = type_identifiant if type_identifiant

  make_chorus_request('POST', '/structures/rechercher', body)
end

#reset_authObject



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

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

#search_flows_afnor(**criteria) ⇒ Object

Searches for AFNOR invoicing flows.



408
409
410
411
412
413
414
415
416
417
418
# File 'lib/factpulse/helpers/client.rb', line 408

def search_flows_afnor(**criteria)
  search_body = {
    'offset' => criteria[:offset] || 0,
    'limit' => criteria[:limit] || 25,
    'where' => {}
  }
  search_body['where']['trackingId'] = criteria[:tracking_id] if criteria[:tracking_id]
  search_body['where']['status'] = criteria[:status] if criteria[:status]

  make_afnor_request('POST', '/flow/v1/flows/search', json_data: search_body)
end

#search_siren_afnor(siren) ⇒ Object

Searches for a company by SIREN in the AFNOR directory.



471
472
473
# File 'lib/factpulse/helpers/client.rb', line 471

def search_siren_afnor(siren)
  make_afnor_request('GET', "/directory/siren/#{siren}")
end

#search_siret_afnor(siret) ⇒ Object

Searches for a company by SIRET in the AFNOR directory.



466
467
468
# File 'lib/factpulse/helpers/client.rb', line 466

def search_siret_afnor(siret)
  make_afnor_request('GET', "/directory/siret/#{siret}")
end

#sign_pdf(pdf_path, **options) ⇒ Object

Signs a PDF with the server-configured certificate.



608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# File 'lib/factpulse/helpers/client.rb', line 608

def sign_pdf(pdf_path, **options)
  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/processing/sign-pdf")
  pdf_content = File.binread(pdf_path)

  parts = [
    { name: 'pdf_file', content: pdf_content, filename: File.basename(pdf_path), content_type: 'application/pdf' },
    { name: 'use_pades_lt', content: (options[:use_pades_lt] ? 'true' : 'false') },
    { name: 'use_timestamp', content: (options.key?(:use_timestamp) ? (options[:use_timestamp] ? 'true' : 'false') : 'true') }
  ]
  parts << { name: 'reason', content: options[:reason] } if options[:reason]
  parts << { name: 'location', content: options[:location] } if options[:location]
  parts << { name: 'contact', content: options[:contact] } if options[:contact]

  boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
  body = build_multipart_body(boundary, parts)

  response = http_multipart_post(uri, body, boundary)
  raise FactPulseValidationError.new("Signature error: #{response.code}") unless response.is_a?(Net::HTTPSuccess)

  result = JSON.parse(response.body) rescue {}
  raise FactPulseValidationError.new("Invalid signature response") unless result['pdf_signe_base64']
  Base64.decode64(result['pdf_signe_base64'])
end

#soumettre_facture_chorus(facture_data) ⇒ Object

Submits an invoice to Chorus Pro.



535
536
537
# File 'lib/factpulse/helpers/client.rb', line 535

def soumettre_facture_chorus(facture_data)
  make_chorus_request('POST', '/factures/soumettre', facture_data)
end

#submit_invoice_afnor(pdf_path, flow_name, **options) ⇒ Object

Submits an invoice to a PDP via the AFNOR API.



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/factpulse/helpers/client.rb', line 389

def submit_invoice_afnor(pdf_path, flow_name, **options)
  pdf_content = File.binread(pdf_path)
  sha256 = Digest::SHA256.hexdigest(pdf_content)

  flow_info = {
    'name' => flow_name,
    'flowSyntax' => options[:flow_syntax] || 'CII',
    'flowProfile' => options[:flow_profile] || 'EN16931',
    'sha256' => sha256
  }
  flow_info['trackingId'] = options[:tracking_id] if options[:tracking_id]

  make_afnor_request('POST', '/flow/v1/flows', multipart: [
    { name: 'file', content: pdf_content, filename: File.basename(pdf_path), content_type: 'application/pdf' },
    { name: 'flowInfo', content: JSON.generate(flow_info), content_type: 'application/json' }
  ])
end

#validate_facturx_pdf(pdf_path, profile: nil, use_verapdf: false) ⇒ Object

Validates a Factur-X PDF.

Parameters:

  • pdf_path (String)

    Path to the PDF file

  • profile (String, nil) (defaults to: nil)

    Factur-X profile (MINIMUM, BASIC, EN16931, EXTENDED). If nil, auto-detected.

  • use_verapdf (Boolean) (defaults to: false)

    Enable strict PDF/A validation with VeraPDF (default: false)

Raises:



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/factpulse/helpers/client.rb', line 552

def validate_facturx_pdf(pdf_path, profile: nil, use_verapdf: false)
  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/processing/validate-facturx-pdf")
  pdf_content = File.binread(pdf_path)

  parts = [
    { name: 'pdf_file', content: pdf_content, filename: File.basename(pdf_path), content_type: 'application/pdf' },
    { name: 'use_verapdf', content: use_verapdf.to_s }
  ]
  parts << { name: 'profile', content: profile } if profile

  boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
  body = build_multipart_body(boundary, parts)

  response = http_multipart_post(uri, body, boundary)
  raise FactPulseValidationError.new("Validation error: #{response.code}") unless response.is_a?(Net::HTTPSuccess)
  JSON.parse(response.body) rescue {}
end

#validate_facturx_xml(xml_content, profile: 'EN16931') ⇒ Object

Validates a Factur-X XML.



572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/factpulse/helpers/client.rb', line 572

def validate_facturx_xml(xml_content, profile: 'EN16931')
  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/processing/validate-xml")

  boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
  body = build_multipart_body(boundary, [
    { name: 'xml_file', content: xml_content, filename: 'invoice.xml', content_type: 'application/xml' },
    { name: 'profile', content: profile }
  ])

  response = http_multipart_post(uri, body, boundary)
  raise FactPulseValidationError.new("Validation error: #{response.code}") unless response.is_a?(Net::HTTPSuccess)
  JSON.parse(response.body) rescue {}
end

#validate_pdf_signature(pdf_path) ⇒ Object

Validates the signature of a signed PDF.



588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/factpulse/helpers/client.rb', line 588

def validate_pdf_signature(pdf_path)
  ensure_authenticated
  uri = URI("#{@api_url}/api/v1/processing/validate-pdf-signature")
  pdf_content = File.binread(pdf_path)

  boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
  body = build_multipart_body(boundary, [
    { name: 'pdf_file', content: pdf_content, filename: File.basename(pdf_path), content_type: 'application/pdf' }
  ])

  response = http_multipart_post(uri, body, boundary)
  raise FactPulseValidationError.new("Validation error: #{response.code}") unless response.is_a?(Net::HTTPSuccess)
  JSON.parse(response.body) rescue {}
end