assinafy 2.3.0 → 2.4.1

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.
@@ -7,18 +7,21 @@ module Assinafy
7
7
  # See https://api.assinafy.com.br/v1/docs#document for the full
8
8
  # documentation of these endpoints.
9
9
  class DocumentResource < BaseResource
10
- READY_STATUSES = %w[metadata_ready pending_signature certificated].freeze
10
+ READY_STATUSES = %w[metadata_ready pending_signature pending_identity_review certificating certificated].freeze
11
11
  FAILED_STATUSES = %w[failed rejected_by_signer rejected_by_user expired].freeze
12
12
  ARTIFACT_TYPES = %w[original certificated certificate-page bundle pades].freeze
13
+ UPLOAD_EXTENSIONS = %w[.pdf .doc .docx .odt].freeze
14
+ private_constant :UPLOAD_EXTENSIONS
13
15
 
14
- # Upload a PDF and create a document.
16
+ # Upload a PDF, or a Word or OpenDocument text file (`.doc`, `.docx`, `.odt`) that the API
17
+ # converts to PDF, and create a document.
15
18
  #
16
- # @param source [String, Hash] either a path to a PDF on disk, or a
19
+ # @param source [String, Hash] either a path to the file on disk, or a
17
20
  # Hash with `:file_path` (path) **or** `:buffer` + `:file_name` (raw bytes).
18
21
  # @param options [Hash]
19
22
  # @option options [String] :account_id override the client default
20
23
  # @return [Hash] document object
21
- # @raise [Assinafy::ValidationError] on invalid input or empty/non-PDF file
24
+ # @raise [Assinafy::ValidationError] on invalid input, an empty file or an unsupported format
22
25
  # @raise [Assinafy::ApiError] on a non-2xx response
23
26
  #
24
27
  # @see POST /accounts/{account_id}/documents
@@ -36,10 +39,10 @@ module Assinafy
36
39
  # 'name' => 'customer_agreement.pdf',
37
40
  # 'status' => 'uploaded',
38
41
  # 'artifacts' => {
39
- # 'original' => 'https://sandbox.assinafy.com.br/v1/documents/<id>/download/original'
42
+ # 'original' => 'https://api.assinafy.com.br/v1/documents/<id>/download/original'
40
43
  # },
41
44
  # 'is_closed' => false,
42
- # 'signing_url' => 'https://app-sandbox.assinafy.com.br/sign/document-id',
45
+ # 'signing_url' => 'https://app.assinafy.com.br/sign/document-id',
43
46
  # 'verification_code' => nil,
44
47
  # 'verification_url' => nil,
45
48
  # 'decline_reason' => nil,
@@ -51,19 +54,23 @@ module Assinafy
51
54
  # }
52
55
  # @example Upload raw bytes from memory
53
56
  # client.documents.upload(buffer: pdf_bytes, file_name: 'in_memory.pdf')
54
- # @note The SDK enforces the `.pdf` extension and 25 MB limit; the API
55
- # performs authoritative PDF-structure validation.
57
+ # @example Upload a Word file; the document is stored as a PDF
58
+ # # Body: file=<binary application/vnd.openxmlformats-officedocument.wordprocessingml.document>
59
+ # client.documents.upload('/tmp/customer_agreement.docx')
60
+ # # => { 'resource' => 'document', 'id' => 'document-id', 'status' => 'uploaded', ... }
61
+ # @note The SDK enforces the file extension and 25 MB limit; the API
62
+ # performs authoritative file-structure validation.
56
63
  # @raise [Assinafy::NetworkError] on transport or TLS failure
57
64
  def upload(source, options = {})
58
65
  options = require_payload(options, 'Upload options')
59
66
  buffer, file_name = read_source(source, max_bytes: MAX_UPLOAD_BYTES)
60
- validate_pdf_source!(buffer, file_name, max_bytes: MAX_UPLOAD_BYTES)
67
+ validate_document_source!(buffer, file_name, UPLOAD_EXTENSIONS)
61
68
 
62
69
  acc_id = account_id(options[:account_id])
63
70
 
64
71
  @logger.info("Uploading document (#{buffer.bytesize} bytes)")
65
72
 
66
- payload = { file: file_part(buffer, file_name, 'application/pdf') }
73
+ payload = { file: file_part(buffer, file_name) }
67
74
 
68
75
  document = call('Document upload failed') do
69
76
  http_post("accounts/#{acc_id}/documents", payload)
@@ -100,18 +107,18 @@ module Assinafy
100
107
  # 'name' => 'customer_agreement.pdf',
101
108
  # 'status' => 'metadata_ready',
102
109
  # 'artifacts' => {
