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,1186 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "stringio"
5
+ require_relative "http_client"
6
+
7
+ module TurboDocxSdk
8
+ # TurboQuote module -- quoting operations.
9
+ #
10
+ # All methods are class-level (static pattern). Call +configure+ once,
11
+ # then invoke any method directly on the class.
12
+ #
13
+ # TurboDocxSdk::TurboQuote.configure(api_key: "...", org_id: "...")
14
+ # quotes = TurboDocxSdk::TurboQuote.list_quotes(limit: 10)
15
+ #
16
+ class TurboQuote
17
+ class << self
18
+ # Configure the TurboQuote module with API credentials.
19
+ #
20
+ # @param api_key [String, nil]
21
+ # @param access_token [String, nil]
22
+ # @param org_id [String, nil]
23
+ # @param base_url [String, nil]
24
+ # @raise [AuthenticationError] if no API key or access token is provided
25
+ def configure(api_key: nil, access_token: nil, org_id: nil, base_url: nil)
26
+ @client = HttpClient.new(
27
+ api_key: api_key,
28
+ access_token: access_token,
29
+ org_id: org_id,
30
+ base_url: base_url,
31
+ skip_sender_validation: true
32
+ )
33
+ end
34
+
35
+ # ============================================
36
+ # QUOTES -- CRUD
37
+ # ============================================
38
+
39
+ # List quotes with optional pagination and filters.
40
+ #
41
+ # @param options [Hash, nil] :limit, :offset, :query, :statuses, :companyId, :contactId, :currency
42
+ # @return [Hash] { "results" => [...], "totalRecords" => N, "stats" => {...} }
43
+ # @raise [AuthenticationError] on invalid credentials
44
+ # @raise [NetworkError] on connection failure
45
+ def list_quotes(options = nil)
46
+ client = get_client
47
+ client.get("/v1/quotes", to_query_params(options))
48
+ end
49
+
50
+ # Create a new quote.
51
+ #
52
+ # @param request [Hash] :name (required), :companyId (required), :contactId (required),
53
+ # :currency, :termDays, :renewalPeriod, :validUntil, :taxRate, :priceBookId
54
+ #
55
+ # +termDays+ defaults to 60 and maxes out at 3650. Pass +-1+ for auto-renewal:
56
+ # +renewalPeriod+ (one of RenewalPeriod::ALL) is REQUIRED when +termDays+ is +-1+
57
+ # and must be omitted/nil for every other +termDays+ value.
58
+ # @return [Hash] the created quote
59
+ # @raise [ValidationError] on invalid request data
60
+ # @raise [AuthenticationError] on invalid credentials
61
+ # @raise [NetworkError] on connection failure
62
+ def create_quote(request)
63
+ client = get_client
64
+ unwrap(client.post("/v1/quotes", request))
65
+ end
66
+
67
+ # Get a quote by ID.
68
+ #
69
+ # @param id [String]
70
+ # @return [Hash] the quote, with "statusInfo" and "preparedBy" merged in if present
71
+ # @raise [NotFoundError] if the quote does not exist
72
+ # @raise [AuthenticationError] on invalid credentials
73
+ # @raise [NetworkError] on connection failure
74
+ #
75
+ # "preparedBy" is the resolved "Prepared by" identity ({ "name", "email" }) shown on the
76
+ # quote PDF and preview. Resolved server-side from the org template then the creator; for
77
+ # an API-key-created quote it is the API key's label with no email. Prefer it over
78
+ # "creator" for customer-facing display — "creator" may be the internal API service user.
79
+ def get_quote(id)
80
+ client = get_client
81
+ response = client.get("/v1/quotes/#{id}")
82
+ quote = response["result"]
83
+ quote["statusInfo"] = response["statusInfo"] if response["statusInfo"]
84
+ quote["preparedBy"] = response["preparedBy"] if response["preparedBy"]
85
+ quote
86
+ end
87
+
88
+ # Update a quote.
89
+ #
90
+ # @param id [String]
91
+ # @param request [Hash] fields to update
92
+ # @return [Hash] the updated quote
93
+ # @raise [NotFoundError] if the quote does not exist
94
+ # @raise [ValidationError] on invalid request data
95
+ # @raise [AuthenticationError] on invalid credentials
96
+ # @raise [NetworkError] on connection failure
97
+ def update_quote(id, request)
98
+ client = get_client
99
+ unwrap(client.patch("/v1/quotes/#{id}", request))
100
+ end
101
+
102
+ # Delete a quote.
103
+ #
104
+ # @param id [String]
105
+ # @return [Hash] { "message" => "..." }
106
+ # @raise [NotFoundError] if the quote does not exist
107
+ # @raise [AuthenticationError] on invalid credentials
108
+ # @raise [NetworkError] on connection failure
109
+ def delete_quote(id)
110
+ client = get_client
111
+ client.delete("/v1/quotes/#{id}")
112
+ end
113
+
114
+ # Duplicate a quote.
115
+ #
116
+ # @param id [String]
117
+ # @return [Hash] the duplicated quote
118
+ # @raise [NotFoundError] if the quote does not exist
119
+ # @raise [AuthenticationError] on invalid credentials
120
+ # @raise [NetworkError] on connection failure
121
+ def duplicate_quote(id)
122
+ client = get_client
123
+ unwrap(client.post("/v1/quotes/#{id}/duplicate"))
124
+ end
125
+
126
+ # Apply a price book to a quote.
127
+ #
128
+ # @param quote_id [String]
129
+ # @param price_book_id [String]
130
+ # @return [Hash] { "quote" => {...}, "message" => "...", "updatedCount" => N, "skippedCount" => N }
131
+ # @raise [NotFoundError] if the quote does not exist
132
+ # @raise [ValidationError] on invalid request data
133
+ # @raise [AuthenticationError] on invalid credentials
134
+ # @raise [NetworkError] on connection failure
135
+ def apply_price_book(quote_id, price_book_id)
136
+ client = get_client
137
+ response = client.post("/v1/quotes/#{quote_id}/apply-pricebook", { "priceBookId" => price_book_id })
138
+ {
139
+ "quote" => response["result"],
140
+ "message" => response["message"],
141
+ "updatedCount" => response["updatedCount"],
142
+ "skippedCount" => response["skippedCount"]
143
+ }
144
+ end
145
+
146
+ # Remove a price book from a quote.
147
+ #
148
+ # @param quote_id [String]
149
+ # @return [Hash] the updated quote
150
+ # @raise [NotFoundError] if the quote does not exist
151
+ # @raise [AuthenticationError] on invalid credentials
152
+ # @raise [NetworkError] on connection failure
153
+ def remove_price_book(quote_id)
154
+ client = get_client
155
+ unwrap(client.post("/v1/quotes/#{quote_id}/remove-pricebook"))
156
+ end
157
+
158
+ # Download a quote as PDF (raw binary).
159
+ #
160
+ # @param id [String]
161
+ # @return [String] raw PDF bytes
162
+ # @raise [NotFoundError] if the quote does not exist
163
+ # @raise [AuthenticationError] on invalid credentials
164
+ # @raise [NetworkError] on connection failure
165
+ def download_quote_pdf(id)
166
+ client = get_client
167
+ client.get_raw("/v1/quotes/#{id}/pdf")
168
+ end
169
+
170
+ # ============================================
171
+ # QUOTES -- STATUS TRANSITIONS
172
+ # ============================================
173
+
174
+ # Send a quote.
175
+ #
176
+ # The +request+ hash is forwarded to the API verbatim as the JSON body, so any camelCase
177
+ # key the endpoint accepts flows through untouched -- no key is whitelisted or re-cased.
178
+ #
179
+ # @param id [String]
180
+ # @param request [Hash, nil] :ccEmails, :validUntil, and the optional reminder/expiration
181
+ # SCHEDULE fields (same eight as +TurboSign.send_signature+, sent FLAT on the JSON body):
182
+ # - +remindersEnabled+ [Boolean], +maxReminders+ [Integer], +expirationEnabled+ [Boolean]
183
+ # - +reminderDelay+ / +reminderInterval+ / +expireAfter+ / +expirationWarning+ /
184
+ # +expirationWarningInterval+ — each a duration +{ value:, unit: }+ (plain object; this
185
+ # is a JSON endpoint, so durations are NOT JSON-encoded the way the multipart signature
186
+ # path encodes them). Keys are camelCase like every other send key.
187
+ # CONSTRAINT: quote expiry is pinned to +validUntil+, so +expireAfter+ is ignored when
188
+ # expiration is on (+expirationEnabled+ still toggles it); the reminder/warning cadence
189
+ # applies (layered over org defaults) and must fit within +validUntil+ or the send is rejected.
190
+ # @return [Hash] { "quote" => {...}, "message" => "..." }
191
+ # @raise [NotFoundError] if the quote does not exist
192
+ # @raise [ValidationError] on invalid request data
193
+ # @raise [AuthenticationError] on invalid credentials
194
+ # @raise [NetworkError] on connection failure
195
+ def send_quote(id, request = nil)
196
+ client = get_client
197
+ response = client.post("/v1/quotes/#{id}/send", request)
198
+ {
199
+ "quote" => response["result"],
200
+ "message" => response["message"]
201
+ }
202
+ end
203
+
204
+ # Send a quote with a deliverable attachment.
205
+ #
206
+ # Like +send_quote+, the +request+ hash is forwarded to the API verbatim as the JSON body.
207
+ #
208
+ # @param id [String]
209
+ # @param request [Hash] :deliverableId, :mergePosition, :ccEmails, and the same
210
+ # optional reminder/expiration SCHEDULE fields as +send_quote+ (the eight camelCase keys:
211
+ # +remindersEnabled+, +maxReminders+, +expirationEnabled+ scalars plus +reminderDelay+ /
212
+ # +reminderInterval+ / +expireAfter+ / +expirationWarning+ / +expirationWarningInterval+
213
+ # durations as plain +{ value:, unit: }+ objects), sent FLAT on the JSON body.
214
+ # CONSTRAINT: quote expiry is pinned to +validUntil+, so +expireAfter+ is ignored when
215
+ # expiration is on (+expirationEnabled+ still toggles it); the reminder/warning cadence
216
+ # applies (layered over org defaults) and must fit within +validUntil+ or the send is rejected.
217
+ # @return [Hash] { "quote" => {...}, "message" => "...", "documentId" => "..." }
218
+ # @raise [NotFoundError] if the quote does not exist
219
+ # @raise [ValidationError] on invalid request data
220
+ # @raise [AuthenticationError] on invalid credentials
221
+ # @raise [NetworkError] on connection failure
222
+ def send_quote_with_deliverable(id, request)
223
+ client = get_client
224
+ response = client.post("/v1/quotes/#{id}/send-with-deliverable", request)
225
+ {
226
+ "quote" => response["result"],
227
+ "message" => response["message"],
228
+ "documentId" => response["documentId"]
229
+ }
230
+ end
231
+
232
+ # Decline a quote.
233
+ #
234
+ # @param id [String]
235
+ # @param request [Hash] :reason
236
+ # @return [Hash] the declined quote
237
+ # @raise [NotFoundError] if the quote does not exist
238
+ # @raise [ValidationError] on invalid request data
239
+ # @raise [AuthenticationError] on invalid credentials
240
+ # @raise [NetworkError] on connection failure
241
+ def decline_quote(id, request)
242
+ client = get_client
243
+ unwrap(client.post("/v1/quotes/#{id}/decline", request))
244
+ end
245
+
246
+ # Void a quote.
247
+ #
248
+ # @param id [String]
249
+ # @param request [Hash] :reason
250
+ # @return [Hash] the voided quote
251
+ # @raise [NotFoundError] if the quote does not exist
252
+ # @raise [ValidationError] on invalid request data
253
+ # @raise [AuthenticationError] on invalid credentials
254
+ # @raise [NetworkError] on connection failure
255
+ def void_quote(id, request)
256
+ client = get_client
257
+ unwrap(client.post("/v1/quotes/#{id}/void", request))
258
+ end
259
+
260
+ # Handle an expired sent quote. Voids or declines the original quote and
261
+ # creates a duplicate carrying the new +newValidUntil+ date.
262
+ #
263
+ # @param id [String]
264
+ # @param request [Hash] all three keys are required:
265
+ # - +action+ [String] — +"void"+ or +"decline"+ (no other value is accepted)
266
+ # - +reason+ [String] — max 190 characters
267
+ # - +newValidUntil+ [String] — ISO 8601 date for the replacement quote
268
+ # @return [Hash] the processed quote
269
+ # @raise [NotFoundError] if the quote does not exist
270
+ # @raise [ValidationError] on invalid request data
271
+ # @raise [AuthenticationError] on invalid credentials
272
+ # @raise [NetworkError] on connection failure
273
+ def handle_expired_quote(id, request)
274
+ client = get_client
275
+ unwrap(client.post("/v1/quotes/#{id}/handle-expired-sent", request))
276
+ end
277
+
278
+ # ============================================
279
+ # LINE ITEMS
280
+ # ============================================
281
+
282
+ # List line items for a quote.
283
+ #
284
+ # @param quote_id [String]
285
+ # @param options [Hash, nil] :limit, :offset, :lineItemType, :billingFrequency, :parentLineItemId
286
+ # @return [Hash] { "results" => [...], "totalRecords" => N }
287
+ # @raise [NotFoundError] if the quote does not exist
288
+ # @raise [AuthenticationError] on invalid credentials
289
+ # @raise [NetworkError] on connection failure
290
+ def list_line_items(quote_id, options = nil)
291
+ client = get_client
292
+ client.get("/v1/quotes/#{quote_id}/items", to_query_params(options))
293
+ end
294
+
295
+ # Add product line items to a quote.
296
+ #
297
+ # @param quote_id [String]
298
+ # @param items [Hash, Array<Hash>] single item or array of items (1-50). Each item includes:
299
+ # - +productId+ [String, nil] — REQUIRED key; catalog product ID (uuid).
300
+ # The value may be +nil+ for an ad-hoc item, but the key must be present.
301
+ # - +productName+ [String] — REQUIRED; display name
302
+ # - +unitPrice+ [Numeric] — REQUIRED; price per unit
303
+ # - +billingFrequency+ [String] — REQUIRED; one of BillingFrequency::ALL
304
+ # - +quantity+ [Integer] — default 1
305
+ # - +discountType+ [String, nil] — +"percent"+ or +"amount"+ (default +"percent"+);
306
+ # see DiscountType
307
+ # - +discountAmount+ [Numeric, nil] — discount value (min 0, 2 decimal places, default 0)
308
+ # @return [Array<Hash>] the created line items
309
+ # @raise [NotFoundError] if the quote does not exist
310
+ # @raise [ValidationError] on invalid request data
311
+ # @raise [AuthenticationError] on invalid credentials
312
+ # @raise [NetworkError] on connection failure
313
+ def add_line_items(quote_id, items)
314
+ client = get_client
315
+ payload = items.is_a?(Array) ? items : [items]
316
+ response = client.post("/v1/quotes/#{quote_id}/items", payload)
317
+ response["results"]
318
+ end
319
+
320
+ # Add bundle line items to a quote. The server expands the bundle's children
321
+ # itself -- do NOT send child products.
322
+ #
323
+ # @param quote_id [String]
324
+ # @param items [Hash, Array<Hash>] single item or array of items (1-50). Each item includes:
325
+ # - +bundleId+ [String] — REQUIRED; catalog bundle ID
326
+ # - +bundleName+ [String] — REQUIRED; display name
327
+ # - +quantity+ [Integer]
328
+ # - +discountType+ [String, nil] — +"percent"+ or +"amount"+ (default +"percent"+);
329
+ # see DiscountType
330
+ # - +discountAmount+ [Numeric, nil] — discount value (min 0, 2 decimal places, default 0)
331
+ # @return [Array<Hash>] the created line items
332
+ # @raise [NotFoundError] if the quote does not exist
333
+ # @raise [ValidationError] on invalid request data
334
+ # @raise [AuthenticationError] on invalid credentials
335
+ # @raise [NetworkError] on connection failure
336
+ def add_bundle_line_items(quote_id, items)
337
+ client = get_client
338
+ payload = items.is_a?(Array) ? items : [items]
339
+ response = client.post("/v1/quotes/#{quote_id}/items/bundle", payload)
340
+ response["results"]
341
+ end
342
+
343
+ # Update a line item.
344
+ #
345
+ # @param quote_id [String]
346
+ # @param item_id [String]
347
+ # @param request [Hash] fields to update. May include:
348
+ # - +unitPrice+ [Numeric]
349
+ # - +quantity+ [Integer]
350
+ # - +discountType+ [String, nil] — +"percent"+ or +"amount"+; see DiscountType
351
+ # - +discountAmount+ [Numeric, nil] — discount value (min 0, 2 decimal places)
352
+ # - +displayOrder+ [Integer, nil] — sort order (integer >=0); pass +nil+ to clear
353
+ # @return [Hash] the updated line item
354
+ # @raise [NotFoundError] if the quote or line item does not exist
355
+ # @raise [ValidationError] on invalid request data
356
+ # @raise [AuthenticationError] on invalid credentials
357
+ # @raise [NetworkError] on connection failure
358
+ def update_line_item(quote_id, item_id, request)
359
+ client = get_client
360
+ unwrap(client.patch("/v1/quotes/#{quote_id}/items/#{item_id}", request))
361
+ end
362
+
363
+ # Remove a line item from a quote.
364
+ #
365
+ # @param quote_id [String]
366
+ # @param item_id [String]
367
+ # @return [Hash] { "message" => "..." }
368
+ # @raise [NotFoundError] if the quote or line item does not exist
369
+ # @raise [AuthenticationError] on invalid credentials
370
+ # @raise [NetworkError] on connection failure
371
+ def remove_line_item(quote_id, item_id)
372
+ client = get_client
373
+ client.delete("/v1/quotes/#{quote_id}/items/#{item_id}")
374
+ end
375
+
376
+ # ============================================
377
+ # PRODUCTS
378
+ # ============================================
379
+
380
+ # List products with optional filters.
381
+ #
382
+ # @param options [Hash, nil] :limit, :offset, :query, :categoryIds, :billingFrequency, :currency, :showInCatalog
383
+ # @return [Hash] paginated response with stats
384
+ # @raise [AuthenticationError] on invalid credentials
385
+ # @raise [NetworkError] on connection failure
386
+ def list_products(options = nil)
387
+ client = get_client
388
+ client.get("/v1/products", to_query_params(options))
389
+ end
390
+
391
+ # Create a product.
392
+ #
393
+ # @param request [Hash] product fields; may include :images (array of file paths or IO)
394
+ # @return [Hash] the created product
395
+ # @raise [ValidationError] on invalid request data
396
+ # @raise [AuthenticationError] on invalid credentials
397
+ # @raise [NetworkError] on connection failure
398
+ def create_product(request)
399
+ client = get_client
400
+ data = request.dup
401
+ images = data.delete("images") || data.delete(:images)
402
+ if images && !images.empty?
403
+ form_data = build_product_form_data(data, images)
404
+ unwrap(client.post_form_data("/v1/products", form_data))
405
+ else
406
+ unwrap(client.post("/v1/products", data))
407
+ end
408
+ end
409
+
410
+ # Bulk create products (administrator or contributor). Partial success:
411
+ # rows that fail are reported in "failed" (1-indexed "row" + "reason")
412
+ # without aborting the rest; server-adjusted rows appear in "adjusted".
413
+ #
414
+ # @param rows [Array<Hash>] product rows, same field shapes as +create_product+.
415
+ # Each row requires +name+, +categoryId+ (a TurboQuote type uuid — there is no
416
+ # +categoryName+ shorthand; resolve or create the category first), +listPrice+
417
+ # and +billingFrequency+.
418
+ # @return [Hash] { "imported" => N, "failed" => [...], "adjusted" => [...] }
419
+ # @raise [ValidationError] on an invalid request envelope
420
+ # @raise [AuthenticationError] on invalid credentials
421
+ # @raise [NetworkError] on connection failure
422
+ def bulk_create_products(rows)
423
+ client = get_client
424
+ response = client.post("/v1/products/bulk", { "rows" => rows })
425
+ response["results"]
426
+ end
427
+
428
+ # Get a product by ID.
429
+ #
430
+ # @param id [String]
431
+ # @return [Hash] the product
432
+ # @raise [NotFoundError] if the product does not exist
433
+ # @raise [AuthenticationError] on invalid credentials
434
+ # @raise [NetworkError] on connection failure
435
+ def get_product(id)
436
+ client = get_client
437
+ unwrap(client.get("/v1/products/#{id}"))
438
+ end
439
+
440
+ # Update a product.
441
+ #
442
+ # @param id [String]
443
+ # @param request [Hash] fields to update; may include :images
444
+ # @return [Hash] the updated product
445
+ # @raise [NotFoundError] if the product does not exist
446
+ # @raise [ValidationError] on invalid request data
447
+ # @raise [AuthenticationError] on invalid credentials
448
+ # @raise [NetworkError] on connection failure
449
+ def update_product(id, request)
450
+ client = get_client
451
+ data = request.dup
452
+ images = data.delete("images") || data.delete(:images)
453
+ if images && !images.empty?
454
+ form_data = build_product_form_data(data, images)
455
+ unwrap(client.patch_form_data("/v1/products/#{id}", form_data))
456
+ else
457
+ unwrap(client.patch("/v1/products/#{id}", data))
458
+ end
459
+ end
460
+
461
+ # Delete a product.
462
+ #
463
+ # @param id [String]
464
+ # @return [Hash] { "message" => "..." }
465
+ # @raise [NotFoundError] if the product does not exist
466
+ # @raise [AuthenticationError] on invalid credentials
467
+ # @raise [NetworkError] on connection failure
468
+ def delete_product(id)
469
+ client = get_client
470
+ client.delete("/v1/products/#{id}")
471
+ end
472
+
473
+ # Duplicate a product.
474
+ #
475
+ # @param id [String]
476
+ # @return [Hash] the duplicated product
477
+ # @raise [NotFoundError] if the product does not exist
478
+ # @raise [AuthenticationError] on invalid credentials
479
+ # @raise [NetworkError] on connection failure
480
+ def duplicate_product(id)
481
+ client = get_client
482
+ unwrap(client.post("/v1/products/#{id}/duplicate"))
483
+ end
484
+
485
+ # Get primary images for multiple products.
486
+ #
487
+ # @param product_ids [Array<String>]
488
+ # @return [Hash] product_id => image_hash or nil
489
+ # @raise [AuthenticationError] on invalid credentials
490
+ # @raise [NetworkError] on connection failure
491
+ def get_product_primary_images(product_ids)
492
+ client = get_client
493
+ response = client.post("/v1/products/primary-images", { "productIds" => product_ids })
494
+ response["results"]
495
+ end
496
+
497
+ # ============================================
498
+ # PRICE BOOKS
499
+ # ============================================
500
+
501
+ # List price books.
502
+ #
503
+ # @param options [Hash, nil]
504
+ # @return [Hash] paginated response with stats
505
+ # @raise [AuthenticationError] on invalid credentials
506
+ # @raise [NetworkError] on connection failure
507
+ def list_price_books(options = nil)
508
+ client = get_client
509
+ client.get("/v1/pricebooks", to_query_params(options))
510
+ end
511
+
512
+ # Create a price book.
513
+ #
514
+ # @param request [Hash] price book fields. May include:
515
+ # - +name+ [String]
516
+ # - +priceBookTypeId+ [String]
517
+ # - +discountPercent+ [Numeric] — default discount for all products in this book
518
+ # - +validFrom+ [String] — ISO date
519
+ # - +validTo+ [String] — ISO date
520
+ # - +showInQuoteBuilder+ [Boolean]
521
+ # - +productPricing+ [Array<Hash>] — per-product overrides; each entry may include:
522
+ # +:productId+, +:discountType+ (+"percent"+|+"amount"+), +:discountAmount+ (Numeric)
523
+ # @return [Hash] the created price book
524
+ # @raise [ValidationError] on invalid request data
525
+ # @raise [AuthenticationError] on invalid credentials
526
+ # @raise [NetworkError] on connection failure
527
+ def create_price_book(request)
528
+ client = get_client
529
+ # Backend requires discountPercent on POST (omitting it 400s) and rejects null; coerce a
530
+ # missing OR explicit-nil value to the documented default 0 (matches JS/Go/PHP/Java).
531
+ data = request.dup
532
+ dp = data["discountPercent"]
533
+ dp = data[:discountPercent] if dp.nil?
534
+ if dp.nil?
535
+ data.delete(:discountPercent)
536
+ data["discountPercent"] = 0
537
+ end
538
+ unwrap(client.post("/v1/pricebooks", data))
539
+ end
540
+
541
+ # Bulk create price books (administrator or contributor). Partial success:
542
+ # rows that fail are reported in "failed" (1-indexed "row" + "reason")
543
+ # without aborting the rest; server-adjusted rows appear in "adjusted".
544
+ #
545
+ # @param rows [Array<Hash>] price book rows, same field shapes as +create_price_book+
546
+ # @return [Hash] { "imported" => N, "failed" => [...], "adjusted" => [...] }
547
+ # @raise [ValidationError] on an invalid request envelope
548
+ # @raise [AuthenticationError] on invalid credentials
549
+ # @raise [NetworkError] on connection failure
550
+ def bulk_create_price_books(rows)
551
+ client = get_client
552
+ response = client.post("/v1/pricebooks/bulk", { "rows" => rows })
553
+ response["results"]
554
+ end
555
+
556
+ # Get a price book by ID.
557
+ #
558
+ # @param id [String]
559
+ # @return [Hash] the price book
560
+ # @raise [NotFoundError] if the price book does not exist
561
+ # @raise [AuthenticationError] on invalid credentials
562
+ # @raise [NetworkError] on connection failure
563
+ def get_price_book(id)
564
+ client = get_client
565
+ unwrap(client.get("/v1/pricebooks/#{id}"))
566
+ end
567
+
568
+ # Update a price book.
569
+ #
570
+ # @param id [String]
571
+ # @param request [Hash] fields to update. May include:
572
+ # - +productPricing+ [Array<Hash>] — per-product overrides; each entry may include:
573
+ # +:productId+, +:discountType+ (+"percent"+|+"amount"+), +:discountAmount+ (Numeric)
574
+ # @return [Hash] the updated price book
575
+ # @raise [NotFoundError] if the price book does not exist
576
+ # @raise [ValidationError] on invalid request data
577
+ # @raise [AuthenticationError] on invalid credentials
578
+ # @raise [NetworkError] on connection failure
579
+ def update_price_book(id, request)
580
+ client = get_client
581
+ unwrap(client.patch("/v1/pricebooks/#{id}", request))
582
+ end
583
+
584
+ # Delete a price book.
585
+ #
586
+ # @param id [String]
587
+ # @return [Hash] { "message" => "..." }
588
+ # @raise [NotFoundError] if the price book does not exist
589
+ # @raise [AuthenticationError] on invalid credentials
590
+ # @raise [NetworkError] on connection failure
591
+ def delete_price_book(id)
592
+ client = get_client
593
+ client.delete("/v1/pricebooks/#{id}")
594
+ end
595
+
596
+ # Duplicate a price book.
597
+ #
598
+ # @param id [String]
599
+ # @return [Hash] the duplicated price book
600
+ # @raise [NotFoundError] if the price book does not exist
601
+ # @raise [AuthenticationError] on invalid credentials
602
+ # @raise [NetworkError] on connection failure
603
+ def duplicate_price_book(id)
604
+ client = get_client
605
+ unwrap(client.post("/v1/pricebooks/#{id}/duplicate"))
606
+ end
607
+
608
+ # List products in a price book.
609
+ #
610
+ # @param id [String]
611
+ # @param options [Hash, nil]
612
+ # @return [Hash] paginated response
613
+ # @raise [NotFoundError] if the price book does not exist
614
+ # @raise [AuthenticationError] on invalid credentials
615
+ # @raise [NetworkError] on connection failure
616
+ def list_price_book_products(id, options = nil)
617
+ client = get_client
618
+ client.get("/v1/pricebooks/#{id}/products", to_query_params(options))
619
+ end
620
+
621
+ # ============================================
622
+ # BUNDLES
623
+ # ============================================
624
+
625
+ # List bundles.
626
+ #
627
+ # @param options [Hash, nil]
628
+ # @return [Hash] paginated response with stats
629
+ # @raise [AuthenticationError] on invalid credentials
630
+ # @raise [NetworkError] on connection failure
631
+ def list_bundles(options = nil)
632
+ client = get_client
633
+ client.get("/v1/bundles", to_query_params(options))
634
+ end
635
+
636
+ # Create a bundle.
637
+ #
638
+ # @param request [Hash] bundle fields. Required: +:categoryId+. Optional fields include:
639
+ # - +name+ [String]
640
+ # - +categoryId+ [String] — REQUIRED; bundle category ID
641
+ # - +sku+ [String]
642
+ # - +description+ [String]
643
+ # - +currency+ [String] — see Currency
644
+ # - +bundleDiscountType+ [String, nil] — +"percent"+ or +"amount"+; see DiscountType
645
+ # - +bundleDiscountAmount+ [Numeric, nil] — bundle-level discount value (min 0, 2 decimal places)
646
+ # - +showInCatalog+ [Boolean]
647
+ # - +showItemsToEndUser+ [Boolean]
648
+ # - +items+ [Array<Hash>] — bundle item inputs; each may include +discountType+, +discountAmount+
649
+ # @return [Hash] the created bundle
650
+ # @raise [ValidationError] on invalid request data
651
+ # @raise [AuthenticationError] on invalid credentials
652
+ # @raise [NetworkError] on connection failure
653
+ def create_bundle(request)
654
+ client = get_client
655
+ unwrap(client.post("/v1/bundles", request))
656
+ end
657
+
658
+ # Bulk create bundles (administrator or contributor). Partial success:
659
+ # rows that fail are reported in "failed" (1-indexed "row" + "reason")
660
+ # without aborting the rest; server-adjusted rows appear in "adjusted"
661
+ # (e.g. a bundle item whose product wasn't found was dropped).
662
+ #
663
+ # @param rows [Array<Hash>] bundle rows, same field shapes as +create_bundle+
664
+ # @return [Hash] { "imported" => N, "failed" => [...], "adjusted" => [...] }
665
+ # @raise [ValidationError] on an invalid request envelope
666
+ # @raise [AuthenticationError] on invalid credentials
667
+ # @raise [NetworkError] on connection failure
668
+ def bulk_create_bundles(rows)
669
+ client = get_client
670
+ response = client.post("/v1/bundles/bulk", { "rows" => rows })
671
+ response["results"]
672
+ end
673
+
674
+ # Get a bundle by ID.
675
+ #
676
+ # @param id [String]
677
+ # @return [Hash] the bundle
678
+ # @raise [NotFoundError] if the bundle does not exist
679
+ # @raise [AuthenticationError] on invalid credentials
680
+ # @raise [NetworkError] on connection failure
681
+ def get_bundle(id)
682
+ client = get_client
683
+ unwrap(client.get("/v1/bundles/#{id}"))
684
+ end
685
+
686
+ # Update a bundle.
687
+ #
688
+ # @param id [String]
689
+ # @param request [Hash] fields to update. May include:
690
+ # - +bundleDiscountType+ [String, nil] — +"percent"+ or +"amount"+; see DiscountType
691
+ # - +bundleDiscountAmount+ [Numeric, nil] — bundle-level discount value (min 0, 2 decimal places)
692
+ # @return [Hash] the updated bundle
693
+ # @raise [NotFoundError] if the bundle does not exist
694
+ # @raise [ValidationError] on invalid request data
695
+ # @raise [AuthenticationError] on invalid credentials
696
+ # @raise [NetworkError] on connection failure
697
+ def update_bundle(id, request)
698
+ client = get_client
699
+ unwrap(client.patch("/v1/bundles/#{id}", request))
700
+ end
701
+
702
+ # Delete a bundle.
703
+ #
704
+ # @param id [String]
705
+ # @return [Hash] { "message" => "..." }
706
+ # @raise [NotFoundError] if the bundle does not exist
707
+ # @raise [AuthenticationError] on invalid credentials
708
+ # @raise [NetworkError] on connection failure
709
+ def delete_bundle(id)
710
+ client = get_client
711
+ client.delete("/v1/bundles/#{id}")
712
+ end
713
+
714
+ # Duplicate a bundle.
715
+ #
716
+ # @param id [String]
717
+ # @return [Hash] the duplicated bundle
718
+ # @raise [NotFoundError] if the bundle does not exist
719
+ # @raise [AuthenticationError] on invalid credentials
720
+ # @raise [NetworkError] on connection failure
721
+ def duplicate_bundle(id)
722
+ client = get_client
723
+ unwrap(client.post("/v1/bundles/#{id}/duplicate"))
724
+ end
725
+
726
+ # ============================================
727
+ # COMPANIES
728
+ # ============================================
729
+
730
+ # List companies.
731
+ #
732
+ # @param options [Hash, nil]
733
+ # @return [Hash] paginated response
734
+ # @raise [AuthenticationError] on invalid credentials
735
+ # @raise [NetworkError] on connection failure
736
+ def list_companies(options = nil)
737
+ client = get_client
738
+ client.get("/v1/companies", to_query_params(options))
739
+ end
740
+
741
+ # Create a company.
742
+ #
743
+ # @param request [Hash] :name, :contacts (array), :phone, :city, :state, :country, :industryId
744
+ # @return [Hash] the created company
745
+ # @raise [ValidationError] on invalid request data
746
+ # @raise [AuthenticationError] on invalid credentials
747
+ # @raise [NetworkError] on connection failure
748
+ def create_company(request)
749
+ client = get_client
750
+ unwrap(client.post("/v1/companies", request))
751
+ end
752
+
753
+ # Bulk create companies (administrator or contributor). Each row requires
754
+ # a +contacts+ array with at least one contact. Partial success: rows
755
+ # that fail are reported in "failed" (1-indexed "row" + "reason") without
756
+ # aborting the rest; server-adjusted rows appear in "adjusted".
757
+ #
758
+ # @param rows [Array<Hash>] company rows, same field shapes as +create_company+
759
+ # @return [Hash] { "imported" => N, "failed" => [...], "adjusted" => [...] }
760
+ # @raise [ValidationError] on an invalid request envelope
761
+ # @raise [AuthenticationError] on invalid credentials
762
+ # @raise [NetworkError] on connection failure
763
+ def bulk_create_companies(rows)
764
+ client = get_client
765
+ response = client.post("/v1/companies/bulk", { "rows" => rows })
766
+ response["results"]
767
+ end
768
+
769
+ # Get a company by ID.
770
+ #
771
+ # @param id [String]
772
+ # @return [Hash] the company
773
+ # @raise [NotFoundError] if the company does not exist
774
+ # @raise [AuthenticationError] on invalid credentials
775
+ # @raise [NetworkError] on connection failure
776
+ def get_company(id)
777
+ client = get_client
778
+ unwrap(client.get("/v1/companies/#{id}"))
779
+ end
780
+
781
+ # Update a company.
782
+ #
783
+ # @param id [String]
784
+ # @param request [Hash]
785
+ # @return [Hash] the updated company
786
+ # @raise [NotFoundError] if the company does not exist
787
+ # @raise [ValidationError] on invalid request data
788
+ # @raise [AuthenticationError] on invalid credentials
789
+ # @raise [NetworkError] on connection failure
790
+ def update_company(id, request)
791
+ client = get_client
792
+ unwrap(client.patch("/v1/companies/#{id}", request))
793
+ end
794
+
795
+ # Delete a company.
796
+ #
797
+ # @param id [String]
798
+ # @return [Hash] { "message" => "..." }
799
+ # @raise [NotFoundError] if the company does not exist
800
+ # @raise [AuthenticationError] on invalid credentials
801
+ # @raise [NetworkError] on connection failure
802
+ def delete_company(id)
803
+ client = get_client
804
+ client.delete("/v1/companies/#{id}")
805
+ end
806
+
807
+ # List contacts for a company.
808
+ #
809
+ # @param company_id [String]
810
+ # @param options [Hash, nil]
811
+ # @return [Hash] paginated response
812
+ # @raise [NotFoundError] if the company does not exist
813
+ # @raise [AuthenticationError] on invalid credentials
814
+ # @raise [NetworkError] on connection failure
815
+ def list_company_contacts(company_id, options = nil)
816
+ client = get_client
817
+ client.get("/v1/companies/#{company_id}/contacts", to_query_params(options))
818
+ end
819
+
820
+ # ============================================
821
+ # CONTACTS
822
+ # ============================================
823
+
824
+ # List contacts.
825
+ #
826
+ # @param options [Hash, nil] :companyId, :limit, :offset, :query
827
+ # @return [Hash] paginated response
828
+ # @raise [AuthenticationError] on invalid credentials
829
+ # @raise [NetworkError] on connection failure
830
+ def list_contacts(options = nil)
831
+ client = get_client
832
+ client.get("/v1/contacts", to_query_params(options))
833
+ end
834
+
835
+ # Create a contact.
836
+ #
837
+ # @param request [Hash] :name, :companyId, :email, :phone, :title
838
+ # @return [Hash] the created contact
839
+ # @raise [ValidationError] on invalid request data
840
+ # @raise [AuthenticationError] on invalid credentials
841
+ # @raise [NetworkError] on connection failure
842
+ def create_contact(request)
843
+ client = get_client
844
+ unwrap(client.post("/v1/contacts", request))
845
+ end
846
+
847
+ # Bulk create contacts (administrator or contributor). Each row requires
848
+ # a +companyId+. Partial success: rows that fail are reported in "failed"
849
+ # (1-indexed "row" + "reason") without aborting the rest; server-adjusted
850
+ # rows appear in "adjusted".
851
+ #
852
+ # @param rows [Array<Hash>] contact rows, same field shapes as +create_contact+
853
+ # @return [Hash] { "imported" => N, "failed" => [...], "adjusted" => [...] }
854
+ # @raise [ValidationError] on an invalid request envelope
855
+ # @raise [AuthenticationError] on invalid credentials
856
+ # @raise [NetworkError] on connection failure
857
+ def bulk_create_contacts(rows)
858
+ client = get_client
859
+ response = client.post("/v1/contacts/bulk", { "rows" => rows })
860
+ response["results"]
861
+ end
862
+
863
+ # Update a contact.
864
+ #
865
+ # @param id [String]
866
+ # @param request [Hash]
867
+ # @return [Hash] the updated contact
868
+ # @raise [NotFoundError] if the contact does not exist
869
+ # @raise [ValidationError] on invalid request data
870
+ # @raise [AuthenticationError] on invalid credentials
871
+ # @raise [NetworkError] on connection failure
872
+ def update_contact(id, request)
873
+ client = get_client
874
+ unwrap(client.patch("/v1/contacts/#{id}", request))
875
+ end
876
+
877
+ # Delete a contact.
878
+ #
879
+ # @param id [String]
880
+ # @return [Hash] { "message" => "..." }
881
+ # @raise [NotFoundError] if the contact does not exist
882
+ # @raise [AuthenticationError] on invalid credentials
883
+ # @raise [NetworkError] on connection failure
884
+ def delete_contact(id)
885
+ client = get_client
886
+ client.delete("/v1/contacts/#{id}")
887
+ end
888
+
889
+ # ============================================
890
+ # TEMPLATES
891
+ # ============================================
892
+
893
+ # List quote templates.
894
+ #
895
+ # @param options [Hash, nil] :limit, :offset, :query
896
+ # @return [Hash] { "results" => [...], "totalRecords" => N }
897
+ # @raise [AuthenticationError] on invalid credentials
898
+ # @raise [NetworkError] on connection failure
899
+ def list_templates(options = nil)
900
+ client = get_client
901
+ client.get("/v1/quote-templates", to_query_params(options))
902
+ end
903
+
904
+ # Get the org's current quote template.
905
+ #
906
+ # @return [Hash] the template
907
+ # @raise [AuthenticationError] on invalid credentials
908
+ # @raise [NetworkError] on connection failure
909
+ def get_template
910
+ client = get_client
911
+ unwrap(client.get("/v1/quote-template"))
912
+ end
913
+
914
+ # Get a quote template by ID.
915
+ #
916
+ # @param id [String]
917
+ # @return [Hash] the template
918
+ # @raise [NotFoundError] if the template does not exist
919
+ # @raise [AuthenticationError] on invalid credentials
920
+ # @raise [NetworkError] on connection failure
921
+ def get_template_by_id(id)
922
+ client = get_client
923
+ unwrap(client.get("/v1/quote-templates/#{id}"))
924
+ end
925
+
926
+ # Create a quote template.
927
+ #
928
+ # @param request [Hash]
929
+ # @return [Hash] the created template
930
+ # @raise [ValidationError] on invalid request data
931
+ # @raise [AuthenticationError] on invalid credentials
932
+ # @raise [NetworkError] on connection failure
933
+ def create_template(request)
934
+ client = get_client
935
+ unwrap(client.post("/v1/quote-templates", request))
936
+ end
937
+
938
+ # Update a quote template.
939
+ #
940
+ # @param id [String]
941
+ # @param request [Hash]
942
+ # @return [Hash] the updated template
943
+ # @raise [NotFoundError] if the template does not exist
944
+ # @raise [ValidationError] on invalid request data
945
+ # @raise [AuthenticationError] on invalid credentials
946
+ # @raise [NetworkError] on connection failure
947
+ def update_template(id, request)
948
+ client = get_client
949
+ unwrap(client.patch("/v1/quote-templates/#{id}", request))
950
+ end
951
+
952
+ # Delete a quote template.
953
+ #
954
+ # @param id [String]
955
+ # @return [Hash] { "message" => "..." }
956
+ # @raise [NotFoundError] if the template does not exist
957
+ # @raise [AuthenticationError] on invalid credentials
958
+ # @raise [NetworkError] on connection failure
959
+ def delete_template(id)
960
+ client = get_client
961
+ client.delete("/v1/quote-templates/#{id}")
962
+ end
963
+
964
+ # ============================================
965
+ # TYPES / CATEGORIES
966
+ # ============================================
967
+
968
+ # List types/categories.
969
+ #
970
+ # @param options [Hash, nil] :categoryType, :includeUsage, :limit, :offset, :query
971
+ # @return [Hash] paginated response
972
+ # @raise [AuthenticationError] on invalid credentials
973
+ # @raise [NetworkError] on connection failure
974
+ def list_types(options = nil)
975
+ client = get_client
976
+ client.get("/v1/types", to_query_params(options))
977
+ end
978
+
979
+ # Create a type/category.
980
+ #
981
+ # @param request [Hash] :name, :categoryType
982
+ # @return [Hash] the created type
983
+ # @raise [ValidationError] on invalid request data
984
+ # @raise [AuthenticationError] on invalid credentials
985
+ # @raise [NetworkError] on connection failure
986
+ def create_type(request)
987
+ client = get_client
988
+ unwrap(client.post("/v1/types", request))
989
+ end
990
+
991
+ # Bulk create types/categories (administrator or contributor). Partial
992
+ # success: rows that fail are reported in "failed" (1-indexed "row" +
993
+ # "reason") without aborting the rest; server-adjusted rows appear in
994
+ # "adjusted".
995
+ #
996
+ # @param rows [Array<Hash>] type rows, same field shapes as +create_type+
997
+ # @return [Hash] { "imported" => N, "failed" => [...], "adjusted" => [...] }
998
+ # @raise [ValidationError] on an invalid request envelope
999
+ # @raise [AuthenticationError] on invalid credentials
1000
+ # @raise [NetworkError] on connection failure
1001
+ def bulk_create_types(rows)
1002
+ client = get_client
1003
+ response = client.post("/v1/types/bulk", { "rows" => rows })
1004
+ response["results"]
1005
+ end
1006
+
1007
+ # Update a type/category.
1008
+ #
1009
+ # @param id [String]
1010
+ # @param request [Hash]
1011
+ # @return [Hash] the updated type
1012
+ # @raise [NotFoundError] if the type does not exist
1013
+ # @raise [ValidationError] on invalid request data
1014
+ # @raise [AuthenticationError] on invalid credentials
1015
+ # @raise [NetworkError] on connection failure
1016
+ def update_type(id, request)
1017
+ client = get_client
1018
+ unwrap(client.patch("/v1/types/#{id}", request))
1019
+ end
1020
+
1021
+ # Delete a type/category.
1022
+ #
1023
+ # @param id [String]
1024
+ # @return [Hash] { "message" => "..." }
1025
+ # @raise [NotFoundError] if the type does not exist
1026
+ # @raise [AuthenticationError] on invalid credentials
1027
+ # @raise [NetworkError] on connection failure
1028
+ def delete_type(id)
1029
+ client = get_client
1030
+ client.delete("/v1/types/#{id}")
1031
+ end
1032
+
1033
+ # ============================================
1034
+ # QUOTE NUMBER CONFIG
1035
+ # ============================================
1036
+
1037
+ # Get the org's quote-number configuration (admin only).
1038
+ #
1039
+ # @return [Hash] { "format" => {...}, "currentFloor" => Integer } where +format+ has the
1040
+ # keys +prefix+, +yearToken+ (see QuoteNumberYearToken), +monthToken+ (see
1041
+ # QuoteNumberMonthToken), +separator+, +padWidth+ (Integer), +suffix+,
1042
+ # +startNumber+ (Integer), and +resetCadence+ (see QuoteNumberResetCadence)
1043
+ # @raise [AuthorizationError] if the caller is not an admin
1044
+ # @raise [AuthenticationError] on invalid credentials
1045
+ # @raise [NetworkError] on connection failure
1046
+ def get_quote_number_config
1047
+ client = get_client
1048
+ response = client.get("/v1/quotes/number-config")
1049
+ response["results"]
1050
+ end
1051
+
1052
+ # Update the org's quote-number configuration (admin only).
1053
+ #
1054
+ # @param format [Hash] the full format object; all keys are required and passed verbatim
1055
+ # (camelCase): +prefix+ [String], +yearToken+ [String] (see QuoteNumberYearToken),
1056
+ # +monthToken+ [String] (see QuoteNumberMonthToken), +separator+ [String],
1057
+ # +padWidth+ [Integer] (0-12), +suffix+ [String], +startNumber+ [Integer] (>= 0),
1058
+ # +resetCadence+ [String] (see QuoteNumberResetCadence)
1059
+ # @return [Hash] { "format" => {...}, "currentFloor" => Integer } (same shape as +get_quote_number_config+)
1060
+ # @raise [AuthorizationError] if the caller is not an admin
1061
+ # @raise [ValidationError] on invalid request data
1062
+ # @raise [AuthenticationError] on invalid credentials
1063
+ # @raise [NetworkError] on connection failure
1064
+ def update_quote_number_config(format)
1065
+ client = get_client
1066
+ response = client.patch("/v1/quotes/number-config", format)
1067
+ response["results"]
1068
+ end
1069
+
1070
+ # ============================================
1071
+ # CONVENIENCE
1072
+ # ============================================
1073
+
1074
+ # Create a quote, optionally add items, and send -- all in one call.
1075
+ #
1076
+ # @param request [Hash] quote fields plus :items, :bundleItems, :send
1077
+ # @return [Hash] { "quote" => {...} }
1078
+ # @raise [ValidationError] on invalid request data
1079
+ # @raise [AuthenticationError] on invalid credentials
1080
+ # @raise [NetworkError] on connection failure
1081
+ def create_and_send(request)
1082
+ client = get_client
1083
+
1084
+ # Separate convenience keys from core quote fields
1085
+ data = request.dup
1086
+ items = data.delete("items") || data.delete(:items)
1087
+ bundle_items = data.delete("bundleItems") || data.delete(:bundleItems)
1088
+ send_opts = data.delete("send") || data.delete(:send)
1089
+ quote_fields = data
1090
+
1091
+ quote = unwrap(client.post("/v1/quotes", quote_fields))
1092
+
1093
+ if items && !items.empty?
1094
+ client.post("/v1/quotes/#{quote["id"]}/items", items)
1095
+ end
1096
+
1097
+ if bundle_items && !bundle_items.empty?
1098
+ client.post("/v1/quotes/#{quote["id"]}/items/bundle", bundle_items)
1099
+ end
1100
+
1101
+ send_response = client.post("/v1/quotes/#{quote["id"]}/send", send_opts)
1102
+
1103
+ { "quote" => send_response["result"] }
1104
+ end
1105
+
1106
+ private
1107
+
1108
+ # Lazy-initialize an HttpClient from env vars if not configured.
1109
+ def get_client
1110
+ @client ||= HttpClient.new(skip_sender_validation: true)
1111
+ end
1112
+
1113
+ # Extract { "result" => T } -> T
1114
+ def unwrap(response)
1115
+ response["result"]
1116
+ end
1117
+
1118
+ # Convert a Ruby hash to query parameter hash (string values).
1119
+ # Returns nil if the result would be empty.
1120
+ def to_query_params(request)
1121
+ return nil if request.nil? || request.empty?
1122
+
1123
+ params = {}
1124
+ request.each do |key, value|
1125
+ str_key = key.to_s
1126
+ next if value.nil?
1127
+
1128
+ case value
1129
+ when true, false
1130
+ params[str_key] = value ? "true" : "false"
1131
+ when Array
1132
+ params[str_key] = value.map(&:to_s)
1133
+ else
1134
+ params[str_key] = value.to_s
1135
+ end
1136
+ end
1137
+ params.empty? ? nil : params
1138
+ end
1139
+
1140
+ # Build form data hash for product creation/update with images.
1141
+ def build_product_form_data(data_fields, images)
1142
+ form_data = {}
1143
+ form_data["data"] = JSON.generate(data_fields)
1144
+
1145
+ file_parts = []
1146
+ images.each do |image|
1147
+ if image.is_a?(String)
1148
+ # File path
1149
+ content = File.binread(image)
1150
+ file_parts << {
1151
+ io: StringIO.new(content),
1152
+ filename: File.basename(image),
1153
+ content_type: detect_image_type(content)
1154
+ }
1155
+ elsif image.respond_to?(:read)
1156
+ content = image.read
1157
+ file_parts << {
1158
+ io: StringIO.new(content),
1159
+ filename: "image.bin",
1160
+ content_type: detect_image_type(content)
1161
+ }
1162
+ end
1163
+ end
1164
+ form_data["images"] = file_parts unless file_parts.empty?
1165
+ form_data
1166
+ end
1167
+
1168
+ # Detect MIME type for product images from magic bytes.
1169
+ # Supports PNG, JPEG, GIF, and WEBP; falls back to application/octet-stream.
1170
+ def detect_image_type(content)
1171
+ bytes = content.bytes
1172
+ # PNG: \x89PNG
1173
+ return "image/png" if bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47
1174
+ # JPEG: \xFF\xD8\xFF
1175
+ return "image/jpeg" if bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF
1176
+ # GIF: GIF8
1177
+ return "image/gif" if bytes[0] == 0x47 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x38
1178
+ # WEBP: RIFF????WEBP
1179
+ if bytes[0] == 0x52 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x46
1180
+ return "image/webp" if content.length >= 12 && content[8, 4] == "WEBP"
1181
+ end
1182
+ "application/octet-stream"
1183
+ end
1184
+ end
1185
+ end
1186
+ end