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.
@@ -0,0 +1,362 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Assinafy
4
+ module Resources
5
+ # Groups documents into one invitation while retaining each document's signatures and artifacts.
6
+ class EnvelopeResource < BaseResource
7
+ # @param params [Hash] search, status (open/closed), page, per_page
8
+ # @param account_id_override [String, nil]
9
+ # @return [Hash] paginated DocumentEnvelope objects
10
+ # @raise [ValidationError] on invalid filters or account ID
11
+ # @raise [ApiError, NetworkError] on API or transport failure
12
+ # @see GET /accounts/{accountId}/envelopes
13
+ # @example
14
+ # client.envelopes.list(status: 'open') # GET .../envelopes?status=open; no body
15
+ # # => { data: [{ 'id' => 'envelope-id', 'name' => 'Contract', 'documents' => [],
16
+ # # 'message' => nil, 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }] }
17
+ def list(params = {}, account_id_override = nil)
18
+ query = query_params(params)
19
+ if query.key?('status') && !%w[open closed].include?(query['status'])
20
+ raise ValidationError.new('status must be open or closed')
21
+ end
22
+ if query.key?('search') && !query['search'].is_a?(String)
23
+ raise ValidationError.new('search must be a String')
24
+ end
25
+
26
+ call_list('Failed to list envelopes') { http_get(envelopes_path(account_id_override), query) }
27
+ end
28
+
29
+ # @param payload [Hash] EnvelopeCreateRequest: name, signers, documents, optional message/max_total_credits
30
+ # @param account_id_override [String, nil]
31
+ # @param idempotency_key [String, nil] reuse after a lost response to avoid creating or charging twice
32
+ # @return [Hash] DocumentEnvelope; notification failure does not undo creation
33
+ # @raise [ValidationError] on invalid payload, key or IDs
34
+ # @raise [ApiError, NetworkError] on API or transport failure
35
+ # @see POST /accounts/{accountId}/envelopes
36
+ # @example
37
+ # client.envelopes.create({ name: 'Contract', signers: [{ id: 'signer-id' }],
38
+ # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }] }, idempotency_key: 'request-id')
39
+ # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
40
+ # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }] }
41
+ # # => { 'resource' => 'envelope', 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil,
42
+ # # 'documents' => [{ 'id' => 'document-id', 'position' => 1, 'name' => 'contract.pdf',
43
+ # # 'status' => 'pending_signature', 'artifacts' => {}, 'signers' => [] }],
44
+ # # 'counts' => { 'pending_signature' => 1 }, 'signing_urls' => [],
45
+ # # 'created_at' => '2026-11-11T12:00:00Z' }
46
+ def create(payload, account_id_override = nil, idempotency_key: nil)
47
+ body = create_payload(payload)
48
+ path = envelopes_path(account_id_override)
49
+ headers = idempotency_headers(idempotency_key)
50
+ call('Failed to create envelope') { http_post(path, body, headers: headers) }
51
+ end
52
+
53
+ # @param payload [Hash] the same EnvelopeCreateRequest as create
54
+ # @param account_id_override [String, nil]
55
+ # @return [Hash] CostEstimate; creates and charges nothing
56
+ # @raise [ValidationError] on invalid payload or IDs
57
+ # @raise [ApiError, NetworkError] on API or transport failure
58
+ # @see POST /accounts/{accountId}/envelopes/estimate-cost
59
+ # @example
60
+ # client.envelopes.estimate_cost(name: 'Contract', signers: [{ id: 'signer-id' }],
61
+ # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }])
62
+ # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
63
+ # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }] }
64
+ # # => { 'total_credits' => 0, 'has_sufficient_resources' => true, 'breakdown' => [] }
65
+ def estimate_cost(payload, account_id_override = nil)
66
+ body = create_payload(payload)
67
+ path = "#{envelopes_path(account_id_override)}/estimate-cost"
68
+ call('Failed to estimate envelope cost') { http_post(path, body) }
69
+ end
70
+
71
+ # Schedule an envelope; no invitations or charges occur until it is sent. Requires documents:write.
72
+ # Available on staging; the environment must publish scheduled sends. No idempotency header is supported.
73
+ # @param payload [Hash] the same EnvelopeCreateRequest as create
74
+ # @param account_id_override [String, nil]
75
+ # @param send_at [String, Integer] from one hour to 90 days ahead; absent offset means UTC
76
+ # @return [Hash] ScheduledSend; each deadline must be at least two hours after send_at
77
+ # @raise [ValidationError] on invalid payload, IDs or timing
78
+ # @raise [ApiError, NetworkError] on API or transport failure
79
+ # @see POST /accounts/{accountId}/scheduled-sends
80
+ # @example
81
+ # client.envelopes.schedule({ name: 'Contract', signers: [{ id: 'signer-id' }],
82
+ # documents: [{ id: 'document-id', signer_ids: ['signer-id'] }] }, send_at: (Time.now + 7200).to_i)
83
+ # # POST body: { "name": "Contract", "signers": [{ "id": "signer-id" }],
84
+ # # "documents": [{ "id": "document-id", "signer_ids": ["signer-id"] }], "send_at": 1796126400 }
85
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'envelope',
86
+ # # 'document_ids' => ['document-id'], 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z',
87
+ # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
88
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }
89
+ def schedule(payload, account_id_override = nil, send_at:)
90
+ time = ScheduledSendResource.require_send_at(send_at)
91
+ raw = body_params(require_payload(payload))
92
+ raw['documents'] = require_array(raw['documents'], 'documents').map do |document|
93
+ entry = require_payload(document, 'Envelope document').dup
94
+ if entry.key?('expires_at')
95
+ entry['expires_at'] = ScheduledSendResource.scheduled_expiration(entry['expires_at'], time)
96
+ end
97
+ entry
98
+ end
99
+ body = create_payload(raw).merge('send_at' => send_at)
100
+ path = "accounts/#{account_id(account_id_override)}/scheduled-sends"
101
+ call('Failed to schedule envelope') { http_post(path, body) }
102
+ end
103
+
104
+ # @param envelope_id [String]
105
+ # @param account_id_override [String, nil]
106
+ # @return [Hash] DocumentEnvelope (see create for its complete shape)
107
+ # @raise [ValidationError] on invalid IDs
108
+ # @raise [ApiError, NetworkError] on API or transport failure
109
+ # @see GET /accounts/{accountId}/envelopes/{envelopeId}
110
+ # @example
111
+ # client.envelopes.get('envelope-id') # GET .../envelopes/envelope-id; no body
112
+ # # => { 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil, 'documents' => [],
113
+ # # 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }
114
+ def get(envelope_id, account_id_override = nil)
115
+ path = envelope_path(envelope_id, account_id_override)
116
+ call('Failed to get envelope') { http_get(path) }
117
+ end
118
+
119
+ # @param envelope_id [String]
120
+ # @param payload [Hash] name, message (nil clears), document_ids in desired order
121
+ # @param account_id_override [String, nil]
122
+ # @return [Hash] updated DocumentEnvelope
123
+ # @raise [ValidationError] on invalid payload or IDs
124
+ # @raise [ApiError, NetworkError] on API or transport failure
125
+ # @see PATCH /accounts/{accountId}/envelopes/{envelopeId}
126
+ # @example
127
+ # client.envelopes.update('envelope-id', message: nil)
128
+ # # PATCH body: { "message": null }
129
+ # # => { 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil, 'documents' => [],
130
+ # # 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }
131
+ def update(envelope_id, payload, account_id_override = nil)
132
+ body = require_payload(payload).transform_keys(&:to_s)
133
+ require_keys!(body, %w[name message document_ids])
134
+ validate_name!(body['name']) if body.key?('name')
135
+ validate_message!(body['message'])
136
+ unique_ids!(body['document_ids'], 'document_ids') if body.key?('document_ids')
137
+ path = envelope_path(envelope_id, account_id_override)
138
+ call('Failed to update envelope') { http_patch(path, body) }
139
+ end
140
+
141
+ # @param envelope_id [String]
142
+ # @param account_id_override [String, nil]
143
+ # @return [nil] deletes only the closed envelope; its documents remain
144
+ # @raise [ValidationError] on invalid IDs
145
+ # @raise [ApiError, NetworkError] on API or transport failure (409 while open)
146
+ # @see DELETE /accounts/{accountId}/envelopes/{envelopeId}
147
+ # @example
148
+ # client.envelopes.delete('envelope-id') # DELETE .../envelopes/envelope-id; no body
149
+ # # => nil
150
+ def delete(envelope_id, account_id_override = nil)
151
+ path = envelope_path(envelope_id, account_id_override)
152
+ call_void('Failed to delete envelope') { http_delete(path) }
153
+ end
154
+
155
+ # @param envelope_id [String]
156
+ # @param params [Hash] sort, page, per_page
157
+ # @param account_id_override [String, nil]
158
+ # @return [Hash] paginated EnvelopeActivity objects
159
+ # @raise [ValidationError] on invalid IDs or query shape
160
+ # @raise [ApiError, NetworkError] on API or transport failure
161
+ # @see GET /accounts/{accountId}/envelopes/{envelopeId}/activities
162
+ # @example
163
+ # client.envelopes.activities('envelope-id', per_page: 20)
164
+ # # GET .../envelopes/envelope-id/activities?per-page=20; no body
165
+ # # => { data: [{ 'document_id' => 'document-id', 'document_name' => 'contract.pdf',
166
+ # # 'event' => 'signature_requested', 'created_at' => '2026-11-11T12:00:00Z' }] }
167
+ def activities(envelope_id, params = {}, account_id_override = nil)
168
+ path = "#{envelope_path(envelope_id, account_id_override)}/activities"
169
+ query = query_params(params)
170
+ call_list('Failed to list envelope activities') { http_get(path, query) }
171
+ end
172
+
173
+ # @param envelope_id [String]
174
+ # @param artifact [String] original, certificated, certificate-page, pades or bundle
175
+ # @param account_id_override [String, nil]
176
+ # @return [String] binary ZIP of available document artifacts in envelope order
177
+ # @raise [ValidationError] on invalid IDs or artifact
178
+ # @raise [ApiError, NetworkError] on API or transport failure (404 if no artifact exists)
179
+ # @see GET /accounts/{accountId}/envelopes/{envelopeId}/download/{artifactName}
180
+ # @example
181
+ # client.envelopes.download('envelope-id', 'original')
182
+ # # GET .../envelopes/envelope-id/download/original; no body; => binary ZIP bytes
183
+ def download(envelope_id, artifact = 'certificated', account_id_override = nil)
184
+ unless DocumentResource::ARTIFACT_TYPES.include?(artifact)
185
+ raise ValidationError.new("artifact must be one of: #{DocumentResource::ARTIFACT_TYPES.join(', ')}")
186
+ end
187
+
188
+ path = "#{envelope_path(envelope_id, account_id_override)}/download/#{artifact}"
189
+ call_binary('Failed to download envelope') { http_get(path) }
190
+ end
191
+
192
+ # @param envelope_id [String]
193
+ # @param account_id_override [String, nil]
194
+ # @return [Array<Hash>] each document's id, status and cancelled flag; repeatable
195
+ # @raise [ValidationError] on invalid IDs
196
+ # @raise [ApiError, NetworkError] on API or transport failure
197
+ # @see PUT /accounts/{accountId}/envelopes/{envelopeId}/cancel
198
+ # @example
199
+ # client.envelopes.cancel('envelope-id') # PUT .../envelopes/envelope-id/cancel; no body
200
+ # # => [{ 'id' => 'document-id', 'status' => 'rejected_by_user', 'cancelled' => true }]
201
+ def cancel(envelope_id, account_id_override = nil)
202
+ path = "#{envelope_path(envelope_id, account_id_override)}/cancel"
203
+ call_array('Failed to cancel envelope') { http_put(path) }
204
+ end
205
+
206
+ # @param envelope_id [String]
207
+ # @param signer_id [String]
208
+ # @param account_id_override [String, nil]
209
+ # @return [Hash] is_sent, envelope_id, signer_id; paid notifications are charged
210
+ # @raise [ValidationError] on invalid IDs
211
+ # @raise [ApiError, NetworkError] on API or transport failure
212
+ # @see PUT /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/resend
213
+ # @example
214
+ # client.envelopes.resend_notification('envelope-id', 'signer-id')
215
+ # # PUT .../envelopes/envelope-id/signers/signer-id/resend; no body
216
+ # # => { 'is_sent' => true, 'envelope_id' => 'envelope-id', 'signer_id' => 'signer-id' }
217
+ def resend_notification(envelope_id, signer_id, account_id_override = nil)
218
+ sid = require_id(signer_id, 'Signer ID')
219
+ path = "#{envelope_path(envelope_id, account_id_override)}/signers/#{sid}/resend"
220
+ call('Failed to resend envelope invitation') { http_put(path) }
221
+ end
222
+
223
+ # Estimate one reminder for the whole envelope without sending or charging. Available on staging.
224
+ # @param envelope_id [String]
225
+ # @param signer_id [String]
226
+ # @param account_id_override [String, nil]
227
+ # @return [Hash] ResendCostEstimate; does not check reminder timing eligibility
228
+ # @raise [ValidationError] on invalid IDs
229
+ # @raise [ApiError, NetworkError] on API or transport failure
230
+ # @see POST /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/estimate-resend-cost
231
+ # @example
232
+ # client.envelopes.estimate_resend_cost('envelope-id', 'signer-id') # POST; no body
233
+ # # => { 'total' => 0, 'breakdown' => [], 'credit_balance' => 100, 'has_sufficient_credits' => true }
234
+ def estimate_resend_cost(envelope_id, signer_id, account_id_override = nil)
235
+ sid = require_id(signer_id, 'Signer ID')
236
+ path = "#{envelope_path(envelope_id, account_id_override)}/signers/#{sid}/estimate-resend-cost"
237
+ call('Failed to estimate envelope reminder cost') { http_post(path) }
238
+ end
239
+
240
+ # @param envelope_id [String]
241
+ # @param payload [Hash] EnvelopeDocumentRequest plus optional max_total_credits
242
+ # @param account_id_override [String, nil]
243
+ # @return [Hash] DocumentEnvelope; notifies the chosen existing envelope signers
244
+ # @raise [ValidationError] on invalid payload or IDs
245
+ # @raise [ApiError, NetworkError] on API or transport failure
246
+ # @see POST /accounts/{accountId}/envelopes/{envelopeId}/documents
247
+ # @example
248
+ # client.envelopes.add_document('envelope-id', id: 'document-id', signer_ids: ['signer-id'])
249
+ # # POST body: { "id": "document-id", "signer_ids": ["signer-id"] }
250
+ # # => DocumentEnvelope, as returned by create, with the document appended
251
+ def add_document(envelope_id, payload, account_id_override = nil)
252
+ body = document_payload(payload)
253
+ path = "#{envelope_path(envelope_id, account_id_override)}/documents"
254
+ call('Failed to add envelope document') { http_post(path, body) }
255
+ end
256
+
257
+ # @param envelope_id [String]
258
+ # @param document_id [String]
259
+ # @param account_id_override [String, nil]
260
+ # @return [Hash] DocumentEnvelope; removes and cancels the open document, notifying its recipients
261
+ # @raise [ValidationError] on invalid IDs
262
+ # @raise [ApiError, NetworkError] on API or transport failure (409 if document is closed)
263
+ # @see DELETE /accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}
264
+ # @example
265
+ # client.envelopes.remove_document('envelope-id', 'document-id')
266
+ # # DELETE .../envelopes/envelope-id/documents/document-id; no body
267
+ # # => { 'id' => 'envelope-id', 'name' => 'Contract', 'message' => nil, 'documents' => [],
268
+ # # 'counts' => nil, 'signing_urls' => [], 'created_at' => '2026-11-11T12:00:00Z' }
269
+ def remove_document(envelope_id, document_id, account_id_override = nil)
270
+ id = require_id(document_id, 'Document ID')
271
+ path = "#{envelope_path(envelope_id, account_id_override)}/documents/#{id}"
272
+ call('Failed to remove envelope document') { http_delete(path) }
273
+ end
274
+
275
+ private
276
+
277
+ def envelopes_path(override)
278
+ "accounts/#{account_id(override)}/envelopes"
279
+ end
280
+
281
+ def envelope_path(envelope_id, override)
282
+ "#{envelopes_path(override)}/#{require_id(envelope_id, 'Envelope ID')}"
283
+ end
284
+
285
+ def require_keys!(body, allowed)
286
+ if body.empty? || (body.keys - allowed).any?
287
+ raise ValidationError.new("Provide only envelope fields: #{allowed.join(', ')}")
288
+ end
289
+ end
290
+
291
+ def validate_name!(name)
292
+ require_string(name, 'Name', max_length: 255)
293
+ raise ValidationError.new('Name cannot contain <') if name.include?('<')
294
+ end
295
+
296
+ def validate_message!(message)
297
+ raise ValidationError.new('message must be a String or nil') unless message.nil? || message.is_a?(String)
298
+ end
299
+
300
+ def unique_ids!(ids, label)
301
+ require_array(ids, label).each { |id| require_id(id, label) }
302
+ raise ValidationError.new("#{label} must not contain duplicates") unless ids.uniq == ids
303
+
304
+ ids
305
+ end
306
+
307
+ def create_payload(payload)
308
+ body = body_params(require_payload(payload))
309
+ require_keys!(body, %w[name message max_total_credits signers documents])
310
+ validate_name!(body['name'])
311
+ validate_message!(body['message'])
312
+ Utils.require_credit_ceiling(body['max_total_credits'])
313
+ body['signers'] = bounded_items(body['signers'], 'signers').map { |signer| envelope_signer(signer) }
314
+ body['documents'] = bounded_items(body['documents'], 'documents').map do |document|
315
+ document_payload(document, body['signers'])
316
+ end
317
+ validate_membership!(body)
318
+ body
319
+ end
320
+
321
+ def validate_membership!(body)
322
+ ids = unique_ids!(body['signers'].map { |signer| signer['id'] }, 'signers')
323
+ unique_ids!(body['documents'].map { |document| document['id'] }, 'documents')
324
+ used = body['documents'].flat_map { |document| document['signer_ids'] }.uniq
325
+ raise ValidationError.new('Every envelope signer must be on a document') unless used.sort == ids.sort
326
+ end
327
+
328
+ def bounded_items(value, label)
329
+ items = require_array(value, label)
330
+ raise ValidationError.new("An envelope supports at most 20 #{label}") if items.length > 20
331
+
332
+ items
333
+ end
334
+
335
+ def envelope_signer(signer)
336
+ require_payload(signer, 'Envelope signer')
337
+ require_keys!(signer, %w[id verification_method notification_methods embedded])
338
+ require_id(signer['id'], 'Signer ID')
339
+ AssignmentResource.build_payload(signers: [signer]).fetch('signers').first
340
+ end
341
+
342
+ def document_payload(payload, signers = nil)
343
+ body = body_params(require_payload(payload, 'Envelope document'))
344
+ allowed = %w[id method entries signer_ids expires_at copy_receiver_ids]
345
+ allowed << 'max_total_credits' unless signers
346
+ require_keys!(body, allowed)
347
+ require_id(body['id'], 'Document ID')
348
+ ids = unique_ids!(body['signer_ids'], 'signer_ids')
349
+ selected = signers ? signers.select { |signer| ids.include?(signer['id']) } : ids
350
+ if signers && selected.length != ids.length
351
+ raise ValidationError.new('Document signers must belong to the envelope')
352
+ end
353
+
354
+ AssignmentResource.build_payload(method: body.fetch('method', 'virtual'), signers: selected,
355
+ entries: body['entries'], expires_at: body['expires_at'],
356
+ copy_receivers: body['copy_receiver_ids'])
357
+ Utils.require_credit_ceiling(body['max_total_credits'])
358
+ body
359
+ end
360
+ end
361
+ end
362
+ end
@@ -201,11 +201,10 @@ module Assinafy
201
201
  end
