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.
@@ -121,8 +121,8 @@ module Assinafy
121
121
  token(
122
122
  grant_type: 'authorization_code',
123
123
  client_id: client_id,
124
- code: require_string(code, 'Authorization code'),
125
- code_verifier: Assinafy::OAuth.validate_code_verifier!(code_verifier),
124
+ code: code,
125
+ code_verifier: code_verifier,
126
126
  redirect_uri: redirect_uri,
127
127
  client_secret: client_secret,
128
128
  resource: resource
@@ -189,7 +189,7 @@ module Assinafy
189
189
  token(
190
190
  grant_type: 'refresh_token',
191
191
  client_id: client_id,
192
- refresh_token: require_string(refresh_token, 'Refresh token'),
192
+ refresh_token: refresh_token,
193
193
  client_secret: client_secret,
194
194
  resource: resource
195
195
  )
@@ -229,10 +229,7 @@ module Assinafy
229
229
  # # 'issued_token_type' => 'urn:ietf:params:oauth:token-type:access_token' }
230
230
  # @raise [Assinafy::NetworkError] on transport or TLS failure
231
231
  def token(grant_type:, client_id:, **params)
232
- grant = require_string(grant_type, 'Grant type')
233
- unless GRANT_TYPES.include?(grant)
234
- raise ValidationError.new("Grant type must be one of: #{GRANT_TYPES.join(', ')}", { grant_type: grant_type })
235
- end
232
+ grant = require_one_of(require_string(grant_type, 'Grant type'), GRANT_TYPES, 'Grant type')
236
233
 
237
234
  body = body_params(params.merge(grant_type: grant, client_id: require_string(client_id, 'Client ID')))
238
235
  validate_token_request!(body)
@@ -289,12 +286,7 @@ module Assinafy
289
286
  def revoke(token:, client_id:, token_type_hint: nil, client_secret: nil)
290
287
  require_string(client_secret, 'Client secret') unless client_secret.nil?
291
288
 
292
- if !token_type_hint.nil? && !TOKEN_TYPE_HINTS.include?(token_type_hint.to_s)
293
- raise ValidationError.new(
294
- "Token type hint must be one of: #{TOKEN_TYPE_HINTS.join(', ')}",
295
- { token_type_hint: token_type_hint }
296
- )
297
- end
289
+ require_one_of(token_type_hint.to_s, TOKEN_TYPE_HINTS, 'Token type hint') unless token_type_hint.nil?
298
290
 
299
291
  body = body_params(
300
292
  token: require_string(token, 'Token'),
@@ -373,7 +365,7 @@ module Assinafy
373
365
  # # 'authorization_servers' => ['https://auth.assinafy.com.br'],
374
366
  # # 'scopes_supported' => [
375
367
  # # 'documents:read', 'documents:write', 'templates:read',
376
- # # 'templates:write', 'account:read', 'openid', 'profile', 'email'
368
+ # # 'templates:write', 'account:read', 'webhooks:write', 'openid', 'profile', 'email'
377
369
  # # ],
378
370
  # # 'bearer_methods_supported' => ['header']
379
371
  # # }
@@ -394,18 +386,23 @@ module Assinafy
394
386
  # authorization server host — not this API — so the SDK sends it without
395
387
  # credentials.
396
388
  #
397
- # @param url [String] override for a non-default authorization server;
398
- # pass `"#{protected_resource_metadata['authorization_servers'].first}" \
399
- # "/.well-known/oauth-authorization-server"` to follow discovery strictly
389
+ # @param url [String, nil] the metadata URL of a known authorization server. When omitted, the
390
+ # server is discovered: the first of {#protected_resource_metadata}'s `authorization_servers`,
391
+ # plus `/.well-known/oauth-authorization-server` (one extra request)
400
392
  # @return [Hash{String=>Object}] the bare metadata object
401
393
  # @raise [Assinafy::OAuthError] on an unsuccessful metadata response
402
394
  # @raise [Assinafy::NetworkError] on transport or TLS failure
403
- # @raise [Assinafy::ValidationError] when the URL is not absolute HTTPS without userinfo or fragment
395
+ # @raise [Assinafy::ValidationError] when the given or discovered URL is not absolute HTTPS without
396
+ # userinfo or fragment
404
397
  # @see GET https://auth.assinafy.com.br/.well-known/oauth-authorization-server
405
398
  #
406
399
  # @example Discover endpoints instead of hardcoding them
407
400
  # metadata = client.oauth.authorization_server_metadata
408
401
  #
402
+ # # Requests (no body, no X-Api-Key/Authorization header):
403
+ # # GET /.well-known/oauth-protected-resource
404
+ # # GET https://auth.assinafy.com.br/.well-known/oauth-authorization-server
405
+ #
409
406
  # # Response (bare metadata, NOT enveloped):
410
407
  # # {
411
408
  # # 'issuer' => 'https://auth.assinafy.com.br',
@@ -425,7 +422,8 @@ module Assinafy
425
422
  # # 'authorization_response_iss_parameter_supported' => true,
426
423
  # # 'client_id_metadata_document_supported' => true
427
424
  # # }
428
- def authorization_server_metadata(url = Assinafy::OAuth::AUTHORIZATION_SERVER_METADATA_URL)
425
+ def authorization_server_metadata(url = nil)
426
+ url ||= "#{discovered_authorization_server}/.well-known/oauth-authorization-server"
429
427
  absolute = Assinafy::OAuth.https_uri!(url, 'Authorization server metadata URL').to_s
430
428
 
431
429
  call('Failed to fetch authorization server metadata') do
@@ -435,6 +433,14 @@ module Assinafy
435
433
 
436
434
  private
437
435
 
436
+ def discovered_authorization_server
437
+ servers = protected_resource_metadata
438
+ servers = servers['authorization_servers'] if servers.is_a?(Hash)
439
+ return servers.first.to_s.chomp('/') if servers.is_a?(Array) && servers.first.is_a?(String)
440
+
441
+ raise Assinafy::Error.new('Protected resource metadata names no authorization server')
442
+ end
443
+
438
444
  def validate_token_request!(body)
439
445
  case body['grant_type']
440
446
  when 'authorization_code'
@@ -466,7 +472,7 @@ module Assinafy
466
472
  # different one leaves nothing to refresh with next time, and sending the
467
473
  # retired one again ends the whole connection.
468
474
  def rotated?(tokens, sent)
469
- replacement = tokens['refresh_token'] if tokens.is_a?(Hash)
475
+ replacement = tokens['refresh_token']
470
476
  replacement.is_a?(String) && !replacement.strip.empty? && replacement != sent
471
477
  end
472
478
  end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Assinafy
4
+ module Resources
5
+ # Pending assignment/envelope requests. All operations require documents:write.
6
+ class ScheduledSendResource < BaseResource
7
+ class << self
8
+ # Validate the delivery window for a scheduled request.
9
+ # @param value [String, Integer] ISO 8601 timestamp (no offset means UTC), or Unix seconds
10
+ # @return [Time] the scheduled instant, from one hour to 90 days ahead
11
+ # @raise [ValidationError] on an invalid timestamp or delivery window
12
+ # @example
13
+ # Assinafy::Resources::ScheduledSendResource.require_send_at((Time.now + 7200).to_i) # => Time two hours ahead
14
+ def require_send_at(value)
15
+ time = schedule_time(value, 'send_at')
16
+ now = Time.now
17
+ unless time.between?(now + 3600, now + (90 * 86_400))
18
+ raise ValidationError.new('send_at must be from one hour to 90 days ahead')
19
+ end
20
+
21
+ time
22
+ end
23
+
24
+ # Normalize a scheduled deadline for the ordinary assignment validators.
25
+ # @param value [String, Integer, nil] ISO 8601 timestamp or Unix seconds; nil means no deadline
26
+ # @param send_time [Time] validated send_at instant
27
+ # @return [String, nil] zoned ISO 8601 deadline, at least two hours after send_at
28
+ # @raise [ValidationError] on an invalid deadline
29
+ # @example
30
+ # Assinafy::Resources::ScheduledSendResource.scheduled_expiration(nil, Time.now + 7200) # => nil
31
+ def scheduled_expiration(value, send_time)
32
+ return nil if value.nil?
33
+
34
+ time = schedule_time(value, 'expires_at')
35
+ raise ValidationError.new('expires_at must be at least two hours after send_at') if time < send_time + 7200
36
+
37
+ return time.utc.iso8601 if value.is_a?(Integer)
38
+
39
+ value.match?(/(?:Z|[+-]\d{2}:\d{2})\z/) ? value : "#{value}Z"
40
+ end
41
+
42
+ private
43
+
44
+ def schedule_time(value, name)
45
+ return Time.at(value).utc if value.is_a?(Integer)
46
+
47
+ # An absent offset means UTC here, so the shared pattern is applied with one assumed.
48
+ zoned = value.to_s.match?(/(?:Z|[+-]\d{2}:\d{2})\z/) ? value : "#{value}Z"
49
+ return DateTime.iso8601(value).to_time if value.is_a?(String) && zoned.match?(Validation::ZONED_ISO8601)
50
+
51
+ raise ArgumentError
52
+ rescue ArgumentError, RangeError
53
+ raise ValidationError.new("#{name} must be an ISO 8601 timestamp or Unix seconds")
54
+ end
55
+ end
56
+
57
+ # @param params [Hash] document_id, page and per_page
58
+ # @param account_id_override [String, nil]
59
+ # @return [Hash] paginated ScheduledSend objects, newest first, including terminal states
60
+ # @raise [ValidationError] on invalid IDs or filters
61
+ # @raise [ApiError, NetworkError] on API or transport failure
62
+ # @see GET /accounts/{accountId}/scheduled-sends
63
+ # @example
64
+ # client.scheduled_sends.list(document_id: 'document-id', per_page: 20)
65
+ # # GET .../scheduled-sends?document_id=document-id&per-page=20; no body
66
+ # # => { data: [{ 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
67
+ # # 'document_ids' => ['document-id'], 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z',
68
+ # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
69
+ # # 'next_attempt_at' => nil,
70
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }],
71
+ # # meta: { current_page: 1, per_page: 20, total: 1, last_page: 1 } }
72
+ def list(params = {}, account_id_override = nil)
73
+ query = query_params(params)
74
+ require_id(query['document_id'], 'Document ID') if query.key?('document_id')
75
+ path = "accounts/#{account_id(account_id_override)}/scheduled-sends"
76
+ call_list('Failed to list scheduled sends') { http_get(path, query) }
77
+ end
78
+
79
+ # Cancel a pending send without sending or charging. Other states answer 409.
80
+ # @param scheduled_send_id [String]
81
+ # @param account_id_override [String, nil]
82
+ # @return [Hash] ScheduledSend, now cancelled
83
+ # @raise [ValidationError] on invalid IDs
84
+ # @raise [ApiError, NetworkError] on API or transport failure
85
+ # @see PUT /accounts/{accountId}/scheduled-sends/{scheduledSendId}/cancel
86
+ # @example
87
+ # client.scheduled_sends.cancel('send-id') # PUT; no body
88
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
89
+ # # 'document_ids' => ['document-id'], 'status' => 'cancelled', 'send_at' => '2026-12-01T12:00:00Z',
90
+ # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
91
+ # # 'next_attempt_at' => nil,
92
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => '2026-12-01T10:30:00Z' }
93
+ def cancel(scheduled_send_id, account_id_override = nil)
94
+ path = "#{scheduled_send_path(scheduled_send_id, account_id_override)}/cancel"
95
+ call('Failed to cancel scheduled send') { http_put(path) }
96
+ end
97
+
98
+ # Send a pending request now, with the original member's permissions, balance and credit ceiling.
99
+ # A refused request stays pending; cancel it to prevent a later scheduled attempt. Never retries.
100
+ # On the free plan a send can stay pending, with `next_attempt_at` up to 7 days ahead, once the
101
+ # daily signer email limit is reached; this call then answers 429 (`FreePlanEmailLimit`) with Retry-After.
102
+ # @param scheduled_send_id [String]
103
+ # @param account_id_override [String, nil]
104
+ # @return [Hash] ScheduledSend, now sent, with assignment_id or envelope_id
105
+ # @raise [ValidationError] on invalid IDs
106
+ # @raise [ApiError, NetworkError] on API or transport failure, including 409 for a non-pending send
107
+ # @see PUT /accounts/{accountId}/scheduled-sends/{scheduledSendId}/send
108
+ # @example
109
+ # client.scheduled_sends.send_now('send-id') # PUT; no body
110
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
111
+ # # 'document_ids' => ['document-id'], 'status' => 'sent', 'send_at' => '2026-12-01T12:00:00Z',
112
+ # # 'assignment_id' => 'assignment-id', 'envelope_id' => nil, 'failure_reason' => nil,
113
+ # # 'next_attempt_at' => nil,
114
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => '2026-12-01T10:30:00Z' }
115
+ def send_now(scheduled_send_id, account_id_override = nil)
116
+ path = "#{scheduled_send_path(scheduled_send_id, account_id_override)}/send"
117
+ call('Failed to send scheduled request') { http_put(path) }
118
+ end
119
+
120
+ private
121
+
122
+ def scheduled_send_path(send_id, override)
123
+ "accounts/#{account_id(override)}/scheduled-sends/#{require_id(send_id, 'Scheduled send ID')}"
124
+ end
125
+ end
126
+ end
127
+ end
@@ -11,7 +11,7 @@ module Assinafy
11
11
  # - {#list} and {#search} authenticate as the signer: they require the access
