assinafy 2.1.1 → 2.2.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.
@@ -77,7 +77,7 @@ module Assinafy
77
77
 
78
78
  # List documents for an account.
79
79
  #
80
- # @param params [Hash] query parameters (`status`, `method`, `search`, `sort`, `tags`, `page`, `per_page`).
80
+ # @param params [Hash] `status`, `method`, `search`, `sort`, `tags`, `envelope_id`, `page`, `per_page`.
81
81
  # `tags` is a comma-separated String of tag IDs or an Array of them; documents must carry every tag.
82
82
  # @param account_id_override [String, nil]
83
83
  # @return [Hash{Symbol=>Array,Hash}] `{ data: [...], meta: { current_page:, per_page:, total:, last_page: } }`
@@ -124,6 +124,7 @@ module Assinafy
124
124
  acc_id = account_id(account_id_override)
125
125
  query = require_payload(params, 'Query parameters').transform_keys(&:to_sym)
126
126
  query[:tags] = query[:tags].join(',') if query[:tags].is_a?(Array)
127
+ require_string(query[:envelope_id], 'Envelope ID') unless query[:envelope_id].nil?
127
128
 
128
129
  call_list('Failed to list documents') do
129
130
  http_get("accounts/#{acc_id}/documents", query)
@@ -166,7 +167,8 @@ module Assinafy
166
167
  # }
167
168
  def search(query = nil, params = {}, account_id_override = nil)
168
169
  acc_id = account_id(account_id_override)
169
- filters = require_payload(params, 'Document search parameters')
170
+ filters = require_payload(params, 'Document search parameters').transform_keys(&:to_sym)
171
+ require_string(filters[:envelope_id], 'Envelope ID') unless filters[:envelope_id].nil?
170
172
  require_string(query, 'Search query') unless query.nil?
171
173
 
172
174
  call_list('Failed to search documents') do
@@ -212,6 +214,7 @@ module Assinafy
212
214
  # @raise [Assinafy::ApiError] on an unsuccessful API response
213
215
  # @raise [Assinafy::NetworkError] on transport or TLS failure
214
216
  # @raise [Assinafy::ValidationError] on invalid required input
217
+ # @param expand [String, Array<String>, nil] `envelope_id`, `envelope`, or both comma-separated
215
218
  # @see GET /documents/{document_id}
216
219
  # @example Fetch a document
217
220
  # # Request: GET /documents/{document_id}
@@ -243,11 +246,12 @@ module Assinafy
243
246
  # 'created_at' => '2026-06-05T21:21:12Z',
244
247
  # 'updated_at' => '2026-06-05T21:21:15Z'
245
248
  # }
246
- def details(document_id)
249
+ def details(document_id, expand: nil)
247
250
  doc_id = require_id(document_id, 'Document ID')
251
+ expansions = document_expansions(expand)
248
252
 
249
253
  call('Failed to fetch document details') do
250
- http_get("documents/#{doc_id}")
254
+ http_get("documents/#{doc_id}", { expand: expansions })
251
255
  end
252
256
  end
253
257
 
@@ -387,6 +391,9 @@ module Assinafy
387
391
  # @raise [Assinafy::ApiError] on an unsuccessful API response
388
392
  # @raise [Assinafy::NetworkError] on transport or TLS failure
389
393
  # @raise [Assinafy::ValidationError] on invalid required input
394
+ # @param artifact [String, nil] `certificated` renders signatures and stamps; other values use the original
395
+ # @note Signed renders require a certificated document and workspace credentials. Rendering can answer
396
+ # 503 with Retry-After; the SDK does not retry. Do not cache signed renders.
390
397
  # @see GET /documents/{document_id}/thumbnail
391
398
  # @example Download the thumbnail and save it
392
399
  # # Request: GET /documents/{document_id}/thumbnail
@@ -396,11 +403,12 @@ module Assinafy
396
403
  # bytes.class # => String
397
404
  # bytes.byteslice(0, 4) # => "\xFF\xD8\xFF\xE0" (JPEG magic bytes)
398
405
  # File.binwrite('thumb.jpg', bytes)
399
- def thumbnail(document_id)
406
+ def thumbnail(document_id, artifact: nil)
407
+ require_string(artifact, 'Artifact') unless artifact.nil?
400
408
  doc_id = require_id(document_id, 'Document ID')
401
409
 
402
410
  call_binary('Failed to download document thumbnail') do
