assinafy 2.1.1 → 2.3.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.
@@ -9,7 +9,7 @@ module Assinafy
9
9
  # See https://api.assinafy.com.br/v1/docs#assignment for the full
10
10
  # documentation of these endpoints.
11
11
  class AssignmentResource < BaseResource
12
- OPTIONAL_FIELDS = %i[message expires_at copy_receivers].freeze
12
+ OPTIONAL_FIELDS = %i[message expires_at copy_receivers max_total_credits].freeze
13
13
  METHODS = %w[virtual collect].freeze
14
14
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL = 'digital_certificate_requires_virtual'
15
15
 
@@ -40,6 +40,11 @@ module Assinafy
40
40
  # subscriptions. When omitted it is inferred from `verification_method`
41
41
  # (`Whatsapp` → `["Whatsapp"]`); when both are omitted it is `["Email"]`.
42
42
  NOTIFICATION_METHODS = %w[Email Whatsapp].freeze
43
+ SIGNER_CAPACITIES = %w[
44
+ Sign Approve Acknowledge Party Witness Intervening Receipt IssuerEndorserGuarantor
45
+ IssuerEndorserGuarantorSurety Surety PartySurety JointDebtor PartyJointDebtor ContractingParty
46
+ ContractedParty Landlord Tenant Buyer Seller AttorneyInFact LegalRepresentative Employer Employee
47
+ ].freeze
43
48
 
