turbodocx-sdk 0.9.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,757 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+ require "json"
5
+ require "net/http"
6
+ require "uri"
7
+ require_relative "http_client"
8
+
9
+ module TurboDocxSdk
10
+ # TurboSign module -- digital signature operations.
11
+ #
12
+ # All methods are class-level (static pattern). Call +configure+ once,
13
+ # then invoke any method directly on the class.
14
+ #
15
+ # TurboDocxSdk::TurboSign.configure(api_key: "...", org_id: "...", sender_email: "...")
16
+ # result = TurboDocxSdk::TurboSign.send_signature(...)
17
+ #
18
+ class TurboSign
19
+ # Shorthand field key => the concrete field type it emits plus its default size.
20
+ #
21
+ # Note +initials+ maps to the +"initial"+ field type -- that is the literal in the
22
+ # signature field-type set (there is no +"initials"+).
23
+ EMBEDDED_FIELD_SPECS = {
24
+ "signature" => { type: "signature", size: { "width" => 100, "height" => 30 } },
25
+ "date" => { type: "date", size: { "width" => 75, "height" => 30 } },
26
+ "initials" => { type: "initial", size: { "width" => 50, "height" => 30 } },
27
+ "fullName" => { type: "full_name", size: { "width" => 150, "height" => 30 } }
28
+ }.freeze
29
+
30
+ class << self
31
+ # Configure the TurboSign module with API credentials.
32
+ #
33
+ # @param api_key [String, nil]
34
+ # @param access_token [String, nil]
35
+ # @param org_id [String, nil]
36
+ # @param sender_email [String, nil] Reply-to email for signature requests (required)
37
+ # @param sender_name [String, nil] Sender display name (optional but recommended)
38
+ # @param base_url [String, nil]
39
+ # @raise [AuthenticationError] if no API key or access token is provided
40
+ # @raise [ValidationError] if senderEmail is missing
41
+ def configure(api_key: nil, access_token: nil, org_id: nil,
42
+ sender_email: nil, sender_name: nil, base_url: nil,
43
+ client_context: nil)
44
+ @client = HttpClient.new(
45
+ api_key: api_key,
46
+ access_token: access_token,
47
+ org_id: org_id,
48
+ sender_email: sender_email,
49
+ sender_name: sender_name,
50
+ base_url: base_url,
51
+ client_context: client_context
52
+ )
53
+ end
54
+
55
+ # Create a signature review link (upload document, do NOT send emails).
56
+ #
57
+ # @param request [Hash] :file or :fileLink or :deliverableId or :templateId,
58
+ # :recipients (Array), :fields (Array), :documentName, :documentDescription,
59
+ # :senderEmail, :senderName, :ccEmails
60
+ # Each field hash may set "required" (Boolean): whether the signer must complete the
61
+ # field. Default true (omit the key). Set false to make the field optional for the
62
+ # signer. Signature and initial fields are always required: the API rejects
63
+ # "required" => false on them with a 400.
64
+ #
65
+ # Template signer roles: when sending a +templateId+ whose signers and fields were set up
66
+ # in TurboDocx, give each recipient a "role" (e.g. "client") instead of a "signingOrder";
67
+ # the fields saved for that role are used, so :fields may be omitted (any passed are
68
+ # added). A role left out uses the template's saved signer. List a template's roles with
69
+ # +get_template_signature_setup+. An unknown role raises ValidationError, code
70
+ # "UnknownSignerRole".
71
+ # @return [Hash] document info with review URL; the API always includes "recipients" on
72
+ # success (this method does not default it)
73
+ # @raise [ValidationError] on invalid request data
74
+ # @raise [AuthenticationError] on invalid credentials
75
+ # @raise [NetworkError] on connection failure
76
+ def create_signature_review_link(request)
77
+ client = get_client
78
+ sender = client.sender_config
79
+ form_data = build_signature_form_data(request, sender, for_review: true)
80
+
81
+ if request[:file] || request["file"]
82
+ file = request[:file] || request["file"]
83
+ client.upload_file(
84
+ "/turbosign/single/prepare-for-review",
85
+ file,
86
+ field_name: "file",
87
+ additional_data: with_file_name(form_data, request)
88
+ )
89
+ else
90
+ form_data["fileLink"] = request[:fileLink] || request["fileLink"] if request[:fileLink] || request["fileLink"]
91
+ form_data["deliverableId"] = request[:deliverableId] || request["deliverableId"] if request[:deliverableId] || request["deliverableId"]
92
+ form_data["templateId"] = request[:templateId] || request["templateId"] if request[:templateId] || request["templateId"]
93
+ client.post("/turbosign/single/prepare-for-review", form_data)
94
+ end
95
+ end
96
+
97
+ # Send signature request (upload document AND send emails immediately).
98
+ #
99
+ # Embedded signing: pass +sendEmail: false+ so the recipients are not emailed their signing
100
+ # link (and the initial CC notice); the document still goes out for signing, and passcode and
101
+ # completed-copy emails are still sent. Recipient hashes may carry (camelCase keys) +phone+
102
+ # (E.164; required for SMS), +externalId+ (your own key, unique in the document) and
103
+ # +identityVerification+ -- { mode: "otp", channel: "email"|"sms" },
104
+ # { mode: "external_idv", provider:, maxAgeMinutes: 5..10080 } or
105
+ # { mode: "override", overrideIdentityVerification: true, reason: }. Omit
106
+ # +identityVerification+ to take the org's default channel. { mode: "otp" } without a channel
107
+ # takes the org's default channel, or email when that default is "none"; on an org with
108
+ # embedded signing off it raises AuthorizationError (403), code EmbeddedSigningNotEnabled.
109
+ # external_idv and override recipients sign only through a single-use +create_signing_url+
110
+ # link and are never sent signing, reminder or resend emails. A blank or whitespace-only
111
+ # +externalId+ counts as absent (stored as null).
112
+ #
113
+ # @param request [Hash] same as create_signature_review_link, plus optional :sendEmail
114
+ # @return [Hash] document info with confirmation; the API always includes "recipients" on
115
+ # success (this method does not default it)
116
+ # @raise [ValidationError] on invalid request data
117
+ # @raise [AuthenticationError] on invalid credentials
118
+ # @raise [NetworkError] on connection failure
119
+ def send_signature(request)
120
+ client = get_client
121
+ sender = client.sender_config
122
+ form_data = build_signature_form_data(request, sender)
123
+
124
+ if request[:file] || request["file"]
125
+ file = request[:file] || request["file"]
126
+ client.upload_file(
127
+ "/turbosign/single/prepare-for-signing",
128
+ file,
129
+ field_name: "file",
130
+ additional_data: with_file_name(form_data, request)
131
+ )
132
+ else
133
+ form_data["fileLink"] = request[:fileLink] || request["fileLink"] if request[:fileLink] || request["fileLink"]
134
+ form_data["deliverableId"] = request[:deliverableId] || request["deliverableId"] if request[:deliverableId] || request["deliverableId"]
135
+ form_data["templateId"] = request[:templateId] || request["templateId"] if request[:templateId] || request["templateId"]
136
+ client.post("/turbosign/single/prepare-for-signing", form_data)
137
+ end
138
+ end
139
+
140
+ # Mint an embedded signing URL for one recipient -- request it the moment the signer is ready
141
+ # (never store it). For otp / no-verification recipients it is the reusable signing link, valid
142
+ # until the document expires; only external_idv / override recipients get a single-use link
143
+ # that expires 5 minutes after issue. The counterpart of DocuSign's createRecipientView / BoldSign's
144
+ # GetEmbeddedSignLink. Open the returned +url+ in a new tab, redirect to it, or embed it.
145
+ #
146
+ # Provide EXACTLY ONE of +recipient_id+ / +external_id+ (an empty string counts as absent);
147
+ # supplying both or neither raises before any HTTP call. +identity_assertion+ is only for
148
+ # external_idv recipients; +return_url+, when given, must be an https URL.
149
+ #
150
+ # The endpoint replies { data: { results } }. The HTTP client strips the outer +data+, so this
151
+ # method peels the remaining +results+ envelope and returns the flat response -- never the
152
+ # +{ "results" => ... }+ wrapper.
153
+ #
154
+ # @param document_id [String] the document the recipient belongs to
155
+ # @param recipient_id [String, nil] select the recipient by TurboDocx recipient id
156
+ # @param external_id [String, nil] ...or by the externalId set when the recipient was created
157
+ # @param identity_assertion [Hash, nil] assertion from your own provider, for external_idv only
158
+ # (keys: provider, verificationId, verifiedAt, subjectEmail; optional audit-trail context:
159
+ # method ("id_document" | "id_document_liveness" | "kba" | "database" | "sso" | "other"),
160
+ # methodDetail (required when method is "other"), assuranceLevel (e.g. "ial2_aal2"),
161
+ # verifiedName, evidenceUrl (https), overrideEmailMatching (true skips the
162
+ # subjectEmail-equals-recipient check; recorded on the audit trail)). Keys are camelCase.
163
+ # @param return_url [String, nil] where TurboSign returns the signer after completion (https only)
164
+ # @return [Hash] with "url", "expiresAt", "recipientId", "externalId",
165
+ # "identityVerificationMode" and "pendingChecks". "expiresAt": single-use links
166
+ # (external_idv / override) expire 5 minutes after issue; for otp/no-verification recipients
167
+ # the URL is the reusable signing link, so it is the document's own expiry, or nil when the
168
+ # document doesn't expire.
169
+ # @raise [ValidationError] if not exactly one selector is given, or return_url is not https
170
+ # @raise [NotFoundError] if the document or recipient does not exist
171
+ # @raise [AuthenticationError] on invalid credentials
172
+ # @raise [NetworkError] on connection failure
173
+ def create_signing_url(document_id, recipient_id: nil, external_id: nil,
174
+ identity_assertion: nil, return_url: nil)
175
+ # Fail fast with actionable messages; the server still enforces everything.
176
+ selector_count = [recipient_id, external_id].count { |v| !v.nil? && v != "" }
177
+ unless selector_count == 1
178
+ raise ValidationError.new(
179
+ "Provide exactly one of recipientId or externalId to createSigningUrl.",
180
+ code: "RecipientSelectorInvalid"
181
+ )
182
+ end
183
+ # An empty-string return_url is treated as ABSENT (not sent, no error), matching js
184
+ # (`if (request.returnUrl && ...)` -- "" is falsy there), Go and Python. Guard so the https
185
+ # check only runs when return_url is a non-empty string.
186
+ if return_url && !return_url.empty? && !return_url.match?(%r{\Ahttps://}i)
187
+ raise ValidationError.new("returnUrl must be an https URL.", code: "InvalidReturnUrl")
188
+ end
189
+
190
+ client = get_client
191
+ body = {}
192
+ body["recipientId"] = recipient_id unless recipient_id.nil? || recipient_id == ""
193
+ body["externalId"] = external_id unless external_id.nil? || external_id == ""
194
+ body["identityAssertion"] = identity_assertion unless identity_assertion.nil?
195
+ body["returnUrl"] = return_url unless return_url.nil? || return_url == ""
196
+
197
+ # The client already stripped the outer { data }; peel the inner { results } envelope here
198
+ # (same convention as the quote/deliverable modules).
199
+ response = client.post("/turbosign/documents/#{document_id}/signing-url", body)
200
+ # `|| response` keeps it correct if the API ever returns a flat body (no `results`
201
+ # envelope), so it degrades gracefully rather than returning nil. PHP/Go/Java guard this too.
202
+ response["results"] || response
203
+ end
204
+
205
+ # Read the org's embedded-signing settings: the set-once, org-wide gates (embedded signing
206
+ # enabled, external identity verification allowed, override allowed), the default OTP channel,
207
+ # and the allowed iframe embedding origins. Use it to see what is permitted before you request
208
+ # signing URLs. Read-only.
209
+ #
210
+ # Same { data: { results } } envelope as +create_signing_url+.
211
+ #
212
+ # @return [Hash] with "enabled", "allowExternalIdv", "allowIdentityOverride",
213
+ # "defaultChannel", "allowChannelOverride" and "allowedFrameAncestors". "defaultChannel"
214
+ # ("none" | "email" | "sms") is the org's default OTP channel: while embedded signing is
215
+ # enabled it applies to every recipient that doesn't set one, SDK/API sends included; "none"
216
+ # means verify only when a request asks for it. "allowChannelOverride" false means the org
217
+ # locked the method: an explicit different channel is rejected with OtpOverrideNotAllowed, so
218
+ # omit it to take the default (always true for a "none" default or when embedded signing is
219
+ # off). An empty "allowedFrameAncestors" means framing is denied everywhere.
220
+ # @raise [AuthenticationError] on invalid credentials
221
+ # @raise [NetworkError] on connection failure
222
+ def get_embedded_signing_settings
223
+ client = get_client
224
+ response = client.get("/turbosign/embedded-signing-settings")
225
+ response["results"]
226
+ end
227
+
228
+ # Create a signature request AND mint a per-recipient embedded signing URL in ONE call -- the
229
+ # embedded-signing counterpart of DocuSeal's create-with-embed and Dropbox Sign's embedded flow.
230
+ # Scales to multiple signers (e.g. in-person, same-device sequential signing): you get one embed
231
+ # URL per recipient, returned IN SIGNING ORDER.
232
+ #
233
+ # This is a thin WRAPPER over +send_signature+ + +create_signing_url+ -- no new endpoint. It
234
+ # maps the ergonomic request (per-recipient +auth+ + +fields+ shorthand) onto those calls, then
235
+ # assembles a per-recipient result carrying the embed URL and the resolved identity mode.
236
+ #
237
+ # Mapping:
238
+ # - +auth[:emailOtp]+ => identityVerification { mode:"otp", channel:"email" };
239
+ # +auth[:sms][:phoneNumber]+ => { mode:"otp", channel:"sms" } and sets the recipient's phone.
240
+ # No +auth+ => the org's default channel applies ("defaultChannel" from
241
+ # +get_embedded_signing_settings+); when "allowChannelOverride" is false, a different
242
+ # channel is rejected with OtpOverrideNotAllowed. +auth+ supports email or SMS passcodes only.
243
+ # For an external_idv or override recipient, call +send_signature+ with identityVerification
244
+ # on the recipient, then +create_signing_url+ for each signer (with +identity_assertion+ for
245
+ # external_idv).
246
+ # - +fields+ shorthand => full field objects (placement:"replace" + a default size). Provide the
247
+ # top-level +fields+ to override the shorthand with full field control.
248
+ # - +signingOrder+ defaults to each recipient's array index + 1.
249
+ # - +sendEmail+ defaults to false: your app shows the signing page, so the signing-link emails
250
+ # (and the initial CC notice) are suppressed. Passcode and completed-copy emails still go out.
251
+ # - +returnUrl+ is passed through to each embed URL only when provided (https, enforced by
252
+ # +create_signing_url+).
253
+ #
254
+ # Turn-aware: with a real (sequential) signing order the backend only mints a URL for the signer
255
+ # whose turn it is. Rather than throw the whole call away, each result carries a "status":
256
+ # - "ready" -- it's their turn; "embedUrl" is set, frame it now.
257
+ # - "pending" -- an earlier signer hasn't finished; "embedUrl" is nil. Re-mint later with
258
+ # +create_signing_url+ once earlier signers complete.
259
+ # - "completed" -- they've already signed; "embedUrl" is nil.
260
+ # A genuine error (anything other than not-in-turn / already-signed) still raises.
261
+ #
262
+ # @param request [Hash] :recipients (Array; each :name, :email, optional :phone, :signingOrder,
263
+ # :auth, :fields, :role -- the template signer role this recipient fills; a role left out
264
+ # falls back to the template's saved signer, who also gets an embed URL in the result), and any of :file/:fileName/:fileLink/:templateId/:deliverableId,
265
+ # :documentName, :documentDescription, :senderName, :senderEmail, :ccEmails, :fields (full
266
+ # field override), :sendEmail, :returnUrl
267
+ # @return [Hash] with "documentId" and "recipients" (each "recipientId", "name", "email",
268
+ # "embedUrl", "status", "identityVerificationMode"). For a "ready" signer
269
+ # "identityVerificationMode" is the mode the backend resolved for the URL; for "pending" /
270
+ # "completed" no URL was minted, so it is the mode you requested via :auth (nil when you set
271
+ # none, even if the org's default channel applies). +create_signing_url+ reports the
272
+ # effective mode. From this call it is only ever "otp" or nil.
273
+ # @raise [ValidationError] if send_signature returns no recipient matching a requested email
274
+ # @raise [AuthenticationError] on invalid credentials
275
+ # @raise [NetworkError] on connection failure
276
+ def create_embedded_signature(request)
277
+ recipients = request[:recipients] || request["recipients"] || []
278
+
279
+ # 1. Map the ergonomic recipients onto full recipient objects (identity + phone + order).
280
+ mapped_recipients = recipients.each_with_index.map do |r, index|
281
+ auth = req_val(r, :auth)
282
+ identity_verification = resolve_identity_verification(auth)
283
+ phone = dig_val(auth, :sms, :phoneNumber)
284
+ phone = req_val(r, :phone) if phone.nil?
285
+
286
+ recipient = {
287
+ "name" => req_val(r, :name),
288
+ "email" => req_val(r, :email),
289
+ "signingOrder" => req_val(r, :signingOrder) || index + 1
290
+ }
291
+ role = req_val(r, :role)
292
+ recipient["role"] = role unless role.nil? || role == ""
293
+ recipient["phone"] = phone unless phone.nil?
294
+ recipient["identityVerification"] = identity_verification unless identity_verification.nil?
295
+ recipient
296
+ end
297
+
298
+ # Client-side fail-fast: an SMS OTP recipient with no resolved phone. Mirrors the JS
299
+ # validateRecipientsIdentity call (and Go/PHP), catching the common mistake with an
300
+ # actionable message BEFORE the send rather than as a raw HTTP 400. The other identity
301
+ # modes are unreachable from this shorthand (auth only ever produces email/sms OTP), so
302
+ # only this check is live; the server remains the source of truth.
303
+ mapped_recipients.each do |recipient|
304
+ iv = recipient["identityVerification"]
305
+ next if iv.nil?
306
+ next unless iv["mode"] == "otp" && iv["channel"] == "sms"
307
+
308
+ phone = recipient["phone"]
309
+ next unless phone.nil? || phone == ""
310
+
311
+ raise ValidationError.new(
312
+ "Recipient \"#{recipient["email"]}\" uses SMS OTP but has no phone (E.164).",
313
+ code: "PhoneRequiredForSmsOtp"
314
+ )
315
+ end
316
+
317
+ # Full `fields` (when non-empty) win verbatim; otherwise expand each recipient's shorthand. An
318
+ # empty list counts as absent, so it can't discard the shorthand and leave the send with no fields.
319
+ fields = req_val(request, :fields)
320
+ fields = recipients.flat_map { |r| expand_recipient_fields(r) } if fields.nil? || fields.empty?
321
+
322
+ send_request = {
323
+ "recipients" => mapped_recipients,
324
+ "fields" => fields,
325
+ # Embedded flow default: suppress recipient emails (the host owns the UX). Explicit
326
+ # request value wins; nil? test keeps a caller's false from being replaced by the default.
327
+ "sendEmail" => req_val(request, :sendEmail).nil? ? false : req_val(request, :sendEmail)
328
+ }
329
+ %i[file fileName fileLink templateId deliverableId documentName documentDescription
330
+ senderName senderEmail ccEmails].each do |key|
331
+ value = req_val(request, key)
332
+ send_request[key.to_s] = value unless value.nil?
333
+ end
334
+
335
+ sent = send_signature(send_request)
336
+
337
+ # Match the backend's recipients back to the request by email so we can carry `name` and know
338
+ # the resolved identity mode. A successful send always returns `recipients`; the empty default
339
+ # only turns a malformed response into EmbeddedRecipientNotReturned.
340
+ sent_recipients = sent["recipients"] || []
341
+ recipient_id_by_email = {}
342
+ sent_recipients.each { |sr| recipient_id_by_email[sr["email"]] = sr["id"] }
343
+
344
+ document_id = sent["documentId"]
345
+ return_url = req_val(request, :returnUrl)
346
+
347
+ # 2 + 3. Mint one embed URL per recipient and assemble the result IN SIGNING ORDER. The index
348
+ # is part of the sort key because Ruby's sort_by is not stable: two recipients with a
349
+ # colliding signingOrder must keep their original relative order (as JS's stable sort does).
350
+ # With template roles the API orders signers by the template's roles (the order it returns
351
+ # them in), not by the order or signingOrder passed here.
352
+ uses_roles = recipients.any? { |r| !req_val(r, :role).to_s.empty? }
353
+ api_order_by_email = {}
354
+ sent_recipients.each_with_index do |sr, api_index|
355
+ api_order_by_email[sr["email"].to_s.downcase] = api_index unless sr["email"].nil?
356
+ end
357
+ ordered = recipients.each_with_index.map do |r, index|
358
+ order = if uses_roles
359
+ api_order_by_email.fetch(req_val(r, :email).to_s.downcase, Float::INFINITY)
360
+ else
361
+ req_val(r, :signingOrder) || index + 1
362
+ end
363
+ [order, index, r]
364
+ end
365
+
366
+ # Signers the API added that the caller did not pass (a template role's saved signer). With
367
+ # sendEmail=false nobody else can reach them, so mint their embed URLs too.
368
+ requested_emails = recipients.map { |r| req_val(r, :email).to_s.downcase }
369
+ sent_recipients.each_with_index do |sr, api_index|
370
+ next if sr["email"].nil? || requested_emails.include?(sr["email"].to_s.downcase)
371
+
372
+ ordered << [uses_roles ? api_index : Float::INFINITY, recipients.length + api_index,
373
+ { name: sr["name"], email: sr["email"] }]
374
+ end
375
+ ordered = ordered.sort_by { |order, index, _r| [order, index] }
376
+
377
+ result_recipients = ordered.map do |_order, _index, r|
378
+ email = req_val(r, :email)
379
+ recipient_id = recipient_id_by_email[email]
380
+ if recipient_id.nil?
381
+ raise ValidationError.new(
382
+ "sendSignature did not return a recipient matching \"#{email}\"; cannot mint an embed URL.",
383
+ code: "EmbeddedRecipientNotReturned"
384
+ )
385
+ end
386
+ mint_embedded_recipient(r, recipient_id, document_id, return_url)
387
+ end
388
+
389
+ { "documentId" => document_id, "recipients" => result_recipients }
390
+ end
391
+
392
+ # Void (cancel) a document.
393
+ #
394
+ # @param document_id [String]
395
+ # @param reason [String]
396
+ # @return [Hash] voided document details
397
+ # @raise [NotFoundError] if the document does not exist
398
+ # @raise [AuthenticationError] on invalid credentials
399
+ # @raise [NetworkError] on connection failure
400
+ def void_document(document_id, reason)
401
+ client = get_client
402
+ client.post("/turbosign/documents/#{document_id}/void", { "reason" => reason })
403
+ end
404
+
405
+ # Resend signature request emails to specific recipients.
406
+ #
407
+ # Recipients whose identity mode is external_idv or override sign only through a single-use
408
+ # +create_signing_url+ link, so they are never emailed. They are skipped, and recipientCount
409
+ # counts only the recipients actually emailed.
410
+ #
411
+ # @param document_id [String]
412
+ # @param recipient_ids [Array<String>]
413
+ # @return [Hash] resend confirmation
414
+ # @raise [NotFoundError] if the document does not exist
415
+ # @raise [ConflictError] 409 with code RecipientRequiresSingleUseUrl when every named
416
+ # recipient signs only through a single-use URL, so no email can be sent. Mint one with
417
+ # +create_signing_url+ instead.
418
+ # @raise [AuthenticationError] on invalid credentials
419
+ # @raise [NetworkError] on connection failure
420
+ def resend_email(document_id, recipient_ids)
421
+ client = get_client
422
+ client.post("/turbosign/documents/#{document_id}/resend-email", { "recipientIds" => recipient_ids })
423
+ end
424
+
425
+ # Send a reminder email to a document's outstanding signers.
426
+ #
427
+ # This is a standalone nudge, deliberately decoupled from the automatic reminder schedule:
428
+ # it ignores the configured cadence, works even when reminders are disabled or the
429
+ # per-signer cap is already spent, and does not consume that cap.
430
+ #
431
+ # Only signers at the CURRENT signing order are emailed. A recipient at a later order (or
432
+ # one who has already signed) is reported back as skipped rather than silently dropped, so
433
+ # the caller can tell that nobody was emailed.
434
+ #
435
+ # Recipients whose identity mode is external_idv or override sign only through a single-use
436
+ # +create_signing_url+ link, so they are never emailed. They come back as
437
+ # "skipped_requires_single_use_url".
438
+ #
439
+ # @param document_id [String]
440
+ # @param recipient_ids [Array<String>, nil] optional subset to remind. Omit to remind every
441
+ # eligible signer. When supplied the request is all-or-nothing: if any id is not a
442
+ # current-order pending signer the API rejects the whole call and sends nothing.
443
+ # @return [Hash] :results, one entry per recipient considered, each with recipientId and
444
+ # status (e.g. "sent", "skipped_wrong_order")
445
+ # @raise [NotFoundError] if the document does not exist
446
+ # @raise [ConflictError] 409 with code RecipientRequiresSingleUseUrl when every named
447
+ # recipient signs only through a single-use URL, so no reminder can be sent. Mint one with
448
+ # +create_signing_url+ instead.
449
+ # @raise [AuthenticationError] on invalid credentials
450
+ # @raise [NetworkError] on connection failure
451
+ def send_reminder(document_id, recipient_ids = nil)
452
+ client = get_client
453
+
454
+ # Only include the filter when it actually names someone. The API requires at least one id
455
+ # when the key is present, so forwarding an empty array would guarantee a 400 -- an empty
456
+ # list is far more likely to mean "no filter" than "remind nobody".
457
+ body = {}
458
+ body["recipientIds"] = recipient_ids if recipient_ids && !recipient_ids.empty?
459
+
460
+ client.post("/turbosign/documents/#{document_id}/send-reminder", body)
461
+ end
462
+
463
+ # Get the audit trail for a document.
464
+ #
465
+ # @param document_id [String]
466
+ # @return [Hash] audit trail with entries
467
+ # @raise [NotFoundError] if the document does not exist
468
+ # @raise [AuthenticationError] on invalid credentials
469
+ # @raise [NetworkError] on connection failure
470
+ def get_audit_trail(document_id)
471
+ client = get_client
472
+ client.get("/turbosign/documents/#{document_id}/audit-trail")
473
+ end
474
+
475
+ # Download the signed document.
476
+ #
477
+ # @param document_id [String]
478
+ # @return [String] raw PDF bytes
479
+ # @raise [NotFoundError] if the document does not exist
480
+ # @raise [TurboDocxError] if the file download from storage fails
481
+ # @raise [AuthenticationError] on invalid credentials
482
+ # @raise [NetworkError] on connection failure
483
+ def download(document_id)
484
+ client = get_client
485
+ response = client.get("/turbosign/documents/#{document_id}/download")
486
+ download_url = response["downloadUrl"]
487
+
488
+ uri = URI.parse(download_url)
489
+ http = Net::HTTP.new(uri.host, uri.port)
490
+ http.use_ssl = uri.scheme == "https"
491
+ file_response = http.request(Net::HTTP::Get.new(uri))
492
+
493
+ unless file_response.is_a?(Net::HTTPSuccess)
494
+ raise TurboDocxError.new("Failed to download file: #{file_response.message}", status_code: file_response.code.to_i)
495
+ end
496
+
497
+ file_response.body
498
+ end
499
+
500
+ # List a template's signer roles, to send it with recipients' +role+.
501
+ #
502
+ # A template whose signers and fields were set up in TurboDocx (upload a PDF, drag fields for
503
+ # each signer, save the signature setup) is sent by naming each recipient's +role+: the fields
504
+ # saved for that role come with it, so +fields+ can be left out. This returns each role's
505
+ # "key" (the value for +role+), in signing order, whether the template has a saved signer
506
+ # used when you leave the role out ("hasSavedSigner", plus "defaultName"/"defaultEmail"), and
507
+ # its "fieldCount".
508
+ #
509
+ # @example
510
+ # setup = TurboDocxSdk::TurboSign.get_template_signature_setup("your-template-id")
511
+ # setup["roles"].first["key"] # => "client"
512
+ #
513
+ # @param template_id [String]
514
+ # @return [Hash] with "templateId" and "roles" (each "key", "label", "order",
515
+ # "hasSavedSigner", optional "defaultName"/"defaultEmail", and "fieldCount")
516
+ # @raise [NotFoundError] (404, code "SignatureSetupNotFound") when the template has no saved
517
+ # signature setup, or is not a template in your organization
518
+ # @raise [AuthenticationError] on invalid credentials
519
+ # @raise [NetworkError] on connection failure
520
+ def get_template_signature_setup(template_id)
521
+ client = get_client
522
+ client.get("/turbosign/templates/#{ERB::Util.url_encode(template_id.to_s)}/signature-setup")
523
+ end
524
+
525
+ # Get the status of a document.
526
+ #
527
+ # The returned Hash carries "status" (e.g. "under_review", "completed", "voided",
528
+ # "expired") and, when expiration is enabled, "expiresAt" — an ISO timestamp for when
529
+ # the signing window closes. "expiresAt" is absent (or nil) when the document never expires.
530
+ #
531
+ # @param document_id [String]
532
+ # @return [Hash] document status, including "expiresAt" when a deadline is set
533
+ # @raise [NotFoundError] if the document does not exist
534
+ # @raise [AuthenticationError] on invalid credentials
535
+ # @raise [NetworkError] on connection failure
536
+ def get_status(document_id)
537
+ client = get_client
538
+ client.get("/turbosign/documents/#{document_id}/status")
539
+ end
540
+
541
+ # Get every recipient on a document with their signing status.
542
+ #
543
+ # Answers "who has signed and who are we still waiting on" in one call, and
544
+ # reports who sent the document.
545
+ #
546
+ # "status" is the raw database value and is only ever "pending", "viewed" or
547
+ # "completed". "effectiveStatus" layers the document's terminal state on top and is
548
+ # what you should display: a signer on a voided or expired document reads
549
+ # "voided"/"expired" there while "status" still says "pending". A completed
550
+ # signature is never revoked.
551
+ #
552
+ # Each recipient's "delivery" is their email history — CC notifications are
553
+ # excluded, since a CC address is not a signer.
554
+ #
555
+ # Two delivery fields are easy to misread:
556
+ # * "reminderCount" counts AUTOMATIC (scheduled) reminders only — the counter
557
+ # maxReminders caps. A manual "remind now" does not increment it (it must not
558
+ # consume the cap budget), though it does land in "totalSent". So it can read 0
559
+ # while reminder emails have genuinely been sent.
560
+ # * "lastRemindedAt" is when the reminder CADENCE CLOCK was last reset, not
561
+ # necessarily when a reminder was sent. The initial signature-request send, each
562
+ # scheduled reminder, each manual "remind now" and each expiry warning all stamp
563
+ # it — so a freshly-sent document normally reads a non-nil "lastRemindedAt"
564
+ # alongside "reminderCount" of 0.
565
+ #
566
+ # "warningCount" / "lastWarningAt" are touched only by an expiry warning.
567
+ #
568
+ # @param document_id [String]
569
+ # @return [Hash] with "document" (id, name, status, createdOn, sentOn, expiresAt,
570
+ # sentBy), "recipients" (each with "status", "effectiveStatus", "signedOn",
571
+ # "signingOrder" and "delivery" = firstSentOn/lastSentOn/totalSent/
572
+ # reminderCount/lastRemindedAt/warningCount/lastWarningAt) and "summary"
573
+ # ("total", "pending", "viewed", "completed", "voided", "expired", "waitingOn")
574
+ # @raise [NotFoundError] if the document does not exist
575
+ # @raise [AuthenticationError] on invalid credentials
576
+ # @raise [NetworkError] on connection failure
577
+ def get_recipients(document_id)
578
+ client = get_client
579
+ client.get("/turbosign/documents/#{document_id}/recipients")
580
+ end
581
+
582
+ private
583
+
584
+ def get_client
585
+ @client ||= HttpClient.new
586
+ end
587
+
588
+ # Read a value from a request/recipient hash, tolerating symbol vs string AND camelCase vs
589
+ # snake_case keys, so idiomatic Ruby snake_case (email_otp, phone_number) resolves the same as
590
+ # the wire's camelCase (emailOtp, phoneNumber). Without the case fold, an idiomatic
591
+ # `auth: { email_otp: true }` would silently be treated as "no identity verification".
592
+ def req_val(hash, key)
593
+ return nil if hash.nil?
594
+
595
+ value = hash[key]
596
+ return value unless value.nil?
597
+ str = key.to_s
598
+ value = hash[str]
599
+ return value unless value.nil?
600
+
601
+ snake = str.gsub(/([a-z0-9])([A-Z])/, '\1_\2').downcase
602
+ camel = str.gsub(/_([a-z0-9])/) { ::Regexp.last_match(1).upcase }
603
+ [snake, camel].each do |variant|
604
+ next if variant == str
605
+
606
+ v = hash[variant.to_sym]
607
+ return v unless v.nil?
608
+
609
+ v = hash[variant]
610
+ return v unless v.nil?
611
+ end
612
+ nil
613
+ end
614
+
615
+ # Two-level +req_val+: the outer key then the inner key, tolerating symbol or string at both.
616
+ def dig_val(hash, outer_key, inner_key)
617
+ inner = req_val(hash, outer_key)
618
+ req_val(inner, inner_key)
619
+ end
620
+
621
+ # Map an embedded recipient's ergonomic +auth+ shorthand to a full identityVerification hash.
622
+ # +emailOtp+ wins if both are set. Returns nil when no auth is requested (no verification).
623
+ def resolve_identity_verification(auth)
624
+ return nil if auth.nil?
625
+ return { "mode" => "otp", "channel" => "email" } if req_val(auth, :emailOtp)
626
+ return { "mode" => "otp", "channel" => "sms" } unless req_val(auth, :sms).nil?
627
+
628
+ nil
629
+ end
630
+
631
+ # Expand a recipient's +fields+ shorthand into full field objects -- one per provided key,
632
+ # anchored to the given text with placement:"replace" and the key's default size.
633
+ def expand_recipient_fields(recipient)
634
+ shorthand = req_val(recipient, :fields)
635
+ return [] if shorthand.nil?
636
+
637
+ email = req_val(recipient, :email)
638
+ EMBEDDED_FIELD_SPECS.each_with_object([]) do |(key, spec), fields|
639
+ anchor = req_val(shorthand, key.to_sym)
640
+ next if anchor.nil?
641
+
642
+ fields << {
643
+ "type" => spec[:type],
644
+ "recipientEmail" => email,
645
+ "template" => { "anchor" => anchor, "placement" => "replace", "size" => spec[:size] }
646
+ }
647
+ end
648
+ end
649
+
650
+ # Mint the embed URL for one already-resolved recipient and build its result entry.
651
+ #
652
+ # Turn-aware: for a real signing order the backend refuses to mint a URL for a signer whose turn
653
+ # hasn't come (+RecipientNotInTurn+ / +NotSignersTurn+) or who already signed
654
+ # (+RecipientAlreadySigned+). Those are expected states, not failures -- degrade to a nil URL +
655
+ # status so the caller can mint the URL later instead of the whole call throwing away. Any
656
+ # OTHER error is a genuine failure and propagates. We rescue the base error class and branch on
657
+ # +code+ alone (never the HTTP status), mirroring the JS surface.
658
+ def mint_embedded_recipient(recipient, recipient_id, document_id, return_url)
659
+ link = create_signing_url(document_id, recipient_id: recipient_id, return_url: return_url)
660
+ {
661
+ "recipientId" => recipient_id,
662
+ "name" => req_val(recipient, :name),
663
+ "email" => req_val(recipient, :email),
664
+ "embedUrl" => link["url"],
665
+ "status" => "ready",
666
+ "identityVerificationMode" => link["identityVerificationMode"]
667
+ }
668
+ rescue TurboDocxError => e
669
+ code = e.code
670
+ raise unless ["RecipientNotInTurn", "NotSignersTurn", "RecipientAlreadySigned"].include?(code)
671
+
672
+ identity_verification = resolve_identity_verification(req_val(recipient, :auth))
673
+ {
674
+ "recipientId" => recipient_id,
675
+ "name" => req_val(recipient, :name),
676
+ "email" => req_val(recipient, :email),
677
+ "embedUrl" => nil,
678
+ "status" => code == "RecipientAlreadySigned" ? "completed" : "pending",
679
+ "identityVerificationMode" => identity_verification && identity_verification["mode"]
680
+ }
681
+ end
682
+
683
+ # Sent as a form field: the API stores it as the document's file name, whatever its extension.
684
+ def with_file_name(form_data, request)
685
+ file_name = request[:fileName] || request["fileName"]
686
+ # An empty fileName is left out: the API rejects an empty one
687
+ file_name.nil? || file_name.to_s.empty? ? form_data : form_data.merge("fileName" => file_name)
688
+ end
689
+
690
+ def build_signature_form_data(request, sender, for_review: false)
691
+ recipients = request[:recipients] || request["recipients"]
692
+ # Without a role the API answers a MISSING "fields" key with 400 FieldsRequired. A review
693
+ # link may have no fields (they are placed in the preview), so it sends []. A send leaves the
694
+ # key out: a role send takes the template's saved fields, and any other send gets
695
+ # FieldsRequired instead of a document with nothing to sign.
696
+ fields = request[:fields] || request["fields"] || []
697
+
698
+ form_data = { "recipients" => JSON.generate(recipients) }
699
+ form_data["fields"] = JSON.generate(fields) if for_review || !fields.empty?
700
+
701
+ doc_name = request[:documentName] || request["documentName"]
702
+ doc_desc = request[:documentDescription] || request["documentDescription"]
703
+ form_data["documentName"] = doc_name if doc_name
704
+ form_data["documentDescription"] = doc_desc if doc_desc
705
+
706
+ req_sender_email = request[:senderEmail] || request["senderEmail"]
707
+ req_sender_name = request[:senderName] || request["senderName"]
708
+ form_data["senderEmail"] = req_sender_email || sender["senderEmail"]
709
+ cfg_name = req_sender_name || sender["senderName"]
710
+ form_data["senderName"] = cfg_name if cfg_name
711
+
712
+ cc = request[:ccEmails] || request["ccEmails"]
713
+ if cc
714
+ cc_array = cc.is_a?(Array) ? cc : [cc]
715
+ form_data["ccEmails"] = JSON.generate(cc_array)
716
+ end
717
+
718
+ apply_schedule_overrides(form_data, request)
719
+
720
+ form_data
721
+ end
722
+
723
+ # Copy per-document reminder/expiration overrides onto an outgoing request body.
724
+ #
725
+ # Durations are JSON-encoded. multipart/form-data has no notion of a nested value, so a
726
+ # { value:, unit: } hash cannot survive the file-upload path as an object. The API decodes a
727
+ # JSON-string duration on both content types, so encoding uniformly keeps one code path for
728
+ # the multipart and JSON branches -- the same treatment recipients and fields already get.
729
+ #
730
+ # Presence is tested with nil?, never truthiness: false (feature off) and 0 (no reminders /
731
+ # never warn) are meaningful values, and Ruby treats 0 as truthy but false as falsey, so a
732
+ # truthiness check would silently drop an explicit "off" and fall back to the org default.
733
+ #
734
+ # Request-body keys stay camelCase -- the API is not snake_case-aware.
735
+ def apply_schedule_overrides(form_data, request)
736
+ # sendEmail rides the same nil?-guarded scalar path: false (suppress recipient emails, the
737
+ # embedded-signing default) is a meaningful value that a truthiness check would silently drop,
738
+ # letting the backend email the recipients. On the multipart upload path it travels as the
739
+ # string "false" via upload_file's value.to_s -- identical treatment to remindersEnabled.
740
+ scalar_keys = %w[sendEmail remindersEnabled maxReminders expirationEnabled]
741
+ scalar_keys.each do |key|
742
+ value = request[key.to_sym]
743
+ value = request[key] if value.nil?
744
+ form_data[key] = value unless value.nil?
745
+ end
746
+
747
+ duration_keys = %w[reminderDelay reminderInterval expireAfter expirationWarning
748
+ expirationWarningInterval]
749
+ duration_keys.each do |key|
750
+ duration = request[key.to_sym]
751
+ duration = request[key] if duration.nil?
752
+ form_data[key] = JSON.generate(duration) unless duration.nil?
753
+ end
754
+ end
755
+ end
756
+ end
757
+ end