103
- # 'original' => 'https://sandbox.assinafy.com.br/v1/documents/1031ff84.../download/original',
104
- # 'thumbnail' => 'https://sandbox.assinafy.com.br/v1/documents/1031ff84.../thumbnail'
110
+ # 'original' => 'https://api.assinafy.com.br/v1/documents/1031ff84.../download/original',
111
+ # 'thumbnail' => 'https://api.assinafy.com.br/v1/documents/1031ff84.../thumbnail'
105
112
  # },
106
113
  # 'is_closed' => false,
107
- # 'signing_url' => 'https://app-sandbox.assinafy.com.br/sign/document-id-3',
114
+ # 'signing_url' => 'https://app.assinafy.com.br/sign/document-id-3',
108
115
  # 'decline_reason' => nil,
109
116
  # 'declined_by' => nil,
110
117
  # 'tags' => [],
111
118
  # 'assignment' => nil,
112
119
  # 'pages' => [
113
120
  # { 'id' => 'page-id-2', 'number' => 1, 'height' => 1651,
114
- # 'width' => 1275, 'download_url' => 'https://sandbox.assinafy.com.br/v1/documents/.../download' }
121
+ # 'width' => 1275, 'download_url' => 'https://api.assinafy.com.br/v1/documents/.../download' }
115
122
  # ],
116
123
  # 'created_at' => '2026-06-05T20:50:31Z',
117
124
  # 'updated_at' => '2026-06-05T20:50:34Z'
@@ -157,7 +164,7 @@ module Assinafy
157
164
  # 'status' => 'metadata_ready',
158
165
  # 'artifacts' => { 'original' => 'https://...', 'thumbnail' => 'https://...' },
159
166
  # 'is_closed' => false,
160
- # 'signing_url' => 'https://app-sandbox.assinafy.com.br/sign/103b0253...',
167
+ # 'signing_url' => 'https://app.assinafy.com.br/sign/103b0253...',
161
168
  # 'tags' => [],
162
169
  # 'created_at' => '2026-07-20T15:53:37Z',
163
170
  # 'updated_at' => '2026-07-20T15:53:41Z'
@@ -172,7 +179,7 @@ module Assinafy
172
179
  require_string(query, 'Search query') unless query.nil?
173
180
 
174
181
  call_list('Failed to search documents') do
175
- http_get("accounts/#{acc_id}/documents/search", filters.merge(search: query))
182
+ http_get("accounts/#{acc_id}/documents/search", query.nil? ? filters : filters.merge(search: query))
176
183
  end
177
184
  end
178
185
 
@@ -198,6 +205,7 @@ module Assinafy
198
205
  # { 'code' => 'certificated', 'deletable' => false },
199
206
  # { 'code' => 'rejected_by_signer', 'deletable' => true },
200
207
  # { 'code' => 'pending_signature', 'deletable' => true },
208
+ # { 'code' => 'pending_identity_review', 'deletable' => true },
201
209
  # { 'code' => 'rejected_by_user', 'deletable' => true },
202
210
  # { 'code' => 'failed', 'deletable' => true }
203
211
  # ]
@@ -229,11 +237,11 @@ module Assinafy
229
237
  # 'name' => 'customer_agreement.pdf',
230
238
  # 'status' => 'metadata_ready',
231
239
  # 'artifacts' => {
232
- # 'original' => 'https://sandbox.assinafy.com.br/v1/documents/1032009d.../download/original',
233
- # 'thumbnail' => 'https://sandbox.assinafy.com.br/v1/documents/1032009d.../thumbnail'
240
+ # 'original' => 'https://api.assinafy.com.br/v1/documents/1032009d.../download/original',
241
+ # 'thumbnail' => 'https://api.assinafy.com.br/v1/documents/1032009d.../thumbnail'
234
242
  # },
235
243
  # 'is_closed' => false,
236
- # 'signing_url' => 'https://app-sandbox.assinafy.com.br/sign/document-id',
244
+ # 'signing_url' => 'https://app.assinafy.com.br/sign/document-id',
237
245
  # 'decline_reason' => nil,
238
246
  # 'declined_by' => nil,
239
247
  # 'tags' => [],
@@ -241,7 +249,7 @@ module Assinafy
241
249
  # 'has_contract' => false,
242
250
  # 'pages' => [
243
251
  # { 'id' => 'page-id', 'number' => 1, 'height' => 1651,
244
- # 'width' => 1275, 'download_url' => 'https://sandbox.assinafy.com.br/v1/documents/.../download' }
252
+ # 'width' => 1275, 'download_url' => 'https://api.assinafy.com.br/v1/documents/.../download' }
245
253
  # ],
246
254
  # 'created_at' => '2026-06-05T21:21:12Z',
247
255
  # 'updated_at' => '2026-06-05T21:21:15Z'
@@ -280,7 +288,7 @@ module Assinafy
280
288
  # 'status' => 'metadata_ready',