202
202
  end
203
203
 
204
- # Validate a single value against a field definition.
204
+ # Validate a single value against a field definition, preserving nil as JSON null.
205
205
  #
206
- # The OpenAPI declares workspace Authorization, which is used when
207
- # `signer_access_code:` is omitted. The deployed API also accepts the signer
208
- # access code: when the keyword is given it must be a non-blank code, and
206
+ # Workspace authorization is used when `signer_access_code:` is omitted.
207
+ # When the keyword is given it must be a non-blank code, and
209
208
  # only the code is sent (never the workspace credentials).
210
209
  #
211
210
  # @param field_id [String]
@@ -231,17 +230,16 @@ module Assinafy
231
230
  def validate(field_id, value, account_id_override = nil, signer_access_code: WORKSPACE)
232
231
  acc_id = account_id(account_id_override)
233
232
  fid = require_id(field_id, 'Field ID')
234
- raise ValidationError.new('Field value is required') if value.nil?
235
233
 
236
234
  access_code = field_access_code(signer_access_code)
237
235
 
238
236
  call('Failed to validate field value') do
239
- http_post("accounts/#{acc_id}/fields/#{fid}/validate", body_params(value: value),
237
+ http_post("accounts/#{acc_id}/fields/#{fid}/validate", { 'value' => value },
240
238
  { signer_access_code: access_code }, workspace_auth: access_code.nil?)
241
239
  end
242
240
  end
243
241
 
244
- # Validate many `{ field_id:, value: }` pairs in a single call.
242
+ # Validate many `{ field_id:, value: }` pairs in a single call. Explicit nil values remain JSON null.
245
243
  #
246
244
  # As with {#validate}, omitting `signer_access_code:` uses the workspace
247
245
  # credentials; giving it requires a non-blank code and sends only the code.
@@ -331,11 +329,11 @@ module Assinafy
331
329
  value_key = payload.key?(:value) ? :value : 'value'
332
330
 
333
331
  require_id(field_id, 'Field ID')
334
- unless payload.key?(value_key) && !payload[value_key].nil?
332
+ unless payload.key?(value_key)
335
333
  raise ValidationError.new('Field value is required')
336
334
  end
337
335
 
338
- body_params(payload)
336
+ body_params(payload).merge('value' => payload[value_key])
339
337
  end
340
338
  end
341
339
  end
@@ -287,6 +287,8 @@ module Assinafy
287
287
  # @raise [Assinafy::NetworkError] on transport or TLS failure
288
288
  # @raise [Assinafy::ValidationError] on invalid required input
289
289
  def revoke(token:, client_id:, token_type_hint: nil, client_secret: nil)
290
+ require_string(client_secret, 'Client secret') unless client_secret.nil?
291
+
290
292
  if !token_type_hint.nil? && !TOKEN_TYPE_HINTS.include?(token_type_hint.to_s)
291
293
  raise ValidationError.new(
292
294
  "Token type hint must be one of: #{TOKEN_TYPE_HINTS.join(', ')}",
@@ -396,6 +398,10 @@ module Assinafy
396
398
  # pass `"#{protected_resource_metadata['authorization_servers'].first}" \
397
399
  # "/.well-known/oauth-authorization-server"` to follow discovery strictly
398
400
  # @return [Hash{String=>Object}] the bare metadata object
401
+ # @raise [Assinafy::OAuthError] on an unsuccessful metadata response
402
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
403
+ # @raise [Assinafy::ValidationError] when the URL is not absolute HTTPS without userinfo or fragment
404
+ # @see GET https://auth.assinafy.com.br/.well-known/oauth-authorization-server
399
405
  #
400
406
  # @example Discover endpoints instead of hardcoding them
401
407
  # metadata = client.oauth.authorization_server_metadata
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Assinafy
4
+ module Resources
5
+ # Pending assignment/envelope requests. Available on staging; 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
+ if value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?
47
+ (?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)?\z/x)
48
+ return DateTime.iso8601(value).to_time
49
+ end
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
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => nil }],
70
+ # # meta: { current_page: 1, per_page: 20, total: 1, last_page: 1 } }
71
+ def list(params = {}, account_id_override = nil)
72
+ query = query_params(params)
73
+ require_id(query['document_id'], 'Document ID') if query.key?('document_id')
74
+ path = "accounts/#{account_id(account_id_override)}/scheduled-sends"
75
+ call_list('Failed to list scheduled sends') { http_get(path, query) }
76
+ end
77
+
78
+ # Cancel a pending send without sending or charging. Other states answer 409.
79
+ # @param scheduled_send_id [String]
80
+ # @param account_id_override [String, nil]
81
+ # @return [Hash] ScheduledSend, now cancelled
82
+ # @raise [ValidationError] on invalid IDs
83
+ # @raise [ApiError, NetworkError] on API or transport failure
84
+ # @see PUT /accounts/{accountId}/scheduled-sends/{scheduledSendId}/cancel
85
+ # @example
86
+ # client.scheduled_sends.cancel('send-id') # PUT; no body
87
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
88
+ # # 'document_ids' => ['document-id'], 'status' => 'cancelled', 'send_at' => '2026-12-01T12:00:00Z',
89
+ # # 'assignment_id' => nil, 'envelope_id' => nil, 'failure_reason' => nil,
90
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => '2026-12-01T10:30:00Z' }
91
+ def cancel(scheduled_send_id, account_id_override = nil)
92
+ path = "#{scheduled_send_path(scheduled_send_id, account_id_override)}/cancel"
93
+ call('Failed to cancel scheduled send') { http_put(path) }
94
+ end
95
+
96
+ # Send a pending request now, with the original member's permissions, balance and credit ceiling.
97
+ # A refused request stays pending; cancel it to prevent a later scheduled attempt. Never retries.
98
+ # @param scheduled_send_id [String]
99
+ # @param account_id_override [String, nil]
100
+ # @return [Hash] ScheduledSend, now sent, with assignment_id or envelope_id
101
+ # @raise [ValidationError] on invalid IDs
102
+ # @raise [ApiError, NetworkError] on API or transport failure, including 409 for a non-pending send
103
+ # @see PUT /accounts/{accountId}/scheduled-sends/{scheduledSendId}/send
104
+ # @example
105
+ # client.scheduled_sends.send_now('send-id') # PUT; no body
106
+ # # => { 'resource' => 'scheduled_send', 'id' => 'send-id', 'type' => 'assignment',
107
+ # # 'document_ids' => ['document-id'], 'status' => 'sent', 'send_at' => '2026-12-01T12:00:00Z',
108
+ # # 'assignment_id' => 'assignment-id', 'envelope_id' => nil, 'failure_reason' => nil,
109
+ # # 'created_at' => '2026-12-01T10:00:00Z', 'processed_at' => '2026-12-01T10:30:00Z' }
110
+ def send_now(scheduled_send_id, account_id_override = nil)
111
+ path = "#{scheduled_send_path(scheduled_send_id, account_id_override)}/send"
112
+ call('Failed to send scheduled request') { http_put(path) }
113
+ end
114
+
115
+ private
116
+
117
+ def scheduled_send_path(send_id, override)
118
+ "accounts/#{account_id(override)}/scheduled-sends/#{require_id(send_id, 'Scheduled send ID')}"
119
+ end
120
+ end
121
+ end
122
+ end