assinafy 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,6 +41,8 @@ module Assinafy
41
41
  attr_reader :signer_documents
42
42
  # @return [Resources::AssignmentResource]
43
43
  attr_reader :assignments
44
+ # @return [Resources::EnvelopeResource]
45
+ attr_reader :envelopes
44
46
  # @return [Resources::WebhookResource]
45
47
  attr_reader :webhooks
46
48
  # @return [Resources::TemplateResource]
@@ -90,6 +92,7 @@ module Assinafy
90
92
  @signers = Resources::SignerResource.new(@connection, account_id, @logger)
91
93
  @signer_documents = Resources::SignerDocumentResource.new(@connection, nil, @logger)
92
94
  @assignments = Resources::AssignmentResource.new(@connection, account_id, @logger)
95
+ @envelopes = Resources::EnvelopeResource.new(@connection, account_id, @logger)
93
96
  @webhooks = Resources::WebhookResource.new(@connection, account_id, @logger)
94
97
  @templates = Resources::TemplateResource.new(@connection, account_id, @logger)
95
98
  @fields = Resources::FieldResource.new(@connection, account_id, @logger)
@@ -39,7 +39,7 @@ module Assinafy
39
39
  attr_reader :response_data
40
40
  # @return [String, nil] the API's `name` field (framework errors only)
41
41
  attr_reader :error_name
42
- # @return [Integer, String, nil] the API's `code` field, when present
42
+ # @return [Integer, String, nil] the API's `code` field, including actionable refusal codes
43
43
  attr_reader :error_code
44
44
 
45
45
  def initialize(message, status_code, response_data = nil)
@@ -79,7 +79,8 @@ module Assinafy
79
79
  end
80
80
 
81
81
  # Build an {ApiError} from an HTTP status and parsed body. Reads the human
82
- # message from `message`, `error`, or `name` (in that order).
82
+ # message from `message`, `error`, or `name` (in that order). Field errors
83
+ # remain available as `response_data['errors']` with their field, code and message.
83
84
  #
84
85
  # @param status_code [Integer]
85
86
  # @param response_data [Hash, Object]
@@ -73,12 +73,14 @@ module Assinafy
73
73
  end
74
74
 
75
75
  # Fetch an account by ID (defaults to the client's account).
76
+ # Pass `expand: 'signing_features'` to include current plan gates for signing.
76
77
  #
77
78
  # @param account_id_override [String, nil]
78
79
  # @return [Hash] the account (envelope `data` unwrapped)
79
80
  # @raise [Assinafy::ApiError] on an unsuccessful API response
80
81
  # @raise [Assinafy::NetworkError] on transport or TLS failure
81
82
  # @raise [Assinafy::ValidationError] on invalid required input
83
+ # @param expand [String, nil] `signing_features` adds five boolean feature flags
82
84
  # @see GET /accounts/{account_id}
83
85
  # @example Fetch the current account
84
86
  # # Request: GET /accounts/{account_id}
@@ -93,11 +95,14 @@ module Assinafy
93
95
  # 'limits' => { 'webhook_endpoints' => 1 },
94
96
  # 'created_at' => '2026-05-12T18:05:11Z'
95
97
  # }
96
- def get(account_id_override = nil)
98
+ def get(account_id_override = nil, expand: nil)
97
99
  acc_id = account_id(account_id_override)
100
+ unless expand.nil? || expand == 'signing_features'
101
+ raise ValidationError.new('expand must be signing_features')
102
+ end
98
103
 
99
104
  call('Failed to fetch account') do
100
- http_get("accounts/#{acc_id}")
105
+ http_get("accounts/#{acc_id}", { expand: expand })
101
106
  end
102
107
  end
103
108
 
@@ -192,7 +197,7 @@ module Assinafy
192
197
  # @note Documented in the API reference, but gated on the account's plan:
193
198
  # this route answers 404 where the KPI feature is not enabled.
194
199
  # @param granularity [String, nil] `"monthly"` or `"daily"`