44
49
  SIGN_ITEM_KEY_MAP = {
45
50
  'item_id' => 'itemId',
@@ -53,17 +58,18 @@ module Assinafy
53
58
  # shape the API expects. Accepts:
54
59
  #
55
60
  # - `signers: ['id1', 'id2']` — bare IDs
56
- # - `signers: [{ id:, verification_method:, notification_methods:, step: }]`
61
+ # - `signers: [{ id:, verification_method:, notification_methods:, step:, embedded:, sign_as: }]`
57
62
  # - Legacy `signer_ids:`/`signerIds:` arrays of IDs
58
63
  #
59
64
  # @note Creation requires top-level `signers` for both methods, and `collect` additionally
60
- # requires positioned `entries`; both are optional in estimate-cost payloads.
65
+ # requires positioned `entries`. Estimates need signers for virtual and entries for collect.
61
66
  # @param payload [Hash]
62
67
  # @param options [Hash]
63
68
  # @option options [Boolean] :allow_signers_without_id allow estimate-cost
64
69
  # payloads where method-only signer descriptors carry no id
65
- # @option options [Boolean] :require_signers (true) false for estimate-cost payloads, where
66
- # `signers` and `entries` are optional; an empty `signers` list is then omitted
70
+ # @option options [Boolean] :require_signers (true) false for collect estimates without signer IDs
71
+ # @option options [Boolean] :validate_steps (true) false when template role metadata is needed
72
+ # to distinguish signers from copy receivers; individual steps are always validated
67
73
  # @return [Hash] string-keyed body suitable for {#create} / {#estimate_cost}
68
74
  # @raise [Assinafy::ValidationError] on missing required fields
69
75
  # @example Bare signer IDs are normalised into { id: } hashes (virtual method)
@@ -126,7 +132,8 @@ module Assinafy
126
132
  result = { method: method }
127
133
  normalised = signers.map { |ref| normalise_signer_ref(ref, options) }
128
134
  validate_certificate_method!(method, normalised)
129
- validate_signing_steps!(normalised)
135
+ validate_signing_steps!(normalised, options)
136
+ validate_collect_entries!(entries, normalised) if method == 'collect' && options.fetch(:require_signers, true)
130
137
  result[:signers] = normalised unless normalised.empty?
131
138
  OPTIONAL_FIELDS.each { |key| result[key] = p[key] if p[key] }
132
139
  result[:entries] = entries if entries
@@ -139,10 +146,7 @@ module Assinafy
139
146
  unless METHODS.include?(method)
140
147
  raise ValidationError.new("Assignment method must be one of: #{METHODS.join(', ')}")
141
148
  end
142
- return unless require_signers
143
-
144
- # Creation needs `signers` for both methods; positioned fields do not replace this list.
145
- if signers.empty?
149
+ if signers.empty? && (require_signers || method == 'virtual')
146
150
  raise ValidationError.new(
147
151
  'At least one signer is required',
148
152
  { signers: payload[:signers] || payload[:signer_ids] || payload[:signerIds] }
@@ -165,6 +169,7 @@ module Assinafy
165
169
  raise ValidationError.new("#{key} must be a String", { key => value })
166
170
  end
167
171
  Utils.require_expiration(payload[:expires_at])
172
+ Utils.require_credit_ceiling(payload[:max_total_credits])
168
173
 
169
174
  receivers = payload[:copy_receivers]
170
175
  return if receivers.nil?
@@ -177,6 +182,57 @@ module Assinafy
177
182
  end
178
183
  end
179
184
 
185
+ def validate_collect_entries!(entries, signers)
186
+ signer_ids = signers.map { |signer| signer[:id] }
187
+ if signer_ids.uniq != signer_ids
188
+ raise ValidationError.new('Collect signers must be distinct')
189
+ end
190
+
191
+ assigned = entries.flat_map do |entry|
192
+ unless entry.is_a?(Hash)
193
+ raise ValidationError.new('Collect entry must be a Hash')
194
+ end
195
+
196
+ page = Utils.body_params(entry)
197
+ require_payload_id!(page['page_id'], 'Collect page ID')
198
+ fields = page['fields']
199
+ unless fields.is_a?(Array) && !fields.empty?
200
+ raise ValidationError.new('Collect fields must be a non-empty Array')
201
+ end
202
+
203
+ fields.map { |field| validate_collect_field!(field, signer_ids) }
204
+ end
205
+ unless (signer_ids - assigned).empty?
206
+ raise ValidationError.new('Every collect signer must own at least one field')
207
+ end
208
+ end
209
+
210
+ def validate_collect_field!(field, signer_ids)
211
+ raise ValidationError.new('Collect field must be a Hash') unless field.is_a?(Hash)
212
+
213
+ require_payload_id!(field['field_id'], 'Collect field ID')
214
+ unless signer_ids.include?(field['signer_id'])
215
+ raise ValidationError.new('Collect field signer must appear in signers')
216
+ end
217
+
218
+ display = field['display_settings']
219
+ raise ValidationError.new('display_settings must be a Hash') unless display.is_a?(Hash)
220
+
221
+ %w[left top width height fontSize].each do |key|
222
+ value = display[key]
223
+ valid = value.is_a?(Numeric) && value.real? && value.finite?
224
+ valid &&= %w[left top].include?(key) ? value >= 0 : value > 0
225
+ raise ValidationError.new("Invalid display_settings #{key}") unless valid
226
+ end
227
+ field['signer_id']
228
+ end
229
+
230
+ def require_payload_id!(value, name)
231
+ return if value.is_a?(String) && !value.strip.empty?
232
+
233
+ raise ValidationError.new("#{name} must be a non-empty String")
234
+ end
235
+
180
236
  def extract_signer_refs(payload)
181
237
  return payload[:signers] if payload[:signers].is_a?(Array) && !payload[:signers].empty?
182
238
 
@@ -201,17 +257,24 @@ module Assinafy
201
257
  r = ref.transform_keys(&:to_sym)
202
258
  id = r[:id] || r[:signer_id]
203
259
 
260
+ normalised = { id: id }.compact.merge(signer_options(r))
261
+
262
+ return normalised if id.is_a?(String) && !id.strip.empty?
263
+ return normalised if id.nil? && options[:allow_signers_without_id]
264
+
265
+ raise ValidationError.new('Invalid signer reference', { ref: ref })
266
+ end
267
+
268
+ def signer_options(r)
204
269
  normalised = {}
205
- normalised[:id] = id if id
206
270
  normalised[:verification_method] = verification_method!(r) unless r[:verification_method].nil?
207
271
  normalised[:notification_methods] = notification_methods!(r) unless r[:notification_methods].nil?
208
272
  normalised[:step] = signer_step!(r[:step]) unless r[:step].nil?
273
+ normalised[:embedded] = embedded_signer!(r) if r.key?(:embedded)
274
+ normalised[:sign_as] = signer_capacity!(r[:sign_as]) unless r[:sign_as].nil?
209
275
  validate_method_pair!(normalised)
210
276
 
211
- return normalised if id.is_a?(String) && !id.strip.empty?
212
- return normalised if id.nil? && options[:allow_signers_without_id]
213
-
214
- raise ValidationError.new('Invalid signer reference', { ref: ref })
277
+ normalised
215
278
  end
216
279
 
217
280
  # The API's enums are closed and it reports an unknown value as a 422
@@ -240,12 +303,28 @@ module Assinafy
240
303
  )
241
304
  end
242
305
 
306
+ def embedded_signer!(ref)
307
+ value = ref[:embedded]
308
+ raise ValidationError.new('embedded must be true or false') unless [true, false].include?(value)
309
+ if value && %w[DigitalCertificate IdDocumentFaceMatchBasic].include?(ref[:verification_method])
310
+ raise ValidationError.new('Embedded signing requires Email or Whatsapp verification')
311
+ end
312
+
313
+ value
314
+ end
315
+
243
316
  def signer_step!(step)
244
317
  return step if step.is_a?(Integer) && step > 0
245
318
 
246
319
  raise ValidationError.new('step must be a positive Integer', { step: step })
247
320
  end
248
321
 
322
+ def signer_capacity!(value)
323
+ return value if SIGNER_CAPACITIES.include?(value)
324
+
325
+ raise ValidationError.new("sign_as must be one of: #{SIGNER_CAPACITIES.join(', ')}")
326
+ end
327
+
249
328
  def validate_method_pair!(signer)
250
329
  verification = signer[:verification_method]
251
330
  notification = signer[:notification_methods]&.first
@@ -266,13 +345,19 @@ module Assinafy
266
345
  )
