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.
@@ -11,7 +11,7 @@ module Assinafy
11
11
  # client = Assinafy::Client.create(ENV['ASSINAFY_API_KEY'], ENV['ASSINAFY_ACCOUNT_ID'])
12
12
  #
13
13
  # @example Construct from a config Hash (e.g. parsed YAML/JSON)
14
- # client = Assinafy::Client.from_config(api_key: '...', account_id: '...')
14
+ # client = Assinafy::Client.from_hash(api_key: '...', account_id: '...')
15
15
  #
16
16
  # @example Act as a user through OAuth 2.1
17
17
  # tokens = Assinafy::Client.new.oauth.exchange_code(
@@ -23,8 +23,6 @@ module Assinafy
23
23
  # @see Assinafy::OAuth
24
24
  # @see https://api.assinafy.com.br/v1/docs
25
25
  class Client
26
- # @return [Resources::AuthResource]
27
- attr_reader :auth
28
26
  # @return [Resources::OAuthResource]
29
27
  attr_reader :oauth
30
28
  # @return [Resources::AccountResource]
@@ -43,6 +41,8 @@ module Assinafy
43
41
  attr_reader :assignments
44
42
  # @return [Resources::EnvelopeResource]
45
43
  attr_reader :envelopes
44
+ # @return [Resources::ScheduledSendResource]
45
+ attr_reader :scheduled_sends
46
46
  # @return [Resources::WebhookResource]
47
47
  attr_reader :webhooks
48
48
  # @return [Resources::TemplateResource]
@@ -54,16 +54,19 @@ module Assinafy
54
54
  # @return [Support::WebhookVerifier]
55
55
  attr_reader :webhook_verifier
56
56
 
57
+ ASSIGNMENT_SIGNER_KEYS = %w[verification_method notification_methods step sign_as embedded].freeze
58
+ private_constant :ASSIGNMENT_SIGNER_KEYS
59
+
57
60
  # @param api_key [String, nil] sent as `X-Api-Key`
58
- # @param token [String, nil] bearer token; sent as
59
- # `Authorization: Bearer ...` when no `api_key` is given. Pass either a
60
- # login session token or an OAuth access token from
61
- # {Resources::OAuthResource#exchange_code} here.
61
+ # @param token [String, nil] OAuth access token from
62
+ # {Resources::OAuthResource#exchange_code}; sent as
63
+ # `Authorization: Bearer ...` when no `api_key` is given
62
64
  # @param account_id [String, nil] default workspace ID for account-scoped
63
65
  # resources; those methods document their supported per-call overrides
64
66
  # @param base_url [String]
65
67
  # @param webhook_secret [String, nil] secret for {Support::WebhookVerifier}
66
- # @param timeout [Integer] Faraday read/open timeout in seconds
68
+ # @param timeout [Integer] Faraday read/open timeout in seconds; keep it above 30, because a
69
+ # certificated page or thumbnail render can hold the response that long before answering 503
67
70
  # @param logger [Logger, nil] receives info-level lifecycle messages
68
71
  #
69
72
  # @example Build a client and reach a resource accessor (no network call)
@@ -83,7 +86,6 @@ module Assinafy
83
86
  @connection = build_connection(config)
84
87
  @logger = config.logger || NullLogger.new
85
88
 
86
- @auth = Resources::AuthResource.new(@connection, nil, @logger)
87
89
  @oauth = Resources::OAuthResource.new(@connection, nil, @logger)
88
90
  @accounts = Resources::AccountResource.new(@connection, account_id, @logger)
89
91
  @users = Resources::UserResource.new(@connection, nil, @logger)
@@ -93,6 +95,7 @@ module Assinafy
93
95
  @signer_documents = Resources::SignerDocumentResource.new(@connection, nil, @logger)
94
96
  @assignments = Resources::AssignmentResource.new(@connection, account_id, @logger)
95
97
  @envelopes = Resources::EnvelopeResource.new(@connection, account_id, @logger)
98
+ @scheduled_sends = Resources::ScheduledSendResource.new(@connection, account_id, @logger)
96
99
  @webhooks = Resources::WebhookResource.new(@connection, account_id, @logger)
