sendly 4.6.0 → 4.7.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6d3251240a21357ede0ab209186128d19d97243664ea9aec810741987ddd4b16
4
- data.tar.gz: ac3997baa32d63a2bc1288007fda43b25b1fd3dd0d9c103d1e69c673eb77e8c5
3
+ metadata.gz: cd8bd2432a03d19a38e0dc47c461f4dbad4c9a4b013ab9e96b7607f8b35b36e2
4
+ data.tar.gz: 79ef91d98be989137f035607ffadc5aed78eaa5eea57a2b688330506ebf046d3
5
5
  SHA512:
6
- metadata.gz: 46f26677c1f2a0aecc13786339e0aeef0d1732d569c1f025435c97096f11a23b51b1ac56e4a34a3c525a4a36da4b1a19e513059a1e4d02bc147607bd706f353c
7
- data.tar.gz: 459079fbabd95db5ffa82ed39356045a86ff962649b9ee6274a563ea9635b2e9a497e5eb6ae7b1834e90ca1ccd2055cb16e63ecec0b720eac97793e26bca5e34
6
+ metadata.gz: 651ea09da682da2609e22a51be6fe5fff359f6d1fa25cb41ef4e1626b9a815e8c2e1ef617968226293a9f4b36d625bf26d03ba84c0c2acc2d439fd35a2c3c65d
7
+ data.tar.gz: 59f52da8b5c0db3ed04db7325ab90af35cfa014a5277aa160bd22e746de9d9a04793606573b936b1cb8229a2bb8839f0cf88c50b9ef8e77770ef5f869b1fe20b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # sendly (Ruby)
2
2
 
3
+ ## 4.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - **`SuggestRepliesResponse` gains `disabled`, `disabled?` and `reason`.** When the workspace's enterprise account turned AI suggestions off, `conversations.suggest_replies` returns no suggestions, `disabled?` is true and `reason` is `"enterprise_policy"`. `to_h` includes both only then.
8
+ - **`Message#batch_id`** is the batch that sent the message, read from `batchId` or `batch_id`; nil unless it is a batch message. `to_h` includes it when present.
9
+ - **Preview a template.** `templates.preview(id, variables: { code: "123456" })` posts to `/templates/:id/preview` and returns the new `Sendly::TemplatePreview` (`template_id`, `original_text`, `rendered_text`, `character_count`, `segment_count`, and `to_h`). It renders one of your templates, or any preset, and sends nothing; without `variables`, each variable takes its fallback. An id that is neither yours nor a preset raises `Sendly::NotFoundError`.
10
+ - **Preview a webhook recovery.** `webhooks.recovery_preview(id, since:, until_:, event_types:)` reads `GET /webhooks/:id/recovery-preview` and returns the new `Sendly::WebhookRecoveryPreview` (`circuit_state`, `circuit_opened_at`, `failure_count`, `audit_failures`, `missing_from_messages`, `histogram`, `samples`, `window_suggestion`, `since`, `until`, `circuit_open?` and `raw`): what `redeliver` and `backfill` would send for the window, without sending anything. Nested values are Hashes with symbol keys, times are `Time`, and `event_types` goes as one comma-separated value. The window is at most 7 days.
11
+ - **Short codes.** The new `client.short_codes` resource: `list` (`GET /short_codes`) returns an Array of `Sendly::ShortCode` (`id`, `short_code`, `country_code`, `status`, `review_status`, `use_case`, `created_at`, `billing`, `active?`), and `application` has `get`, `update(**answers)` (`PUT /short_codes/application`), `check(**answers)` (`POST /short_codes/application/preflight`) and `submit(accept_terms: true, **answers)` (`POST /short_codes/application/submit`). `get`, `update` and `submit` return `Sendly::ShortCodeApplicationView` (`application` as `Sendly::ShortCodeApplication`, `documents` as `Sendly::ShortCodeDocument`, `editable?`, `lock_message`, and `prefill`, `quote`, `billing`, `verification`, `carriers` and `payment` as Hashes with snake_case Symbol keys); `check` returns `Sendly::ShortCodePreflight` (`ok?`, `issues` as `Sendly::ShortCodeIssue`, `missing_documents`). Answers take snake_case or camelCase keys. `update` and `submit` take `idempotency_key:`. Submitting charges the one-time $999 setup fee.
12
+ - **Idempotency keys on WhatsApp signup and template create.** `whatsapp.signup.create` (both the Facebook signup and adding a number by code) and `whatsapp.templates.create` take `idempotency_key:`, sent as the `Idempotency-Key` header; a repeat with the same key within 24 hours returns the first answer instead of starting another charged signup or creating the template again. Without it the client still generates one per call, as before.
13
+ - **`messages.schedule(timezone:)`.** Sends `timezone`, a label stored with the scheduled message and returned as sent (`"UTC"` when left out). It does not change how `scheduled_at` is read, so give `scheduled_at` an offset or `Z`.
14
+ - **`enterprise.upload_verification_document(content_type:)`.** The API accepts only PNG, JPEG, GIF, WEBP and PDF, and reads the type from the part's content type, which the SDK takes from the file's extension. Pass `content_type:` for a file without an extension or with a different one; a blank value or one with a line break raises `ArgumentError` before anything is sent.
15
+ - **`conversations.list(label:)`** keeps only conversations with that label id; `conversations.each(label:)` passes it on.
16
+ - **`enterprise.workspaces.list` takes the API's filters:** `limit:` (up to 100), `page:`, `search:`, `status:`, `verification:` (`"unverified"` keeps workspaces without one), `sort:` (`"created_desc"`, `"created_asc"`, `"name_asc"`, `"name_desc"`, `"credits_desc"` or `"credits_asc"`), `compact:` and `tags:` (an Array or String, sent comma-separated). Calling it with no arguments sends the same request as before.
17
+
18
+ ### Patch Changes
19
+
20
+ - `whatsapp.templates.update` documents how to remove parts of a template: `header: ""` or `footer: ""` removes the header or footer, and `buttons: []` removes every button. The SDK already sent these; only `nil` is left out.
21
+ - **`Webhook#metadata` is always a Hash.** The API returns a webhook's metadata as it was stored, which can be an array, string, number or boolean; `webhooks.list` and `webhooks.get` passed such a value through, so `metadata` (and `to_h[:metadata]`) could be something other than the documented Hash. It now reads as `{}`, as `null` already did.
22
+
3
23
  ## 4.5.0
4
24
 
5
25
  ### Patch Changes
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- sendly (4.6.0)
4
+ sendly (4.7.0)
5
5
  faraday (~> 2.0)
6
6
  faraday-retry (~> 2.0)
7
7
 