12
12
  # code and never send workspace credentials. The same routes also accept
13
13
  # workspace credentials; use {#list_as_workspace} / {#search_as_workspace} for that.
14
- # - {#download} only needs the document/artifact IDs.
14
+ # - {#download} requires the signer access code and serves only the original.
15
15
  #
16
16
  # See https://api.assinafy.com.br/v1/docs#signer for the full
17
17
  # documentation of these endpoints.
@@ -46,12 +46,21 @@ module Assinafy
46
46
  # # "declined_by" => nil,
47
47
  # # "created_at" => "2023-07-21T13:43:17Z",
48
48
  # # "updated_at" => "2023-07-21T13:43:17Z",
49
+ # # "is_signer_access_closed" => false,
50
+ # # "certified_copy" => { "available" => false, "notification_method" => "Email",
51
+ # # "resends_left" => nil },
49
52
  # # "current_signer" => { "id" => "signer-id", "full_name" => "Signer Name",
50
- # # "email" => "signer@example.com",
53
+ # # "email" => "signer@example.com", "completed" => false,
51
54
  # # "verification_method" => "Email", "notification_methods" => ["Email"] },
52
55
  # # "assignment" => { "id" => "1", "method" => "virtual", "items" => [{ ... }] }
53
56
  # # # ... (see docs for full shape)