195
- # @param month [String, nil] e.g. `"2026-06"`
200
+ # @param month [String, nil] e.g. `"2026-06"`; required with daily granularity
196
201
  # @param account_id_override [String, nil]
197
202
  # @return [Array<Hash>] one KPI entry per period
198
203
  # @raise [Assinafy::ApiError] on an unsuccessful API response
@@ -303,8 +308,191 @@ module Assinafy
303
308
  end
304
309
  end
305
310
 
311
+ # Read the plan name, renewal date, document allowance and credit balance.
312
+ # Billing data is unavailable to third-party OAuth applications.
313
+ #
314
+ # @param account_id_override [String, nil]
315
+ # @return [Hash] AccountUsage
316
+ # @raise [Assinafy::ValidationError] on an invalid account ID
317
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
318
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
319
+ # @see GET /accounts/{accountId}/usage
320
+ # @example Read the workspace allowance
321
+ # client.accounts.usage
322
+ # # Request: GET /accounts/{accountId}/usage (no body)
323
+ # # => { 'plan' => 'Pro', 'documents_renewal_date' => '2026-12-01',
324
+ # # 'balances' => { 'documents' => { 'balance' => 90, 'limit' => 100, 'spent' => 10 },
325
+ # # 'credits' => { 'balance' => 40, 'limit' => nil, 'spent' => 5 } } }
326
+ def usage(account_id_override = nil)
327
+ acc_id = account_id(account_id_override)
328
+ call('Failed to fetch account usage') { http_get("accounts/#{acc_id}/usage") }
329
+ end
330
+
331
+ # Read workspace document-alert rules. `editable` identifies owners who can change them.
332
+ # Third-party OAuth applications cannot access this policy.
333
+ #
334
+ # @param account_id_override [String, nil]
335
+ # @return [Hash] NotificationPolicy with all event flags
336
+ # @raise [Assinafy::ValidationError] on an invalid account ID
337
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
338
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
339
+ # @see GET /accounts/{accountId}/notification-policy
340
+ # @example Read workspace notification rules
341
+ # client.accounts.notification_policy
342
+ # # Request: GET /accounts/{accountId}/notification-policy (no body)
343
+ # # => { 'editable' => true, 'owners_receive_all' => false, 'events' => {
344
+ # # 'DocumentCompleted' => true, 'SignerDeclined' => true, 'DocumentCancelled' => true,
345
+ # # 'DocumentAboutToExpire' => true, 'DocumentExpired' => true, 'DocumentExpirationReset' => true,
346
+ # # 'DocumentProcessingFailed' => true, 'TemplateProcessingFailed' => true,
347
+ # # 'SignerWhatsappFailed' => true, 'ContractRenewalNotice' => true, 'ContractExpiring' => true,
348
+ # # 'ContractExpired' => true, 'ContractRenewed' => true, 'SignerViewed' => false,
349
+ # # 'SignerSigned' => true, 'SignerIdentityReviewRequired' => true } }
350
+ def notification_policy(account_id_override = nil)
351
+ acc_id = account_id(account_id_override)
352
+ call('Failed to fetch notification policy') { http_get("accounts/#{acc_id}/notification-policy") }
353
+ end
354
+
355
+ # Merge workspace notification rules. Only owners can write this policy.
356
+ # Disabling identity-review alerts stops push only; its email is always sent.
357
+ # Third-party OAuth applications cannot access this policy.
358
+ #
359
+ # @param payload [Hash] partial `events` map and/or boolean `owners_receive_all`
360
+ # @param account_id_override [String, nil]
361
+ # @return [Hash] the full NotificationPolicy shown by {#notification_policy}
362
+ # @raise [Assinafy::ValidationError] on empty, unknown or invalid fields
363
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
364
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
365
+ # @see PUT /accounts/{accountId}/notification-policy
366
+ # @example Stop signer-viewed alerts
367
+ # client.accounts.update_notification_policy(events: { SignerViewed: false }, owners_receive_all: true)
368
+ # # Request: PUT /accounts/{accountId}/notification-policy
369
+ # # Body: { "events": { "SignerViewed": false }, "owners_receive_all": true }
370
+ # # Response: the full policy from #notification_policy with owners_receive_all true.
371
+ def update_notification_policy(payload, account_id_override = nil)
372
+ acc_id = account_id(account_id_override)
373
+ raw = require_payload(payload, 'Notification policy').transform_keys(&:to_s)
374
+ validate_notification_policy!(raw)
375
+ call('Failed to update notification policy') do
376
+ http_put("accounts/#{acc_id}/notification-policy", body_params(raw))
377
+ end
378
+ end
379
+
380
+ # List allowed embedding origins, oldest first. Requires embedded signing on the plan;
381
+ # OAuth applications cannot manage origins.
382
+ #
383
+ # @param account_id_override [String, nil]
384
+ # @return [Array<Hash>] EmbedOrigin objects
385
+ # @raise [Assinafy::ValidationError] on an invalid account ID
386
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
387
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
388
+ # @see GET /accounts/{accountId}/embed-origins
389
+ # @example List embedding origins
390
+ # client.accounts.list_embed_origins
391
+ # # Request: GET /accounts/{accountId}/embed-origins (no body)
392
+ # # => [{ 'id' => 'origin-id', 'origin' => 'https://app.example.com',
393
+ # # 'created_at' => '2026-11-04T12:05:00Z' }]
394
+ def list_embed_origins(account_id_override = nil)
395
+ acc_id = account_id(account_id_override)
396
+ call_array('Failed to list embed origins') { http_get("accounts/#{acc_id}/embed-origins") }
397
+ end
398
+
399
+ # Allow an exact HTTPS origin to embed signing pages. HTTP is accepted only for localhost
400
+ # and 127.0.0.1. At most ten origins are allowed; requires the plan feature and non-OAuth auth.
401
+ #
402
+ # @param origin [String] scheme://host[:port], optionally with a trailing slash
403
+ # @param account_id_override [String, nil]
404
+ # @return [Hash] created EmbedOrigin
405
+ # @raise [Assinafy::ValidationError] on an invalid origin or account ID
406
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
407
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
408
+ # @see POST /accounts/{accountId}/embed-origins
409
+ # @example Allow the application's origin
410
+ # client.accounts.create_embed_origin('https://app.example.com')
411
+ # # Request: POST /accounts/{accountId}/embed-origins
412
+ # # Body: { "origin": "https://app.example.com" }
413
+ # # => { 'id' => 'origin-id', 'origin' => 'https://app.example.com',
414
+ # # 'created_at' => '2026-11-04T12:05:00Z' }
415
+ def create_embed_origin(origin, account_id_override = nil)
416
+ acc_id = account_id(account_id_override)
417
+ validate_embed_origin!(origin)
418
+ call('Failed to create embed origin') do
419
+ http_post("accounts/#{acc_id}/embed-origins", body_params(origin: origin))
420
+ end
421
+ end
422
+
423
+ # Replace one allowed origin, retaining its ID. The same restrictions as {#create_embed_origin} apply.
424
+ #
425
+ # @param origin_id [String]
426
+ # @param origin [String] exact allowed origin
427
+ # @param account_id_override [String, nil]
428
+ # @return [Hash] updated EmbedOrigin
429
+ # @raise [Assinafy::ValidationError] on an invalid origin or ID
430
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
431
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
432
+ # @see PUT /accounts/{accountId}/embed-origins/{originId}
433
+ # @example Replace an embedding origin
434
+ # client.accounts.update_embed_origin('origin-id', 'https://new.example.com')
435
+ # # Request: PUT /accounts/{accountId}/embed-origins/origin-id
436
+ # # Body: { "origin": "https://new.example.com" }
437
+ # # => { 'id' => 'origin-id', 'origin' => 'https://new.example.com',
438
+ # # 'created_at' => '2026-11-04T12:05:00Z' }
439
+ def update_embed_origin(origin_id, origin, account_id_override = nil)
440
+ acc_id = account_id(account_id_override)
441
+ oid = require_id(origin_id, 'Origin ID')
442
+ validate_embed_origin!(origin)
443
+ call('Failed to update embed origin') do
444
+ http_put("accounts/#{acc_id}/embed-origins/#{oid}", body_params(origin: origin))
445
+ end
446
+ end
447
+
448
+ # Remove an allowed origin. Removing the last origin prevents new embed sessions.
449
+ # Requires embedded signing on the plan; OAuth applications cannot manage origins.
450
+ #
451
+ # @param origin_id [String]
452
+ # @param account_id_override [String, nil]
453
+ # @return [nil] the empty success payload is discarded
454
+ # @raise [Assinafy::ValidationError] on an invalid ID
455
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
456
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
457
+ # @see DELETE /accounts/{accountId}/embed-origins/{originId}
458
+ # @example Stop allowing an origin
459
+ # client.accounts.delete_embed_origin('origin-id')
460
+ # # Request: DELETE /accounts/{accountId}/embed-origins/origin-id (no body)
461
+ # # Response data: []; SDK return: nil
462
+ def delete_embed_origin(origin_id, account_id_override = nil)
463
+ acc_id = account_id(account_id_override)
464
+ oid = require_id(origin_id, 'Origin ID')
465
+ call_void('Failed to delete embed origin') { http_delete("accounts/#{acc_id}/embed-origins/#{oid}") }
466
+ end
467
+
306
468
  private