data/README.md CHANGED
@@ -184,6 +184,16 @@ scheduled = client.messages.schedule(
184
184
  puts scheduled["id"]
185
185
  puts scheduled["scheduledAt"]
186
186
 
187
+ # timezone is a label stored with the message and returned as sent ("UTC"
188
+ # when left out). It does not change how scheduled_at is read, so give
189
+ # scheduled_at an offset or Z.
190
+ client.messages.schedule(
191
+ to: "+15125550123",
192
+ text: "Doors open at 9!",
193
+ scheduled_at: "2026-11-20T09:00:00-05:00",
194
+ timezone: "America/New_York"
195
+ )
196
+
187
197
  # List scheduled messages (returns a Hash with "data" array)
188
198
  result = client.messages.list_scheduled
189
199
  result["data"].each { |msg| puts "#{msg['id']}: #{msg['scheduledAt']}" }
@@ -423,6 +433,10 @@ circuit is still open, so reset first:
423
433
  ```ruby
424
434
  client.webhooks.reset_circuit("whk_xxx")
425
435
 
436
+ # See what a recovery would send, without sending anything
437
+ preview = client.webhooks.recovery_preview("whk_xxx", since: (Time.now.utc - 86_400).iso8601)
438
+ puts preview.audit_failures[:total], preview.missing_from_messages[:total]
439
+
426
440
  # Re-fire deliveries we recorded but could not deliver
427
441
  client.webhooks.redeliver("whk_xxx",
428
442
  since: (Time.now.utc - 86_400).iso8601,
@@ -771,6 +785,10 @@ client.templates.publish(template.id)
771
785
  copy = client.templates.clone(template.id, name: "Order shipped (v2)")
772
786
  client.templates.delete(template.id)
773
787
 
788
+ # Render a template, or any preset, with values. Nothing is sent.
789
+ preview = client.templates.preview("tpl_preset_otp", variables: { code: "123456" })
790
+ puts "#{preview.rendered_text} (#{preview.segment_count} segments)"
791
+
774
792
  # Generate a template with AI
775
793
  generated = client.templates.generate(description: "A friendly appointment reminder")
776
794
  puts generated.text
@@ -784,6 +802,7 @@ Two-way messaging threads with your contacts.
784
802
  ```ruby
785
803
  # List conversations (Enumerable)
786
804
  conversations = client.conversations.list(status: "active")
805
+ vip = client.conversations.list(label: "lbl_xxx") # only conversations with this label id
787
806
  conversations.each { |c| puts "#{c.phone_number}: #{c.last_message_text}" }
788
807
 
789
808
  # Get one, optionally with its messages
@@ -1015,10 +1034,54 @@ client.ten_dlc.list_assignments[:assignments].each { |a| puts "#{a.phone_number}
1015
1034
 
1016
1035
  ## Short Codes
1017
1036
 
1018
- **This SDK has no short-code resource.** There is no `client.short_codes`;
1019
- short-code applications are handled in the dashboard, or over REST. What
1020
- the SDK does carry is the four lifecycle events, as constants you can
1021
- subscribe to and branch on:
1037
+ A short code is a 5 or 6 digit US sender. Getting one is an application,
1038
+ not a purchase: you fill it in, Sendly reviews it, the carrier forms are
1039
+ signed, Sendly files it, and each carrier certifies the code. Reads need
1040
+ the `short_codes:read` scope and writes `short_codes:write`.
1041
+
1042
+ ```ruby
1043
+ # Every application and code, newest first (drafts and rejected ones too)
1044
+ client.short_codes.list.select(&:active?).each { |code| puts code.short_code }
1045
+
1046
+ # The application, with the documents it needs, the quote and billing
1047
+ view = client.short_codes.application.get
1048
+ puts view.lock_message unless view.editable?
1049
+ puts view.quote[:setup_usd] # 999
1050
+ puts view.billing[:setup_fee][:status] # "unpaid"
1051
+
1052
+ # Save answers (snake_case or camelCase keys); the first save creates it
1053
+ client.short_codes.application.update(
1054
+ use_case: "Delivery alerts for Acme orders",
1055
+ message_frequency: "4 messages per month",
1056
+ sample_messages: ["Acme: your order shipped. Reply STOP to opt out."]
1057
+ )
1058
+
1059
+ # Check against the carrier rules without saving anything
1060
+ check = client.short_codes.application.check
1061
+ check.issues.each { |issue| puts "#{issue.path}: #{issue.message}" } unless check.ok?
1062
+
1063
+ # Submit: charges the one-time $999 setup fee to the card on file, and
1064
+ # accepts the monthly lease from go-live and the 3-month minimum
1065
+ result = client.short_codes.application.submit(
1066
+ accept_terms: true,
1067
+ idempotency_key: "short-code-submit-1"
1068
+ )
1069
+ puts result.application.review_status # "awaiting_review"
1070
+ puts result.payment # { status: "paid", charged: true }
1071
+ ```
1072
+
1073
+ `update` and `submit` accept `idempotency_key:`; a repeat with the same key
1074
+ returns the first answer. Submitting twice is safe anyway: the second call
1075
+ reports `already_submitted?` and charges nothing. Nested values (`prefill`,
1076
+ `quote`, `billing`, `verification`, `carriers`, `payment`) are Hashes with
1077
+ snake_case Symbol keys. Submit raises `Sendly::APIError` 403
1078
+ `verification_required` until the business is verified,
1079
+ `Sendly::ValidationError` 422 `short_code_invalid_application` naming every
1080
+ field, and `Sendly::InsufficientCreditsError` 402 when the fee can't be
1081
+ charged (`e.response_body["checkoutUrl"]` is the payment page when the bank
1082
+ needs to confirm it).
1083
+
1084
+ The four lifecycle events are constants you can subscribe to and branch on:
1022
1085
 
1023
1086
  ```ruby
1024
1087
  client.webhooks.create(
@@ -1044,33 +1107,6 @@ These are lifecycle events, so `event.message` is `nil` and you read
1044
1107
  `data.object` through `event.data` or `event.raw_object`, as with every
1045
1108
  other non-message event.
1046
1109
 
1047
- To drive an application from code meanwhile, call the REST endpoints
1048
- directly with an API key holding the `short_codes:read` /
1049
- `short_codes:write` scopes:
1050
-
1051
- | Method | Path | Scope |
1052
- |--------|------|-------|
1053
- | `GET` | `/api/v1/short_codes` | `short_codes:read` |
1054
- | `POST` | `/api/v1/short_codes/requests` | `short_codes:write` |
1055
- | `GET` | `/api/v1/short_codes/application` | `short_codes:read` |
1056
- | `PUT` | `/api/v1/short_codes/application` | `short_codes:write` |
1057
- | `POST` | `/api/v1/short_codes/application/preflight` | `short_codes:read` |
1058
- | `POST` | `/api/v1/short_codes/application/submit` | `short_codes:write` |
1059
-
1060
- The client's own HTTP
1061
- methods reach them without a dedicated resource — paths are relative to the
1062
- `/api/v1` base:
1063
-
1064
- ```ruby
1065
- application = client.get("/short_codes/application")
1066
- ```
1067
-
1068
- The write endpoints take the application form's fields as their body. This
1069
- SDK does not model them, so check the API reference for the shape rather
1070
- than guessing: `client.put` and `client.post` pass a Hash through as JSON
1071
- unchanged (`client.delete` takes no body), and every `client.post` carries an
1072
- `Idempotency-Key` as usual.
1073
-
1074
1110
  ## Business Entity Upgrade
1075
1111
 
1076
1112
  `client.business_upgrade` runs the toll-free entity upgrade: when you form
@@ -1193,8 +1229,10 @@ gives its slot back. Note: Meta
1193
1229
  has paused marketing template delivery to US (+1) numbers.
1194
1230
 
1195
1231
  ```ruby
1196
- # 1. Connect a number ($9.99 one-time; a human must open the connect URL)
1197
- signup = client.whatsapp.signup.create(phone_number: "+15125550123")
1232
+ # 1. Connect a number ($9.99 one-time; a human must open the connect URL).
1233
+ # Pass idempotency_key: so a repeat after a restart returns the same signup.
1234
+ signup = client.whatsapp.signup.create(phone_number: "+15125550123",
1235
+ idempotency_key: "connect-+15125550123")
1198
1236
  puts "Have your user open: #{signup.connect_url}"
1199
1237
 
1200
1238
  # 2. Poll until active. After the Facebook step the signup is "registering"
@@ -1275,7 +1313,8 @@ template = client.whatsapp.templates.create(
1275
1313
  category: "UTILITY",
1276
1314
  header: "Order update", # fixed text only: a header with {{n}} is refused
1277
1315
  body: "Hi {{1}}, your order {{2}} has shipped!",
1278
- examples: { "1" => "Sam", "2" => "#4821" }
1316
+ examples: { "1" => "Sam", "2" => "#4821" },
1317
+ idempotency_key: "tpl-order-shipped" # optional: a repeat returns the first answer
1279
1318
  )
1280
1319
  puts template.status # "PENDING"
1281
1320
 
@@ -1283,6 +1322,8 @@ puts template.status # "PENDING"
1283
1322
  client.whatsapp.templates.list[:templates].each { |t| puts "#{t.name} — #{t.status}" }
1284
1323
  client.whatsapp.templates.update(template.id, body: "Hi {{1}}, order {{2}} is on its way!",
1285
1324
  examples: { "1" => "Sam", "2" => "#4821" })
1325
+ # "" removes the header or footer, [] removes every button
1326
+ client.whatsapp.templates.update(template.id, footer: "", buttons: [])
1286
1327
  client.whatsapp.templates.delete(template.id)
1287
1328
 
1288
1329
  # 4. Send — free-form inside an open 24h window, template anytime. The window
@@ -2154,6 +2195,10 @@ Three provisioning modes:
2154
2195
  ```ruby
2155
2196
  ws = client.enterprise.workspaces.create(name: "Acme Insurance")
2156
2197
  list = client.enterprise.workspaces.list
2198
+ # Filters: limit (up to 100), page, search, status, verification ("unverified"),
2199
+ # sort ("created_desc", "name_asc", "credits_desc", ...), compact, tags
2200
+ unverified = client.enterprise.workspaces.list(verification: "unverified", sort: "name_asc",
2201
+ tags: ["tag_vip"], limit: 100)
2157
2202
  detail = client.enterprise.workspaces.get("ws_xxx")
2158
2203
  client.enterprise.workspaces.delete("ws_xxx")
2159
2204
  ```
@@ -2206,6 +2251,8 @@ client.enterprise.workspaces.inherit_verification("ws_other", source_workspace_i
2206
2251
  purchase_new_number: true)
2207
2252
  client.enterprise.workspaces.get_verification("ws_xxx")
2208
2253
  client.enterprise.upload_verification_document("./CP-575.pdf", workspace_id: "ws_xxx")
2254
+ # The type comes from the extension; pass content_type: for a file without one
2255
+ client.enterprise.upload_verification_document("./ein-letter", content_type: "application/pdf")
2209
2256
 
2210
2257
  # Hosted opt-in pages, and a generated business page
2211
2258
  client.enterprise.workspaces.list_opt_in_pages("ws_xxx")
data/lib/sendly/client.rb CHANGED
@@ -192,6 +192,17 @@ module Sendly
192
192
  @rcs ||= RcsResource.new(self)
193
193
  end
194
194
 
195
+ # Access the Short Codes resource (apply for a US short code and track it)
196
+ #
197
+ # @return [Sendly::ShortCodesResource]
198
+ #
199
+ # @example
200
+ # view = client.short_codes.application.get
201
+ # client.short_codes.application.submit(accept_terms: true)
202
+ def short_codes
203
+ @short_codes ||= ShortCodesResource.new(self)
204
+ end
205
+
195
206
  # Access the Calls resource (phone calls handled by your AI agents)
196
207
  #
197
208
  # @return [Sendly::CallsResource]
@@ -6,12 +6,20 @@ module Sendly
6
6
  @client = client
7
7
  end
8
8
 
9
- def list(limit: 20, offset: 0, status: nil)
9
+ # List conversations, most recent activity first.
10
+ #
11
+ # @param limit [Integer] Page size (max 100)
12
+ # @param offset [Integer] How many conversations to skip
13
+ # @param status [String, nil] Only conversations with this status, such as "active"
14
+ # @param label [String, nil] Only conversations with this label id
15
+ # @return [ConversationList]
16
+ def list(limit: 20, offset: 0, status: nil, label: nil)
10
17
  params = {
11
18
  limit: [limit, 100].min,
12
19
  offset: offset
13
20
  }
14
21
  params[:status] = status if status
22
+ params[:label] = label if label
15
23
 
16
24
  response = @client.get("/conversations", params.compact)
17
25
  ConversationList.new(response)
@@ -127,12 +135,12 @@ module Sendly
127
135
  SuggestRepliesResponse.new(response)
128
136
  end
129
137
 
130
- def each(status: nil, batch_size: 100, &block)
131
- return enum_for(:each, status: status, batch_size: batch_size) unless block_given?
138
+ def each(status: nil, label: nil, batch_size: 100, &block)
139
+ return enum_for(:each, status: status, label: label, batch_size: batch_size) unless block_given?
132
140
 
133
141
  offset = 0
134
142
  loop do
135
- page = list(limit: batch_size, offset: offset, status: status)
143
+ page = list(limit: batch_size, offset: offset, status: status, label: label)
136
144
  page.each(&block)
137
145
 
138
146
  break if !page.has_more || page.count.zero?
@@ -15,8 +15,39 @@ module Sendly
15
15
  @client.post("/enterprise/workspaces", body)
16
16
  end
17
17
 
18
- def list
19
- @client.get("/enterprise/workspaces")
18
+ # List the workspaces the enterprise key's owner owns, with totals over
19
+ # all of them. Every filter is optional; with none the API returns the
20
+ # first page of 50, newest first.
21
+ #
22
+ # @param limit [Integer, nil] Page size, up to 100 (default 50)
23
+ # @param page [Integer, nil] The page, starting at 1
24
+ # @param search [String, nil] Only workspaces whose name contains this, ignoring case
25
+ # @param status [String, nil] Only workspaces with this status ("all", the default, keeps all)
26
+ # @param verification [String, nil] Only workspaces whose verification has this
27
+ # status; "unverified" keeps those with none ("all", the default, keeps all)
28
+ # @param sort [String, nil] "created_desc" (the default), "created_asc",
29
+ # "name_asc", "name_desc", "credits_desc" or "credits_asc"
30
+ # @param compact [Boolean, nil] +true+ returns every workspace's id, name and
31
+ # balance instead, ignoring the other filters and paging
32
+ # @param tags [Array<String>, String, nil] Tag ids: only workspaces with at
33
+ # least one of them. Sent comma-separated
34
+ # @return [Hash]
35
+ #
36
+ # @example
37
+ # client.enterprise.workspaces.list(search: "acme", sort: "name_asc", limit: 50)
38
+ def list(limit: nil, page: nil, search: nil, status: nil, verification: nil, sort: nil,
39
+ compact: nil, tags: nil)
40
+ params = {}
41
+ params[:limit] = limit unless limit.nil?
42
+ params[:page] = page unless page.nil?
43
+ params[:search] = search unless search.nil?
44
+ params[:status] = status unless status.nil?
45
+ params[:verification] = verification unless verification.nil?
46
+ params[:sort] = sort unless sort.nil?
47
+ params[:compact] = compact unless compact.nil?
48
+ params[:tags] = Array(tags).join(",") unless tags.nil?
49
+
50
+ @client.get("/enterprise/workspaces", params)
20
51
  end
21
52
 
22
53
  def get(workspace_id)
@@ -468,18 +499,38 @@ module Sendly
468
499
  @client.post("/enterprise/business-page/generate", body)
469
500
  end
470
501
 
471
- def upload_verification_document(file_path, workspace_id: nil, verification_id: nil)
502
+ # Upload a business registration document for a toll-free verification.
503
+ #
504
+ # The API accepts a PNG, JPEG, GIF or WEBP image or a PDF, up to 10 MB,
505
+ # and reads the type from the part's content type. It is taken from the
506
+ # file's extension; pass +content_type+ when the file has no extension
507
+ # or a different one, or the upload is refused.
508
+ #
509
+ # @param file_path [String] Path to the document
510
+ # @param workspace_id [String, nil] Make it that workspace's verification document
511
+ # @param verification_id [String, nil] Make it that verification's registration document
512
+ # @param content_type [String, nil] The file's type, such as "image/png" or
513
+ # "application/pdf" (default: from the extension)
514
+ # @return [Hash] The stored document's +url+ and +id+
515
+ #
516
+ # @example
517
+ # client.enterprise.upload_verification_document("/tmp/ein-letter", content_type: "application/pdf")
518
+ def upload_verification_document(file_path, workspace_id: nil, verification_id: nil, content_type: nil)
472
519
  raise ArgumentError, "File path is required" if file_path.nil? || file_path.empty?
473
520
  raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)
521
+ if !content_type.nil? && (content_type.to_s.strip.empty? || content_type.to_s.match?(/[\r\n]/))
522
+ raise ArgumentError, "content_type must be a MIME type such as \"application/pdf\""
523
+ end
474
524
 
475
- content_type = case File.extname(file_path).downcase
476
- when ".jpg", ".jpeg" then "image/jpeg"
477
- when ".png" then "image/png"
478
- when ".gif" then "image/gif"
479
- when ".pdf" then "application/pdf"
480
- when ".webp" then "image/webp"
481
- else "application/octet-stream"
482
- end
525
+ content_type = content_type.nil? ? nil : content_type.to_s.strip
526
+ content_type ||= case File.extname(file_path).downcase
527
+ when ".jpg", ".jpeg" then "image/jpeg"
528
+ when ".png" then "image/png"
529
+ when ".gif" then "image/gif"
530
+ when ".pdf" then "application/pdf"
531
+ when ".webp" then "image/webp"
532
+ else "application/octet-stream"
533
+ end
483
534
 
484
535
  filename = File.basename(file_path).gsub('"', "%22").gsub("\r", "%0D").gsub("\n", "%0A")
485
536
 
@@ -392,6 +392,10 @@ module Sendly
392
392
  # @param to [String] Recipient phone number in E.164 format
393
393
  # @param text [String] Message content (max 1600 characters)
394
394
  # @param scheduled_at [String] ISO 8601 datetime for when to send
395
+ # @param timezone [String] A time zone label such as "America/New_York"
396
+ # (optional). It is stored with the message and returned as sent; it
397
+ # does not change how +scheduled_at+ is read, so give +scheduled_at+ an
398
+ # offset or +Z+. The API stores "UTC" when it is left out.
395
399
  # @param from [String] Sender ID or phone number (optional)
396
400
  # @param message_type [String] Message type: "marketing" (default) or "transactional"
397
401
  # @param metadata [Hash] Custom JSON metadata to attach to the message (max 4KB)
@@ -408,12 +412,14 @@ module Sendly
408
412
  # scheduled_at: "2025-01-20T10:00:00Z"
409
413
  # )
410
414
  # puts scheduled["id"]
411
- def schedule(to:, text:, scheduled_at:, from: nil, message_type: nil, metadata: nil, idempotency_key: nil)
415
+ def schedule(to:, text:, scheduled_at:, timezone: nil, from: nil, message_type: nil, metadata: nil,
416
+ idempotency_key: nil)
412
417
  validate_phone!(to)
413
418
  validate_text!(text)
414
419
  raise ValidationError, "scheduled_at is required" if scheduled_at.nil? || scheduled_at.empty?
415
420
 
416
421
  body = { to: to, text: text, scheduledAt: scheduled_at }
422
+ body[:timezone] = timezone if timezone
417
423
  body[:from] = from if from
418
424
  body[:messageType] = message_type if message_type
419
425
  body[:metadata] = metadata if metadata
@@ -19,7 +19,7 @@ module Sendly
19
19
  Rule.new(response)
20
20
  end
21
21
 
22
- def update(id, name: nil, conditions: nil, actions: nil, priority: nil)
22
+ def update(id, name: nil, conditions: nil, actions: nil, priority: nil, enabled: nil)
23
23
  raise ValidationError, "Rule ID is required" if id.nil? || id.empty?
24
24
 
25
25
  body = {}
@@ -27,6 +27,7 @@ module Sendly
27
27
  body[:conditions] = conditions if conditions
28
28
  body[:actions] = actions if actions
29
29
  body[:priority] = priority if priority
30
+ body[:enabled] = enabled unless enabled.nil?
30
31
 
31
32
  response = @client.patch("/rules/#{URI.encode_www_form_component(id)}", body)
32
33
  Rule.new(response)
@@ -0,0 +1,336 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendly
4
+ # A compliance problem with a short code application. +path+ is the field
5
+ # it is about, such as "helpResponse" or "documents.loa"; +message+ says
6
+ # what to change.
7
+ class ShortCodeIssue
8
+ attr_reader :path, :message
9
+
10
+ def initialize(data)
11
+ data ||= {}
12
+ @path = data["path"]
13
+ @message = data["message"]
14
+ end
15
+
16
+ def to_h
17
+ { path: path, message: message }.compact
18
+ end
19
+ end
20
+
21
+ # A carrier form the application needs, and where it stands.
22
+ class ShortCodeDocument
23
+ attr_reader :kind, :template_ready, :signed_at, :signed_by_name, :awaiting_signature
24
+
25
+ def initialize(data)
26
+ data ||= {}
27
+ @kind = data["kind"]
28
+ @template_ready = data["templateReady"]
29
+ @signed_at = data["signedAt"]
30
+ @signed_by_name = data["signedByName"]
31
+ @awaiting_signature = data["awaitingSignature"]
32
+ end
33
+
34
+ def to_h
35
+ {
36
+ kind: kind, template_ready: template_ready, signed_at: signed_at,
37
+ signed_by_name: signed_by_name, awaiting_signature: awaiting_signature
38
+ }.compact
39
+ end
40
+ end
41
+
42
+ # The workspace's short code application. With no application yet it is
43
+ # the empty shape: +id+ is nil, the choices show their defaults and every
44
+ # answer is nil. +status+ is where the code stands (see {STATUSES}) and
45
+ # +review_status+ where Sendly's review stands (see {REVIEW_STATUSES});
46
+ # a value this SDK predates comes through unchanged.
47
+ class ShortCodeApplication
48
+ STATUSES = %w[requested provisioning parked active suspended cancelled].freeze
49
+ REVIEW_STATUSES = %w[draft awaiting_review changes_requested approved_for_filing filed rejected].freeze
50
+
51
+ FIELDS = {
52
+ id: "id", short_code: "shortCode", country_code: "countryCode", status: "status",
53
+ review_status: "reviewStatus", review_note: "reviewNote", order_type: "orderType",
54
+ code_type: "codeType", content_provider_same_as_brand: "contentProviderSameAsBrand",
55
+ sample_messages: "sampleMessages", use_case: "useCase", opt_in_flow: "optInFlow",
56
+ opt_in_confirmation: "optInConfirmation", help_response: "helpResponse",
57
+ stop_confirmation: "stopConfirmation", message_frequency: "messageFrequency",
58
+ campaign_keyword: "campaignKeyword", expected_monthly_volume: "expectedMonthlyVolume",
59
+ expected_daily_volume: "expectedDailyVolume", privacy_policy_url: "privacyPolicyUrl",
60
+ terms_url: "termsUrl", requested_digits: "requestedDigits", losing_provider: "losingProvider",
61
+ brand_contact_name: "brandContactName", brand_contact_email: "brandContactEmail",
62
+ brand_contact_phone: "brandContactPhone", content_provider_legal_name: "contentProviderLegalName",
63
+ content_provider_ein: "contentProviderEin", content_provider_contact_name: "contentProviderContactName",
64
+ content_provider_contact_email: "contentProviderContactEmail",
65
+ content_provider_contact_phone: "contentProviderContactPhone",
66
+ brand_registration_status: "brandRegistrationStatus",
67
+ content_provider_registration_status: "contentProviderRegistrationStatus",
68
+ submitted_at: "submittedAt", reviewed_at: "reviewedAt", filed_at: "filedAt",
69
+ activated_at: "activatedAt", registry_revetting_due_at: "registryRevettingDueAt",
70
+ created_at: "createdAt", updated_at: "updatedAt"
71
+ }.freeze
72
+
73
+ attr_reader(*FIELDS.keys)
74
+
75
+ def initialize(data)
76
+ data ||= {}
77
+ FIELDS.each { |attr, key| instance_variable_set("@#{attr}", data[key]) }
78
+ @sample_messages ||= []
79
+ end
80
+
81
+ def active?
82
+ status == "active"
83
+ end
84
+
85
+ def to_h
86
+ FIELDS.keys.to_h { |attr| [attr, public_send(attr)] }.compact
87
+ end
88
+ end
89
+
90
+ # The application plus everything needed to act on it. +prefill+,
91
+ # +generated_defaults+, +quote+, +billing+, +verification+, +carriers+
92
+ # and +payment+ are Hashes with snake_case Symbol keys (for example
93
+ # +quote[:setup_usd]+, +billing[:setup_fee][:status]+ and
94
+ # +carriers[:by_carrier]+). +ignored_fields+ is set on a save or a
95
+ # check; +submitted+, +already_submitted+, +notified+ and +payment+ on a
96
+ # submit (+payment+ is nil when the application was already in review).
97
+ class ShortCodeApplicationView
98
+ attr_reader :enabled, :application, :prefill, :editable, :lock_message,
99
+ :can_start_new_application, :generated_defaults,
100
+ :required_documents, :missing_documents, :documents, :quote,
101
+ :billing, :verification, :carriers, :ignored_fields,
102
+ :submitted, :already_submitted, :notified, :payment
103
+
104
+ def initialize(data)
105
+ data ||= {}
106
+ @enabled = data["enabled"]
107
+ @application = ShortCodeApplication.new(data["application"])
108
+ @prefill = RcsRegistrationInput.underscore(data["prefill"] || {})
109
+ @editable = data["editable"]
110
+ @lock_message = data["lockMessage"]
111
+ @can_start_new_application = data["canStartNewApplication"]
112
+ @generated_defaults = data["generatedDefaults"] && RcsRegistrationInput.underscore(data["generatedDefaults"])
113
+ @required_documents = data["requiredDocuments"] || []
114
+ @missing_documents = data["missingDocuments"] || []
115
+ @documents = (data["documents"] || []).map { |d| ShortCodeDocument.new(d) }
116
+ @quote = RcsRegistrationInput.underscore(data["quote"] || {})
117
+ @billing = RcsRegistrationInput.underscore(data["billing"] || {})
118
+ @verification = RcsRegistrationInput.underscore(data["verification"] || {})
119
+ @carriers = RcsRegistrationInput.underscore(data["carriers"] || {})
120
+ @ignored_fields = data["ignoredFields"]
121
+ @submitted = data["submitted"]
122
+ @already_submitted = data["alreadySubmitted"]
123
+ @notified = data["notified"]
124
+ @payment = data["payment"] && RcsRegistrationInput.underscore(data["payment"])
125
+ end
126
+
127
+ def editable?
128
+ editable == true
129
+ end
130
+
131
+ def already_submitted?
132
+ already_submitted == true
133
+ end
134
+
135
+ def to_h
136
+ {
137
+ enabled: enabled, application: application.to_h, prefill: prefill,
138
+ editable: editable, lock_message: lock_message,
139
+ can_start_new_application: can_start_new_application,
140
+ generated_defaults: generated_defaults,
141
+ required_documents: required_documents, missing_documents: missing_documents,
142
+ documents: documents.map(&:to_h), quote: quote, billing: billing,
143
+ verification: verification, carriers: carriers, ignored_fields: ignored_fields,
144
+ submitted: submitted, already_submitted: already_submitted,
145
+ notified: notified, payment: payment
146
+ }.compact
147
+ end
148
+ end
149
+
150
+ # A dry run of submitting the application. Nothing is saved. +ok+ is
151
+ # false when there is any issue; +issues+ lists every one at once.
152
+ class ShortCodePreflight
153
+ attr_reader :ok, :issues, :required_documents, :missing_documents, :documents, :ignored_fields
154
+
155
+ def initialize(data)
156
+ data ||= {}
157
+ @ok = data["ok"]
158
+ @issues = (data["issues"] || []).map { |i| ShortCodeIssue.new(i) }
159
+ @required_documents = data["requiredDocuments"] || []
160
+ @missing_documents = data["missingDocuments"] || []
161
+ @documents = (data["documents"] || []).map { |d| ShortCodeDocument.new(d) }
162
+ @ignored_fields = data["ignoredFields"]
163
+ end
164
+
165
+ def ok?
166
+ ok == true
167
+ end
168
+
169
+ def to_h
170
+ {
171
+ ok: ok, issues: issues.map(&:to_h), required_documents: required_documents,
172
+ missing_documents: missing_documents, documents: documents.map(&:to_h),
173
+ ignored_fields: ignored_fields
174
+ }.compact
175
+ end
176
+ end
177
+
178
+ # One of the workspace's short code applications, with its code once
179
+ # Sendly assigns one. +short_code+ is nil until then, and drafts,
180
+ # rejected and cancelled applications are listed too. +billing+ is a Hash
181
+ # with snake_case Symbol keys (+billing[:setup_fee][:status]+,
182
+ # +billing[:lease][:state]+).
183
+ class ShortCode
184
+ attr_reader :id, :short_code, :country_code, :status, :review_status, :use_case, :created_at, :billing
185
+
186
+ def initialize(data)
187
+ data ||= {}
188
+ @id = data["id"]
189
+ @short_code = data["shortCode"]
190
+ @country_code = data["countryCode"]
191
+ @status = data["status"]
192
+ @review_status = data["reviewStatus"]
193
+ @use_case = data["useCase"]
194
+ @created_at = data["createdAt"]
195
+ @billing = RcsRegistrationInput.underscore(data["billing"] || {})
196
+ end
197
+
198
+ def active?
199
+ status == "active"
200
+ end
201
+
202
+ def to_h
203
+ {
204
+ id: id, short_code: short_code, country_code: country_code, status: status,
205
+ review_status: review_status, use_case: use_case, created_at: created_at,
206
+ billing: billing
207
+ }.compact
208
+ end
209
+ end
210
+
211
+ # The workspace's short code application: read it, save answers, check
212
+ # it against the carrier rules and submit it. Answers are passed as
213
+ # keywords in snake_case or camelCase (+use_case:+ or +useCase:+), the
214
+ # same fields the API takes, such as +use_case+, +opt_in_flow+,
215
+ # +sample_messages+, +order_type+, +code_type+ and +brand_contact_email+.
216
+ class ShortCodeApplicationResource
217
+ def initialize(client)
218
+ @client = client
219
+ end
220
+
221
+ # Fetch the application, with the documents it needs, the quote, and
222
+ # +billing+: where the setup fee and the monthly lease stand. Requires
223
+ # the +short_codes:read+ scope.
224
+ #
225
+ # @return [ShortCodeApplicationView]
226
+ # @raise [Sendly::NotFoundError] +short_codes_not_enabled+ (404) when
227
+ # short codes aren't enabled for the account
228
+ #
229
+ # @example
230
+ # view = client.short_codes.application.get
231
+ # puts view.lock_message unless view.editable?
232
+ def get
233
+ ShortCodeApplicationView.new(@client.get("/short_codes/application"))
234
+ end
235
+
236
+ # Save answers on the application, creating it on the first call.
237
+ # Fields Sendly or the carriers own (the digits, the status, the review
238
+ # state) are ignored and named back in +ignored_fields+. Requires the
239
+ # +short_codes:write+ scope.
240
+ #
241
+ # @param idempotency_key [String, nil] Idempotency key for this operation
242
+ # (1-255 printable ASCII characters), so a repeat of the same save
243
+ # returns the first answer
244
+ # @param application [Hash] The answers to save
245
+ # @return [ShortCodeApplicationView]
246
+ # @raise [Sendly::APIError] 409 +short_code_locked+ once the application
247
+ # is with Sendly or the carriers
248
+ #
249
+ # @example
250
+ # client.short_codes.application.update(
251
+ # use_case: "Delivery alerts for Acme orders",
252
+ # message_frequency: "4 messages per month"
253
+ # )
254
+ def update(idempotency_key: nil, **application)
255
+ response = @client.put("/short_codes/application", RcsRegistrationInput.camelize(application),
256
+ idempotency_key: idempotency_key)
257
+ ShortCodeApplicationView.new(response)
258
+ end
259
+
260
+ # Check the application against the carrier rules without changing
261
+ # anything. Unsaved answers can be passed and are checked on top of
262
+ # what is saved. Requires the +short_codes:read+ scope.
263
+ #
264
+ # @param application [Hash] Optional unsaved answers to check as well
265
+ # @return [ShortCodePreflight]
266
+ #
267
+ # @example
268
+ # check = client.short_codes.application.check
269
+ # check.issues.each { |issue| puts "#{issue.path}: #{issue.message}" }
270
+ def check(**application)
271
+ response = @client.post("/short_codes/application/preflight", RcsRegistrationInput.camelize(application))
272
+ ShortCodePreflight.new(response)
273
+ end
274
+
275
+ # Submit the application to Sendly for review. Submitting charges the
276
+ # one-time $999 setup fee to the workspace's card on file, so pass
277
+ # +accept_terms: true+ to accept it, the monthly lease from go-live and
278
+ # the 3-month minimum. The fee is refunded in full if Sendly rejects
279
+ # the application before filing it. Submitting twice is safe: the
280
+ # second call reports +already_submitted+ and charges nothing. Requires
281
+ # the +short_codes:write+ scope.
282
+ #
283
+ # @param idempotency_key [String, nil] Idempotency key for this operation
284
+ # (1-255 printable ASCII characters), so a repeat of the same submit
285
+ # returns the first answer
286
+ # @param application [Hash] +accept_terms+, plus optional final answers
287
+ # saved before the check
288
+ # @return [ShortCodeApplicationView] With +submitted+, +already_submitted+,
289
+ # +notified+ and +payment+ (whether this call charged the fee)
290
+ # @raise [Sendly::APIError] 403 +verification_required+ until
291
+ # the workspace's business is verified; the answers sent are saved anyway
292
+ # @raise [Sendly::ValidationError] 422 +short_code_invalid_application+
293
+ # (with an +errors+ array naming every field, +acceptTerms+ included) or
294
+ # +short_code_ai_draft_unedited+
295
+ # @raise [Sendly::InsufficientCreditsError] 402 +payment_method_required+,
296
+ # +payment_failed+ or +payment_requires_authentication+ when the fee
297
+ # can't be charged; the application stays a draft
298
+ #
299
+ # @example
300
+ # result = client.short_codes.application.submit(accept_terms: true)
301
+ # puts result.application.review_status # "awaiting_review"
302
+ # puts result.billing[:setup_fee][:status] # "paid"
303
+ def submit(idempotency_key: nil, **application)
304
+ response = @client.post("/short_codes/application/submit", RcsRegistrationInput.camelize(application),
305
+ idempotency_key: idempotency_key)
306
+ ShortCodeApplicationView.new(response)
307
+ end
308
+ end
309
+
310
+ # Short codes: 5 or 6 digit US senders. Getting one is an application,
311
+ # not a purchase: you fill it in, Sendly reviews it, the carrier forms are
312
+ # signed, Sendly files it, and each carrier certifies the code.
313
+ class ShortCodesResource
314
+ # @return [ShortCodeApplicationResource] The workspace's application
315
+ attr_reader :application
316
+
317
+ def initialize(client)
318
+ @client = client
319
+ @application = ShortCodeApplicationResource.new(client)
320
+ end
321
+
322
+ # List every short code application of the workspace, newest first,
323
+ # with its code once Sendly assigns one. Drafts, rejected and cancelled
324
+ # applications are listed too, so filter on +status+ for the codes you
325
+ # can send from. Requires the +short_codes:read+ scope.
326
+ #
327
+ # @return [Array<ShortCode>]
328
+ #
329
+ # @example
330
+ # sendable = client.short_codes.list.select(&:active?)
331
+ def list
332
+ response = @client.get("/short_codes")
333
+ (response["shortCodes"] || []).map { |code| ShortCode.new(code) }
334
+ end
335
+ end
336
+ end
@@ -229,6 +229,27 @@ module Sendly
229
229
  Template.new(response)
230
230
  end
231
231
 
232
+ # Render one of the workspace's templates, or any preset, with the values
233
+ # you give. Nothing is sent or saved.
234
+ #
235
+ # @param id [String] Template ID
236
+ # @param variables [Hash, nil] Values by variable key:
237
+ # +{ "code" => "123456" }+ fills +{{code}}+. Without it, each variable
238
+ # renders with its fallback.
239
+ # @return [Sendly::TemplatePreview]
240
+ # @raise [Sendly::NotFoundError] if no preset and no template of the key's
241
+ # workspace has this id
242
+ #
243
+ # @example
244
+ # preview = client.templates.preview("tpl_preset_otp", variables: { code: "123456" })
245
+ # puts preview.rendered_text
246
+ def preview(id, variables: nil)
247
+ body = {}
248
+ body[:variables] = variables if variables
249
+ response = @client.post("/templates/#{URI.encode_www_form_component(id)}/preview", body)
250
+ TemplatePreview.new(response)
251
+ end
252
+
232
253
  def generate(description:, category: nil)
233
254
  body = { description: description }
234
255
  body[:category] = category if category
data/lib/sendly/types.rb CHANGED
@@ -77,6 +77,10 @@ module Sendly
77
77
  # message it replaced
78
78
  attr_reader :fallback_of
79
79
 
80
+ # @return [String, nil] The batch that sent the message; nil unless it is
81
+ # a batch message
82
+ attr_reader :batch_id
83
+
80
84
  # Message status constants (sending removed - doesn't exist in database)
81
85
  STATUSES = %w[queued sent delivered failed bounced retrying].freeze
82
86
 
@@ -108,6 +112,7 @@ module Sendly
108
112
  @message_format = data["messageFormat"] || data["message_format"] || "sms"
109
113
  @fallback = data["fallback"].is_a?(Hash) ? WhatsAppSmsFallback.new(data["fallback"]) : nil
110
114
  @fallback_of = data["fallbackOf"] || data["fallback_of"]
115
+ @batch_id = data["batchId"] || data["batch_id"]
111
116
  end
112
117
 
113
118
  # Check if message was delivered
@@ -155,7 +160,8 @@ module Sendly
155
160
  media_urls: media_urls,
156
161
  message_format: message_format,
157
162
  fallback: fallback&.to_h,
158
- fallback_of: fallback_of
163
+ fallback_of: fallback_of,
164
+ batch_id: batch_id
159
165
  }.compact