403
- http_get("documents/#{doc_id}/thumbnail")
411
+ http_get("documents/#{doc_id}/thumbnail", { artifact: artifact })
404
412
  end
405
413
  end
406
414
 
@@ -412,6 +420,10 @@ module Assinafy
412
420
  # @raise [Assinafy::ApiError] on an unsuccessful API response
413
421
  # @raise [Assinafy::NetworkError] on transport or TLS failure
414
422
  # @raise [Assinafy::ValidationError] on invalid required input
423
+ # @param artifact [String, nil] `certificated` renders signatures and stamps; other values use the original
424
+ # @note Signed renders require a certificated document and workspace credentials. Rendering can answer
425
+ # 503 with Retry-After; the SDK does not retry. Certificate pages have no page ID.
426
+ # Digital-certificate seals are visible only in the pades artifact. Do not cache signed renders.
415
427
  # @see GET /documents/{document_id}/pages/{page_id}/download
416
428
  # @example Download a single page image
417
429
  # # Request: GET /documents/{document_id}/pages/{page_id}/download
@@ -421,22 +433,24 @@ module Assinafy
421
433
  # # Response: raw image bytes (NOT a JSON envelope):
422
434
  # bytes.class # => String
423
435
  # File.binwrite('page-1.png', bytes)
424
- def download_page(document_id, page_id)
436
+ def download_page(document_id, page_id, artifact: nil)
437
+ require_string(artifact, 'Artifact') unless artifact.nil?
425
438
  doc_id = require_id(document_id, 'Document ID')
426
439
  pid = require_id(page_id, 'Page ID')
427
440
 
428
441
  call_binary('Failed to download page') do
429
- http_get("documents/#{doc_id}/pages/#{pid}/download")
442
+ http_get("documents/#{doc_id}/pages/#{pid}/download", { artifact: artifact })
430
443
  end
431
444
  end
432
445
 
433
- # List the activity log for a document.
446
+ # Read one page of document activities as an Array. Use {#activities_page} for pagination metadata.
434
447
  #
435
448
  # @param document_id [String]
436
449
  # @return [Array<Hash>] newest-first activity entries (empty Array when there are none)
437
450
  # @raise [Assinafy::ApiError] on an unsuccessful API response
438
451
  # @raise [Assinafy::NetworkError] on transport or TLS failure
439
452
  # @raise [Assinafy::ValidationError] on invalid required input
453
+ # @param params [Hash] `sort` (`id` or `-id`), `page`, `per_page`
440
454
  # @see GET /documents/{documentId}/activities
441
455
  # @example List a document's activity log
442
456
  # # Request: GET /documents/{document_id}/activities
@@ -461,11 +475,30 @@ module Assinafy
461
475
  # 'created_at' => '2026-06-05T21:21:13Z'
462
476
  # }
463
477
  # ]
464
- def activities(document_id)
465
- doc_id = require_id(document_id, 'Document ID')
478
+ def activities(document_id, params = {})
479
+ activities_page(document_id, params).fetch(:data)
480
+ end
466
481
 
467
- call_array('Failed to fetch document activities') do
468
- http_get("documents/#{doc_id}/activities")
482
+ # Read document activities together with pagination metadata (20 entries per page by default).
483
+ #
484
+ # @param document_id [String]
485
+ # @param params [Hash] `sort` (`id` or `-id`), `page`, `per_page`
486
+ # @return [Hash] `{ data: [DocumentActivity, ...], meta: { current_page:, per_page:, total:, last_page: } }`
487
+ # @raise [Assinafy::ValidationError] on invalid document ID or query parameters
488
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
489
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
490
+ # @see GET /documents/{documentId}/activities
491
+ # @example Read the oldest activities and their pagination headers
492
+ # client.documents.activities_page('document-id', sort: 'id', page: 1, per_page: 20)
493
+ # # Request: GET /documents/document-id/activities?sort=id&page=1&per-page=20 (no body)
494
+ # # => { data: [{ 'id' => 1, 'event' => 'document_uploaded', 'message' => 'Document created.',
495
+ # # 'payload' => [], 'origin' => nil, 'created_at' => '2026-11-04T12:00:00Z' }],
496
+ # # meta: { current_page: 1, per_page: 20, total: 1, last_page: 1 } }
497
+ def activities_page(document_id, params = {})
498
+ doc_id = require_id(document_id, 'Document ID')
499
+ query = activity_params(params)
500
+ call_list('Failed to fetch document activities') do
501
+ http_get("documents/#{doc_id}/activities", query)
469
502
  end