307
469
 
470
+ def validate_notification_policy!(body)
471
+ if body.empty? || (body.keys - %w[events owners_receive_all]).any?
472
+ raise ValidationError.new('Notification policy requires events and/or owners_receive_all')
473
+ end
474
+
475
+ require_boolean(body['owners_receive_all'], 'owners_receive_all') if body.key?('owners_receive_all')
476
+ return unless body.key?('events')
477
+
478
+ events = require_payload(body['events'], 'Notification policy events')
479
+ codes = UserResource::NOTIFICATION_PREFERENCE_CODES | UserResource::PUSH_PREFERENCE_CODES
480
+ require_preferences(events, codes, 'Notification policy events') unless events.empty?
481
+ end
482
+
483
+ def validate_embed_origin!(origin)
484
+ uri = URI.parse(require_string(origin, 'Embed origin'))
485
+ secure = uri.is_a?(URI::HTTPS) || (uri.is_a?(URI::HTTP) && %w[localhost
486
+ 127.0.0.1].include?(uri.host.to_s.downcase))
487
+ valid = secure && uri.host && !uri.host.include?('*') && (1..65_535).cover?(uri.port) &&
488
+ ['', '/'].include?(uri.path) && !uri.userinfo && !uri.query && !uri.fragment
489
+ return if valid
490
+
491
+ raise ValidationError.new('Embed origin must be an exact HTTPS origin (HTTP is allowed only on localhost)')
492
+ rescue URI::InvalidURIError
493
+ raise ValidationError.new('Embed origin must be a valid origin URL')
494
+ end
495
+
308
496
  def validate_sender_type!(body)