160
166
  end
161
167
 
@@ -368,7 +374,7 @@ module Sendly
368
374
  @circuit_state = data["circuit_state"] || data["circuitState"] || "closed"
369
375
  @circuit_opened_at = parse_time(data["circuit_opened_at"] || data["circuitOpenedAt"])
370
376
  @api_version = data["api_version"] || data["apiVersion"] || "2024-01"
371
- @metadata = data["metadata"] || {}
377
+ @metadata = data["metadata"].is_a?(Hash) ? data["metadata"] : {}
372
378
  @created_at = parse_time(data["created_at"] || data["createdAt"])
373
379
  @updated_at = parse_time(data["updated_at"] || data["updatedAt"])
374
380
  @total_deliveries = data["total_deliveries"] || data["totalDeliveries"] || 0
@@ -548,6 +554,98 @@ module Sendly
548
554
  end
549
555
  end
550
556
 
557
+ # What a webhook recovery would do for a window, without sending anything
558
+ #
559
+ # Returned by {Sendly::WebhooksResource#recovery_preview}. The API sends
560
+ # its keys in camelCase; the readers are snake_case and nested values are
561
+ # Hashes with symbol keys. Count maps keep the API's string keys, such as
562
+ # "failed" or "message.delivered".
563
+ class WebhookRecoveryPreview
564
+ # @return [String] "closed", "open" or "half_open"
565
+ attr_reader :circuit_state
566
+
567
+ # @return [Time, nil] When the circuit opened
568
+ attr_reader :circuit_opened_at
569
+
570
+ # @return [Integer] Failed deliveries in the current streak
571
+ attr_reader :failure_count
572
+
573
+ # @return [Hash] Failed and cancelled deliveries in the window, what
574
+ # {Sendly::WebhooksResource#redeliver} would send:
575
+ # +{ total:, by_status:, by_event_type: }+
576
+ attr_reader :audit_failures
577
+
578
+ # @return [Hash] Message events with no delivery in the window, what
579
+ # {Sendly::WebhooksResource#backfill} would send: +{ total:, by_event_type: }+
580
+ attr_reader :missing_from_messages
581
+
582
+ # @return [Array<Hash>] The window in up to 24 equal buckets, oldest
583
+ # first: +{ bucket:, missing:, failed: }+
584
+ attr_reader :histogram
585
+
586
+ # @return [Array<Hash>] Up to 5 affected events:
587
+ # +{ id:, to_masked:, event_type:, occurred_at: }+
588
+ attr_reader :samples
589
+
590
+ # @return [Hash, nil] The outage window, +{ since:, until: }+, when the
591
+ # circuit has an opening time
592
+ attr_reader :window_suggestion
593
+
594
+ # @return [Time, nil] The window's start
595
+ attr_reader :since
596
+
597
+ # @return [Time, nil] The window's end
598
+ attr_reader :until
599
+
600
+ # @return [Hash] The raw parsed response
601
+ attr_reader :raw
602
+
603
+ def initialize(data)
604
+ @raw = data
605
+ @circuit_state = data["circuitState"]
606
+ @circuit_opened_at = parse_time(data["circuitOpenedAt"])
607
+ @failure_count = data["failureCount"] || 0
608
+ audit = data["auditFailures"] || {}
609
+ @audit_failures = {
610
+ total: audit["total"] || 0,
611
+ by_status: audit["byStatus"] || {},
612
+ by_event_type: audit["byEventType"] || {}
613
+ }
614
+ missing = data["missingFromMessages"] || {}
615
+ @missing_from_messages = {
616
+ total: missing["total"] || 0,
617
+ by_event_type: missing["byEventType"] || {}
618
+ }
619
+ @histogram = (data["histogram"] || []).map do |b|
620
+ { bucket: parse_time(b["bucket"]), missing: b["missing"], failed: b["failed"] }
621
+ end
622
+ @samples = (data["samples"] || []).map do |s|
623
+ { id: s["id"], to_masked: s["toMasked"], event_type: s["eventType"],
624
+ occurred_at: parse_time(s["occurredAt"]) }
625
+ end
626
+ suggestion = data["windowSuggestion"]
627
+ @window_suggestion = suggestion && {
628
+ since: parse_time(suggestion["since"]),
629
+ until: parse_time(suggestion["until"])
630
+ }
631
+ @since = parse_time(data["since"])
632
+ @until = parse_time(data["until"])
633
+ end
634
+
635
+ def circuit_open?
636
+ circuit_state == "open"
637
+ end
638
+
639
+ private
640
+
641
+ def parse_time(value)
642
+ return nil if value.nil?
643
+ Time.parse(value)
644
+ rescue ArgumentError
645
+ nil
646
+ end
647
+ end
648
+
551
649
  # ============================================================================