267
346
  end
268
347
 
269
- def validate_signing_steps!(signers)
348
+ def validate_signing_steps!(signers, options)
349
+ return unless options.fetch(:validate_steps, true)
350
+
270
351
  steps = signers.map { |signer| signer[:step] }
271
352
  contiguous = steps.compact.uniq.sort.each_with_index.all? { |step, index| step == index + 1 }
272
353
  if steps.any? && (steps.any?(nil) || !contiguous)
273
354
  raise ValidationError.new('Signing steps must be supplied for every signer and be contiguous from 1')
274
355
  end
275
356
 
357
+ validate_certificate_steps!(signers)
358
+ end
359
+
360
+ def validate_certificate_steps!(signers)
276
361
  step_counts = signers.map { |signer| signer[:step] || 1 }.tally
277
362
  signers.each do |signer|
278
363
  next unless signer[:verification_method] == 'DigitalCertificate'
@@ -283,9 +368,7 @@ module Assinafy
283
368
  end
284
369
  end
285
370
 
286
- # List assignments for an account. The API requires an account context,
287
- # supplied as the `accountId` query parameter — note the camelCase, which
288
- # is unusual for this otherwise snake_case API (verified live).
371
+ # List assignments for an account. API keys need accountId; OAuth tokens can infer their workspace.
289
372
  #
290
373
  # @param params [Hash] documented `page` and `per_page` query parameters
291
374
  # @param account_id_override [String, nil]
@@ -318,8 +401,11 @@ module Assinafy
318
401
  # ]
319
402
  # }
320
403
  def list(params = {}, account_id_override = nil)
321
- acc_id = account_id(account_id_override)
322
- query = require_payload(params, 'Assignment query parameters')
404
+ acc_id = account_id_override.nil? ? @default_account_id : account_id_override
405
+ unless acc_id.nil? && @connection.headers['Authorization'].to_s.start_with?('Bearer ')
406
+ acc_id = account_id(acc_id)
407
+ end
408
+ query = require_payload(params, 'Assignment query parameters')
323
409
 