97
100
  @templates = Resources::TemplateResource.new(@connection, account_id, @logger)
98
101
  @fields = Resources::FieldResource.new(@connection, account_id, @logger)
@@ -122,19 +125,7 @@ module Assinafy
122
125
  #
123
126
  # @example Build from a credentials Hash loaded from YAML/JSON (string or symbol keys both work)
124
127
  # creds = YAML.load_file('config/assinafy.yml') # { 'api_key' => '...', 'account_id' => '...' }
125
- # client = Assinafy::Client.from_config(creds)
126
- # client #=> #<Assinafy::Client ...>
127
- def self.from_config(config)
128
- from_hash(config)
129
- end
130
-
131
- # Alias of {.from_config} for symmetry with {Configuration.from_hash}.
132
- #
133
- # @param config [Hash]
134
- # @return [Client]
135
- #
136
- # @example Build from a symbol-keyed Hash
137
- # client = Assinafy::Client.from_hash(api_key: 'example_api_key', account_id: 'account_example')
128
+ # client = Assinafy::Client.from_hash(creds)
138
129
  # client #=> #<Assinafy::Client ...>
139
130
  def self.from_hash(config)
140
131
  cfg = Configuration.from_hash(config)
@@ -149,20 +140,42 @@ module Assinafy
149
140
  )
150
141
  end
151
142
 
143
+ class << self
144
+ # Same as {.from_hash}.
145
+ #
146
+ # @param config [Hash]
147
+ # @return [Client]
148
+ #
149
+ # @example Build from a symbol-keyed Hash
150
+ # client = Assinafy::Client.from_config(api_key: 'example_api_key', account_id: 'account_example')
151
+ # client #=> #<Assinafy::Client ...>
152
+ alias from_config from_hash
153
+ end
154
+
152
155
  # High-level helper that bundles the most common workflow:
153
156
  # upload PDF → (optionally wait for metadata) → create signers → create a
154
157
  # virtual assignment for them.
155
158
  #
159
+ # Each signer Hash carries the contact fields of {Resources::SignerResource#create} and may also
160
+ # carry the assignment's per-signer keys: `verification_method`, `notification_methods`, `step`,
161
+ # `sign_as` and `embedded`. The contact fields create the signer; the assignment keys go on the
162
+ # assignment. Everything is validated before the upload, including that each signer has the
163
+ # contact its notification needs: `email` for Email (the default), `whatsapp_phone_number` for Whatsapp.
164
+ #
156
165
  # @param source [String, Hash] see {Resources::DocumentResource#upload}
157
- # @param signers [Array<Hash>] see {Resources::SignerResource#create}
166
+ # @param signers [Array<Hash>] contact fields plus optional per-signer assignment keys
158
167
  # @param message [String, nil]
159
168
  # @param wait_for_ready [Boolean] poll until the document is metadata-ready (default true)
160
169
  # @param expires_at [String, nil] ISO 8601 expiration for the assignment
161
170
  # @param copy_receivers [Array<String>, nil] signer IDs that only receive copies
162
171
  # @param account_id [String, nil] override the client default
172
+ # @param max_total_credits [Numeric, String, nil] refuse the assignment when it would cost more credits
163
173
  # @return [Hash{Symbol=>Object}] `{ document: {Hash}, assignment: {Hash}, signer_ids: [String, ...] }`
164
174
  # where `document` is the (unwrapped) document payload, `assignment` is the (unwrapped) virtual
165
175
  # assignment, and `signer_ids` lists the IDs of the signers created during the workflow.
176
+ # @raise [Assinafy::ValidationError] on invalid input, before anything is uploaded or created
177
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
178
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
166
179
  # @note This helper is not transactional. If a later API call fails, an uploaded
167
180
  # document or newly created signer may remain and should be cleaned up by the caller.
168
181
  # After an upload succeeds, SDK errors include the latest `document` and the
@@ -208,31 +221,41 @@ module Assinafy
208
221
  # # },
209
222
  # # signer_ids: ["signer-id"]
210
223
  # # }