552
650
  # Account & Credits
553
651
  # ============================================================================
@@ -854,10 +952,24 @@ module Sendly
854
952
  # @return [String, nil] Model that generated the suggestions
855
953
  attr_reader :model
856
954
 
955
+ # @return [Boolean] True when the workspace's enterprise account turned
956
+ # AI suggestions off; {#suggestions} is then empty
957
+ attr_reader :disabled
958
+
959
+ # @return [String, nil] Why suggestions are off: "enterprise_policy".
960
+ # Nil unless {#disabled} is true
961
+ attr_reader :reason
962
+
857
963
  def initialize(data)
858
964
  @suggestions = (data["suggestions"] || []).map { |s| SuggestedReply.new(s) }
859
965
  @based_on_message_id = data["basedOnMessageId"] || data["based_on_message_id"]
860
966
  @model = data["model"]
967
+ @disabled = data["disabled"] == true
968
+ @reason = data["reason"]
969
+ end
970
+
971
+ def disabled?
972
+ disabled
861
973
  end
862
974
 
863
975
  def each(&block)
@@ -883,7 +995,9 @@ module Sendly
883
995
  {
884
996
  suggestions: suggestions.map(&:to_h),
885
997
  based_on_message_id: based_on_message_id,
886
- model: model
998
+ model: model,
999
+ disabled: (disabled || nil),
1000
+ reason: reason
887
1001
  }.compact