324
410
  call_list('Failed to list assignments') do
325
411
  http_get('assignments', query.merge(accountId: acc_id))
@@ -373,12 +459,39 @@ module Assinafy
373
459
  end
374
460
  end
375
461
 
462
+ # Schedule an assignment without creating or charging it now. Requires documents:write.
463
+ # Available on staging; the environment must publish scheduled sends.
464
+ # @param document_id [String]
465
+ # @param payload [Hash] the same assignment payload as create, including sign_as when needed
466
+ # @param send_at [String, Integer] from one hour to 90 days ahead; absent offset means UTC
467
+ # @return [Hash] ScheduledSend; its deadline must be at least two hours after send_at
468
+ # @raise [ValidationError] on invalid IDs, payload or timing
469
+ # @raise [ApiError, NetworkError] on API or transport failure
470
+ # @see POST /documents/{documentId}/scheduled-sends
471
+ # @example
472
+ # client.assignments.schedule('document-id', { signers: ['signer-id'] },
473
+ # send_at: (Time.now + 7200).iso8601)
474
+ # # POST body: { "method": "virtual", "signers": [{ "id": "signer-id" }],
475
+ # # "send_at": "2026-12-01T12:00:00Z" }
476
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
477
+ # # 'document_ids' => ['document-id'], 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z',
478
+ # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
479
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }
480
+ def schedule(document_id, payload, send_at:)
481
+ id = require_id(document_id, 'Document ID')
482
+ time = ScheduledSendResource.require_send_at(send_at)
483
+ raw = require_payload(payload).transform_keys(&:to_s)
484
+ raw['expires_at'] = ScheduledSendResource.scheduled_expiration(raw['expires_at'], time)
485
+ body = self.class.build_payload(raw).merge('send_at' => send_at)
486
+ call('Failed to schedule assignment') { http_post("documents/#{id}/scheduled-sends", body) }
487
+ end
488
+
376
489
  # Estimate the credit cost of a potential assignment, without creating it.
377
490
  # Accepts the same payload as {#create}, but signer descriptors may omit
378
491
  # `id`. An empty descriptor (`{}`) defaults both methods to `Email`.
379
492
  #
380
493
  # @param document_id [String]
381
- # @param payload [Hash] `method`, and optional `signers` (method-only descriptors) and `entries`
494
+ # @param payload [Hash] method with signers for virtual or entries for collect
382
495
  # @return [Hash] cost breakdown (documents, credits, needs_extra_document, extra_document_cost,
383
496
  # total_credits, breakdown[], document_balance, credit_balance, has_sufficient_resources,
384
497
  # blocking_reason, message)
@@ -474,6 +587,7 @@ module Assinafy
474
587
  end
475
588
 
476
589
  # Estimate the credit cost of resending the notification to a signer.
590
+ # Does not check deadline or reminder frequency eligibility.
477
591
  #
478
592
  # @param document_id [String]
479
593
  # @param assignment_id [String]
@@ -592,10 +706,64 @@ module Assinafy
592
706
  end
593
707
  end
594
708
 