281
289
  # 'artifacts' => { 'original' => 'https://...', 'thumbnail' => 'https://...' },
282
290
  # 'is_closed' => false,
283
- # 'signing_url' => 'https://app-sandbox.assinafy.com.br/sign/103b0253...',
291
+ # 'signing_url' => 'https://app.assinafy.com.br/sign/103b0253...',
284
292
  # 'tags' => [],
285
293
  # 'created_at' => '2026-07-20T15:53:37Z',
286
294
  # 'updated_at' => '2026-07-20T15:53:41Z'
@@ -325,7 +333,6 @@ module Assinafy
325
333
  clock = Process::CLOCK_MONOTONIC
326
334
  deadline = Process.clock_gettime(clock) + max_wait_seconds
327
335
  attempts = 0
328
- # @type var last_document: Assinafy::api_object?
329
336
  last_document = nil
330
337
 
331
338
  @logger.info("Waiting for document to be ready: #{doc_id}")
@@ -363,7 +370,7 @@ module Assinafy
363
370
  # @param artifact_name [String] `original`, `certificated`, `certificate-page`, `pades`, or
364
371
  # `bundle` (default `certificated`)
365
372
  # @return [String] binary PDF body
366
- # @raise [Assinafy::ValidationError] on unknown artifact type
373
+ # @raise [Assinafy::ValidationError] on an invalid ID or unknown artifact
367
374
  # @see GET /documents/{document_id}/download/{artifact_name}
368
375
  # @example Download the original upload and save it to disk
369
376
  # # Request: GET /documents/{document_id}/download/original
@@ -377,7 +384,7 @@ module Assinafy
377
384
  # @raise [Assinafy::ApiError] on an unsuccessful API response
378
385
  def download(document_id, artifact_name = 'certificated')
379
386
  doc_id = require_id(document_id, 'Document ID')
380
- art = artifact_type(artifact_name)
387
+ art = require_one_of(artifact_name, ARTIFACT_TYPES, 'artifact')
381
388
 
382
389
  call_binary('Failed to download document') do
383
390
  http_get("documents/#{doc_id}/download/#{art}")
@@ -502,11 +509,14 @@ module Assinafy
502
509
  end
503
510
  end
504
511
 
505
- # Permanently delete a document. Only allowed for "deletable" statuses.
512
+ # Permanently delete a document. Only allowed for "deletable" statuses. A document in
513
+ # `pending_signature` or `pending_identity_review` is cancelled first, exactly as {#cancel} does;
514
+ # use {#cancel} to stop signing and keep the document.
506
515
  #
507
516
  # @param document_id [String]
508
517
  # @return [nil]
509
- # @raise [Assinafy::ApiError] on an unsuccessful API response
518
+ # @raise [Assinafy::ApiError] on an unsuccessful API response: `409` (`EnvelopeOpen`) for a document
519
+ # of an open envelope, `400` for a certificated document or one still being processed
510
520
  # @raise [Assinafy::NetworkError] on transport or TLS failure
511
521
  # @raise [Assinafy::ValidationError] on invalid required input
512
522
  # @see DELETE /documents/{documentId}
@@ -524,6 +534,27 @@ module Assinafy
524
534
  end
525
535
  end
526
536
 
537
+ # Cancel a document that is `pending_signature` or `pending_identity_review` and keep it.
538
+ # It moves to `rejected_by_user`; its signers and owner are notified and its files and history stay.
539
+ # A fully signed document answers `409` (`DocumentClosed`). A document of an open envelope answers
540
+ # `409` (`EnvelopeOpen`): cancel the envelope or remove the document from it instead.
541
+ #
542
+ # @param document_id [String]
543
+ # @return [Hash] the cancelled Document
544
+ # @raise [Assinafy::ApiError] on an unsuccessful API response (`400` when not cancellable)
545
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
546
+ # @raise [Assinafy::ValidationError] on an invalid ID
547
+ # @see PUT /documents/{documentId}/cancel
548
+ # @example Cancel signing and keep the document
549
+ # client.documents.cancel('document-id') # PUT; no body
550
+ # # => { 'resource' => 'document', 'id' => 'document-id', 'status' => 'rejected_by_user',
551
+ # # 'is_closed' => true, 'name' => 'contract.pdf', ... }
552
+ def cancel(document_id)
553
+ doc_id = require_id(document_id, 'Document ID')
554
+
555
+ call('Failed to cancel document') { http_put("documents/#{doc_id}/cancel") }
556
+ end
557
+
527
558
  # Create a document from a template; its assignment is created asynchronously.
528
559
  # Poll until pending_signature or failed. Placed signer fields use collect; DigitalCertificate
529
560
  # requires a template without those fields. Editor roles are filled through editor_fields.
@@ -634,9 +665,9 @@ module Assinafy
634
665
  end