309
497
  return unless body.key?('notification_sender_type')
310
498
  return if %w[User Account].include?(body['notification_sender_type'])
@@ -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
 
@@ -57,13 +57,14 @@ module Assinafy
57
57
  # - Legacy `signer_ids:`/`signerIds:` arrays of IDs
58
58
  #
59
59
  # @note Creation requires top-level `signers` for both methods, and `collect` additionally
60
- # requires positioned `entries`; both are optional in estimate-cost payloads.
60
+ # requires positioned `entries`. Estimates need signers for virtual and entries for collect.
61
61
  # @param payload [Hash]
62
62
  # @param options [Hash]
63
63
  # @option options [Boolean] :allow_signers_without_id allow estimate-cost
64
64
  # 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
65
+ # @option options [Boolean] :require_signers (true) false for collect estimates without signer IDs
66
+ # @option options [Boolean] :validate_steps (true) false when template role metadata is needed
67
+ # to distinguish signers from copy receivers; individual steps are always validated
67
68
  # @return [Hash] string-keyed body suitable for {#create} / {#estimate_cost}
68
69
  # @raise [Assinafy::ValidationError] on missing required fields
69
70
  # @example Bare signer IDs are normalised into { id: } hashes (virtual method)
@@ -126,7 +127,8 @@ module Assinafy
126
127
  result = { method: method }