709
+ # Create a single-use iframe URL for a signer marked embedded. Open it within five minutes.
710
+ #
711
+ # @param document_id [String]
712
+ # @param assignment_id [String]
713
+ # @param signer_id [String]
714
+ # @return [Hash] url and expires_at
715
+ # @raise [Assinafy::ValidationError] on invalid IDs
716
+ # @raise [Assinafy::ApiError] on a plan restriction, unavailable document or exhausted session limit
717
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
718
+ # @see POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/embed-sessions
719
+ # @example Create a session with workspace credentials (no request body)
720
+ # client.assignments.create_embed_session('document-id', 'assignment-id', 'signer-id')
721
+ # # => { 'url' => 'https://app.assinafy.com.br/embed/session-token',
722
+ # # 'expires_at' => '2026-11-11T12:05:00Z' }
723
+ def create_embed_session(document_id, assignment_id, signer_id)
724
+ doc_id = require_id(document_id, 'Document ID')
725
+ asg_id = require_id(assignment_id, 'Assignment ID')
726
+ sid = require_id(signer_id, 'Signer ID')
727
+
728
+ call('Failed to create embed session') do
729
+ http_post("documents/#{doc_id}/assignments/#{asg_id}/signers/#{sid}/embed-sessions")
730
+ end
731
+ end
732
+
733
+ # Exchange the token on Assinafy's embed page. Integrations normally load the session URL instead.
734
+ # The token is spent even on 409; never retry this operation automatically.
735
+ #
736
+ # @param token [String] 64-character session token
737
+ # @param parent_origin [String, nil] origin of the page hosting the iframe
738
+ # @return [Hash] signer_access_code, signer_id, document_id, verification_method and embed_origins
739
+ # @raise [Assinafy::ValidationError] on an invalid token or parent origin
740
+ # @raise [Assinafy::ApiError] on an unavailable document or expired/used token
741
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
742
+ # @see POST /embed/sessions/{token}/exchange
743
+ # @example Exchange with the token as the only credential
744
+ # client.assignments.exchange_embed_session('a' * 64, parent_origin: 'https://app.example.com')
745
+ # # Body: { 'parent_origin' => 'https://app.example.com' }
746
+ # # => { 'signer_access_code' => 'access-code', 'signer_id' => 'signer-id',
747
+ # # 'document_id' => 'document-id', 'verification_method' => 'Email',
748
+ # # 'embed_origins' => ['https://app.example.com'] }
749
+ def exchange_embed_session(token, parent_origin: nil)
750
+ session_token = require_id(token, 'Embed session token')
751
+ raise ValidationError.new('Embed session token must contain 64 characters') unless session_token.length == 64
752
+
753
+ require_string(parent_origin, 'Parent origin') unless parent_origin.nil?
754
+
755
+ call('Failed to exchange embed session') do
756
+ http_post("embed/sessions/#{session_token}/exchange", body_params(parent_origin: parent_origin),
757
+ workspace_auth: false)
758
+ end
759
+ end
760
+
595
761
  # Fetch the document a signer is being asked to sign (signer-access-code auth).
596
762
  #
597
763
  # @param signer_access_code [String]
598
764
  # @param has_accepted_terms [Boolean, nil]
765
+ # @param expand [String, Array<String>, nil] envelope to include its id and name
766
+ # @param document_id [String, nil] another document in the access code's envelope
599
767
  # @return [Hash] the document (id, account_id, name, status, artifacts, signing_url, ...) with an
600
768
  # embedded current_signer and assignment (items filtered to the current signer); no pages array
601
769
  # @raise [Assinafy::ApiError] on an unsuccessful API response
@@ -618,18 +786,23 @@ module Assinafy
618
786
  # # "assignment" => { "id" => "1", "method" => "virtual", "expires_at" => nil,
619
787
  # # "items" => [{ "id" => "assignment-item-id", "field" => { "type" => "virtual" }, ... }] }
620
788
  # # } # ... (see docs for full shape)
621
- def signer_document(signer_access_code:, has_accepted_terms: nil)
789
+ def signer_document(signer_access_code:, has_accepted_terms: nil, expand: nil, document_id: nil)
622
790
  access_code = require_signer_access_code(signer_access_code)
623
791
  accepted = has_accepted_terms.nil? ? nil : require_boolean(has_accepted_terms, 'has_accepted_terms')
792
+ require_id(document_id, 'Document ID') unless document_id.nil?
793
+ expansion = signing_expansion(expand)
624
794
 
625
795
  call('Failed to fetch signer assignment document') do
626
796
  http_get('sign',
627
- { signer_access_code: access_code, has_accepted_terms: accepted },
797
+ { signer_access_code: access_code, has_accepted_terms: accepted, expand: expansion,
798
+ document_id: document_id },
628
799
  workspace_auth: false)
629
800
  end
630
801
  end
631
802
 
632
803
  # Submit signatures for an assignment as a signer.