635
666
  end
636
667
 
637
- # Verify a certificated document by its signature hash.
668
+ # Verify a certificated document by its signature hash or its verification code.
638
669
  #
639
- # @param hash [String]
670
+ # @param hash [String] the signature hash, or the document's verification code
640
671
  # @return [Hash] verification result; `is_valid` is false when the hash is unknown
641
672
  # @raise [Assinafy::ApiError] on an unsuccessful API response
642
673
  # @raise [Assinafy::NetworkError] on transport or TLS failure
@@ -656,6 +687,7 @@ module Assinafy
656
687
  # 'signer_count' => '1',
657
688
  # 'completed_count' => 1,
658
689
  # 'completed_at' => '2023-01-27T19:27:44Z',
690
+ # 'certificated_at' => '2023-01-27T19:27:45Z',
659
691
  # 'verified_at' => '2023-01-27T19:27:46Z',
660
692
  # 'is_valid' => true,
661
693
  # 'message' => ''
@@ -700,8 +732,10 @@ module Assinafy
700
732
  end
701
733
  end
702
734
 
703
- # Email a 6-digit access token for the document to its signer (public endpoint;
704
- # no workspace credentials are sent).
735
+ # Sends the signer this document's signature request again by email, with its existing link and,
736
+ # when the verification method uses one, its verification code; nothing is renewed. At most once
737
+ # every two minutes per signer; an envelope's documents share that interval. Public endpoint: no
738
+ # workspace credentials are sent.
705
739
  #
706
740
  # @param document_id [String]
707
741
  # @param recipient [String] the signer's email address (required)
@@ -713,7 +747,7 @@ module Assinafy
713
747
  # @raise [Assinafy::ValidationError] when the recipient is missing or not an email address,
714
748
  # when the channel is not `email`, or when both `recipient:` and `email:` are given
715
749
  # @see PUT /public/documents/{document_id}/send-token
716
- # @example Email the access token to the signer (no auth required)
750
+ # @example Send the signature request again (no auth required)
717
751
  # client.documents.send_token('document-id', recipient: 'signer@example.com')
718
752
  #
719
753
  # # Request: PUT /public/documents/{document_id}/send-token
@@ -917,7 +951,7 @@ module Assinafy
917
951
  { signed: signed, total: total, pending: pending, percentage: percentage }
918
952
  end
919
953
 
920
- # Read the sender's stated signing capacities. Available on staging; requires documents:read.
954
+ # Read the sender's stated signing capacities. Requires documents:read.
921
955
  # @param document_id [String]
922
956
  # @return [Array<Hash>] signer_id and sign_as, or [] before assignment creation
923
957
  # @raise [ValidationError] on an invalid ID
@@ -932,7 +966,7 @@ module Assinafy
932
966
  end
933
967
 
934
968
  # Read invitation delivery/open timestamps. Opens are hints, not proof a person read the message.
935
- # Available on staging; requires documents:read.
969
+ # Requires documents:read.
936
970
  # @param document_id [String]
937
971
  # @return [Array<Hash>] signer_id and notification_history, or [] before assignment creation
938
972
  # @raise [ValidationError] on an invalid ID
@@ -948,7 +982,7 @@ module Assinafy
948
982
  call_array('Failed to read notification history') { http_get("documents/#{id}/notification-history") }
949
983
  end
950
984
 
951
- # Read contacts following this document without signing. Available on staging; requires documents:read.
985
+ # Read contacts following this document without signing. Requires documents:read.
952
986
  # @param document_id [String]
953
987
  # @return [Array<Hash>] Signer objects, in configured order, excluding deleted contacts
954
988
  # @raise [ValidationError] on an invalid ID
@@ -964,7 +998,7 @@ module Assinafy
964
998
  end
965
999
 
966
1000
  # Replace watchers before a document ends. They receive a completion/decline/expiry email without a file/link.
967
- # Available on staging; requires documents:write. Workspace notification policy does not suppress these emails.
1001
+ # Requires documents:write. Workspace notification policy does not suppress these emails.
968
1002
  # @param document_id [String]
969
1003
  # @param watcher_ids [Array<String>] at most ten workspace contact IDs with email; [] clears all
970
1004
  # @return [Array<Hash>] Signer objects, as returned by watchers
@@ -1003,25 +1037,15 @@ module Assinafy
1003
1037
 
1004
1038
  def activity_params(params)
1005
1039
  query = query_params(require_payload(params, 'Activity parameters'))