54
57
  # # }
58
+ # # Once the signer's access has closed, only the status remains:
59
+ # # => { "id" => "document-id", "name" => "my_document.pdf", "status" => "certificated",
60
+ # # "is_signer_access_closed" => true,
61
+ # # "certified_copy" => { "available" => true, "notification_method" => "Email",
62
+ # # "resends_left" => nil },
63
+ # # "current_signer" => { "completed" => true } }
55
64
  def current(signer_id, signer_access_code:, expand: nil)
56
65
  sid = require_id(signer_id, 'Signer ID')
57
66
  access_code = require_signer_access_code(signer_access_code)
@@ -69,7 +78,8 @@ module Assinafy
69
78
  # authenticated with the signer access code only (no workspace credentials).
70
79
  #
71
80
  # @param signer_id [String]
72
- # @param params [Hash] documented `page` and `per_page` query parameters
81
+ # @param params [Hash] documented `page`, `per_page` and `envelope_id` (only the members
82
+ # of this envelope) query parameters
73
83
  # @param signer_access_code [String] required; may also be given as `params[:signer_access_code]`
74
84
  # @return [Hash{Symbol=>Array,Hash}] `{ data: [...], meta: { current_page:, per_page:, total:, last_page: } }`
75
85
  # @raise [Assinafy::ApiError] on an unsuccessful API response