804
+ # Virtual assignments send []; collect requires stored signature and initial images.
805
+ # Omitted read-only/optional collect fields are filled or left empty by the API.
633
806
  #
634
807
  # The API uses camelCase for this body. Callers may pass snake_case
635
808
  # (`item_id`, `field_id`, `page_id`, `value`) — this method maps them
@@ -637,11 +810,10 @@ module Assinafy
637
810
  #
638
811
  # @param document_id [String]
639
812
  # @param assignment_id [String]
640
- # @param items [Array<Hash>]
813
+ # @param items [Array<Hash>] [] for virtual; the API validates required collect values
641
814
  # @param signer_access_code [String]
642
- # @return [Hash] empty Hash `{}` on success per the API reference. Signing
643
- # requires an emailed OTP, so this exact shape is not independently
644
- # verifiable with a workspace API key.
815
+ # @return [Hash] signing result; staging returns the signer's assignment with only their items,
816
+ # without signing URLs or other parties' contact details and government IDs
645
817
  # @raise [Assinafy::ApiError] on an unsuccessful API response
646
818
  # @raise [Assinafy::NetworkError] on transport or TLS failure
647
819
  # @raise [Assinafy::ValidationError] on invalid required input
@@ -654,11 +826,14 @@ module Assinafy
654
826
  # # Request body the SDK sends (snake_case keys mapped to camelCase):
655
827
  # # [{ "itemId" => "assignment-item-id", "fieldId" => "field-id",
656
828
  # # "pageId" => "page-id", "value" => "Signed by Example Signer" }]
657
- # # => {} # per the API reference (unverified via workspace key)
829
+ # # => { 'resource' => 'assignment', 'id' => 'assignment-id', 'document_id' => 'document-id',
830
+ # # 'method' => 'collect', 'items' => [{ 'id' => 'assignment-item-id', 'completed' => true, ... }], ... }
658
831
  def sign(document_id, assignment_id, items, signer_access_code:)
659
832
  doc_id = require_id(document_id, 'Document ID')
660
833
  asg_id = require_id(assignment_id, 'Assignment ID')
661
- body = require_array(items, 'Assignment items').map { |item| normalise_sign_item(item) }
834
+ raise ValidationError.new('Assignment items must be an Array') unless items.is_a?(Array)
835
+
836
+ body = items.map { |item| normalise_sign_item(item) }
662
837
  access_code = require_signer_access_code(signer_access_code)
663
838
 
664
839
  call('Failed to sign assignment') do
@@ -746,7 +921,7 @@ module Assinafy
746
921
  %w[itemId fieldId pageId].each do |key|
747
922
  require_id(normalised[key], "Assignment item #{key}")
748
923
  end
749
- value = require_present(normalised['value'], 'Assignment item value')
924
+ value = normalised['value']
750
925
  raise ValidationError.new('Assignment item value must be a String') unless value.is_a?(String)
751
926
 
752
927
  normalised
@@ -83,6 +83,20 @@ module Assinafy
83
83
  raise ValidationError.new("#{name} must be a non-empty Array")
84
84
  end
85
85
 
86
+ def require_preferences(value, allowed, name = 'Notification preferences')
87
+ preferences = require_payload(value, name)
88
+ raise ValidationError.new("#{name} must not be empty") if preferences.empty?
89
+
90
+ preferences.each do |code, enabled|
91
+ unless allowed.include?(code.to_s)
92
+ raise ValidationError.new("Unknown notification preference: #{code}")
93
+ end
94
+
95
+ require_boolean(enabled, "Notification preference #{code}")
96
+ end
97
+ preferences
98
+ end
99
+
86
100
  def require_signer_access_code(value)
87
101
  require_string(value, 'Signer access code')
88
102
  end
@@ -194,13 +208,30 @@ module Assinafy
194
208
  end
195
209
  end
196
210
 
197
- def http_post(path, body = nil, params = {}, workspace_auth: true)
211
+ def http_post(path, body = nil, params = {}, workspace_auth: true, headers: {})
198
212
  @connection.post(path) do |request|