888
1002
  end
889
1003
  end
@@ -1087,7 +1201,7 @@ module Sendly
1087
1201
  # ============================================================================
1088
1202
 
1089
1203
  class Rule
1090
- attr_reader :id, :name, :conditions, :actions, :priority, :created_at, :updated_at
1204
+ attr_reader :id, :name, :conditions, :actions, :priority, :enabled, :created_at, :updated_at
1091
1205
 
1092
1206
  def initialize(data)
1093
1207
  @id = data["id"]
@@ -1095,6 +1209,7 @@ module Sendly
1095
1209
  @conditions = data["conditions"] || {}
1096
1210
  @actions = data["actions"] || {}
1097
1211
  @priority = data["priority"]
1212
+ @enabled = data["enabled"]
1098
1213
  @created_at = parse_time(data["createdAt"] || data["created_at"])
1099
1214
  @updated_at = parse_time(data["updatedAt"] || data["updated_at"])
1100
1215
  end
@@ -1121,6 +1236,42 @@ module Sendly
1121
1236
  # Generated Template
1122
1237
  # ============================================================================
1123
1238
 
1239
+ # A template rendered with the values you gave. Nothing is sent or saved.
1240
+ class TemplatePreview
1241
+ # @return [String] The template's id
1242
+ attr_reader :template_id
1243
+
1244
+ # @return [String] The template's text, unrendered
1245
+ attr_reader :original_text
1246
+
1247
+ # @return [String] The text with each +{{key}}+ replaced by the value you
1248
+ # sent, else the variable's fallback. A variable with neither stays as
1249
+ # +{{key}}+.
1250
+ attr_reader :rendered_text
1251
+
1252
+ # @return [Integer, nil] The rendered text's length, in UTF-16 code units
1253
+ attr_reader :character_count
1254
+
1255
+ # @return [Integer, nil] How many SMS segments the rendered text needs
1256
+ attr_reader :segment_count
1257
+
1258
+ def initialize(data)
1259
+ @template_id = data["template_id"] || data["templateId"]
1260
+ @original_text = data["original_text"] || data["originalText"]
1261
+ @rendered_text = data["rendered_text"] || data["renderedText"]
1262
+ @character_count = data["character_count"] || data["characterCount"]
1263
+ @segment_count = data["segment_count"] || data["segmentCount"]
1264
+ end
1265
+
1266
+ def to_h
1267
+ {
1268
+ template_id: template_id, original_text: original_text,
1269
+ rendered_text: rendered_text, character_count: character_count,
1270
+ segment_count: segment_count
1271
+ }.compact
1272
+ end
1273
+ end
1274
+
1124
1275
  class GeneratedTemplate