@@ -113,7 +123,8 @@ module Assinafy
113
123
  # instead of the signer access code. Same response as {#list}.
114
124
  #
115
125
  # @param signer_id [String]
116
- # @param params [Hash] documented `page` and `per_page` query parameters
126
+ # @param params [Hash] documented `page`, `per_page` and `envelope_id` (only the members of this
127
+ # envelope) query parameters
117
128
  # @return [Hash{Symbol=>Array,Hash}] `{ data: [...], meta: { current_page:, per_page:, total:, last_page: } }`
118
129
  # @raise [Assinafy::ApiError] on an unsuccessful API response
119
130
  # @raise [Assinafy::NetworkError] on transport or TLS failure
@@ -137,7 +148,8 @@ module Assinafy
137
148
  #
138
149
  # @param signer_id [String]
139
150
  # @param query [String, nil] optional free-text search term; nil omits `search`
140
- # @param params [Hash] optional deployment-specific query parameters
151
+ # @param params [Hash] optional query parameters, such as `envelope_id` (only the members
152
+ # of this envelope)
141
153
  # @param signer_access_code [String] required; may also be given as `params[:signer_access_code]`
142
154
  # @return [Hash{Symbol=>Array,Hash}] `{ data: [...], meta: {..} | nil }`
143
155
  # @raise [Assinafy::ApiError] on an unsuccessful API response