127
128
  normalised = signers.map { |ref| normalise_signer_ref(ref, options) }
128
129
  validate_certificate_method!(method, normalised)
129
- validate_signing_steps!(normalised)
130
+ validate_signing_steps!(normalised, options)
131
+ validate_collect_entries!(entries, normalised) if method == 'collect' && options.fetch(:require_signers, true)
130
132
  result[:signers] = normalised unless normalised.empty?
131
133
  OPTIONAL_FIELDS.each { |key| result[key] = p[key] if p[key] }
132
134
  result[:entries] = entries if entries
@@ -139,10 +141,7 @@ module Assinafy
139
141
  unless METHODS.include?(method)
140
142
  raise ValidationError.new("Assignment method must be one of: #{METHODS.join(', ')}")
141
143
  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?
144
+ if signers.empty? && (require_signers || method == 'virtual')
146
145
  raise ValidationError.new(
147
146
  'At least one signer is required',
148
147
  { signers: payload[:signers] || payload[:signer_ids] || payload[:signerIds] }
@@ -165,6 +164,7 @@ module Assinafy
165
164
  raise ValidationError.new("#{key} must be a String", { key => value })
166
165
  end
167
166
  Utils.require_expiration(payload[:expires_at])
167
+ Utils.require_credit_ceiling(payload[:max_total_credits])
168
168
 
169
169
  receivers = payload[:copy_receivers]
170
170
  return if receivers.nil?
@@ -177,6 +177,57 @@ module Assinafy
177
177
  end
178
178
  end
179
179
 
180
+ def validate_collect_entries!(entries, signers)
181
+ signer_ids = signers.map { |signer| signer[:id] }
182
+ if signer_ids.uniq != signer_ids
183
+ raise ValidationError.new('Collect signers must be distinct')
184
+ end
185
+
186
+ assigned = entries.flat_map do |entry|
187
+ unless entry.is_a?(Hash)
188
+ raise ValidationError.new('Collect entry must be a Hash')
189
+ end
190
+
191
+ page = Utils.body_params(entry)
192
+ require_payload_id!(page['page_id'], 'Collect page ID')
193
+ fields = page['fields']
194
+ unless fields.is_a?(Array) && !fields.empty?
195
+ raise ValidationError.new('Collect fields must be a non-empty Array')
196
+ end
197
+
198
+ fields.map { |field| validate_collect_field!(field, signer_ids) }
199
+ end
200
+ unless (signer_ids - assigned).empty?
201
+ raise ValidationError.new('Every collect signer must own at least one field')
202
+ end
203
+ end
204
+
205
+ def validate_collect_field!(field, signer_ids)
206
+ raise ValidationError.new('Collect field must be a Hash') unless field.is_a?(Hash)
207
+
208
+ require_payload_id!(field['field_id'], 'Collect field ID')
209
+ unless signer_ids.include?(field['signer_id'])
210
+ raise ValidationError.new('Collect field signer must appear in signers')
211
+ end
212
+
213
+ display = field['display_settings']
214
+ raise ValidationError.new('display_settings must be a Hash') unless display.is_a?(Hash)
215
+
216
+ %w[left top width height fontSize].each do |key|
217
+ value = display[key]
218
+ valid = value.is_a?(Numeric) && value.real? && value.finite?
219
+ valid &&= %w[left top].include?(key) ? value >= 0 : value > 0
220
+ raise ValidationError.new("Invalid display_settings #{key}") unless valid
221
+ end
222
+ field['signer_id']
223
+ end
224
+
225
+ def require_payload_id!(value, name)
226
+ return if value.is_a?(String) && !value.strip.empty?
227
+
228
+ raise ValidationError.new("#{name} must be a non-empty String")
229
+ end
230
+
180
231
  def extract_signer_refs(payload)
181
232
  return payload[:signers] if payload[:signers].is_a?(Array) && !payload[:signers].empty?
182
233
 
@@ -206,6 +257,7 @@ module Assinafy
206
257
  normalised[:verification_method] = verification_method!(r) unless r[:verification_method].nil?
207
258
  normalised[:notification_methods] = notification_methods!(r) unless r[:notification_methods].nil?
208
259
  normalised[:step] = signer_step!(r[:step]) unless r[:step].nil?
260
+ normalised[:embedded] = embedded_signer!(r) if r.key?(:embedded)
209
261
  validate_method_pair!(normalised)
210
262
 
211
263
  return normalised if id.is_a?(String) && !id.strip.empty?
@@ -240,6 +292,16 @@ module Assinafy
240
292
  )