224
+ # @example A WhatsApp signer with a spending ceiling
225
+ # client.upload_and_request_signatures(
226
+ # source: '/path/to/contract.pdf',
227
+ # signers: [{ full_name: 'Example Signer', whatsapp_phone_number: '+5511999999999',
228
+ # verification_method: 'Whatsapp', notification_methods: ['Whatsapp'] }],
229
+ # max_total_credits: 1
230
+ # )
231
+ # # POST /accounts/{account_id}/signers body:
232
+ # # { "full_name": "Example Signer", "whatsapp_phone_number": "+5511999999999" }
233
+ # # POST /documents/{document_id}/assignments body:
234
+ # # { "method": "virtual", "max_total_credits": 1,
235
+ # # "signers": [{ "id": "signer-id", "verification_method": "Whatsapp",
236
+ # # "notification_methods": ["Whatsapp"] }] }
237
+ # # => the same { document:, assignment:, signer_ids: } Hash as above
211
238
  def upload_and_request_signatures(source:, signers:, message: nil,
212
239
  wait_for_ready: true, expires_at: nil,
213
- copy_receivers: nil, account_id: nil)
214
- validate_signature_workflow!(signers, wait_for_ready)
215
-
216
- # Placeholder IDs stand in for the signers created below, so the whole
217
- # assignment body is validated before anything is uploaded or created.
218
- assignment_payload = { method: 'virtual', signers: Array.new(signers.length, 'preflight'),
219
- message: message, expires_at: expires_at,
220
- copy_receivers: copy_receivers }
221
- Resources::AssignmentResource.build_payload(assignment_payload)
240
+ copy_receivers: nil, account_id: nil, max_total_credits: nil)
241
+ Validation.require_boolean(wait_for_ready, 'wait_for_ready')
242
+ assignment_payload = { method: 'virtual', message: message, expires_at: expires_at,
243
+ copy_receivers: copy_receivers, max_total_credits: max_total_credits }
244
+ contacts, options = preflight_workflow(signers, assignment_payload)
222
245
 
223
246
  @logger.info("Starting upload and signature workflow for #{signers.length} signer(s)")
224
247
 
225
- upload_opts = account_id.nil? ? {} : { account_id: account_id }
226
- document = @documents.upload(source, upload_opts)
248
+ document = @documents.upload(source, { account_id: account_id }.compact)
227
249
  signer_ids = []
228
250
 
229
251
  begin
230
252
  document = @documents.wait_until_ready(document['id']) if wait_for_ready
231
- signers.each do |signer|
232
- signer_ids << signer_id!(@signers.create(signer, account_id))
253
+ contacts.each do |contact|
254
+ signer_ids << created_resource_id!(@signers.create(contact, account_id), 'Signer')
233
255
  end
234
256
 
235
- assignment = @assignments.create(document['id'], assignment_payload.merge(signers: signer_ids))
257
+ assignment_signers = signer_ids.zip(options).map { |id, option| { id: id, **option } }
258
+ assignment = @assignments.create(document['id'], assignment_payload.merge(signers: assignment_signers))
236
259
  created_resource_id!(assignment, 'Assignment')
237
260
 
238
261
  @logger.info("Upload and signature workflow completed for document #{document['id']}")
@@ -278,24 +301,38 @@ module Assinafy
278
301
  end
279
302
  end
280
303
 
281
- def validate_signature_workflow!(signers, wait_for_ready)
304
+ # Placeholder IDs stand in for the signers created later, so the whole
305
+ # assignment body is validated before anything is uploaded or created.
306
+ def preflight_workflow(signers, assignment_payload)
282
307
  unless signers.is_a?(Array) && !signers.empty? && signers.all?(Hash)
283
308
  raise ValidationError.new('Signers must be a non-empty Array of Hashes')
284
309
  end
285
- unless [true, false].include?(wait_for_ready)
286
- raise ValidationError.new('wait_for_ready must be true or false')
287
- end
288
310
 