1125
1276
  attr_reader :name, :text, :variables, :category
1126
1277
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Sendly
4
- VERSION = "4.6.0"
4
+ VERSION = "4.7.0"
5
5
  end
@@ -168,6 +168,26 @@ module Sendly
168
168
  @client.post("/webhooks/#{URI.encode_www_form_component(webhook_id)}/backfill", body)
169
169
  end
170
170
 
171
+ # Preview a recovery: count what {#redeliver} and {#backfill} would send
172
+ # for a window, without sending anything. The window is at most 7 days.
173
+ #
174
+ # @param webhook_id [String] Webhook ID
175
+ # @param since [String, nil] ISO-8601, default now − 24h
176
+ # @param until_ [String, nil] ISO-8601, default now
177
+ # @param event_types [Array<String>, nil] Event types to count, sent
178
+ # comma-separated (default all)
179
+ # @return [Sendly::WebhookRecoveryPreview]
180
+ def recovery_preview(webhook_id, since: nil, until_: nil, event_types: nil)
181
+ validate_webhook_id!(webhook_id)
182
+ params = {}
183
+ params[:since] = since unless since.nil?
184
+ params[:until] = until_ unless until_.nil?
185
+ params[:event_types] = event_types.join(",") unless event_types.nil? || event_types.empty?
186
+
187
+ response = @client.get("/webhooks/#{URI.encode_www_form_component(webhook_id)}/recovery-preview", params)
188
+ WebhookRecoveryPreview.new(response)
189
+ end
190
+
171
191
  # Rotate the webhook signing secret