241
293
  end
242
294
 
295
+ def embedded_signer!(ref)
296
+ value = ref[:embedded]
297
+ raise ValidationError.new('embedded must be true or false') unless [true, false].include?(value)
298
+ if value && %w[DigitalCertificate IdDocumentFaceMatchBasic].include?(ref[:verification_method])
299
+ raise ValidationError.new('Embedded signing requires Email or Whatsapp verification')
300
+ end
301
+
302
+ value
303
+ end
304
+
243
305
  def signer_step!(step)
244
306
  return step if step.is_a?(Integer) && step > 0
245
307
 
@@ -266,13 +328,19 @@ module Assinafy
266
328
  )
267
329
  end
268
330
 
269
- def validate_signing_steps!(signers)
331
+ def validate_signing_steps!(signers, options)
332
+ return unless options.fetch(:validate_steps, true)
333
+
270
334
  steps = signers.map { |signer| signer[:step] }
271
335
  contiguous = steps.compact.uniq.sort.each_with_index.all? { |step, index| step == index + 1 }
272
336
  if steps.any? && (steps.any?(nil) || !contiguous)
273
337
  raise ValidationError.new('Signing steps must be supplied for every signer and be contiguous from 1')
274
338
  end
275
339
 
340
+ validate_certificate_steps!(signers)
341
+ end
342
+
343
+ def validate_certificate_steps!(signers)
276
344
  step_counts = signers.map { |signer| signer[:step] || 1 }.tally
277
345
  signers.each do |signer|
278
346
  next unless signer[:verification_method] == 'DigitalCertificate'
@@ -283,9 +351,7 @@ module Assinafy
283
351
  end
284
352
  end
285
353
 
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).
354
+ # List assignments for an account. API keys need accountId; OAuth tokens can infer their workspace.
289
355
  #
290
356
  # @param params [Hash] documented `page` and `per_page` query parameters
291
357
  # @param account_id_override [String, nil]
@@ -318,8 +384,11 @@ module Assinafy
318
384
  # ]
319
385
  # }
320
386
  def list(params = {}, account_id_override = nil)
321
- acc_id = account_id(account_id_override)
322
- query = require_payload(params, 'Assignment query parameters')
387
+ acc_id = account_id_override.nil? ? @default_account_id : account_id_override
388
+ unless acc_id.nil? && @connection.headers['Authorization'].to_s.start_with?('Bearer ')
389
+ acc_id = account_id(acc_id)
390
+ end
391
+ query = require_payload(params, 'Assignment query parameters')
323
392
 
324
393
  call_list('Failed to list assignments') do
325
394
  http_get('assignments', query.merge(accountId: acc_id))
@@ -378,7 +447,7 @@ module Assinafy
378
447
  # `id`. An empty descriptor (`{}`) defaults both methods to `Email`.
379
448
  #
380
449
  # @param document_id [String]
381
- # @param payload [Hash] `method`, and optional `signers` (method-only descriptors) and `entries`
450
+ # @param payload [Hash] method with signers for virtual or entries for collect
382
451
  # @return [Hash] cost breakdown (documents, credits, needs_extra_document, extra_document_cost,
383
452
  # total_credits, breakdown[], document_balance, credit_balance, has_sufficient_resources,