289
- signers.each { |signer| @signers.validate_create!(signer) }
311
+ contacts, options = signers.map do |signer|
312
+ option, contact = signer.partition { |key, _| ASSIGNMENT_SIGNER_KEYS.include?(key.to_s) }.map(&:to_h)
313
+ [@signers.validate_create!(contact), option.transform_keys(&:to_sym)]
314
+ end.transpose
315
+ placeholders = options.each_with_index.map { |option, index| { id: "preflight-#{index}", **option } }
316
+ preflight = Resources::AssignmentResource.build_payload(assignment_payload.merge(signers: placeholders))
317
+ require_notification_contacts!(contacts, preflight['signers'])
318
+ [contacts, options]
290
319
  end
291
320
 
292
- def signer_id!(response)
293
- created_resource_id!(response, 'Signer')
321
+ # A signer without the contact its notification uses makes the API refuse
322
+ # the assignment only after the document and signers already exist.
323
+ def require_notification_contacts!(contacts, assignment_signers)
324
+ contacts.zip(assignment_signers) do |contact, signer|
325
+ whatsapp = (signer['notification_methods']&.first || signer['verification_method']) == 'Whatsapp'
326
+ field = whatsapp ? 'whatsapp_phone_number' : 'email'
327
+ next unless contact[field].to_s.strip.empty?
328
+
329
+ raise ValidationError.new("Signer #{field} is required for #{whatsapp ? 'Whatsapp' : 'Email'} notification")
330
+ end
294
331
  end
295
332
 
296
333
  def created_resource_id!(response, resource_name)
297
334
  id = response['id'] if response.is_a?(Hash)
298
- return id if id.is_a?(String) && Resources::BaseResource::PATH_SEGMENT.match?(id) && !%w[. ..].include?(id)
335
+ return id if Validation.path_segment?(id)
299
336
 
300
337
  raise Error.new(
301
338
  "#{resource_name} created but the API returned no usable ID",
@@ -24,8 +24,9 @@ module Assinafy
24
24
  class Configuration
25
25
  # Default base URL (production v1 API).
26
26
  DEFAULT_BASE_URL = 'https://api.assinafy.com.br/v1'
27
- # Default Faraday open/read timeout, in seconds.
28
- DEFAULT_TIMEOUT = 30
27
+ # Default Faraday open/read timeout, in seconds. It exceeds the 30 seconds a certificated
28
+ # page or thumbnail render may hold a response before answering 503 with Retry-After.
29
+ DEFAULT_TIMEOUT = 60
29
30
  # Schemes accepted for {#base_url}. Credentials are attached to every request
30
31
  # sent to this host, so anything that is not absolute HTTP(S) is rejected.
31
32
  BASE_URL_SCHEMES = %w[http https].freeze
@@ -33,7 +34,7 @@ module Assinafy
33
34
  # @!attribute [rw] api_key
34
35
  # @return [String, nil] sent as `X-Api-Key`
35
36
  # @!attribute [rw] token
36
- # @return [String, nil] legacy bearer token (used when `api_key` is nil)
37
+ # @return [String, nil] OAuth access token (used when `api_key` is blank)
37
38
  # @!attribute [rw] account_id
38
39
  # @return [String, nil] default workspace ID
39
40
  # @!attribute [rw] base_url
@@ -48,11 +49,11 @@ module Assinafy
48
49
  attr_reader :base_url, :timeout
49
50
 
50
51
  # Build a configuration directly from keyword arguments. Prefer passing
51
- # `api_key` (the documented `X-Api-Key` mechanism); `token` is the legacy
52
+ # `api_key` (the documented `X-Api-Key` mechanism); `token` is the OAuth
52
53
  # bearer fallback. `base_url` has its trailing slash stripped on assignment.
53
54
  #
54
55
  # @param api_key [String, nil] sent as the `X-Api-Key` header
55
- # @param token [String, nil] legacy bearer token (used only when `api_key` is nil)
56
+ # @param token [String, nil] OAuth access token (used only when `api_key` is blank)
56
57
  # @param account_id [String, nil] default workspace account ID
57
58
  # @param base_url [String] API base URL (trailing slash is stripped)
58
59
  # @param webhook_secret [String, nil] secret for {Support::WebhookVerifier}
@@ -65,7 +66,7 @@ module Assinafy
65
66
  # account_id: 'account_example'
66
67
  # )
67
68
  # config.base_url # => "https://api.assinafy.com.br/v1"
68
- # config.timeout # => 30
69
+ # config.timeout # => 60
69
70
  # config.auth_headers # => { "X-Api-Key" => "example_api_key" }
70
71
  #
71
72
  # @example Trailing slash on base_url is stripped
@@ -117,7 +118,7 @@ module Assinafy
117
118
  account_id: h['account_id'],
118
119
  base_url: h.key?('base_url') ? h['base_url'] : DEFAULT_BASE_URL,
119
120
  webhook_secret: h['webhook_secret'],
120
- timeout: h.key?('timeout') ? h['timeout'] : DEFAULT_TIMEOUT,
121
+ timeout: h['timeout'],
121
122
  logger: h['logger']
122
123
  )