470
503
  end
471
504
 
@@ -491,15 +524,21 @@ module Assinafy
491
524
  end
492
525
  end
493
526
 
494
- # Create a document from a template, optionally creating its virtual assignment.
527
+ # Create a document from a template; its assignment is created asynchronously.
528
+ # Poll until pending_signature or failed. Placed signer fields use collect; DigitalCertificate
529
+ # requires a template without those fields. Editor roles are filled through editor_fields.
530
+ # The server validates signing-step relationships using the template's role types; copy receivers
531
+ # do not participate in signing steps.
495
532
  #
496
533
  # @param template_id [String]
497
- # @param signers_or_payload [Array<Hash>, Hash] signer references (`role_id` + `id`)
534
+ # @param signers_or_payload [Array<Hash>, Hash] signer references (`role_id` + `id` or `email`)
498
535
  # or a full payload Hash. When a Hash is passed, `options` is merged into it.
499
536
  # @param options [Hash] additional body fields (`name`, `message`,
500
- # `editor_fields`, `expires_at`, ...)
537
+ # `editor_fields`, `expires_at`, `max_total_credits`, ...)
538
+ # @option options [String] :idempotency_key sent as Idempotency-Key, never in the JSON body;
539
+ # also accepted in a full payload Hash, with options taking precedence
501
540
  # @param account_id_override [String, nil]
502
- # @return [Hash] document object with an embedded `assignment` (signers, items, signing_urls)
541
+ # @return [Hash] uploaded document with assignment: nil until background processing finishes
503
542
  #
504
543
  # @raise [Assinafy::ApiError] on an unsuccessful API response
505
544
  # @raise [Assinafy::NetworkError] on transport or TLS failure
@@ -531,15 +570,7 @@ module Assinafy
531
570
  # 'template_id' => 'template-id',
532
571
  # 'name' => 'sample-contract.pdf',
533
572
  # 'status' => 'uploaded',
534
- # 'assignment' => {
535
- # 'id' => 'assignment-id',
536
- # 'method' => 'virtual',
537
- # 'signers' => [{ 'id' => 'fa8c140c...', 'full_name' => 'Suzana Cordeiro',
538
- # 'email' => 'signer@example.com', 'has_accepted_terms' => false }],
539
- # 'summary' => { 'signer_count' => 1, 'completed_count' => 0, 'signers' => [] },
540
- # 'signing_urls' => [{ 'signer_id' => 'customid1', 'url' => 'https://.../sign/...' }]
541
- # # ... (also items, copy_receivers, expires_at, message)
542
- # },
573
+ # 'assignment' => nil,
543
574
  # 'tags' => [{ 'id' => 'ab12cd34...', 'name' => 'Onboarding' }],
544
575
  # 'created_at' => '2024-07-23T15:05:17Z',
545
576
  # 'updated_at' => '2024-07-23T15:05:17Z'
@@ -548,12 +579,14 @@ module Assinafy
548
579
  def create_from_template(template_id, signers_or_payload, options = {}, account_id_override = nil)
549
580
  tmpl_id = require_id(template_id, 'Template ID')
550
581
  acc_id = account_id(account_id_override)
582
+ options = require_payload(options, 'Template document options').transform_keys(&:to_s)
551
583
  body = template_body(signers_or_payload, options, require_signer_id: true)
584
+ headers = idempotency_headers(body.delete('idempotency_key'))
552
585
 
553
586
  @logger.info("Creating document from template #{tmpl_id} for account #{acc_id}")
554
587
 
555
588
  call('Failed to create document from template') do
556
- http_post("accounts/#{acc_id}/templates/#{tmpl_id}/documents", body)
589
+ http_post("accounts/#{acc_id}/templates/#{tmpl_id}/documents", body, headers: headers)
557
590
  end
558
591
  end
559
592
 
@@ -886,6 +919,34 @@ module Assinafy
886
919
 
887
920
  private
888
921
 