213
+ request.headers.update(headers)
199
214
  prepare_request(request, params, workspace_auth: workspace_auth)
200
215
  request.body = body unless body.nil?
201
216
  end
202
217
  end
203
218
 
219
+ def idempotency_headers(key)
220
+ return {} if key.nil?
221
+
222
+ require_string(key, 'Idempotency key')
223
+ raise ValidationError.new('Idempotency key contains invalid characters') if key.match?(/[\r\n]/)
224
+
225
+ { 'Idempotency-Key' => key }
226
+ end
227
+
228
+ def signing_expansion(value)
229
+ return nil if value.nil?
230
+ return 'envelope' if ['envelope', ['envelope']].include?(value)
231
+
232
+ raise ValidationError.new('expand must be envelope')
233
+ end
234
+
204
235
  # RFC 6749 §4.1.3/§6 and RFC 7009 §2.1 define token and revocation
205
236
  # requests as form posts. The connection's JSON and multipart middleware
206
237
  # leave a pre-encoded String body alone.
@@ -156,6 +156,7 @@ module Assinafy
156
156
  # @raise [Assinafy::ApiError] on an unsuccessful response other than 404
157
157
  # @raise [Assinafy::NetworkError] on transport or TLS failure
158
158
  # @raise [Assinafy::ValidationError] on an invalid ID
159
+ # @param expand [String, nil] `document` embeds the root document, including its name
159
160
  # @see GET /accounts/{accountId}/documents/{documentId}/contract/related
160
161
  # @example Read a family from one of its amendments
161
162
  # client.contracts.related('amendment-id')
@@ -169,9 +170,13 @@ module Assinafy
169
170
  # # 'amendments' => [{ 'document_id' => 'amendment-id', 'relation_type' => 'amendment',
170
171
  # # 'number' => 1, 'status' => 'applied', 'terms' => { 'value' => 130000 } }],
171
172
  # # 'created_at' => '2026-10-23T12:00:00Z', 'updated_at' => '2027-05-12T18:20:00Z' }
172
- def related(document_id, account_id_override = nil)
173
+ def related(document_id, account_id_override = nil, expand: nil)
174
+ unless expand.nil? || expand == 'document'
175
+ raise ValidationError.new('expand must be document')
176
+ end
177
+
173
178
  call_optional('Failed to fetch related contracts') do
174
- http_get("#{contract_path(document_id, account_id_override)}/related")
179
+ http_get("#{contract_path(document_id, account_id_override)}/related", { expand: expand })
175
180
  end
176
181
  end
177
182
 
@@ -230,7 +235,7 @@ module Assinafy
230
235
  def terminate(document_id, payload = {}, account_id_override = nil)
231
236
  body = contract_payload(payload, TERMINATE_FIELDS, 'Contract termination payload')
232
237
  validate_optional_string!(body, 'reason', 'Termination reason', max_length: 500)
233
- validate_optional_string!(body, 'updated_at', 'updated_at')
238
+ validate_optional_timestamp!(body, 'updated_at')
234
239
 
235
240
  call('Failed to terminate contract') do
236
241
  http_post("#{contract_path(document_id, account_id_override)}/terminate", body)
@@ -315,8 +320,12 @@ module Assinafy
315
320
  validate_number!(body['value'], 'value', 0, 9_999_999_999_999.99)
316
321
  end
317
322
  validate_boolean!(body, 'auto_renew')
318
- validate_integer!(body['renewal_term_months'], 'renewal_term_months', 1, 600) if body['renewal_term_months']
319
- validate_integer!(body['notice_period_days'], 'notice_period_days', 0, 3650) if body['notice_period_days']
323
+ unless body['renewal_term_months'].nil?
324
+ validate_integer!(body['renewal_term_months'], 'renewal_term_months', 1, 600)
325
+ end
326
+ unless body['notice_period_days'].nil?
327
+ validate_integer!(body['notice_period_days'], 'notice_period_days', 0, 3650)
328
+ end
320
329
  end
321
330
 
322
331
  def validate_contract_collections!(body)