172
192
  #
173
193
  # Deliveries are signed with the new secret as soon as this returns, and
@@ -574,6 +574,11 @@ module Sendly
574
574
  # the number (at most 512 characters). Defaults to the account's
575
575
  # existing sender display name, then its business name. Only with
576
576
  # +business_account_id+.
577
+ # @param idempotency_key [String, nil] Idempotency key for this operation
578
+ # (1-255 printable ASCII characters). The client already sends one per
579
+ # call; pass your own to make a repeat after a restart, or after an
580
+ # error the client does not retry, return the first answer instead of
581
+ # starting another charged signup.
577
582
  # @return [WhatsAppSignupSession]
578
583
  # @raise [Sendly::ServerError] +whatsapp_unavailable+ (503) while
579
584
  # WhatsApp connections are unavailable. Nothing is charged. Only
@@ -617,7 +622,8 @@ module Sendly
617
622
  # business_account_id: "102290129340398"
618
623
  # )
619
624
  # puts signup.status # "verifying"
620
- def create(phone_number:, business_account_id: nil, verification_method: nil, display_name: nil)
625
+ def create(phone_number:, business_account_id: nil, verification_method: nil, display_name: nil,
626
+ idempotency_key: nil)
621
627
  raise ValidationError, "phone_number is required" if phone_number.nil? || phone_number.to_s.empty?