@@ -165,7 +177,7 @@ module Assinafy
165
177
 
166
178
  call_list('Failed to search signer documents') do
167
179
  http_get("signers/#{sid}/documents/search",
168
- filters.merge(search: query, signer_access_code: access_code),
180
+ filters.merge({ search: query, signer_access_code: access_code }.compact),
169
181
  workspace_auth: false)
170
182
  end
171
183
  end
@@ -175,7 +187,8 @@ module Assinafy
175
187
  #
176
188
  # @param signer_id [String]
177
189
  # @param query [String, nil] optional free-text search term; nil omits `search`
178
- # @param params [Hash] optional deployment-specific query parameters
190
+ # @param params [Hash] optional query parameters, such as `envelope_id` (only the members of this
191
+ # envelope)
179
192
  # @return [Hash{Symbol=>Array,Hash}] `{ data: [...], meta: {..} | nil }`
180
193
  # @raise [Assinafy::ApiError] on an unsuccessful API response
181
194
  # @raise [Assinafy::NetworkError] on transport or TLS failure
@@ -190,7 +203,7 @@ module Assinafy
190
203
  require_string(query, 'Search query') unless query.nil?
191
204
 
192
205
  call_list('Failed to search signer documents') do
193
- http_get("signers/#{sid}/documents/search", workspace_query(params).merge(search: query))
206
+ http_get("signers/#{sid}/documents/search", workspace_query(params).merge({ search: query }.compact))
194
207
  end
195
208
  end
196
209
 
@@ -259,7 +272,7 @@ module Assinafy
259
272
  #
260
273
  # @param signer_id [String]
261
274
  # @param document_id [String]
262
- # @param artifact_name [String] original; other names are passed to the API for compatibility
275
+ # @param artifact_name [String] only `original` is served to a signer
263
276
  # @param signer_access_code [String] required; no workspace credentials are transmitted
264
277
  # @return [String] binary PDF bytes
265
278
  # @raise [Assinafy::ValidationError] on invalid IDs, artifact or access code
@@ -270,13 +283,10 @@ module Assinafy
270
283
  # client.signer_documents.download('signer-id', 'document-id', signer_access_code: 'access-code')
271
284
  # # GET /signers/signer-id/documents/document-id/download/original?signer-access-code=access-code
272
285
  # # => "%PDF-1.7..." # binary String
273
- def download(signer_id, document_id, artifact_name = 'original', signer_access_code: nil)
286
+ def download(signer_id, document_id, artifact_name = 'original', signer_access_code:)
274
287
  sid = require_id(signer_id, 'Signer ID')
275
288
  did = require_id(document_id, 'Document ID')
276
- art = require_id(artifact_name, 'Artifact name')
277
- unless DocumentResource::ARTIFACT_TYPES.include?(art)
278
- raise ValidationError.new('Invalid artifact type', { artifact_name: artifact_name })
279
- end
289
+ art = require_one_of(artifact_name, %w[original], 'artifact')
280
290
 
281
291
  code = require_signer_access_code(signer_access_code)
282
292
 
