assinafy 2.2.0 → 2.4.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.
@@ -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,6 +951,77 @@ module Assinafy
917
951
  { signed: signed, total: total, pending: pending, percentage: percentage }
918
952
  end
919
953
 
954
+ # Read the sender's stated signing capacities. Requires documents:read.
955
+ # @param document_id [String]
956
+ # @return [Array<Hash>] signer_id and sign_as, or [] before assignment creation
957
+ # @raise [ValidationError] on an invalid ID
958
+ # @raise [ApiError, NetworkError] on API or transport failure
959
+ # @see GET /documents/{documentId}/signer-capacities
960
+ # @example
961
+ # client.documents.signer_capacities('document-id') # GET; no body
962
+ # # => [{ 'signer_id' => 'signer-id', 'sign_as' => 'Witness' }]
963
+ def signer_capacities(document_id)
964
+ id = require_id(document_id, 'Document ID')
965
+ call_array('Failed to read signer capacities') { http_get("documents/#{id}/signer-capacities") }
966
+ end
967
+
968
+ # Read invitation delivery/open timestamps. Opens are hints, not proof a person read the message.
969
+ # Requires documents:read.
970
+ # @param document_id [String]
971
+ # @return [Array<Hash>] signer_id and notification_history, or [] before assignment creation
972
+ # @raise [ValidationError] on an invalid ID
973
+ # @raise [ApiError, NetworkError] on API or transport failure
974
+ # @see GET /documents/{documentId}/notification-history
975
+ # @example
976
+ # client.documents.notification_history('document-id') # GET; no body
977
+ # # => [{ 'signer_id' => 'signer-id', 'notification_history' => [{ 'event' => 'signature_request',
978
+ # # 'status' => 'sent', 'error_code' => nil, 'error_message' => nil, 'failed_at' => nil,
979
+ # # 'sent_at' => '2026-12-01T12:00:00Z', 'delivered_at' => nil, 'opened_at' => nil }] }]
980
+ def notification_history(document_id)
981
+ id = require_id(document_id, 'Document ID')
982
+ call_array('Failed to read notification history') { http_get("documents/#{id}/notification-history") }
983
+ end
984
+
985
+ # Read contacts following this document without signing. Requires documents:read.
986
+ # @param document_id [String]
987
+ # @return [Array<Hash>] Signer objects, in configured order, excluding deleted contacts
988
+ # @raise [ValidationError] on an invalid ID
989
+ # @raise [ApiError, NetworkError] on API or transport failure
990
+ # @see GET /documents/{documentId}/watchers
991
+ # @example
992
+ # client.documents.watchers('document-id') # GET; no body
993
+ # # => [{ 'id' => 'contact-id', 'full_name' => 'Example Watcher', 'email' => 'watcher@example.com',
994
+ # # 'whatsapp_phone_number' => nil, 'government_id' => nil, 'has_accepted_terms' => false }]
995
+ def watchers(document_id)
996
+ id = require_id(document_id, 'Document ID')
997
+ call_array('Failed to read document watchers') { http_get("documents/#{id}/watchers") }
998
+ end
999
+
1000
+ # Replace watchers before a document ends. They receive a completion/decline/expiry email without a file/link.
1001
+ # Requires documents:write. Workspace notification policy does not suppress these emails.
1002
+ # @param document_id [String]
1003
+ # @param watcher_ids [Array<String>] at most ten workspace contact IDs with email; [] clears all
1004
+ # @return [Array<Hash>] Signer objects, as returned by watchers
1005
+ # @raise [ValidationError] on invalid IDs or list shape
1006
+ # @raise [ApiError, NetworkError] on API or transport failure
1007
+ # @see PUT /documents/{documentId}/watchers
1008
+ # @example
1009
+ # client.documents.set_watchers('document-id', ['contact-id'])
1010
+ # # PUT body: { "watcher_ids": ["contact-id"] }
1011
+ # # => [{ 'id' => 'contact-id', 'full_name' => 'Example Watcher', 'email' => 'watcher@example.com',
1012
+ # # 'whatsapp_phone_number' => nil, 'government_id' => nil, 'has_accepted_terms' => false }]
1013
+ def set_watchers(document_id, watcher_ids)
1014
+ id = require_id(document_id, 'Document ID')
1015
+ unless watcher_ids.is_a?(Array) && watcher_ids.length <= 10
1016
+ raise ValidationError.new('watcher_ids must be an Array with at most ten contacts')
1017
+ end
1018
+
1019
+ watcher_ids.each { |watcher| require_id(watcher, 'Watcher ID') }
1020
+ call_array('Failed to set document watchers') do
1021
+ http_put("documents/#{id}/watchers", { 'watcher_ids' => watcher_ids })
1022
+ end
1023
+ end
1024
+
920
1025
  private