123
124
  end
@@ -45,8 +45,8 @@ module Assinafy
45
45
  module OAuth
46
46
  # Production authorization server, which owns the browser-facing flow.
47
47
  # Published by `GET /.well-known/oauth-protected-resource` as
48
- # `authorization_servers[0]`, and the `iss` its callbacks carry. The
49
- # sandbox publishes its own, `https://auth-sandbox.assinafy.com.br`.
48
+ # `authorization_servers[0]`, and the `iss` its callbacks carry. Another
49
+ # environment publishes its own issuer there; store and check that one.
50
50
  AUTHORIZATION_SERVER = 'https://auth.assinafy.com.br'
51
51
 
52
52
  # RFC 8414 discovery document for {AUTHORIZATION_SERVER}.
@@ -143,8 +143,8 @@ module Assinafy
143
143
  # @param redirect_uri [String] must match the URI registered for the client
144
144
  # @param code_verifier [String, nil] PKCE verifier; the S256 challenge is derived from it
145
145
  # @param code_challenge [String, nil] pre-computed S256 challenge, if the verifier lives elsewhere
146
- # @param scope [Array<String>, String, nil] requested scopes; include
147
- # `offline_access` to be issued a refresh token
146
+ # @param scope [Array<String>, String] requested scopes, at least one (the server
147
+ # answers `invalid_scope` for none); include `offline_access` to be issued a refresh token
148
148
  # @param state [String, nil] CSRF token echoed back on the callback
149
149
  # @param resource [String, nil] RFC 8707 resource indicator; when sent
150
150
  # here it must also be sent to the token endpoint, and must be the
@@ -153,7 +153,7 @@ module Assinafy
153
153
  # server; store that server's issuer for the callback's `iss` check
154
154
  # @param extra_params [Hash] additional query parameters (e.g. nonce); protocol fields cannot be overridden
155
155
  # @return [String] the absolute URL to redirect to
156
- # @raise [ValidationError] on a missing client_id/redirect_uri, an invalid
156
+ # @raise [ValidationError] on a missing client_id/redirect_uri/scope, an invalid
157
157
  # verifier, or when neither (or both) of verifier/challenge are given
158
158
  #
159
159
  # @example Minimal read-only request
@@ -169,11 +169,14 @@ module Assinafy
169
169
  authorization_endpoint: AUTHORIZATION_ENDPOINT, **extra_params)
170
170
  challenge = resolve_code_challenge(code_verifier, code_challenge)
171
171
 