384
453
  # blocking_reason, message)
@@ -592,10 +661,64 @@ module Assinafy
592
661
  end
593
662
  end
594
663
 
664
+ # Create a single-use iframe URL for a signer marked embedded. Open it within five minutes.
665
+ #
666
+ # @param document_id [String]
667
+ # @param assignment_id [String]
668
+ # @param signer_id [String]
669
+ # @return [Hash] url and expires_at
670
+ # @raise [Assinafy::ValidationError] on invalid IDs
671
+ # @raise [Assinafy::ApiError] on a plan restriction, unavailable document or exhausted session limit
672
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
673
+ # @see POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/embed-sessions
674
+ # @example Create a session with workspace credentials (no request body)
675
+ # client.assignments.create_embed_session('document-id', 'assignment-id', 'signer-id')
676
+ # # => { 'url' => 'https://app.assinafy.com.br/embed/session-token',
677
+ # # 'expires_at' => '2026-11-11T12:05:00Z' }
678
+ def create_embed_session(document_id, assignment_id, signer_id)
679
+ doc_id = require_id(document_id, 'Document ID')
680
+ asg_id = require_id(assignment_id, 'Assignment ID')
681
+ sid = require_id(signer_id, 'Signer ID')
682
+
683
+ call('Failed to create embed session') do
684
+ http_post("documents/#{doc_id}/assignments/#{asg_id}/signers/#{sid}/embed-sessions")
685
+ end
686
+ end
687
+
688
+ # Exchange the token on Assinafy's embed page. Integrations normally load the session URL instead.
689
+ # The token is spent even on 409; never retry this operation automatically.
690
+ #
691
+ # @param token [String] 64-character session token
692
+ # @param parent_origin [String, nil] origin of the page hosting the iframe
693
+ # @return [Hash] signer_access_code, signer_id, document_id, verification_method and embed_origins
694
+ # @raise [Assinafy::ValidationError] on an invalid token or parent origin
695
+ # @raise [Assinafy::ApiError] on an unavailable document or expired/used token
696
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
697
+ # @see POST /embed/sessions/{token}/exchange
698
+ # @example Exchange with the token as the only credential
699
+ # client.assignments.exchange_embed_session('a' * 64, parent_origin: 'https://app.example.com')
700
+ # # Body: { 'parent_origin' => 'https://app.example.com' }
701
+ # # => { 'signer_access_code' => 'access-code', 'signer_id' => 'signer-id',
702
+ # # 'document_id' => 'document-id', 'verification_method' => 'Email',
703
+ # # 'embed_origins' => ['https://app.example.com'] }
704
+ def exchange_embed_session(token, parent_origin: nil)
705
+ session_token = require_id(token, 'Embed session token')
706
+ raise ValidationError.new('Embed session token must contain 64 characters') unless session_token.length == 64
707
+
708
+ require_string(parent_origin, 'Parent origin') unless parent_origin.nil?
709
+
710
+ call('Failed to exchange embed session') do
711
+ http_post("embed/sessions/#{session_token}/exchange", body_params(parent_origin: parent_origin),
712
+ workspace_auth: false)
713
+ end
714
+ end
715
+
595
716
  # Fetch the document a signer is being asked to sign (signer-access-code auth).
596
717
  #
597
718
  # @param signer_access_code [String]
598
719
  # @param has_accepted_terms [Boolean, nil]
720
+ # @param expand [String, Array<String>, nil] envelope to include its id and name
721
+ # @param document_id [String, nil] another document in the access code's envelope
599
722
  # @return [Hash] the document (id, account_id, name, status, artifacts, signing_url, ...) with an
600
723
  # embedded current_signer and assignment (items filtered to the current signer); no pages array
601
724
  # @raise [Assinafy::ApiError] on an unsuccessful API response
@@ -618,13 +741,16 @@ module Assinafy
618
741
  # # "assignment" => { "id" => "1", "method" => "virtual", "expires_at" => nil,
619
742
  # # "items" => [{ "id" => "assignment-item-id", "field" => { "type" => "virtual" }, ... }] }