922
+ def document_expansions(expand)
923
+ return nil if expand.nil?
924
+
925
+ values = expand.is_a?(String) ? expand.split(',', -1) : expand
926
+ unless values.is_a?(Array) && !values.empty? && (values - %w[envelope_id envelope]).empty?
927
+ raise ValidationError.new('expand must contain envelope_id and/or envelope')
928
+ end
929
+
930
+ values.join(',')
931
+ end
932
+
933
+ def activity_params(params)
934
+ query = query_params(require_payload(params, 'Activity parameters'))
935
+ if query.key?('sort') && !%w[id -id].include?(query['sort'])
936
+ raise ValidationError.new('Activity sort must be id or -id')
937
+ end
938
+
939
+ %w[page per-page].each do |key|
940
+ next unless query.key?(key)
941
+
942
+ value = query[key]
943
+ unless value.is_a?(Integer) && value > 0 && (key != 'per-page' || value <= 100)
944
+ raise ValidationError.new("#{key} must be a positive Integer (per_page at most 100)")
945
+ end
946
+ end
947
+ query
948
+ end
949
+
889
950
  def uploaded_document_id(document)
890
951
  id = document['id'] if document.is_a?(Hash)
891
952
  require_id(id, 'Uploaded document ID')
@@ -919,8 +980,9 @@ module Assinafy
919
980
  body = body_params(body)
920
981
  validate_template_signers!(body['signers'], require_signer_id)
921
982
  normalised = AssignmentResource.build_payload(
922
- { signers: body['signers'], expires_at: body['expires_at'], message: body['message'] },
923
- allow_signers_without_id: !require_signer_id
983
+ { signers: body['signers'], expires_at: body['expires_at'], message: body['message'],
984
+ max_total_credits: body['max_total_credits'] },
985
+ allow_signers_without_id: true, validate_steps: false
924
986
  )
925
987
  body['signers'].zip(normalised['signers']).each { |signer, ref| signer.merge!(ref) }
926
988
  validate_editor_fields!(body['editor_fields']) if body.key?('editor_fields')
@@ -931,7 +993,13 @@ module Assinafy
931
993
  require_array(signers, 'Signers').each do |signer|
932
994
  require_payload(signer, 'Signer')
933
995
  require_id(signer['role_id'], 'Template role ID')
934
- require_id(signer['id'], 'Signer ID') if require_signer_id
996
+ if signer.key?('id')
997
+ require_id(signer['id'], 'Signer ID')
998
+ elsif require_signer_id
999
+ Utils.require_email(signer['email'])
1000
+ require_string(signer['name'], 'Signer name') if signer.key?('name')
1001
+ require_string(signer['whatsapp_phone_number'], 'WhatsApp number') if signer.key?('whatsapp_phone_number')
1002
+ end
935
1003
  end
936
1004
  %w[role_id id].each do |key|
937
1005
  values = signers.filter_map { |signer| signer[key] }
@@ -945,7 +1013,7 @@ module Assinafy
945
1013
  fields.each do |field|
946
1014
  require_payload(field, 'Editor field')
947
1015
  require_id(field['field_id'], 'Editor field ID')
948
- raise ValidationError.new('Editor field value must be a String') unless field['value'].is_a?(String)
1016
+ require_string(field['value'], 'Editor field value')
949
1017
  end
950
1018
  end
951
1019
 