172
+ requested = normalize_scope(scope)
173
+ raise ValidationError.new('scope is required') if requested.nil?
174
+
172
175
  params = {
173
176
  'response_type' => 'code',
174
- 'client_id' => require_value!(client_id, 'client_id'),
175
- 'redirect_uri' => require_value!(redirect_uri, 'redirect_uri'),
176
- 'scope' => normalize_scope(scope),
177
+ 'client_id' => Validation.require_string(client_id, 'client_id'),
178
+ 'redirect_uri' => Validation.require_string(redirect_uri, 'redirect_uri'),
179
+ 'scope' => requested,
177
180
  'state' => state,
178
181
  'resource' => resource,
179
182
  'code_challenge' => challenge,
@@ -243,7 +246,7 @@ module Assinafy
243
246
  # @return [URI::HTTPS]
244
247
  # @raise [ValidationError] for anything else
245
248
  def https_uri!(value, name)
246
- uri = URI.parse(require_value!(value, name))
249
+ uri = URI.parse(Validation.require_string(value, name))
247
250
  return uri if uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.userinfo.nil? && uri.fragment.nil?
248
251
 
249
252
  raise ValidationError.new("#{name} must be an absolute HTTPS URL without userinfo or fragment")
@@ -263,12 +266,6 @@ module Assinafy
263
266
 
264
267
  raise ValidationError.new('code_challenge must be an unpadded S256 challenge')
265
268
  end
266
-
267
- def require_value!(value, name)
268
- return value if value.is_a?(String) && !value.strip.empty?
269
-
270
- raise ValidationError.new("#{name} is required")
271
- end
272
269
  end
273
270
  end
274
271
  end
@@ -131,6 +131,8 @@ module Assinafy
131
131
  def update(payload, account_id_override = nil)
132
132
  acc_id = account_id(account_id_override)
133
133
  body = body_params(require_payload(payload, 'Account payload'))
134
+ raise ValidationError.new('Account payload must change at least one field') if body.empty?
135
+
134
136
  require_string(body['name'], 'name') if body.key?('name')
135
137
  validate_sender_type!(body)
136
138
 
@@ -139,15 +141,15 @@ module Assinafy
139
141
  end
140
142
  end
141
143
 
142
- # Delete an account. Deletion is blocked while documents are pending.
143
- # For an active paid subscription, pass `force: true` to cancel the
144
- # subscription as part of deletion.
144
+ # Delete an account. An active paid subscription blocks deletion, together with any pending
145
+ # documents; pass `force: true` to cancel both as part of deletion.
145
146
  #
146
- # @param force [Boolean] cancel an active paid subscription and continue
147
- # deletion (default false); it does not bypass pending-document checks
147
+ # @param force [Boolean] cancel the blocking paid subscription and pending documents, then
148
+ # delete (default false)
148
149
  # @param account_id_override [String, nil]
149
150
  # @return [nil] the API returns `data: []`; the SDK normalizes this to `nil`
150
- # @raise [Assinafy::ApiError] on an unsuccessful API response
151
+ # @raise [Assinafy::ApiError] on an unsuccessful API response; a blocked deletion answers `400`
152
+ # with `response_data['restrictions']` codes `ActivePaidSubscription` and `PendingDocuments`
151
153
  # @raise [Assinafy::NetworkError] on transport or TLS failure
152
154
  # @raise [Assinafy::ValidationError] on invalid required input
153
155
  # @see DELETE /accounts/{account_id}
@@ -468,14 +470,16 @@ module Assinafy
468
470
  private
469
471
 
470
472
  def validate_notification_policy!(body)
471
- if body.empty? || (body.keys - %w[events owners_receive_all]).any?
473
+ events = body['events']
474
+ if (body.keys - %w[events owners_receive_all]).any? ||
475
+ (!body.key?('owners_receive_all') && (events.nil? || events == {}))
472
476
  raise ValidationError.new('Notification policy requires events and/or owners_receive_all')
473
477
  end
474
478
 
475
479
  require_boolean(body['owners_receive_all'], 'owners_receive_all') if body.key?('owners_receive_all')
476
480
  return unless body.key?('events')
477
481
 
478
- events = require_payload(body['events'], 'Notification policy events')
482
+ require_payload(events, 'Notification policy events')
479
483
  codes = UserResource::NOTIFICATION_PREFERENCE_CODES | UserResource::PUSH_PREFERENCE_CODES
480
484
  require_preferences(events, codes, 'Notification policy events') unless events.empty?
481
485
  end
@@ -495,9 +499,8 @@ module Assinafy
495
499
 
496
500
  def validate_sender_type!(body)
497
501
  return unless body.key?('notification_sender_type')
498
- return if %w[User Account].include?(body['notification_sender_type'])
499
502
 
500
- raise ValidationError.new('notification_sender_type must be User or Account')
503
+ require_one_of(body['notification_sender_type'], %w[User Account], 'notification_sender_type')
501
504
  end
502
505
  end
503
506
  end