620
743
  # # } # ... (see docs for full shape)
621
- def signer_document(signer_access_code:, has_accepted_terms: nil)
744
+ def signer_document(signer_access_code:, has_accepted_terms: nil, expand: nil, document_id: nil)
622
745
  access_code = require_signer_access_code(signer_access_code)
623
746
  accepted = has_accepted_terms.nil? ? nil : require_boolean(has_accepted_terms, 'has_accepted_terms')
747
+ require_id(document_id, 'Document ID') unless document_id.nil?
748
+ expansion = signing_expansion(expand)
624
749
 
625
750
  call('Failed to fetch signer assignment document') do
626
751
  http_get('sign',
627
- { signer_access_code: access_code, has_accepted_terms: accepted },
752
+ { signer_access_code: access_code, has_accepted_terms: accepted, expand: expansion,
753
+ document_id: document_id },
628
754
  workspace_auth: false)
629
755
  end
630
756
  end
@@ -639,9 +765,7 @@ module Assinafy
639
765
  # @param assignment_id [String]
640
766
  # @param items [Array<Hash>]
641
767
  # @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.
768
+ # @return [Hash] empty Hash `{}` on success
645
769
  # @raise [Assinafy::ApiError] on an unsuccessful API response
646
770
  # @raise [Assinafy::NetworkError] on transport or TLS failure
647
771
  # @raise [Assinafy::ValidationError] on invalid required input
@@ -654,7 +778,7 @@ module Assinafy
654
778
  # # Request body the SDK sends (snake_case keys mapped to camelCase):
655
779
  # # [{ "itemId" => "assignment-item-id", "fieldId" => "field-id",
656
780
  # # "pageId" => "page-id", "value" => "Signed by Example Signer" }]
657
- # # => {} # per the API reference (unverified via workspace key)
781
+ # # => {}
658
782
  def sign(document_id, assignment_id, items, signer_access_code:)
659
783
  doc_id = require_id(document_id, 'Document ID')
660
784
  asg_id = require_id(assignment_id, 'Assignment ID')
@@ -712,7 +836,7 @@ module Assinafy
712
836
  # resource.whatsapp_notifications("document-id", "assignment-id")
713
837
  # # (no request body)
714
838
  # # => [
715
- # # { "sent_at" => 1710000000,
839
+ # # { "sent_at" => "2026-07-07T12:00:00Z",
716
840
  # # "header" => "Documento para assinatura: Contrato de Servico",
717
841
  # # "body" => "Oi, Maria.\n\nJoao Silva enviou um documento...",
718
842
  # # "buttons" => [{ "text" => "Abrir documento" }],
@@ -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
@@ -95,6 +109,9 @@ module Assinafy
95
109
  unless granularity.nil? || STATS_GRANULARITIES.include?(granularity)
96
110
  raise ValidationError.new('granularity must be monthly or daily')
97
111
  end
112
+ if granularity == 'daily' && month.nil?
113
+ raise ValidationError.new('month is required when granularity is daily')
114
+ end
98
115
  unless month.nil? || (month.is_a?(String) && month.match?(/\A\d{4}-(0[1-9]|1[0-2])\z/))
99
116
  raise ValidationError.new('month must be YYYY-MM')
100
117
  end
@@ -191,13 +208,30 @@ module Assinafy
191
208
  end
192
209
  end
193
210
 
194
- def http_post(path, body = nil, params = {}, workspace_auth: true)
211
+ def http_post(path, body = nil, params = {}, workspace_auth: true, headers: {})
195
212
  @connection.post(path) do |request|
213
+ request.headers.update(headers)
196
214
  prepare_request(request, params, workspace_auth: workspace_auth)
197
215
  request.body = body unless body.nil?
198
216
  end
199
217
  end
200
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
+
201
235
  # RFC 6749 §4.1.3/§6 and RFC 7009 §2.1 define token and revocation
202
236
  # requests as form posts. The connection's JSON and multipart middleware
203
237
  # leave a pre-encoded String body alone.