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,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "digest"
5
+ require "rbconfig"
6
+
7
+ module TurboDocxSdk
8
+ # Client-context detection for audit-trail device/location reporting.
9
+ #
10
+ # The TurboDocx backend derives the signature audit trail's device + location
11
+ # from the request's User-Agent, X-Timezone, Accept-Language, X-Forwarded-For
12
+ # and X-Device-Fingerprint headers. When the SDK runs in a container/VM these
13
+ # should describe that environment instead of defaulting to a generic
14
+ # User-Agent (recorded as device "Unknown") and a loopback/proxy IP (location
15
+ # "Unknown").
16
+ #
17
+ # The backend only classifies a request as an SDK call when the User-Agent
18
+ # starts with the canonical "@turbodocx/sdk/<version>" token, so the
19
+ # auto-generated User-Agent always uses that prefix.
20
+ #
21
+ # Everything here is best-effort: detection failures degrade to a bare SDK
22
+ # User-Agent rather than raising.
23
+ class ClientContext
24
+ attr_reader :user_agent, :ip_address, :timezone, :language, :device_fingerprint
25
+
26
+ # @param user_agent [String, nil] override the auto-generated descriptive User-Agent
27
+ # @param ip_address [String, nil] client IP reported as X-Forwarded-For for geolocation.
28
+ # Opt-in: omitted by default so a container's private IP never overrides the
29
+ # production load balancer's real public IP (X-Forwarded-For is leftmost-wins).
30
+ # @param timezone [String, nil] override the auto-detected timezone (X-Timezone)
31
+ # @param language [String, nil] override the auto-detected BCP-47 tag (Accept-Language)
32
+ # @param device_fingerprint [String, nil] override the auto-generated device fingerprint
33
+ def initialize(user_agent: nil, ip_address: nil, timezone: nil, language: nil, device_fingerprint: nil)
34
+ @user_agent = user_agent
35
+ @ip_address = ip_address
36
+ @timezone = timezone
37
+ @language = language
38
+ @device_fingerprint = device_fingerprint
39
+ end
40
+
41
+ class << self
42
+ # Resolve the effective client-context request headers, applying caller
43
+ # overrides over auto-detected host values.
44
+ # @param ctx [ClientContext, nil]
45
+ # @return [Hash{String=>String}]
46
+ def resolve_headers(ctx = nil)
47
+ headers = {}
48
+
49
+ headers["User-Agent"] = present(ctx&.user_agent) ? ctx.user_agent : build_default_user_agent
50
+
51
+ timezone = present(ctx&.timezone) ? ctx.timezone : detect_timezone
52
+ headers["X-Timezone"] = timezone if present(timezone)
53
+
54
+ language = present(ctx&.language) ? ctx.language : detect_locale
55
+ headers["Accept-Language"] = language if present(language)
56
+
57
+ fingerprint = present(ctx&.device_fingerprint) ? ctx.device_fingerprint : build_device_fingerprint
58
+ headers["X-Device-Fingerprint"] = fingerprint if present(fingerprint)
59
+
60
+ # Opt-in only (see #ip_address).
61
+ headers["X-Forwarded-For"] = ctx.ip_address if ctx && present(ctx.ip_address)
62
+
63
+ headers
64
+ end
65
+
66
+ # e.g. "@turbodocx/sdk/0.4.0 (Ruby/3.2.2; linux; x86_64; host=svc-1)".
67
+ def build_default_user_agent
68
+ base = "@turbodocx/sdk/#{sdk_version}"
69
+ host = Socket.gethostname
70
+ return base if host.nil? || host.empty?
71
+
72
+ os_name = RbConfig::CONFIG["host_os"]
73
+ arch = RbConfig::CONFIG["host_cpu"]
74
+ "#{base} (Ruby/#{RUBY_VERSION}; #{os_name}; #{arch}; host=#{host})"
75
+ rescue StandardError
76
+ "@turbodocx/sdk/#{sdk_version}"
77
+ end
78
+
79
+ # Detect the host timezone name (e.g. "UTC"); "" if unavailable.
80
+ def detect_timezone
81
+ Time.now.zone.to_s
82
+ rescue StandardError
83
+ ""
84
+ end
85
+
86
+ # Detect the host BCP-47 language tag (e.g. "en-US") from the environment;
87
+ # "" if unavailable or a non-language locale (C/POSIX).
88
+ def detect_locale
89
+ raw = ENV["LC_ALL"] || ENV["LC_MESSAGES"] || ENV["LANG"] || ""
90
+ return "" if raw.empty?
91
+
92
+ tag = raw.split(".").first.to_s.tr("_", "-").strip
93
+ return "" if tag.empty? || %w[C POSIX].include?(tag.upcase)
94
+
95
+ tag
96
+ rescue StandardError
97
+ ""
98
+ end
99
+
100
+ # Stable, non-reversible fingerprint of the host; "" if unavailable.
101
+ def build_device_fingerprint
102
+ host = Socket.gethostname
103
+ return "" if host.nil? || host.empty?
104
+
105
+ seed = [host, RbConfig::CONFIG["host_os"], RbConfig::CONFIG["host_cpu"]].join("|")
106
+ Digest::SHA256.hexdigest(seed)
107
+ rescue StandardError
108
+ ""
109
+ end
110
+
111
+ private
112
+
113
+ def sdk_version
114
+ defined?(TurboDocxSdk::VERSION) ? TurboDocxSdk::VERSION : "0.0.0"
115
+ end
116
+
117
+ def present(value)
118
+ !value.nil? && !value.to_s.empty?
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,184 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TurboDocxSdk
4
+ module QuoteStatus
5
+ DRAFT = "draft"
6
+ PENDING_APPROVAL = "pending_approval"
7
+ SENT = "sent"
8
+ ACCEPTED = "accepted"
9
+ DECLINED = "declined"
10
+ VOIDED = "voided"
11
+ ALL = [DRAFT, PENDING_APPROVAL, SENT, ACCEPTED, DECLINED, VOIDED].freeze
12
+ end
13
+
14
+ module BillingFrequency
15
+ MONTHLY = "monthly"
16
+ QUARTERLY = "quarterly"
17
+ ANNUAL = "annual"
18
+ ONE_TIME = "one-time"
19
+ ALL = [MONTHLY, QUARTERLY, ANNUAL, ONE_TIME].freeze
20
+ end
21
+
22
+ module LineItemType
23
+ PRODUCT = "product"
24
+ BUNDLE = "bundle"
25
+ ALL = [PRODUCT, BUNDLE].freeze
26
+ end
27
+
28
+ module CategoryType
29
+ PRODUCT_CATEGORY = "product_category"
30
+ PRICEBOOK_TYPE = "pricebook_type"
31
+ COMPANY_INDUSTRY = "company_industry"
32
+ BUNDLE_CATEGORY = "bundle_category"
33
+ ALL = [PRODUCT_CATEGORY, PRICEBOOK_TYPE, COMPANY_INDUSTRY, BUNDLE_CATEGORY].freeze
34
+ end
35
+
36
+ module RenewalPeriod
37
+ WEEKLY = "weekly"
38
+ MONTHLY = "monthly"
39
+ QUARTERLY = "quarterly"
40
+ ANNUALLY = "annually"
41
+ ALL = [WEEKLY, MONTHLY, QUARTERLY, ANNUALLY].freeze
42
+ end
43
+
44
+ module Currency
45
+ USD = "USD"
46
+ EUR = "EUR"
47
+ GBP = "GBP"
48
+ CAD = "CAD"
49
+ INR = "INR"
50
+ AUD = "AUD"
51
+ ALL = [USD, EUR, GBP, CAD, INR, AUD].freeze
52
+ end
53
+
54
+ module BundleItemStatus
55
+ ACTIVE = "active"
56
+ PRODUCT_DELETED = "product_deleted"
57
+ PRODUCT_UNAVAILABLE = "product_unavailable"
58
+ CURRENCY_MISMATCH = "currency_mismatch"
59
+ ALL = [ACTIVE, PRODUCT_DELETED, PRODUCT_UNAVAILABLE, CURRENCY_MISMATCH].freeze
60
+ end
61
+
62
+ module DiscountType
63
+ PERCENT = "percent"
64
+ AMOUNT = "amount"
65
+ ALL = [PERCENT, AMOUNT].freeze
66
+ end
67
+
68
+ # Year token included in a generated quote number.
69
+ module QuoteNumberYearToken
70
+ NONE = "none"
71
+ TWO = "two"
72
+ FOUR = "four"
73
+ ALL = [NONE, TWO, FOUR].freeze
74
+ end
75
+
76
+ # Month token included in a generated quote number.
77
+ module QuoteNumberMonthToken
78
+ OFF = "off"
79
+ TWO = "two"
80
+ ALL = [OFF, TWO].freeze
81
+ end
82
+
83
+ # Cadence on which the quote number sequence resets.
84
+ module QuoteNumberResetCadence
85
+ NEVER = "never"
86
+ YEARLY = "yearly"
87
+ MONTHLY = "monthly"
88
+ ALL = [NEVER, YEARLY, MONTHLY].freeze
89
+ end
90
+
91
+ # The 7 TurboSign webhook events (create_webhook / update_webhook +events:+,
92
+ # test_webhook / notify_webhook +event_type:+).
93
+ #
94
+ # +events:+ stays an Array of plain Strings, so raw strings keep working and
95
+ # the backend can add events without a gem release.
96
+ #
97
+ # On every signature, +recipient_signed+ fires first, then exactly one of
98
+ # +completed+ / +finalization_failed+ (that was the final signature) or
99
+ # +signed+ (signers still remain).
100
+ module WebhookEvent
101
+ # The document is dispatched to recipients.
102
+ SENT = "signature.document.sent"
103
+
104
+ # A recipient opens the document for the first time.
105
+ VIEWED = "signature.document.viewed"
106
+
107
+ # Any individual signer completes their signature -- fires ONCE PER SIGNER,
108
+ # including the last one. The payload carries the signer's identity plus
109
+ # +is_final_signer+ (true only on the last signature) and +remaining_signers+.
110
+ #
111
+ # This is the per-person event, and it always fires before the
112
+ # document-level outcome (SIGNED, COMPLETED, or FINALIZATION_FAILED).
113
+ RECIPIENT_SIGNED = "signature.document.recipient_signed"
114
+
115
+ # A signer signs but the document is NOT yet complete -- document-level
116
+ # partial progress.
117
+ #
118
+ # Two consequences worth internalizing:
119
+ # - It NEVER fires on the final signature. To detect "the whole document is
120
+ # done", use COMPLETED (or RECIPIENT_SIGNED with +is_final_signer: true+)
121
+ # -- NOT this event.
122
+ # - A single-signer document never emits it at all. That document emits
123
+ # +recipient_signed+ (+is_final_signer: true+) then +completed+.
124
+ SIGNED = "signature.document.signed"
125
+
126
+ # All recipients have signed and the signed PDF is finalized.
127
+ COMPLETED = "signature.document.completed"
128
+
129
+ # The signed PDF fails to finalize (e.g. a KMS signing error). The document
130
+ # is NOT completed -- this fires INSTEAD OF COMPLETED on the final signature.
131
+ FINALIZATION_FAILED = "signature.document.finalization_failed"
132
+
133
+ # The document is voided or cancelled.
134
+ VOIDED = "signature.document.voided"
135
+
136
+ # All 7 events, in lifecycle order. Pass straight to
137
+ # +create_webhook(events: WebhookEvent::ALL)+ to subscribe to everything.
138
+ ALL = [
139
+ SENT,
140
+ VIEWED,
141
+ RECIPIENT_SIGNED,
142
+ SIGNED,
143
+ COMPLETED,
144
+ FINALIZATION_FAILED,
145
+ VOIDED,
146
+ ].freeze
147
+ end
148
+
149
+ # Granular permission scopes for a TurboPartner API key
150
+ # (create_partner_api_key / update_partner_api_key).
151
+ module PartnerScope
152
+ ORG_CREATE = "org:create"
153
+ ORG_READ = "org:read"
154
+ ORG_UPDATE = "org:update"
155
+ ORG_DELETE = "org:delete"
156
+ ENTITLEMENTS_UPDATE = "entitlements:update"
157
+ ORG_USERS_CREATE = "org-users:create"
158
+ ORG_USERS_READ = "org-users:read"
159
+ ORG_USERS_UPDATE = "org-users:update"
160
+ ORG_USERS_DELETE = "org-users:delete"
161
+ PARTNER_USERS_CREATE = "partner-users:create"
162
+ PARTNER_USERS_READ = "partner-users:read"
163
+ PARTNER_USERS_UPDATE = "partner-users:update"
164
+ PARTNER_USERS_DELETE = "partner-users:delete"
165
+ ORG_APIKEYS_CREATE = "org-apikeys:create"
166
+ ORG_APIKEYS_READ = "org-apikeys:read"
167
+ ORG_APIKEYS_UPDATE = "org-apikeys:update"
168
+ ORG_APIKEYS_DELETE = "org-apikeys:delete"
169
+ PARTNER_APIKEYS_CREATE = "partner-apikeys:create"
170
+ PARTNER_APIKEYS_READ = "partner-apikeys:read"
171
+ PARTNER_APIKEYS_UPDATE = "partner-apikeys:update"
172
+ PARTNER_APIKEYS_DELETE = "partner-apikeys:delete"
173
+ AUDIT_READ = "audit:read"
174
+ ALL = [
175
+ ORG_CREATE, ORG_READ, ORG_UPDATE, ORG_DELETE,
176
+ ENTITLEMENTS_UPDATE,
177
+ ORG_USERS_CREATE, ORG_USERS_READ, ORG_USERS_UPDATE, ORG_USERS_DELETE,
178
+ PARTNER_USERS_CREATE, PARTNER_USERS_READ, PARTNER_USERS_UPDATE, PARTNER_USERS_DELETE,
179
+ ORG_APIKEYS_CREATE, ORG_APIKEYS_READ, ORG_APIKEYS_UPDATE, ORG_APIKEYS_DELETE,
180
+ PARTNER_APIKEYS_CREATE, PARTNER_APIKEYS_READ, PARTNER_APIKEYS_UPDATE, PARTNER_APIKEYS_DELETE,
181
+ AUDIT_READ,
182
+ ].freeze
183
+ end
184
+ end
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "http_client"
5
+
6
+ module TurboDocxSdk
7
+ # Deliverable module -- document generation and management operations.
8
+ #
9
+ # Provides operations for generating documents from templates, managing
10
+ # deliverables, and downloading files.
11
+ #
12
+ # All methods are class-level (static pattern). Call +configure+ once,
13
+ # then invoke any method directly on the class.
14
+ #
15
+ # TurboDocxSdk::Deliverable.configure(api_key: "...", org_id: "...")
16
+ # result = TurboDocxSdk::Deliverable.generate_deliverable(...)
17
+ #
18
+ class Deliverable
19
+ class << self
20
+ # Configure the Deliverable module with API credentials.
21
+ #
22
+ # @param api_key [String, nil]
23
+ # @param access_token [String, nil]
24
+ # @param org_id [String, nil]
25
+ # @param base_url [String, nil]
26
+ # @raise [AuthenticationError] if no API key or access token is provided
27
+ def configure(api_key: nil, access_token: nil, org_id: nil, base_url: nil)
28
+ @client = HttpClient.new(
29
+ api_key: api_key,
30
+ access_token: access_token,
31
+ org_id: org_id,
32
+ base_url: base_url,
33
+ skip_sender_validation: true
34
+ )
35
+ end
36
+
37
+ # ============================================
38
+ # DELIVERABLE CRUD
39
+ # ============================================
40
+
41
+ # List deliverables with pagination, search, and filtering.
42
+ #
43
+ # @param options [Hash, nil] :limit, :offset, :query, :show_tags
44
+ # @return [Hash] { "results" => [...], "totalRecords" => N }
45
+ # @raise [AuthenticationError] on invalid credentials
46
+ # @raise [NetworkError] on connection failure
47
+ def list_deliverables(options = nil)
48
+ client = get_client
49
+ params = {}
50
+
51
+ if options
52
+ limit = fetch_option(options, :limit, "limit")
53
+ offset = fetch_option(options, :offset, "offset")
54
+ query = fetch_option(options, :query, "query")
55
+ show_tags = fetch_option(options, :show_tags, :showTags, "show_tags", "showTags")
56
+
57
+ params[:limit] = limit unless limit.nil?
58
+ params[:offset] = offset unless offset.nil?
59
+ params[:query] = query unless query.nil?
60
+ params[:showTags] = show_tags unless show_tags.nil?
61
+ end
62
+
63
+ client.get("/v1/deliverable", params)
64
+ end
65
+
66
+ # Generate a new deliverable document from a template with variable substitution.
67
+ #
68
+ # @param request [Hash] :templateId (required), :name (required),
69
+ # :variables (Array, required), :description, :tags
70
+ # @return [Hash] { "results" => { "deliverable" => {...} } }
71
+ # @raise [ValidationError] on invalid request data
72
+ # @raise [AuthenticationError] on invalid credentials
73
+ # @raise [NetworkError] on connection failure
74
+ def generate_deliverable(request)
75
+ client = get_client
76
+ client.post("/v1/deliverable", request)
77
+ end
78
+
79
+ # Get full details of a single deliverable, including variables, fonts, and template info.
80
+ #
81
+ # @param id [String]
82
+ # @param options [Hash, nil] :show_tags
83
+ # @return [Hash] the deliverable record
84
+ # @raise [NotFoundError] if the deliverable does not exist
85
+ # @raise [AuthenticationError] on invalid credentials
86
+ # @raise [NetworkError] on connection failure
87
+ def get_deliverable_details(id, options = nil)
88
+ client = get_client
89
+ params = {}
90
+ if options
91
+ show_tags = fetch_option(options, :show_tags, :showTags, "show_tags", "showTags")
92
+ params[:showTags] = show_tags unless show_tags.nil?
93
+ end
94
+
95
+ response = client.get("/v1/deliverable/#{id}", params)
96
+ response["results"]
97
+ end
98
+
99
+ # Update a deliverable's name, description, or tags.
100
+ #
101
+ # Note: When providing tags, all existing tags are replaced.
102
+ #
103
+ # @param id [String]
104
+ # @param request [Hash] :name, :description, :tags (all optional)
105
+ # @return [Hash] { "message" => "...", "deliverableId" => "..." }
106
+ # @raise [NotFoundError] if the deliverable does not exist
107
+ # @raise [ValidationError] on invalid request data
108
+ # @raise [AuthenticationError] on invalid credentials
109
+ # @raise [NetworkError] on connection failure
110
+ def update_deliverable_info(id, request)
111
+ client = get_client
112
+ client.patch("/v1/deliverable/#{id}", request)
113
+ end
114
+
115
+ # Soft-delete a deliverable.
116
+ #
117
+ # @param id [String]
118
+ # @return [Hash] { "message" => "...", "deliverableId" => "..." }
119
+ # @raise [NotFoundError] if the deliverable does not exist
120
+ # @raise [AuthenticationError] on invalid credentials
121
+ # @raise [NetworkError] on connection failure
122
+ def delete_deliverable(id)
123
+ client = get_client
124
+ client.delete("/v1/deliverable/#{id}")
125
+ end
126
+
127
+ # ============================================
128
+ # FILE DOWNLOADS
129
+ # ============================================
130
+
131
+ # Download the original source file (DOCX or PPTX) of a deliverable.
132
+ #
133
+ # @param deliverable_id [String]
134
+ # @return [String] raw file bytes
135
+ # @raise [NotFoundError] if the deliverable does not exist
136
+ # @raise [AuthenticationError] on invalid credentials
137
+ # @raise [NetworkError] on connection failure
138
+ def download_source_file(deliverable_id)
139
+ client = get_client
140
+ client.get_raw("/v1/deliverable/file/#{deliverable_id}")
141
+ end
142
+
143
+ # Download the PDF version of a deliverable.
144
+ #
145
+ # @param deliverable_id [String]
146
+ # @return [String] raw PDF bytes
147
+ # @raise [NotFoundError] if the deliverable does not exist
148
+ # @raise [AuthenticationError] on invalid credentials
149
+ # @raise [NetworkError] on connection failure
150
+ def download_pdf(deliverable_id)
151
+ client = get_client
152
+ client.get_raw("/v1/deliverable/file/pdf/#{deliverable_id}")
153
+ end
154
+
155
+ private
156
+
157
+ # Lazy-initialize an HttpClient from env vars if not configured.
158
+ def get_client
159
+ @client ||= HttpClient.new(skip_sender_validation: true)
160
+ end
161
+
162
+ # Fetch an option value, accepting any of the given keys (symbol or string).
163
+ def fetch_option(options, *keys)
164
+ keys.each do |key|
165
+ return options[key] if options.key?(key)
166
+ end
167
+ nil
168
+ end
169
+ end
170
+ end
171
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TurboDocxSdk
4
+ # Base error class for all TurboDocx SDK errors.
5
+ class TurboDocxError < StandardError
6
+ attr_reader :status_code, :code
7
+
8
+ def initialize(message = "TurboDocx API error", status_code: nil, code: nil)
9
+ @status_code = status_code
10
+ @code = code
11
+ super(message)
12
+ end
13
+ end
14
+
15
+ # Raised when authentication fails (HTTP 401).
16
+ class AuthenticationError < TurboDocxError
17
+ def initialize(message = "Authentication failed", code: nil)
18
+ super(message, status_code: 401, code: code || "AUTHENTICATION_ERROR")
19
+ end
20
+ end
21
+
22
+ # Raised when the caller is authenticated but lacks the required permissions (HTTP 403).
23
+ class AuthorizationError < TurboDocxError
24
+ def initialize(message = "Forbidden: API key lacks required permissions", code: nil)
25
+ super(message, status_code: 403, code: code || "AUTHORIZATION_ERROR")
26
+ end
27
+ end
28
+
29
+ # Raised when request validation fails (HTTP 400).
30
+ class ValidationError < TurboDocxError
31
+ def initialize(message, code: nil)
32
+ super(message, status_code: 400, code: code || "VALIDATION_ERROR")
33
+ end
34
+ end
35
+
36
+ # Raised when the requested resource is not found (HTTP 404).
37
+ class NotFoundError < TurboDocxError
38
+ def initialize(message = "Resource not found", code: nil)
39
+ super(message, status_code: 404, code: code || "NOT_FOUND")
40
+ end
41
+ end
42
+
43
+ # Raised when a request conflicts with the current resource state (HTTP 409).
44
+ class ConflictError < TurboDocxError
45
+ def initialize(message = "Conflict with existing resource", code: nil)
46
+ super(message, status_code: 409, code: code || "CONFLICT")
47
+ end
48
+ end
49
+
50
+ # Raised when rate limit is exceeded (HTTP 429).
51
+ class RateLimitError < TurboDocxError
52
+ def initialize(message = "Rate limit exceeded", code: nil)
53
+ super(message, status_code: 429, code: code || "RATE_LIMIT_EXCEEDED")
54
+ end
55
+ end
56
+
57
+ # Raised on network/connection failures (no HTTP status).
58
+ class NetworkError < TurboDocxError
59
+ def initialize(message)
60
+ super(message, status_code: nil, code: "NETWORK_ERROR")
61
+ end
62
+ end
63
+ end