@@ -0,0 +1,312 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Assinafy
4
+ module Resources
5
+ # Groups documents into one invitation while retaining each document's signatures and artifacts.
6
+ class EnvelopeResource < BaseResource
7
+ # @param params [Hash] search, status (open/closed), page, per_page
8
+ # @param account_id_override [String, nil]
9
+ # @return [Hash] paginated DocumentEnvelope objects
10
+ # @raise [ValidationError] on invalid filters or account ID
11
+ # @raise [ApiError, NetworkError] on API or transport failure
12
+ # @see GET /accounts/{accountId}/envelopes
13
+ # @example
14
+ # client.envelopes.list(status: 'open') # GET .../envelopes?status=open; no body
15
+ # # => { data: [{ 'id' => 'envelope-id', 'name' => 'Contract', 'documents' => [],
16
+ # # 'message' => nil, 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }] }
17
+ def list(params = {}, account_id_override = nil)
18
+ query = query_params(params)
19
+ if query.key?('status') && !%w[open closed].include?(query['status'])
20
+ raise ValidationError.new('status must be open or closed')
21
+ end
22
+ if query.key?('search') && !query['search'].is_a?(String)
23
+ raise ValidationError.new('search must be a String')
24
+ end
25
+
26
+ call_list('Failed to list envelopes') { http_get(envelopes_path(account_id_override), query) }
27
+ end
28
+
29
+ # @param payload [Hash] EnvelopeCreateRequest: name, signers, documents, optional message/max_total_credits
30
+ # @param account_id_override [String, nil]
31
+ # @param idempotency_key [String, nil] reuse after a lost response to avoid creating or charging twice
32
+ # @return [Hash] DocumentEnvelope; notification failure does not undo creation
33
+ # @raise [ValidationError] on invalid payload, key or IDs
34
+ # @raise [ApiError, NetworkError] on API or transport failure
35
+ # @see POST /accounts/{accountId}/envelopes
36
+ # @example
37
+ # client.envelopes.create({ name: 'Contract', signers: [{ id: 'signer-id' }],
38
+ # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }] }, idempotency_key: 'request-id')
39
+ # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
40
+ # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }] }
41
+ # # => { 'resource' => 'envelope', 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil,
42
+ # # 'documents' => [{ 'id' => 'document-id', 'position' => 1, 'name' => 'contract.pdf',
43
+ # # 'status' => 'pending_signature', 'artifacts' => {}, 'signers' => [] }],
44
+ # # 'counts' => { 'pending_signature' => 1 }, 'signing_urls' => [],
45
+ # # 'created_at' => '2026-11-11T12:00:00Z' }
46
+ def create(payload, account_id_override = nil, idempotency_key: nil)
47
+ body = create_payload(payload)
48
+ path = envelopes_path(account_id_override)
49
+ headers = idempotency_headers(idempotency_key)
50
+ call('Failed to create envelope') { http_post(path, body, headers: headers) }
51
+ end
52
+
53
+ # @param payload [Hash] the same EnvelopeCreateRequest as create
54
+ # @param account_id_override [String, nil]
55
+ # @return [Hash] CostEstimate; creates and charges nothing
56
+ # @raise [ValidationError] on invalid payload or IDs
57
+ # @raise [ApiError, NetworkError] on API or transport failure
58
+ # @see POST /accounts/{accountId}/envelopes/estimate-cost
59
+ # @example
60
+ # client.envelopes.estimate_cost(name: 'Contract', signers: [{ id: 'signer-id' }],
61
+ # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }])
62
+ # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
63
+ # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }] }
64
+ # # => { 'total_credits' => 0, 'has_sufficient_resources' => true, 'breakdown' => [] }
65
+ def estimate_cost(payload, account_id_override = nil)
66
+ body = create_payload(payload)
67
+ path = "#{envelopes_path(account_id_override)}/estimate-cost"
68
+ call('Failed to estimate envelope cost') { http_post(path, body) }
69
+ end
70
+
71
+ # @param envelope_id [String]
72
+ # @param account_id_override [String, nil]
73
+ # @return [Hash] DocumentEnvelope (see create for its complete shape)
74
+ # @raise [ValidationError] on invalid IDs
75
+ # @raise [ApiError, NetworkError] on API or transport failure
76
+ # @see GET /accounts/{accountId}/envelopes/{envelopeId}
77
+ # @example
78
+ # client.envelopes.get('envelope-id') # GET .../envelopes/envelope-id; no body
79
+ # # => { 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil, 'documents' => [],
80
+ # # 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }
81
+ def get(envelope_id, account_id_override = nil)
82
+ path = envelope_path(envelope_id, account_id_override)
83
+ call('Failed to get envelope') { http_get(path) }
84
+ end
85
+
86
+ # @param envelope_id [String]
87
+ # @param payload [Hash] name, message (nil clears), document_ids in desired order
88
+ # @param account_id_override [String, nil]
89
+ # @return [Hash] updated DocumentEnvelope
90
+ # @raise [ValidationError] on invalid payload or IDs
91
+ # @raise [ApiError, NetworkError] on API or transport failure
92
+ # @see PATCH /accounts/{accountId}/envelopes/{envelopeId}
93
+ # @example
94
+ # client.envelopes.update('envelope-id', message: nil)
95
+ # # PATCH body: { "message": null }
96
+ # # => { 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil, 'documents' => [],
97
+ # # 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }
98
+ def update(envelope_id, payload, account_id_override = nil)
99
+ body = require_payload(payload).transform_keys(&:to_s)
100
+ require_keys!(body, %w[name message document_ids])
101
+ validate_name!(body['name']) if body.key?('name')
102
+ validate_message!(body['message'])
103
+ unique_ids!(body['document_ids'], 'document_ids') if body.key?('document_ids')
104
+ path = envelope_path(envelope_id, account_id_override)
105
+ call('Failed to update envelope') { http_patch(path, body) }
106
+ end
107
+
108
+ # @param envelope_id [String]
109
+ # @param account_id_override [String, nil]
110
+ # @return [nil] deletes only the closed envelope; its documents remain
111
+ # @raise [ValidationError] on invalid IDs
112
+ # @raise [ApiError, NetworkError] on API or transport failure (409 while open)
113
+ # @see DELETE /accounts/{accountId}/envelopes/{envelopeId}
114
+ # @example
115
+ # client.envelopes.delete('envelope-id') # DELETE .../envelopes/envelope-id; no body
116
+ # # => nil
117
+ def delete(envelope_id, account_id_override = nil)
118
+ path = envelope_path(envelope_id, account_id_override)
119
+ call_void('Failed to delete envelope') { http_delete(path) }
120
+ end
121
+
122
+ # @param envelope_id [String]
123
+ # @param params [Hash] sort, page, per_page
124
+ # @param account_id_override [String, nil]
125
+ # @return [Hash] paginated EnvelopeActivity objects
126
+ # @raise [ValidationError] on invalid IDs or query shape
127
+ # @raise [ApiError, NetworkError] on API or transport failure
128
+ # @see GET /accounts/{accountId}/envelopes/{envelopeId}/activities
129
+ # @example
130
+ # client.envelopes.activities('envelope-id', per_page: 20)
131
+ # # GET .../envelopes/envelope-id/activities?per-page=20; no body
132
+ # # => { data: [{ 'document_id' => 'document-id', 'document_name' => 'contract.pdf',
133
+ # # 'event' => 'signature_requested', 'created_at' => '2026-11-11T12:00:00Z' }] }
134
+ def activities(envelope_id, params = {}, account_id_override = nil)
135
+ path = "#{envelope_path(envelope_id, account_id_override)}/activities"
136
+ query = query_params(params)
137
+ call_list('Failed to list envelope activities') { http_get(path, query) }
138
+ end
139
+
140
+ # @param envelope_id [String]
141
+ # @param artifact [String] original, certificated, certificate-page, pades or bundle
142
+ # @param account_id_override [String, nil]
143
+ # @return [String] binary ZIP of available document artifacts in envelope order
144
+ # @raise [ValidationError] on invalid IDs or artifact
145
+ # @raise [ApiError, NetworkError] on API or transport failure (404 if no artifact exists)
146
+ # @see GET /accounts/{accountId}/envelopes/{envelopeId}/download/{artifactName}
147
+ # @example
148
+ # client.envelopes.download('envelope-id', 'original')
149
+ # # GET .../envelopes/envelope-id/download/original; no body; => binary ZIP bytes
150
+ def download(envelope_id, artifact = 'certificated', account_id_override = nil)
151
+ unless DocumentResource::ARTIFACT_TYPES.include?(artifact)
152
+ raise ValidationError.new("artifact must be one of: #{DocumentResource::ARTIFACT_TYPES.join(', ')}")
153
+ end
154
+
155
+ path = "#{envelope_path(envelope_id, account_id_override)}/download/#{artifact}"
156
+ call_binary('Failed to download envelope') { http_get(path) }
157
+ end
158
+
159
+ # @param envelope_id [String]
160
+ # @param account_id_override [String, nil]
161
+ # @return [Array<Hash>] each document's id, status and cancelled flag; repeatable
162
+ # @raise [ValidationError] on invalid IDs
163
+ # @raise [ApiError, NetworkError] on API or transport failure
164
+ # @see PUT /accounts/{accountId}/envelopes/{envelopeId}/cancel
165
+ # @example
166
+ # client.envelopes.cancel('envelope-id') # PUT .../envelopes/envelope-id/cancel; no body
167
+ # # => [{ 'id' => 'document-id', 'status' => 'rejected_by_user', 'cancelled' => true }]
168
+ def cancel(envelope_id, account_id_override = nil)
169
+ path = "#{envelope_path(envelope_id, account_id_override)}/cancel"
170
+ call_array('Failed to cancel envelope') { http_put(path) }
171
+ end
172
+
173
+ # @param envelope_id [String]
174
+ # @param signer_id [String]
175
+ # @param account_id_override [String, nil]
176
+ # @return [Hash] is_sent, envelope_id, signer_id; paid notifications are charged
177
+ # @raise [ValidationError] on invalid IDs
178
+ # @raise [ApiError, NetworkError] on API or transport failure
179
+ # @see PUT /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/resend
180
+ # @example
181
+ # client.envelopes.resend_notification('envelope-id', 'signer-id')
182
+ # # PUT .../envelopes/envelope-id/signers/signer-id/resend; no body
183
+ # # => { 'is_sent' => true, 'envelope_id' => 'envelope-id', 'signer_id' => 'signer-id' }
184
+ def resend_notification(envelope_id, signer_id, account_id_override = nil)
185
+ sid = require_id(signer_id, 'Signer ID')
186
+ path = "#{envelope_path(envelope_id, account_id_override)}/signers/#{sid}/resend"
187
+ call('Failed to resend envelope invitation') { http_put(path) }
188
+ end
189
+
190
+ # @param envelope_id [String]
191
+ # @param payload [Hash] EnvelopeDocumentRequest plus optional max_total_credits
192
+ # @param account_id_override [String, nil]
193
+ # @return [Hash] DocumentEnvelope; notifies the chosen existing envelope signers
194
+ # @raise [ValidationError] on invalid payload or IDs
195
+ # @raise [ApiError, NetworkError] on API or transport failure
196
+ # @see POST /accounts/{accountId}/envelopes/{envelopeId}/documents
197
+ # @example
198
+ # client.envelopes.add_document('envelope-id', id: 'document-id', signer_ids: ['signer-id'])
199
+ # # POST body: { "id": "document-id", "signer_ids": ["signer-id"] }
200
+ # # => DocumentEnvelope, as returned by create, with the document appended
201
+ def add_document(envelope_id, payload, account_id_override = nil)
202
+ body = document_payload(payload)
203
+ path = "#{envelope_path(envelope_id, account_id_override)}/documents"
204
+ call('Failed to add envelope document') { http_post(path, body) }
205
+ end
206
+
207
+ # @param envelope_id [String]
208
+ # @param document_id [String]
209
+ # @param account_id_override [String, nil]
210
+ # @return [Hash] DocumentEnvelope; removes and cancels the open document, notifying its recipients
211
+ # @raise [ValidationError] on invalid IDs
212
+ # @raise [ApiError, NetworkError] on API or transport failure (409 if document is closed)
213
+ # @see DELETE /accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}
214
+ # @example
215
+ # client.envelopes.remove_document('envelope-id', 'document-id')
216
+ # # DELETE .../envelopes/envelope-id/documents/document-id; no body
217
+ # # => { 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil, 'documents' => [],
218
+ # # 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }
219
+ def remove_document(envelope_id, document_id, account_id_override = nil)
220
+ id = require_id(document_id, 'Document ID')
221
+ path = "#{envelope_path(envelope_id, account_id_override)}/documents/#{id}"
222
+ call('Failed to remove envelope document') { http_delete(path) }
223
+ end
224
+
225
+ private
226
+
227
+ def envelopes_path(override)
228
+ "accounts/#{account_id(override)}/envelopes"
229
+ end
230
+
231
+ def envelope_path(envelope_id, override)
232
+ "#{envelopes_path(override)}/#{require_id(envelope_id, 'Envelope ID')}"
233
+ end
234
+
235
+ def require_keys!(body, allowed)
236
+ if body.empty? || (body.keys - allowed).any?
237
+ raise ValidationError.new("Provide only envelope fields: #{allowed.join(', ')}")
238
+ end
239
+ end
240
+
241
+ def validate_name!(name)
242
+ require_string(name, 'Name', max_length: 255)
243
+ raise ValidationError.new('Name cannot contain <') if name.include?('<')
244
+ end
245
+
246
+ def validate_message!(message)
247
+ raise ValidationError.new('message must be a String or nil') unless message.nil? || message.is_a?(String)
248
+ end
249
+
250
+ def unique_ids!(ids, label)
251
+ require_array(ids, label).each { |id| require_id(id, label) }
252
+ raise ValidationError.new("#{label} must not contain duplicates") unless ids.uniq == ids
253
+
254
+ ids
255
+ end
256
+
257
+ def create_payload(payload)
258
+ body = body_params(require_payload(payload))
259
+ require_keys!(body, %w[name message max_total_credits signers documents])
260
+ validate_name!(body['name'])
261
+ validate_message!(body['message'])
262
+ Utils.require_credit_ceiling(body['max_total_credits'])
263
+ body['signers'] = bounded_items(body['signers'], 'signers').map { |signer| envelope_signer(signer) }
264
+ body['documents'] = bounded_items(body['documents'], 'documents').map do |document|
265
+ document_payload(document, body['signers'])
266
+ end
267
+ validate_membership!(body)
268
+ body
269
+ end
270
+
271
+ def validate_membership!(body)
272
+ ids = unique_ids!(body['signers'].map { |signer| signer['id'] }, 'signers')
273
+ unique_ids!(body['documents'].map { |document| document['id'] }, 'documents')
274
+ used = body['documents'].flat_map { |document| document['signer_ids'] }.uniq
275
+ raise ValidationError.new('Every envelope signer must be on a document') unless used.sort == ids.sort
276
+ end
277
+
278
+ def bounded_items(value, label)
279
+ items = require_array(value, label)
280
+ raise ValidationError.new("An envelope supports at most 20 #{label}") if items.length > 20
281
+
282
+ items
283
+ end
284
+
285
+ def envelope_signer(signer)
286
+ require_payload(signer, 'Envelope signer')
287
+ require_keys!(signer, %w[id verification_method notification_methods embedded])
288
+ require_id(signer['id'], 'Signer ID')
289
+ AssignmentResource.build_payload(signers: [signer]).fetch('signers').first
290
+ end
291
+
292
+ def document_payload(payload, signers = nil)
293
+ body = body_params(require_payload(payload, 'Envelope document'))
294
+ allowed = %w[id method entries signer_ids expires_at copy_receiver_ids]
295
+ allowed << 'max_total_credits' unless signers
296
+ require_keys!(body, allowed)
297
+ require_id(body['id'], 'Document ID')
298
+ ids = unique_ids!(body['signer_ids'], 'signer_ids')
299
+ selected = signers ? signers.select { |signer| ids.include?(signer['id']) } : ids
300
+ if signers && selected.length != ids.length
301
+ raise ValidationError.new('Document signers must belong to the envelope')
302
+ end
303
+
304
+ AssignmentResource.build_payload(method: body.fetch('method', 'virtual'), signers: selected,
305
+ entries: body['entries'], expires_at: body['expires_at'],
306
+ copy_receivers: body['copy_receiver_ids'])
307
+ Utils.require_credit_ceiling(body['max_total_credits'])
308
+ body
309
+ end
310
+ end
311
+ end
312
+ end
@@ -203,9 +203,8 @@ module Assinafy
203
203
 