921
1026
 
922
1027
  def document_expansions(expand)
@@ -932,25 +1037,15 @@ module Assinafy
932
1037
 
933
1038
  def activity_params(params)
934
1039
  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
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) }
947
1042
  query
948
1043
  end
949
1044
 
950
1045
  def uploaded_document_id(document)
951
1046
  id = document['id'] if document.is_a?(Hash)
952
- require_id(id, 'Uploaded document ID')
953
- rescue ValidationError
1047
+ return id if path_segment?(id)
1048
+
954
1049
  raise Assinafy::Error.new(
955
1050
  'Upload succeeded but no usable document ID was returned',
956
1051
  { document: document }
@@ -965,7 +1060,6 @@ module Assinafy
965
1060
  end
966
1061
 
967
1062
  def template_body(signers_or_payload, options = {}, require_signer_id: false)
968
- require_payload(options, 'Template document options')
969
1063
  body =
970
1064
  if signers_or_payload.is_a?(Hash)
971
1065
  signers_or_payload.merge(options)
@@ -973,10 +1067,6 @@ module Assinafy
973
1067
  options.merge(signers: signers_or_payload)
974
1068
  end
975
1069
 
976
- unless body[:signers] || body['signers']
977
- raise ValidationError.new('signers are required')
978
- end
979
-
980
1070
  body = body_params(body)
981
1071
  validate_template_signers!(body['signers'], require_signer_id)
982
1072
  normalised = AssignmentResource.build_payload(
@@ -1028,13 +1118,6 @@ module Assinafy
1028
1118
 
1029
1119
  tags.each { |tag| require_string(tag, 'Tag ID') }
1030
1120
  end
1031
-
1032
- def artifact_type(artifact_name)
1033
- value = require_id(artifact_name, 'Artifact name').to_s
1034
- return value if ARTIFACT_TYPES.include?(value)
1035
-
1036
- raise ValidationError.new('Invalid artifact type', { artifact_name: artifact_name })
1037
- end
1038
1121
  end
1039
1122
  end
1040
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,13 +60,48 @@ 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"
68
69
  call('Failed to estimate envelope cost') { http_post(path, body) }
69
70
  end
70
71
 
72
+ # Schedule an envelope; no invitations or charges occur until it is sent. Requires documents:write.
73
+ # No idempotency header is supported.
74
+ # @param payload [Hash] the same EnvelopeCreateRequest as create
75
+ # @param account_id_override [String, nil]
76
+ # @param send_at [String, Integer] from one hour to 90 days ahead; absent offset means UTC
77
+ # @return [Hash] ScheduledSend; each deadline must be at least two hours after send_at
78
+ # @raise [ValidationError] on invalid payload, IDs or timing
79
+ # @raise [ApiError, NetworkError] on API or transport failure
80
+ # @see POST /accounts/{accountId}/scheduled-sends
81
+ # @example
82
+ # client.envelopes.schedule({ name: 'Contract', signers: [{ id: 'signer-id' }],
83
+ # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }] }, send_at: (Time.now + 7200).to_i)
84
+ # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
85
+ # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }], "send_at": 1796126400 }
86
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'envelope',
87
+ # # 'document_ids' => ['document-id'], 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z',
88
+ # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
89
+ # # 'next_attempt_at' => nil, 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }
90
+ def schedule(payload, account_id_override = nil, send_at:)
91
+ time = ScheduledSendResource.require_send_at(send_at)
92
+ raw = body_params(require_payload(payload))
93
+ raw['documents'] = require_array(raw['documents'], 'documents').map do |document|
94
+ entry = require_payload(document, 'Envelope document').dup
95
+ if entry.key?('expires_at')
96
+ entry['expires_at'] = ScheduledSendResource.scheduled_expiration(entry['expires_at'], time)
97
+ end
98
+ entry
99
+ end
100
+ body = create_payload(raw).merge('send_at' => send_at)
101
+ path = "accounts/#{account_id(account_id_override)}/scheduled-sends"
102
+ call('Failed to schedule envelope') { http_post(path, body) }
103
+ end
104
+
71
105
  # @param envelope_id [String]
72
106
  # @param account_id_override [String, nil]
73
107
  # @return [Hash] DocumentEnvelope (see create for its complete shape)
@@ -148,10 +182,7 @@ module Assinafy
148
182
  # client.envelopes.download('envelope-id', 'original')
149
183
  # # GET .../envelopes/envelope-id/download/original; no body; => binary ZIP bytes
150
184
  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
-
185
+ require_one_of(artifact, DocumentResource::ARTIFACT_TYPES, 'artifact')
155
186
  path = "#{envelope_path(envelope_id, account_id_override)}/download/#{artifact}"
156
187
  call_binary('Failed to download envelope') { http_get(path) }
157
188
  end
@@ -187,6 +218,23 @@ module Assinafy
187
218
  call('Failed to resend envelope invitation') { http_put(path) }
188
219
  end
189
220
 
221
+ # Estimate one reminder for the whole envelope without sending or charging.
222
+ # @param envelope_id [String]
223
+ # @param signer_id [String]
224
+ # @param account_id_override [String, nil]
225
+ # @return [Hash] ResendCostEstimate; does not check reminder timing eligibility
226
+ # @raise [ValidationError] on invalid IDs
227
+ # @raise [ApiError, NetworkError] on API or transport failure
228
+ # @see POST /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/estimate-resend-cost
229
+ # @example
230
+ # client.envelopes.estimate_resend_cost('envelope-id', 'signer-id') # POST; no body
231
+ # # => { 'total' => 0, 'breakdown' => [], 'credit_balance' => 100, 'has_sufficient_credits' => true }
232
+ def estimate_resend_cost(envelope_id, signer_id, account_id_override = nil)
233
+ sid = require_id(signer_id, 'Signer ID')
234
+ path = "#{envelope_path(envelope_id, account_id_override)}/signers/#{sid}/estimate-resend-cost"
235
+ call('Failed to estimate envelope reminder cost') { http_post(path) }
236
+ end
237
+
190
238
  # @param envelope_id [String]
191
239
  # @param payload [Hash] EnvelopeDocumentRequest plus optional max_total_credits
192
240
  # @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')
@@ -201,7 +199,7 @@ module Assinafy
201
199
  end
202
200
  end
203
201
 
204
- # Validate a single value against a field definition.
202
+ # Validate a single value against a field definition, preserving nil as JSON null.
205
203
  #
206
204
  # Workspace authorization is used when `signer_access_code:` is omitted.
207
205
  # When the keyword is given it must be a non-blank code, and
@@ -230,17 +228,16 @@ module Assinafy
230
228
  def validate(field_id, value, account_id_override = nil, signer_access_code: WORKSPACE)
231
229
  acc_id = account_id(account_id_override)
232
230
  fid = require_id(field_id, 'Field ID')
233
- raise ValidationError.new('Field value is required') if value.nil?
234
231
 
235
232
  access_code = field_access_code(signer_access_code)
236
233
 
237
234
  call('Failed to validate field value') do
238
- http_post("accounts/#{acc_id}/fields/#{fid}/validate", body_params(value: value),
235
+ http_post("accounts/#{acc_id}/fields/#{fid}/validate", { 'value' => value },
239
236
  { signer_access_code: access_code }, workspace_auth: access_code.nil?)
240
237
  end
241
238
  end
242
239
 
243
- # Validate many `{ field_id:, value: }` pairs in a single call.
240
+ # Validate many `{ field_id:, value: }` pairs in a single call. Explicit nil values remain JSON null.
244
241
  #
245
242
  # As with {#validate}, omitting `signer_access_code:` uses the workspace
246
243
  # credentials; giving it requires a non-blank code and sends only the code.
@@ -318,23 +315,17 @@ module Assinafy
318
315
  signer_access_code.equal?(WORKSPACE) ? nil : require_signer_access_code(signer_access_code)
319
316
  end
320
317
 
321
- # `regex` is nullable: an explicit nil is sent as JSON null to clear it.
322
- def with_explicit_regex(raw, body)
323
- body['regex'] = nil if [:regex, 'regex'].any? { |key| raw.key?(key) && raw[key].nil? }
324
- body
325
- end
326
-
327
318
  def field_value_payload(item)
328
319
  payload = require_payload(item, 'Field value')
329
320
  field_id = payload.key?(:field_id) ? payload[:field_id] : payload['field_id']
330
321
  value_key = payload.key?(:value) ? :value : 'value'
331
322
 
332
323
  require_id(field_id, 'Field ID')
333
- unless payload.key?(value_key) && !payload[value_key].nil?
324
+ unless payload.key?(value_key)
334
325
  raise ValidationError.new('Field value is required')
335
326
  end
336
327
 
337
- body_params(payload)
328
+ body_params(payload).merge('value' => payload[value_key])
338
329
  end
339
330
  end
340
331
  end