1006
- if query.key?('sort') && !%w[id -id].include?(query['sort'])
1007
- raise ValidationError.new('Activity sort must be id or -id')
1008
- end
1009
-
1010
- %w[page per-page].each do |key|
1011
- next unless query.key?(key)
1012
-
1013
- value = query[key]
1014
- unless value.is_a?(Integer) && value > 0 && (key != 'per-page' || value <= 100)
1015
- raise ValidationError.new("#{key} must be a positive Integer (per_page at most 100)")
1016
- end
1017
- end
1040
+ require_one_of(query['sort'], %w[id -id], 'Activity sort') if query.key?('sort')
1041
+ %w[page per-page].each { |key| require_integer(query[key], key, 1) if query.key?(key) }
1018
1042
  query
1019
1043
  end
1020
1044
 
1021
1045
  def uploaded_document_id(document)
1022
1046
  id = document['id'] if document.is_a?(Hash)
1023
- require_id(id, 'Uploaded document ID')
1024
- rescue ValidationError
1047
+ return id if path_segment?(id)
1048
+
1025
1049
  raise Assinafy::Error.new(
1026
1050
  'Upload succeeded but no usable document ID was returned',
1027
1051
  { document: document }
@@ -1036,7 +1060,6 @@ module Assinafy
1036
1060
  end
1037
1061
 
1038
1062
  def template_body(signers_or_payload, options = {}, require_signer_id: false)
1039
- require_payload(options, 'Template document options')
1040
1063
  body =
1041
1064
  if signers_or_payload.is_a?(Hash)
1042
1065
  signers_or_payload.merge(options)
@@ -1044,10 +1067,6 @@ module Assinafy
1044
1067
  options.merge(signers: signers_or_payload)
1045
1068
  end
1046
1069
 
1047
- unless body[:signers] || body['signers']
1048
- raise ValidationError.new('signers are required')
1049
- end
1050
-
1051
1070
  body = body_params(body)
1052
1071
  validate_template_signers!(body['signers'], require_signer_id)
1053
1072
  normalised = AssignmentResource.build_payload(
@@ -1099,13 +1118,6 @@ module Assinafy
1099
1118
 
1100
1119
  tags.each { |tag| require_string(tag, 'Tag ID') }
1101
1120
  end
1102
-
1103
- def artifact_type(artifact_name)
1104
- value = require_id(artifact_name, 'Artifact name').to_s
1105
- return value if ARTIFACT_TYPES.include?(value)
1106
-
1107
- raise ValidationError.new('Invalid artifact type', { artifact_name: artifact_name })
1108
- end
1109
1121
  end
1110
1122
  end
1111
1123
  end
@@ -16,9 +16,7 @@ module Assinafy
16
16
  # # 'message' => nil, 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }] }
17
17
  def list(params = {}, account_id_override = nil)
18
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
19
+ require_one_of(query['status'], %w[open closed], 'status') if query.key?('status')
22
20
  if query.key?('search') && !query['search'].is_a?(String)
23
21
  raise ValidationError.new('search must be a String')
24
22
  end
@@ -31,7 +29,8 @@ module Assinafy
31
29
  # @param idempotency_key [String, nil] reuse after a lost response to avoid creating or charging twice
32
30
  # @return [Hash] DocumentEnvelope; notification failure does not undo creation
33
31
  # @raise [ValidationError] on invalid payload, key or IDs
34
- # @raise [ApiError, NetworkError] on API or transport failure
32
+ # @raise [ApiError, NetworkError] on API or transport failure; `429` (`FreePlanEmailLimit`, with
33
+ # Retry-After) once a free plan reaches its daily signer email limit
35
34
  # @see POST /accounts/{accountId}/envelopes
36
35
  # @example
37
36
  # client.envelopes.create({ name: 'Contract', signers: [{ id: 'signer-id' }],
@@ -61,7 +60,9 @@ module Assinafy
61
60
  # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }])
62
61
  # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
63
62
  # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }] }
64
- # # => { 'total_credits' => 0, 'has_sufficient_resources' => true, 'breakdown' => [] }
63
+ # # => { 'documents' => 1, 'credits' => 0, 'needs_extra_document' => false, 'extra_document_cost' => 0,
64
+ # # 'total_credits' => 0, 'breakdown' => [], 'document_balance' => 62, 'credit_balance' => 0,
65
+ # # 'has_sufficient_resources' => true, 'blocking_reason' => nil, 'message' => nil }
65
66
  def estimate_cost(payload, account_id_override = nil)
66
67
  body = create_payload(payload)
67
68
  path = "#{envelopes_path(account_id_override)}/estimate-cost"
@@ -69,7 +70,7 @@ module Assinafy
69
70
  end
70
71
 
71
72
  # Schedule an envelope; no invitations or charges occur until it is sent. Requires documents:write.
72
- # Available on staging; the environment must publish scheduled sends. No idempotency header is supported.
73
+ # No idempotency header is supported.
73
74
  # @param payload [Hash] the same EnvelopeCreateRequest as create
74
75
  # @param account_id_override [String, nil]
75
76
  # @param send_at [String, Integer] from one hour to 90 days ahead; absent offset means UTC
@@ -85,7 +86,7 @@ module Assinafy
85
86
  # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'envelope',
86
87
  # # 'document_ids' => ['document-id'], 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z',
87
88
  # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
88
- # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }
89
+ # # 'next_attempt_at' => nil, 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }
89
90
  def schedule(payload, account_id_override = nil, send_at:)
90
91
  time = ScheduledSendResource.require_send_at(send_at)
91
92
  raw = body_params(require_payload(payload))
@@ -181,10 +182,7 @@ module Assinafy
181
182
  # client.envelopes.download('envelope-id', 'original')
182
183
  # # GET .../envelopes/envelope-id/download/original; no body; => binary ZIP bytes
183
184
  def download(envelope_id, artifact = 'certificated', account_id_override = nil)
184
- unless DocumentResource::ARTIFACT_TYPES.include?(artifact)
185
- raise ValidationError.new("artifact must be one of: #{DocumentResource::ARTIFACT_TYPES.join(', ')}")
186
- end
187
-
185
+ require_one_of(artifact, DocumentResource::ARTIFACT_TYPES, 'artifact')
188
186
  path = "#{envelope_path(envelope_id, account_id_override)}/download/#{artifact}"
189
187
  call_binary('Failed to download envelope') { http_get(path) }
190
188
  end
@@ -220,7 +218,7 @@ module Assinafy
220
218
  call('Failed to resend envelope invitation') { http_put(path) }
221
219
  end
222
220
 
223
- # Estimate one reminder for the whole envelope without sending or charging. Available on staging.
221
+ # Estimate one reminder for the whole envelope without sending or charging.
224
222
  # @param envelope_id [String]
225
223
  # @param signer_id [String]
226
224
  # @param account_id_override [String, nil]
@@ -46,8 +46,7 @@ module Assinafy
46
46
  # # }
47
47
  def create(payload, account_id_override = nil)
48
48
  acc_id = account_id(account_id_override)
49
- raw = require_payload(payload)
50
- body = with_explicit_regex(raw, body_params(raw))
49
+ body = nullable_body(require_payload(payload), %w[regex])
51
50
  require_string(body['name'], 'Field name')
52
51
  require_string(body['type'], 'Field type')
53
52
  require_string(body['regex'], 'Field regex') if body.key?('regex') && !body['regex'].nil?
@@ -139,7 +138,7 @@ module Assinafy
139
138
  # @param field_id [String]
140
139
  # @param payload [Hash]
141
140
  # @option payload [String] :name display label
142
- # @option payload [String] :regex validation regex (text fields)
141
+ # @option payload [String, nil] :regex validation regex (text fields); nil clears it
143
142
  # @option payload [Boolean] :is_active enable/disable the field
144
143
  # @param account_id_override [String, nil]
145
144
  # @return [Hash] the updated field definition (envelope `data` unwrapped)
@@ -169,8 +168,7 @@ module Assinafy
169
168
  def update(field_id, payload, account_id_override = nil)
170
169
  acc_id = account_id(account_id_override)
171
170
  fid = require_id(field_id, 'Field ID')
172
- raw = require_payload(payload)
173
- body = with_explicit_regex(raw, body_params(raw))
171
+ body = nullable_body(require_payload(payload), %w[regex])
174
172
  require_string(body['name'], 'Field name') if body.key?('name')
175
173
  require_string(body['regex'], 'Field regex') if body.key?('regex') && !body['regex'].nil?
176
174
  require_boolean(body['is_active'], 'is_active') if body.key?('is_active')
@@ -317,12 +315,6 @@ module Assinafy
317
315
  signer_access_code.equal?(WORKSPACE) ? nil : require_signer_access_code(signer_access_code)
318
316
  end
319
317
 
320
- # `regex` is nullable: an explicit nil is sent as JSON null to clear it.
321
- def with_explicit_regex(raw, body)
322
- body['regex'] = nil if [:regex, 'regex'].any? { |key| raw.key?(key) && raw[key].nil? }
323
- body
324
- end
325
-
326
318
  def field_value_payload(item)
327
319
  payload = require_payload(item, 'Field value')
328
320
  field_id = payload.key?(:field_id) ? payload[:field_id] : payload['field_id']
@@ -121,8 +121,8 @@ module Assinafy
121
121
  token(
122
122
  grant_type: 'authorization_code',
123
123
  client_id: client_id,
124
- code: require_string(code, 'Authorization code'),
125
- code_verifier: Assinafy::OAuth.validate_code_verifier!(code_verifier),
124
+ code: code,
125
+ code_verifier: code_verifier,
126
126
  redirect_uri: redirect_uri,
127
127
  client_secret: client_secret,
128
128
  resource: resource
@@ -189,7 +189,7 @@ module Assinafy
189
189
  token(
190
190
  grant_type: 'refresh_token',
191
191
  client_id: client_id,
192
- refresh_token: require_string(refresh_token, 'Refresh token'),
192
+ refresh_token: refresh_token,
193
193
  client_secret: client_secret,
194
194
  resource: resource
195
195
  )
@@ -229,10 +229,7 @@ module Assinafy
229
229
  # # 'issued_token_type' => 'urn:ietf:params:oauth:token-type:access_token' }
230
230
  # @raise [Assinafy::NetworkError] on transport or TLS failure
231
231
  def token(grant_type:, client_id:, **params)
232
- grant = require_string(grant_type, 'Grant type')
233
- unless GRANT_TYPES.include?(grant)
234
- raise ValidationError.new("Grant type must be one of: #{GRANT_TYPES.join(', ')}", { grant_type: grant_type })
235
- end
232
+ grant = require_one_of(require_string(grant_type, 'Grant type'), GRANT_TYPES, 'Grant type')
236
233
 
237
234
  body = body_params(params.merge(grant_type: grant, client_id: require_string(client_id, 'Client ID')))
238
235
  validate_token_request!(body)
@@ -289,12 +286,7 @@ module Assinafy
289
286
  def revoke(token:, client_id:, token_type_hint: nil, client_secret: nil)
290
287
  require_string(client_secret, 'Client secret') unless client_secret.nil?
291
288
 
292
- if !token_type_hint.nil? && !TOKEN_TYPE_HINTS.include?(token_type_hint.to_s)
293
- raise ValidationError.new(
294
- "Token type hint must be one of: #{TOKEN_TYPE_HINTS.join(', ')}",
295
- { token_type_hint: token_type_hint }
296
- )
297
- end
289
+ require_one_of(token_type_hint.to_s, TOKEN_TYPE_HINTS, 'Token type hint') unless token_type_hint.nil?
298
290
 
299
291
  body = body_params(
300
292
  token: require_string(token, 'Token'),
@@ -373,7 +365,7 @@ module Assinafy
373
365
  # # 'authorization_servers' => ['https://auth.assinafy.com.br'],
374
366
  # # 'scopes_supported' => [
375
367
  # # 'documents:read', 'documents:write', 'templates:read',
376
- # # 'templates:write', 'account:read', 'openid', 'profile', 'email'
368
+ # # 'templates:write', 'account:read', 'webhooks:write', 'openid', 'profile', 'email'
377
369
  # # ],
378
370
  # # 'bearer_methods_supported' => ['header']
379
371
  # # }
@@ -394,18 +386,23 @@ module Assinafy
394
386
  # authorization server host — not this API — so the SDK sends it without
395
387
  # credentials.
396
388
  #
397
- # @param url [String] override for a non-default authorization server;
398
- # pass `"#{protected_resource_metadata['authorization_servers'].first}" \
399
- # "/.well-known/oauth-authorization-server"` to follow discovery strictly
389
+ # @param url [String, nil] the metadata URL of a known authorization server. When omitted, the
390
+ # server is discovered: the first of {#protected_resource_metadata}'s `authorization_servers`,
391
+ # plus `/.well-known/oauth-authorization-server` (one extra request)
400
392
  # @return [Hash{String=>Object}] the bare metadata object
401
393
  # @raise [Assinafy::OAuthError] on an unsuccessful metadata response
402
394
  # @raise [Assinafy::NetworkError] on transport or TLS failure
403
- # @raise [Assinafy::ValidationError] when the URL is not absolute HTTPS without userinfo or fragment
395
+ # @raise [Assinafy::ValidationError] when the given or discovered URL is not absolute HTTPS without
396
+ # userinfo or fragment
404
397
  # @see GET https://auth.assinafy.com.br/.well-known/oauth-authorization-server
405
398
  #
406
399
  # @example Discover endpoints instead of hardcoding them
407
400
  # metadata = client.oauth.authorization_server_metadata
408
401
  #
402
+ # # Requests (no body, no X-Api-Key/Authorization header):
403
+ # # GET /.well-known/oauth-protected-resource
404
+ # # GET https://auth.assinafy.com.br/.well-known/oauth-authorization-server
405
+ #
409
406
  # # Response (bare metadata, NOT enveloped):
410
407
  # # {
411
408
  # # 'issuer' => 'https://auth.assinafy.com.br',
@@ -425,7 +422,8 @@ module Assinafy
425
422
  # # 'authorization_response_iss_parameter_supported' => true,
426
423
  # # 'client_id_metadata_document_supported' => true
427
424
  # # }
428
- def authorization_server_metadata(url = Assinafy::OAuth::AUTHORIZATION_SERVER_METADATA_URL)
425
+ def authorization_server_metadata(url = nil)
426
+ url ||= "#{discovered_authorization_server}/.well-known/oauth-authorization-server"
429
427
  absolute = Assinafy::OAuth.https_uri!(url, 'Authorization server metadata URL').to_s
430
428
 
431
429
  call('Failed to fetch authorization server metadata') do
@@ -435,6 +433,14 @@ module Assinafy
435
433
 
436
434
  private
437
435
 
436
+ def discovered_authorization_server
437
+ servers = protected_resource_metadata
438
+ servers = servers['authorization_servers'] if servers.is_a?(Hash)
439
+ return servers.first.to_s.chomp('/') if servers.is_a?(Array) && servers.first.is_a?(String)
440
+
441
+ raise Assinafy::Error.new('Protected resource metadata names no authorization server')
442
+ end
443
+
438
444
  def validate_token_request!(body)
439
445
  case body['grant_type']
440
446
  when 'authorization_code'
@@ -466,7 +472,7 @@ module Assinafy
466
472
  # different one leaves nothing to refresh with next time, and sending the
467
473
  # retired one again ends the whole connection.
468
474
  def rotated?(tokens, sent)
469
- replacement = tokens['refresh_token'] if tokens.is_a?(Hash)
475
+ replacement = tokens['refresh_token']
470
476
  replacement.is_a?(String) && !replacement.strip.empty? && replacement != sent
471
477
  end
472
478
  end
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Assinafy
4
4
  module Resources
5
- # Pending assignment/envelope requests. Available on staging; all operations require documents:write.
5
+ # Pending assignment/envelope requests. All operations require documents:write.
6
6
  class ScheduledSendResource < BaseResource
7
7
  class << self
8
8
  # Validate the delivery window for a scheduled request.
@@ -43,10 +43,10 @@ module Assinafy
43
43
 
44
44
  def schedule_time(value, name)
45
45
  return Time.at(value).utc if value.is_a?(Integer)
46
- if value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?
47
- (?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)?\z/x)
48
- return DateTime.iso8601(value).to_time
49
- end
46
+
47
+ # An absent offset means UTC here, so the shared pattern is applied with one assumed.
48
+ zoned = value.to_s.match?(/(?:Z|[+-]\d{2}:\d{2})\z/) ? value : "#{value}Z"
49
+ return DateTime.iso8601(value).to_time if value.is_a?(String) && zoned.match?(Validation::ZONED_ISO8601)
50
50
 
51
51
  raise ArgumentError
52
52
  rescue ArgumentError, RangeError
@@ -66,6 +66,7 @@ module Assinafy
66
66
  # # => { data: [{ 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
67
67
  # # 'document_ids' => ['document-id'], 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z',
68
68
  # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
69
+ # # 'next_attempt_at' => nil,
69
70
  # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }],
70
71
  # # meta: { current_page: 1, per_page: 20, total: 1, last_page: 1 } }
71
72
  def list(params = {}, account_id_override = nil)
@@ -87,6 +88,7 @@ module Assinafy
87
88
  # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
88
89
  # # 'document_ids' => ['document-id'], 'status' => 'cancelled', 'send_at' => '2026-12-01T12:00:00Z',
89
90
  # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
91
+ # # 'next_attempt_at' => nil,
90
92
  # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => '2026-12-01T10:30:00Z' }
91
93
  def cancel(scheduled_send_id, account_id_override = nil)
92
94
  path = "#{scheduled_send_path(scheduled_send_id, account_id_override)}/cancel"
@@ -95,6 +97,8 @@ module Assinafy
95
97
 
96
98
  # Send a pending request now, with the original member's permissions, balance and credit ceiling.
97
99
  # A refused request stays pending; cancel it to prevent a later scheduled attempt. Never retries.
100
+ # On the free plan a send can stay pending, with `next_attempt_at` up to 7 days ahead, once the
101
+ # daily signer email limit is reached; this call then answers 429 (`FreePlanEmailLimit`) with Retry-After.
98
102
  # @param scheduled_send_id [String]
99
103
  # @param account_id_override [String, nil]
100
104
  # @return [Hash] ScheduledSend, now sent, with assignment_id or envelope_id
@@ -106,6 +110,7 @@ module Assinafy
106
110
  # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
107
111
  # # 'document_ids' => ['document-id'], 'status' => 'sent', 'send_at' => '2026-12-01T12:00:00Z',
108
112
  # # 'assignment_id' => 'assignment-id', 'envelope_id' => nil, 'failure_reason' => nil,
113
+ # # 'next_attempt_at' => nil,
109
114
  # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => '2026-12-01T10:30:00Z' }
110
115
  def send_now(scheduled_send_id, account_id_override = nil)
111
116
  path = "#{scheduled_send_path(scheduled_send_id, account_id_override)}/send"