622
628
  if !business_account_id.nil? && business_account_id.to_s.strip.empty?
623
629
  raise ValidationError, "business_account_id must be a non-empty string"
@@ -629,7 +635,8 @@ module Sendly
629
635
  body[:displayName] = display_name unless display_name.nil?
630
636
 
631
637
  by_code = !business_account_id.nil? && !business_account_id.to_s.empty?
632
- response = @client.post("/whatsapp/signup", body, retry_server_errors: !by_code)
638
+ response = @client.post("/whatsapp/signup", body, idempotency_key: idempotency_key,
639
+ retry_server_errors: !by_code)
633
640
  WhatsAppSignupSession.new(response)
634
641
  end
635
642
 
@@ -1039,6 +1046,10 @@ module Sendly
1039
1046
  # @param examples [Hash, nil] Example values for body placeholders,
1040
1047
  # keyed by placeholder number: { "1" => "Acme Inc", "2" => "#4821" }.
1041
1048
  # Required when the body has variables.
1049
+ # @param idempotency_key [String, nil] Idempotency key for this operation
1050
+ # (1-255 printable ASCII characters). Repeating the call with the same
1051
+ # key within 24 hours returns the first answer instead of creating the
1052
+ # template again.
1042
1053
  # @return [WhatsAppTemplate] The created template (status "PENDING"),
1043
1054
  # with any submission warnings
1044
1055
  # @raise [Sendly::NotFoundError] +whatsapp_sender_not_connected+ (404) if
@@ -1062,7 +1073,7 @@ module Sendly
1062
1073
  # )
1063
1074
  # puts template.status # "PENDING"
1064
1075
  def create(sender:, name:, language:, category:, body:,
1065
- header: nil, footer: nil, buttons: nil, examples: nil)
1076
+ header: nil, footer: nil, buttons: nil, examples: nil, idempotency_key: nil)
1066
1077
  raise ValidationError, "sender is required" if sender.nil? || sender.to_s.empty?
1067
1078
  raise ValidationError, "name is required" if name.nil? || name.to_s.empty?
1068
1079
  raise ValidationError, "language is required" if language.nil? || language.to_s.empty?
@@ -1081,7 +1092,7 @@ module Sendly
1081
1092
  payload[:buttons] = buttons if buttons
1082
1093
  payload[:examples] = examples if examples
1083
1094
 
1084
- response = @client.post("/whatsapp/templates", payload)
1095
+ response = @client.post("/whatsapp/templates", payload, idempotency_key: idempotency_key)
1085
1096
  WhatsAppTemplate.new(response)
1086
1097
  end
1087
1098
 
@@ -1097,9 +1108,11 @@ module Sendly
1097
1108
  # @param id [String] The template's id
1098
1109
  # @param body [String, nil] Replacement body text
1099
1110
  # @param header [String, nil] Replacement text header; it can't contain
1100
- # {{n}} variables (+template_header_variable_unsupported+)
1101
- # @param footer [String, nil] Replacement footer
1102
- # @param buttons [Array<Hash>, nil] Replacement buttons
1111
+ # {{n}} variables (+template_header_variable_unsupported+). Pass +""+
1112
+ # to remove the header
1113
+ # @param footer [String, nil] Replacement footer. Pass +""+ to remove it
1114
+ # @param buttons [Array<Hash>, nil] Replacement buttons. Pass +[]+ to
1115
+ # remove every button
1103
1116
  # @param examples [Hash, nil] Replacement example values for body placeholders
1104
1117
  # @return [WhatsAppTemplate] The updated template (status "PENDING")
1105
1118
  # @raise [Sendly::NotFoundError] If no such template exists
data/lib/sendly.rb CHANGED
@@ -27,6 +27,7 @@ require_relative "sendly/tendlc_resource"
27
27
  require_relative "sendly/links_resource"
28
28
  require_relative "sendly/whatsapp_resource"
29
29
  require_relative "sendly/rcs_resource"
30
+ require_relative "sendly/short_codes_resource"
30
31
  require_relative "sendly/calls_resource"
31
32
  require_relative "sendly/voice_resource"
32
33
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sendly
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.6.0
4
+ version: 4.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sendly
@@ -141,6 +141,7 @@ files:
141
141
  - lib/sendly/numbers_resource.rb
142
142
  - lib/sendly/rcs_resource.rb
143
143
  - lib/sendly/rules_resource.rb
144
+ - lib/sendly/short_codes_resource.rb
144
145
  - lib/sendly/templates_resource.rb
145
146
  - lib/sendly/tendlc_resource.rb
146
147
  - lib/sendly/types.rb