@@ -12,6 +12,8 @@ module Assinafy
12
12
  class SignerResource < BaseResource
13
13
  EMAIL_REGEX = Utils::EMAIL_PATTERN
14
14
  SIGNATURE_TYPES = %w[signature initial].freeze
15
+ SIGNATURE_CONTENT_TYPES = %w[image/png image/jpeg].freeze
16
+ private_constant :SIGNATURE_CONTENT_TYPES
15
17
 
16
18
  # Validate and normalize a payload accepted by {#create} without sending
17
19
  # a request. Useful for preflighting multi-step workflows before they
@@ -63,6 +65,7 @@ module Assinafy
63
65
  # # "full_name" => "Example Signer",
64
66
  # # "email" => "signer@example.com",
65
67
  # # "whatsapp_phone_number" => nil,
68
+ # # "government_id" => nil,
66
69
  # # "has_accepted_terms" => false
67
70
  # # }
68
71
  def create(payload, account_id_override = nil)
@@ -94,6 +97,7 @@ module Assinafy
94
97
  # # "full_name" => "Example Signer",
95
98
  # # "email" => "signer@example.com",
96
99
  # # "whatsapp_phone_number" => nil,
100
+ # # "government_id" => nil,
97
101
  # # "has_accepted_terms" => false
98
102
  # # }
99
103
  def get(signer_id, account_id_override = nil)
@@ -124,6 +128,7 @@ module Assinafy
124
128
  # # "full_name" => "Example Signer",
125
129
  # # "email" => "signer@example.com",
126
130
  # # "whatsapp_phone_number" => nil,
131
+ # # "government_id" => nil,
127
132
  # # "has_accepted_terms" => false
128
133
  # # }
129
134
  # # # ... (one Hash per signer)
@@ -142,14 +147,16 @@ module Assinafy
142
147
  # `email` or `whatsapp_phone_number` is rejected while that channel is
143
148
  # verified on an in-flight document; changing an unverified channel rotates
144
149
  # its access and verification codes.
150
+ # Explicit nil or empty String clears email, WhatsApp number or government ID.
145
151
  #
146
152
  # @param signer_id [String]
147
153
  # @param payload [Hash]
148
154
  # @option payload [String] :full_name
149
- # @option payload [String] :email
150
- # @option payload [String] :whatsapp_phone_number E.164; normalized on save
151
- # @option payload [String] :phone alias for `:whatsapp_phone_number`
152
- # @option payload [String] :government_id CPF (digits) or CNPJ (may be alphanumeric); normalized on save
155
+ # @option payload [String, nil] :email
156
+ # @option payload [String, nil] :whatsapp_phone_number E.164; normalized on save
157
+ # @option payload [String, nil] :phone alias for `:whatsapp_phone_number`; the canonical key wins when both
158
+ # are given, even when it is nil
159
+ # @option payload [String, nil] :government_id CPF (digits) or CNPJ (may be alphanumeric); normalized on save
153
160
  # @param account_id_override [String, nil]
154
161
  # @return [Hash] updated signer object (envelope `data` unwrapped)
155
162
  # @raise [Assinafy::ApiError] on an unsuccessful API response
@@ -169,6 +176,7 @@ module Assinafy
169
176
  # # "full_name" => "Updated Signer",
170
177
  # # "email" => "signer@example.com",
171
178
  # # "whatsapp_phone_number" => nil,
179
+ # # "government_id" => "00000000000",
172
180
  # # "has_accepted_terms" => false
173
181
  # # }
174
182
  def update(signer_id, payload, account_id_override = nil)
@@ -221,12 +229,13 @@ module Assinafy
221
229
  # # "full_name" => "Example Signer",
222
230
  # # "email" => "signer@example.com",
223
231
  # # "whatsapp_phone_number" => nil,
232
+ # # "government_id" => nil,
224
233
  # # "has_accepted_terms" => false
225
234
  # # }
226
235
  # #
227
236
  # # => nil # when no returned signer matches
228
237
  def find_by_email(email, account_id_override = nil)
229
- assert_email!(email)
238
+ Utils.require_email(email)
230
239
  target = email.downcase
231
240
  page = 1
232
241
 
@@ -260,7 +269,9 @@ module Assinafy
260
269
  # # "full_name" => "Signer Name",