204
204
  # Validate a single value against a field definition.
205
205
  #
206
- # The OpenAPI declares workspace Authorization, which is used when
207
- # `signer_access_code:` is omitted. The deployed API also accepts the signer
208
- # access code: when the keyword is given it must be a non-blank code, and
206
+ # Workspace authorization is used when `signer_access_code:` is omitted.
207
+ # When the keyword is given it must be a non-blank code, and
209
208
  # only the code is sent (never the workspace credentials).
210
209
  #
211
210
  # @param field_id [String]
@@ -287,6 +287,8 @@ module Assinafy
287
287
  # @raise [Assinafy::NetworkError] on transport or TLS failure
288
288
  # @raise [Assinafy::ValidationError] on invalid required input
289
289
  def revoke(token:, client_id:, token_type_hint: nil, client_secret: nil)
290
+ require_string(client_secret, 'Client secret') unless client_secret.nil?
291
+
290
292
  if !token_type_hint.nil? && !TOKEN_TYPE_HINTS.include?(token_type_hint.to_s)
291
293
  raise ValidationError.new(
292
294
  "Token type hint must be one of: #{TOKEN_TYPE_HINTS.join(', ')}",
@@ -396,6 +398,10 @@ module Assinafy
396
398
  # pass `"#{protected_resource_metadata['authorization_servers'].first}" \
397
399
  # "/.well-known/oauth-authorization-server"` to follow discovery strictly
398
400
  # @return [Hash{String=>Object}] the bare metadata object
401
+ # @raise [Assinafy::OAuthError] on an unsuccessful metadata response
402
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
403
+ # @raise [Assinafy::ValidationError] when the URL is not absolute HTTPS without userinfo or fragment
404
+ # @see GET https://auth.assinafy.com.br/.well-known/oauth-authorization-server
399
405
  #
400
406
  # @example Discover endpoints instead of hardcoding them
401
407
  # metadata = client.oauth.authorization_server_metadata