261
270
  # # "email" => "signer@example.com",
262
271
  # # "whatsapp_phone_number" => "+15555550100",
272
+ # # "government_id" => nil,
263
273
  # # "has_accepted_terms" => false,
274
+ # # "verification_method" => "Email",
264
275
  # # "has_signature" => false, # self-only field
265
276
  # # "has_initial" => false, # self-only field
266
277
  # # "is_signature_reusable" => false # self-only field
@@ -390,12 +401,13 @@ module Assinafy
390
401
  end
391
402
 
392
403
  # Confirm the contact used by the assignment and optionally accept terms. Certificate signers
393
- # must do both before opening GET /sign. Existing additional payload fields are passed through.
404
+ # must do both before opening GET /sign. The API reads only email, whatsapp_phone_number and
405
+ # has_accepted_terms, so those are the only keys sent.
394
406
  #
395
407
  # @param document_id [String]
396
- # @param payload [Hash] email, whatsapp_phone_number and has_accepted_terms
408
+ # @param payload [Hash] email, whatsapp_phone_number (or its phone alias) and has_accepted_terms
397
409
  # @param signer_access_code [String]
398
- # @return [Array] empty Array on success
410
+ # @return [Array, nil] empty Array on success; nil when the response carries no data
399
411
  # @raise [Assinafy::ApiError] on an unsuccessful API response
400
412
  # @raise [Assinafy::NetworkError] on transport or TLS failure
401
413
  # @raise [Assinafy::ValidationError] on invalid required input
@@ -408,11 +420,11 @@ module Assinafy
408
420
  # # => []
409
421
  def confirm_data(document_id, payload, signer_access_code:)
410
422
  doc_id = require_id(document_id, 'Document ID')
411
- body = body_params(require_payload(payload))
423
+ raw = require_payload(payload).transform_keys(&:to_s)
412
424
  code = require_signer_access_code(signer_access_code)
413
- require_string(body['full_name'], 'Full name') if body.key?('full_name')
425
+ raw['whatsapp_phone_number'] = raw['phone'] unless raw.key?('whatsapp_phone_number')
426
+ body = body_params(raw.slice('email', 'whatsapp_phone_number', 'has_accepted_terms'))
414
427
  Utils.require_email(body['email']) if body.key?('email')
415
- require_string(body['government_id'], 'Government ID') if body.key?('government_id')
416
428
  require_string(body['whatsapp_phone_number'], 'WhatsApp number') if body.key?('whatsapp_phone_number')
417
429
  require_boolean(body['has_accepted_terms'], 'has_accepted_terms') if body.key?('has_accepted_terms')
418
430
 
@@ -422,12 +434,12 @@ module Assinafy
422
434
  end
423
435
  end
424
436
 
425
- # Upload the signer's signature image. The request body is raw image bytes.
437
+ # Upload the signer's signature image, PNG or JPEG. The request body is raw image bytes.
426
438
  #
427
439
  # @param content [String] raw image bytes
428
440
  # @param signer_access_code [String]
429
441
  # @param type [String] `signature` or `initial`
430
- # @param content_type [String] must be `image/png`
442
+ # @param content_type [String] `image/png` or `image/jpeg`
431
443
  # @param reuse [Boolean, nil] when true, marks the signature as
432
444
  # reusable for future documents (documented `reuse` query flag)
433
445
  # @return [Array, nil] empty Array; nil for older no-data responses
@@ -453,24 +465,14 @@ module Assinafy
453
465
  raise ValidationError.new('Signature content must be a non-empty String')
454
466
  end
455
467
 
456
- unless content_type == 'image/png'
457
- raise ValidationError.new('Signature content type must be image/png')
458
- end
459
-
468
+ require_one_of(content_type, SIGNATURE_CONTENT_TYPES, 'Signature content type')
460
469
  require_boolean(reuse, 'reuse') unless reuse.nil?
461
470
  sig_type = signature_type(type)
462
471
  code = require_signer_access_code(signer_access_code)
463
472
 
464
473
  call('Failed to upload signer signature') do
465
- @connection.post('signature') do |request|
466
- prepare_request(
467
- request,
468
- { signer_access_code: code, type: sig_type, reuse: reuse },
469
- workspace_auth: false
470
- )
471
- request.headers['Content-Type'] = content_type
472
- request.body = content
473
- end
474
+ http_post('signature', content, { signer_access_code: code, type: sig_type, reuse: reuse },
475
+ workspace_auth: false, headers: { 'Content-Type' => content_type })
474
476
  end
475
477
  end
476
478
 
@@ -544,58 +546,41 @@ module Assinafy
544
546
 
545
547
  private
546
548
 
547
- def assert_email!(email)
548
- Utils.require_email(email)
549
- end
549
+ SIGNER_KEY_ALIASES = { 'full_name' => 'name', 'whatsapp_phone_number' => 'phone' }.freeze
550
+ private_constant :SIGNER_KEY_ALIASES
550
551
 
552
+ # An alias is read only when its canonical key is absent (on create, also
553
+ # when it is nil), so an update's explicit nil clears the field instead
554
+ # of being replaced by the alias.
551
555
  def signer_payload(payload, require_full_name:)
552
- raw = require_payload(payload, 'Signer payload')
553
- p = raw.transform_keys(&:to_s)
554
-
555
- full_name = signer_full_name(p, require_full_name)
556
-
557
- email = p['email']
558
- assert_email!(email) unless email.nil?
559
-
560
- phone = signer_phone(p)
556
+ p = signer_fields(require_payload(payload, 'Signer payload').transform_keys(&:to_s), require_full_name)
561
557
 
562
- body = body_params(
563
- full_name: full_name,
564
- email: email,
565
- whatsapp_phone_number: phone
566
- )
567
- government_id = signer_government_id(p)
568
- body['government_id'] = government_id unless government_id.nil?
569
- body
570
- end
558
+ if (require_full_name || p.key?('full_name')) && !non_blank_string?(p['full_name'])
559
+ raise ValidationError.new('full_name must be a non-empty String')
560
+ end
571
561
 
572
- def signer_full_name(payload, required)
573
- full_name = payload['full_name'].nil? ? payload['name'] : payload['full_name']
574
- return full_name if !required && full_name.nil?
575
- return full_name if full_name.is_a?(String) && !full_name.strip.empty?
562
+ Utils.require_email(p['email']) unless p['email'].nil? || (!require_full_name && p['email'] == '')
563
+ %w[whatsapp_phone_number government_id].each do |key|
564
+ raise ValidationError.new("#{key} must be a String") unless p[key].nil? || p[key].is_a?(String)
565
+ end
576
566
 
577
- raise ValidationError.new('full_name must be a non-empty String')
567
+ nullable_body(p, require_full_name ? [] : %w[email whatsapp_phone_number government_id])
578
568
  end
579
569
 
580
- def signer_phone(payload)
581
- phone = payload['whatsapp_phone_number'].nil? ? payload['phone'] : payload['whatsapp_phone_number']
582
- return phone if phone.nil? || phone.is_a?(String)
583
-
584
- raise ValidationError.new('whatsapp_phone_number must be a String')
570
+ def signer_fields(raw, create)
571
+ %w[full_name email whatsapp_phone_number government_id].each_with_object({}) do |key, fields|
572
+ source = key
573
+ source = SIGNER_KEY_ALIASES.fetch(key, key) if create ? raw[key].nil? : !raw.key?(key)
574
+ fields[key] = raw[source] if raw.key?(source)
575
+ end
585
576
  end
586
577
 
587
- def signer_government_id(payload)
588
- government_id = payload['government_id']
589
- return government_id if government_id.nil? || government_id.is_a?(String)
590
-
591
- raise ValidationError.new('government_id must be a String')
578
+ def non_blank_string?(value)
579
+ value.is_a?(String) && !value.strip.empty?
592
580
  end
593
581
 
594
582
  def signature_type(type)
595
- value = require_id(type, 'Signature type').to_s
596
- return value if SIGNATURE_TYPES.include?(value)
597
-
598
- raise ValidationError.new('Signature type must be signature or initial', { type: type })
583
+ require_one_of(type, SIGNATURE_TYPES, 'Signature type')
599
584
  end
600
585
  end
601
586
  end