unitpost 0.4.0 → 0.5.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.
@@ -30,8 +30,10 @@ module Unitpost
30
30
  FORWARD_ONLY_MESSAGE = "list_all pages forward only: `before` is not supported (use list to page backward)."
31
31
 
32
32
  # Forward only, refused up front: a `before` cursor used to ride along
33
- # with the moving `after` and 422 on the second page.
34
- def paginate(path, params)
33
+ # with the moving `after` and 422 on the second page. `cursor` is the
34
+ # row field the next `after` reads: "id", except for a list paged by
35
+ # another key (organization usage rows page by "workspace_id").
36
+ def paginate(path, params, cursor: "id")
35
37
  before = params[:before] || params["before"]
36
38
  raise ArgumentError, FORWARD_ONLY_MESSAGE if before && !before.to_s.empty?
37
39
 
@@ -47,20 +49,34 @@ module Unitpost
47
49
  rows.each { |row| yielder << row }
48
50
  break if !page["has_more"] || rows.empty?
49
51
 
50
- after = rows.last["id"]
52
+ after = rows.last[cursor]
53
+ break if after.nil? || after.to_s.empty?
51
54
  end
52
55
  end
53
56
  end
54
57
  end
55
58
 
56
59
  class Sms < Base
57
- attr_reader :templates, :campaigns, :topics
60
+ # SMS setup: messaging_programs, test_destinations, consent_setups,
61
+ # billing, registrations and quotes. Carrier purchases go through quotes
62
+ # (a price, then a confirm with the opt-in sms:purchase scope); a brand's
63
+ # documents and the carrier send-backs work here too (ADR-0159), and so
64
+ # do releasing a number, removing a 10DLC setup and replacing a brand
65
+ # registration (ADR-0160).
66
+ attr_reader :templates, :campaigns, :topics, :messaging_programs, :test_destinations, :consent_setups, :billing,
67
+ :registrations, :quotes
58
68
 
59
69
  def initialize(http)
60
70
  super(http)
61
71
  @templates = SmsTemplates.new(http)
62
72
  @campaigns = SmsCampaigns.new(http)
63
73
  @topics = SmsTopics.new(http)
74
+ @messaging_programs = SmsMessagingPrograms.new(http)
75
+ @test_destinations = SmsTestDestinations.new(http)
76
+ @consent_setups = SmsConsentSetups.new(http)
77
+ @billing = SmsBilling.new(http)
78
+ @registrations = SmsRegistrations.new(http)
79
+ @quotes = SmsQuotes.new(http)
64
80
  end
65
81
 
66
82
  # SMS channel (paid plans). Recipient must be E.164; marketing sends require
@@ -75,12 +91,35 @@ module Unitpost
75
91
  @http.request("GET", "/sms/#{enc(id)}")
76
92
  end
77
93
 
94
+ # Make the sender of a received text a contact, or file the text under
95
+ # the contact that already has the number. Phone only: no name and no
96
+ # consent (texting a number isn't consent to marketing). Every earlier
97
+ # text with that number that no contact holds is filed under the contact
98
+ # too, so contact_id reads it from then on. Answers the contact: 201 when
99
+ # it is new, 200 when it existed, so a retry is safe. It counts against
100
+ # the plan's contacts (403 limit_reached when full), and a number that
101
+ # texted STOP stays opted out. A text you sent is refused (409). Needs
102
+ # contacts:write and sms:read.
103
+ def add_contact(id)
104
+ @http.request("POST", "/sms/#{enc(id)}/contact", body: {})
105
+ end
106
+
78
107
  # Cancel a queued/scheduled SMS ({ cancel: true }, credit refunded) or
79
108
  # move a scheduled one ({ scheduled_at: "<ISO 8601>" }).
80
109
  def update(id, body)
81
110
  @http.request("PATCH", "/sms/#{enc(id)}", body: body)
82
111
  end
83
112
 
113
+ # params: direction, status, from, to, participant (the other party,
114
+ # both directions), contact_id, campaign_id, created_after,
115
+ # created_before, q (the message text; 3 or more digits also match
116
+ # either number; at most 200 characters), type ("transactional" or
117
+ # "marketing"), sender_id (a number's "snum_…" id: its texts, both
118
+ # directions), tag (texts sent with that tag, "name:value"; several
119
+ # comma-separated, e.g. "customer:acme,flow:reminders", must all match;
120
+ # received texts have none). A q, type or sender_id value the list
121
+ # can't apply is ignored and named in the Unitpost-Warning response
122
+ # header; Unitpost-Strict: true refuses it instead.
84
123
  def list(params = {})
85
124
  @http.request("GET", "/sms", query: params)
86
125
  end
@@ -96,24 +135,144 @@ module Unitpost
96
135
  # +status+ says whether you or the carrier is the blocker, and +missing+
97
136
  # lists exactly what is still required.
98
137
  #
99
- # Read-only — creating a brand is a paid carrier submission and is only
100
- # available in the dashboard.
138
+ # Create and edit a brand with create_brand / update_brand (free).
139
+ # Registering it with carriers is a paid order: sms.quotes.create prices
140
+ # it, sms.quotes.confirm places it. Needs sms:read.
101
141
  def brands(params = {})
102
142
  @http.request("GET", "/sms/brands", query: params)
103
143
  end
104
144
 
145
+ # Create a brand (201): the business identity carriers register before
146
+ # they approve a number. A draft may be partial (only :name is
147
+ # required); missing says what is still needed. Free, with no carrier
148
+ # call; one brand per website domain (409). The tax id is write-only:
149
+ # stored encrypted, read back as tax_id_on_file. Registering the brand
150
+ # with carriers is a paid order through sms.quotes. Needs sms:manage. Pass an idempotency_key so a retry never makes a second
151
+ # brand; one is generated when you don't.
152
+ def create_brand(body, idempotency_key: nil)
153
+ @http.request("POST", "/sms/brands", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
154
+ end
155
+
156
+ # One brand with every field you can edit, its status and missing list.
157
+ # Needs sms:read.
158
+ def get_brand(id)
159
+ @http.request("GET", "/sms/brands/#{enc(id)}")
160
+ end
161
+
162
+ # Edit a brand: only the fields you send change, nil clears an optional
163
+ # one; send { archived: ... } alone to archive or restore it. The tax id
164
+ # is write-only. A locked brand (editable: false: carriers are reviewing
165
+ # or approved it, or it has numbers) refuses carrier-field edits with
166
+ # 409 brand_locked, details naming each field, except those a correction
167
+ # request opened. Needs sms:manage.
168
+ def update_brand(id, body)
169
+ @http.request("PATCH", "/sms/brands/#{enc(id)}", body: body)
170
+ end
171
+
172
+ # A brand's documents (sdoc_ ids): the files and numbers a country's
173
+ # carriers ask for, one per slot (kind, plus carrier / country for a
174
+ # variant). Needs sms:read.
175
+ def list_brand_documents(brand_id)
176
+ @http.request("GET", "/sms/brands/#{enc(brand_id)}/documents")
177
+ end
178
+
179
+ # Add a document to a brand's slot (201): a file kind takes file_id (a
180
+ # file from files.create, purpose sms_document, or sms_opt_in_evidence
181
+ # for opt_in_screenshot), a text kind takes text. A document in an
182
+ # occupied slot replaces the current one. Needs sms:manage. Pass an
183
+ # idempotency_key so a retry adds one document; one is generated when
184
+ # you don't.
185
+ def add_brand_document(brand_id, body, idempotency_key: nil)
186
+ @http.request("POST", "/sms/brands/#{enc(brand_id)}/documents", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
187
+ end
188
+
189
+ # One brand document. Needs sms:read.
190
+ def get_brand_document(brand_id, document_id)
191
+ @http.request("GET", "/sms/brands/#{enc(brand_id)}/documents/#{enc(document_id)}")
192
+ end
193
+
194
+ # Remove a brand document from its slot. Needs sms:manage.
195
+ def remove_brand_document(brand_id, document_id)
196
+ @http.request("DELETE", "/sms/brands/#{enc(brand_id)}/documents/#{enc(document_id)}")
197
+ end
198
+
199
+ # A 5-minute signed link to a file document's bytes. The link is a
200
+ # bearer credential: fetch it yourself, don't log or share it. An
201
+ # identity document needs sms:manage; the rest sms:read.
202
+ def brand_document_url(brand_id, document_id)
203
+ @http.request("GET", "/sms/brands/#{enc(brand_id)}/documents/#{enc(document_id)}/url")
204
+ end
205
+
105
206
  # List SMS phone numbers.
106
207
  #
107
208
  # Only numbers with +status+ of "active" can send. A +ten_dlc+ number has
108
209
  # no +phone_number+ until carriers approve it, and a +simulator+ number
109
210
  # only reaches verified test destinations.
110
211
  #
111
- # Read-only — requesting or releasing a number is only available in the
112
- # dashboard.
212
+ # Order a number through sms.quotes; release one with release_number.
113
213
  def numbers(params = {})
114
214
  @http.request("GET", "/sms/numbers", query: params)
115
215
  end
116
216
 
217
+ # One number, or one country of a Sender ID (snum_…), as numbers reads
218
+ # it: its status, what carriers sent back (feedback) and its use case.
219
+ # Read a resubmit, a retry or a release back with it. Needs sms:read.
220
+ def get_number(number_id)
221
+ @http.request("GET", "/sms/numbers/#{enc(number_id)}")
222
+ end
223
+
224
+ # Release a number, or one country of a Sender ID, back to the carrier.
225
+ # PERMANENT: it stops sending at once, reads released from then on and
226
+ # can't be had back; its monthly fee ends with it (no proration), and a
227
+ # 10DLC number's campaign registration goes with it. Refused while an
228
+ # automation uses it (409 resource_in_use) and, unless { force: true },
229
+ # while campaigns are scheduled on it or texts are queued through it
230
+ # (409 sender_release_blocked, counts in error.blockers). Releasing a
231
+ # released number answers it. Needs sms:manage. Pass an idempotency_key
232
+ # so a retry releases once; one is generated when you don't.
233
+ def release_number(number_id, body = {}, idempotency_key: nil)
234
+ @http.request("POST", "/sms/numbers/#{enc(number_id)}/release", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
235
+ end
236
+
237
+ # Resubmit a toll-free verification carriers sent back (free): fix what
238
+ # the number's feedback names, then send the new evidence
239
+ # (opt_in_evidence_file_id, or reuse_opt_in_evidence), a
240
+ # business_registration_document_file_id, consent_source_url, or
241
+ # acknowledge_unchanged. Needs sms:manage. Pass an idempotency_key so a
242
+ # retry resubmits once; one is generated when you don't.
243
+ def resubmit_number(number_id, body, idempotency_key: nil)
244
+ @http.request("POST", "/sms/numbers/#{enc(number_id)}/resubmit", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
245
+ end
246
+
247
+ # Text-to-join: the words people can text this number (snum_…) to sign
248
+ # up. registration_warning is set when the number's carrier registration
249
+ # doesn't list keyword opt-in, so carriers could flag the sign-ups. Needs
250
+ # sms:read.
251
+ def list_join_keywords(number_id)
252
+ @http.request("GET", "/sms/numbers/#{enc(number_id)}/join-keywords")
253
+ end
254
+
255
+ # Add a join keyword to a number ({ keyword: "JOIN", segment_id: ...,
256
+ # topic_id: ... }). A text that is exactly this word (any case) gets the
257
+ # double opt-in request ("Reply YES to get … texts"); the YES records
258
+ # marketing consent, makes the texter a contact if they aren't one, and
259
+ # adds them to segment_id (a static segment) and/or topic_id (an SMS
260
+ # topic). A keyword is never consent by itself and never lifts a STOP.
261
+ # STOP, HELP, START, YES and their variants are refused; at most 10 per
262
+ # number, and only on numbers people can text back. Answers the keyword
263
+ # with registration_warning: 201 when added, 200 when the same keyword
264
+ # with the same settings is already there, so a retry is safe (the same
265
+ # word with other settings is 409). Needs sms:manage.
266
+ def add_join_keyword(number_id, body)
267
+ @http.request("POST", "/sms/numbers/#{enc(number_id)}/join-keywords", body: body)
268
+ end
269
+
270
+ # Remove a join keyword (sjk_…): it stops answering. People who already
271
+ # joined keep their consent, contact and memberships. Needs sms:manage.
272
+ def remove_join_keyword(number_id, keyword_id)
273
+ @http.request("DELETE", "/sms/numbers/#{enc(number_id)}/join-keywords/#{enc(keyword_id)}")
274
+ end
275
+
117
276
  # SMS delivery stats over a rolling window (days: 1–365, defaults to 30
118
277
  # server-side): queued, sent, delivered, failed, suppressed, canceled,
119
278
  # inbound and segments billed, with delivery, failure and suppression
@@ -131,6 +290,14 @@ module Unitpost
131
290
  def record_sms_consent(contact_id, body)
132
291
  @http.request("POST", "/contacts/#{enc(contact_id)}/sms-consent", body: body)
133
292
  end
293
+
294
+ # Text the contact a request to reply YES to confirm marketing texts.
295
+ # Optional body `{ phone: "+1..." }` picks the number. It sends a real
296
+ # text, so pass an idempotency_key to make a retry safe; one is generated
297
+ # when you don't.
298
+ def request_sms_opt_in(contact_id, body = {}, idempotency_key: nil)
299
+ @http.request("POST", "/contacts/#{enc(contact_id)}/sms-opt-in-request", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
300
+ end
134
301
  end
135
302
 
136
303
  # SMS templates: plain-text bodies with {{variable}} placeholders.
@@ -158,6 +325,25 @@ module Unitpost
158
325
  def delete(id)
159
326
  @http.request("DELETE", "/sms/templates/#{enc(id)}")
160
327
  end
328
+
329
+ # What uses the template, and whether a change would be accepted now: its
330
+ # live campaigns and automations, queued texts, and can_edit_content /
331
+ # can_unpublish with the reason when not. Read it before an edit or a
332
+ # delete. Needs templates:read.
333
+ def usage(id)
334
+ @http.request("GET", "/sms/templates/#{enc(id)}/usage")
335
+ end
336
+
337
+ # Send ONE test text of the template to body[:to], which must be a
338
+ # simulator number (+14254147755 delivers, +14254147167 fails) or a
339
+ # verified number from sms.test_destinations.list (any other is a 403).
340
+ # Every {{variable}} needs a value in :variables (422). It goes from
341
+ # :sender_id, or is routed by the destination's country. It is a real
342
+ # text, billed like any. Needs sms:send. Pass an idempotency_key so a
343
+ # retry never texts twice; one is generated when you don't.
344
+ def test_send(id, body, idempotency_key: nil)
345
+ @http.request("POST", "/sms/templates/#{enc(id)}/test-send", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
346
+ end
161
347
  end
162
348
 
163
349
  # SMS campaigns: a published SMS template sent to a segment. create makes a
@@ -204,6 +390,19 @@ module Unitpost
204
390
  @http.request("POST", "/sms/campaigns/#{enc(id)}/resume")
205
391
  end
206
392
 
393
+ # Move a scheduled campaign back to draft so it can be edited; clears its
394
+ # send time.
395
+ def unschedule(id)
396
+ @http.request("POST", "/sms/campaigns/#{enc(id)}/unschedule")
397
+ end
398
+
399
+ # Copy a campaign into a new draft (201). Optional body `{ name: "..." }`.
400
+ # Pass an idempotency_key so a retry returns the same copy; one is
401
+ # generated when you don't.
402
+ def duplicate(id, body = {}, idempotency_key: nil)
403
+ @http.request("POST", "/sms/campaigns/#{enc(id)}/duplicate", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
404
+ end
405
+
207
406
  def reschedule(id, body)
208
407
  @http.request("POST", "/sms/campaigns/#{enc(id)}/reschedule", body: body)
209
408
  end
@@ -211,6 +410,15 @@ module Unitpost
211
410
  def validate(id)
212
411
  @http.request("GET", "/sms/campaigns/#{enc(id)}/validate")
213
412
  end
413
+
414
+ # How each recipient fared: the carrier's answer for a text that went out
415
+ # (delivered, sent, failed, ...), or why none was sent (skipped, with
416
+ # reason_code). Newest first, cursor-paginated on id; q matches digits of
417
+ # the number. skipped_by_reason counts skipped recipients over the whole
418
+ # campaign.
419
+ def list_recipients(id, limit: nil, after: nil, before: nil, q: nil)
420
+ @http.request("GET", "/sms/campaigns/#{enc(id)}/recipients", query: list_params(limit: limit, after: after, before: before, q: q))
421
+ end
214
422
  end
215
423
 
216
424
  # SMS subscription topics (independent from email topics); delete archives.
@@ -238,10 +446,209 @@ module Unitpost
238
446
  def delete(id)
239
447
  @http.request("DELETE", "/sms/topics/#{enc(id)}")
240
448
  end
449
+
450
+ # Opt many contacts out of this SMS topic as a background job (202, the
451
+ # job): { contact_ids: [...] } or { emails: [...] } (up to 1,000) or
452
+ # { segment_id: } (every member). Follow it with jobs.get(id). Pass an
453
+ # idempotency_key so a retry answers the same job; one is generated when
454
+ # you don't. There is no bulk opt-in.
455
+ def opt_out(id, body, idempotency_key: nil)
456
+ @http.request("POST", "/sms/topics/#{enc(id)}/opt-out", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
457
+ end
458
+ end
459
+
460
+ # Messaging programs (/sms/messaging-programs): what a sender registration
461
+ # says your texts are for, how people opt in, the help and stop replies and
462
+ # sample messages. A registration copies the program when it is submitted,
463
+ # so a later edit never changes one. Reads need sms:read; the writes need
464
+ # sms:manage, which FULL keys have and SENDING keys don't. Submitting a
465
+ # registration is a paid order through sms.quotes.
466
+ class SmsMessagingPrograms < Base
467
+ # Your programs, newest first, cursor-paginated (limit, after, before);
468
+ # archived: true includes archived ones.
469
+ def list(archived: nil, limit: nil, after: nil, before: nil)
470
+ flag = archived.nil? ? nil : (archived ? "true" : "false")
471
+ @http.request("GET", "/sms/messaging-programs", query: list_params(limit: limit, after: after, before: before, archived: flag))
472
+ end
473
+
474
+ # Create a program (201; name is required). Each field is checked by the
475
+ # carriers' rules: lengths, help and stop replies that are a sentence and
476
+ # not just a keyword, links to a real web address. Pass an
477
+ # idempotency_key so a retry never makes a second one; one is generated
478
+ # when you don't.
479
+ def create(body, idempotency_key: nil)
480
+ @http.request("POST", "/sms/messaging-programs", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
481
+ end
482
+
483
+ # One program, archived ones too.
484
+ def get(id)
485
+ @http.request("GET", "/sms/messaging-programs/#{enc(id)}")
486
+ end
487
+
488
+ # Edit a program: only the fields you send change, nil clears one, and
489
+ # the result must still pass the carriers' rules. revision moves on a
490
+ # material change. An archived program is a 409: duplicate it to keep
491
+ # editing.
492
+ def update(id, body)
493
+ @http.request("PATCH", "/sms/messaging-programs/#{enc(id)}", body: body)
494
+ end
495
+
496
+ # Archive a program. Registrations that copied it keep their copy.
497
+ def delete(id)
498
+ @http.request("DELETE", "/sms/messaging-programs/#{enc(id)}")
499
+ end
500
+
501
+ # Copy a program (an archived one too) into a new editable one named
502
+ # "... (copy)" at revision 1 (201). It sends no body. Pass an
503
+ # idempotency_key so a retry returns the same copy; one is generated when
504
+ # you don't.
505
+ def duplicate(id, idempotency_key: nil)
506
+ # No body: the route takes none, and nil sends nothing. It is passed as
507
+ # body: like every idempotent send, which sdk:check reads.
508
+ body = nil
509
+ @http.request("POST", "/sms/messaging-programs/#{enc(id)}/duplicate", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
510
+ end
511
+ end
512
+
513
+ # Test numbers (/sms/test-destinations): the numbers a template test may
514
+ # text besides the simulator, pending until the code texted to one is
515
+ # entered, then verified. Adding and verifying one stays in the dashboard
516
+ # (Phone numbers → Testing), because it proves the phone is yours. list
517
+ # needs sms:read; delete needs sms:manage.
518
+ class SmsTestDestinations < Base
519
+ # Your test numbers, newest first, cursor-paginated (limit, after,
520
+ # before).
521
+ def list(limit: nil, after: nil, before: nil)
522
+ @http.request("GET", "/sms/test-destinations", query: list_params(limit: limit, after: after, before: before))
523
+ end
524
+
525
+ # Remove a test number; template tests can no longer text it.
526
+ def delete(id)
527
+ @http.request("DELETE", "/sms/test-destinations/#{enc(id)}")
528
+ end
529
+ end
530
+
531
+ # Consent setups (/sms/consent-setups): where and how people opt in to your
532
+ # texts, the form or page and the brand and purpose it discloses. A
533
+ # messaging program points at one with consent_setup_id. Needs sms:read.
534
+ class SmsConsentSetups < Base
535
+ # Your consent setups except archived ones, newest first,
536
+ # cursor-paginated (limit, after, before).
537
+ def list(limit: nil, after: nil, before: nil)
538
+ @http.request("GET", "/sms/consent-setups", query: list_params(limit: limit, after: after, before: before))
539
+ end
540
+ end
541
+
542
+ # SMS billing (/sms/billing). Needs sms:read; buying goes through
543
+ # sms.quotes.
544
+ class SmsBilling < Base
545
+ # What the workspace pays for SMS every month: each number and 10DLC
546
+ # campaign, its monthly price, status and next charge, and for a past-due
547
+ # number the date it is released (grace_until). Newest first,
548
+ # cursor-paginated (limit, after, before).
549
+ def list_resources(limit: nil, after: nil, before: nil)
550
+ @http.request("GET", "/sms/billing/resources", query: list_params(limit: limit, after: after, before: before))
551
+ end
552
+ end
553
+
554
+ # Carrier purchases (/sms/quotes): register a 10DLC brand, vet it,
555
+ # register a campaign, order a number. Each is two calls: create prices
556
+ # the order and binds what it buys, confirm places it at the price you
557
+ # showed.
558
+ class SmsQuotes < Base
559
+ # Price an order (201). The quote binds the action and what it buys, and
560
+ # returns due_now_cents, monthly_cents, line_items and a single-use
561
+ # confirm_token (only in this response). It lasts 10 minutes and
562
+ # charges nothing. Needs sms:manage.
563
+ def create(body)
564
+ @http.request("POST", "/sms/quotes", body: body)
565
+ end
566
+
567
+ # One quote: its price, status and, once confirmed, what the order made.
568
+ # Needs sms:read.
569
+ def get(id)
570
+ @http.request("GET", "/sms/quotes/#{enc(id)}")
571
+ end
572
+
573
+ # Place the quoted order and charge it. Show the person the quote's
574
+ # price and get their yes first. Needs sms:purchase, which a key or app
575
+ # has only when a member who holds it ticked it, and the owner's monthly
576
+ # cap for SMS purchases by API. A changed price or content answers 409:
577
+ # quote again. If you don't pass idempotency_key, one is generated so a
578
+ # retry can't buy twice; pass your own to replay the same answer later.
579
+ def confirm(id, body, idempotency_key: nil)
580
+ @http.request("POST", "/sms/quotes/#{enc(id)}/confirm", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
581
+ end
582
+ end
583
+
584
+ # Carrier registrations (/sms/registrations): 10DLC brand and campaign
585
+ # registrations and toll-free verifications, with their review state and
586
+ # the carrier's feedback. Submitting one is a paid order through
587
+ # sms.quotes; fixing a campaign carriers sent back is resubmit, a failed
588
+ # number whose fee is paid is request_number, taking down a 10DLC setup
589
+ # is remove, and archiving an approved brand registration to register it
590
+ # again is replace. Reads need sms:read, the writes sms:manage.
591
+ class SmsRegistrations < Base
592
+ # Your registrations, newest first, cursor-paginated (limit, after,
593
+ # before). A 10DLC campaign also carries the number it backs (sender) and
594
+ # one setup_state.
595
+ def list(limit: nil, after: nil, before: nil)
596
+ @http.request("GET", "/sms/registrations", query: list_params(limit: limit, after: after, before: before))
597
+ end
598
+
599
+ # One registration (sreg_…), as list reads it. Read a resubmit, a
600
+ # removal or a replacement back with it.
601
+ def get(registration_id)
602
+ @http.request("GET", "/sms/registrations/#{enc(registration_id)}")
603
+ end
604
+
605
+ # Resubmit a 10DLC campaign carriers sent back (free), after fixing what
606
+ # its feedback names: an optional opt_in_screenshot_file_id, or
607
+ # acknowledge_unchanged when the fix was made outside Unitpost. Pass an
608
+ # idempotency_key so a retry resubmits once; one is generated when you
609
+ # don't.
610
+ def resubmit(registration_id, body, idempotency_key: nil)
611
+ @http.request("POST", "/sms/registrations/#{enc(registration_id)}/resubmit", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
612
+ end
613
+
614
+ # Request a campaign's number again after it failed, when its fee is
615
+ # already committed (free). A number the fee doesn't cover answers 409
616
+ # quote_required: order it through sms.quotes (ten_dlc_number). Pass an
617
+ # idempotency_key so a retry requests one number; one is generated when
618
+ # you don't.
619
+ def request_number(registration_id, body = {}, idempotency_key: nil)
620
+ @http.request("POST", "/sms/registrations/#{enc(registration_id)}/number", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
621
+ end
622
+
623
+ # Remove a 10DLC setup: take down a campaign registration
624
+ # (us_ten_dlc_campaign) that has no active number. The carrier
625
+ # registration is deleted, the campaign's monthly fee ends (no
626
+ # proration) and the registration reads archived_at from then on. A
627
+ # campaign with a number answers 409 resource_in_use (release the number
628
+ # first with sms.release_number); one under carrier review answers 409
629
+ # conflict. Pass an idempotency_key so a retry removes once; one is
630
+ # generated when you don't.
631
+ def remove(registration_id, body = {}, idempotency_key: nil)
632
+ @http.request("POST", "/sms/registrations/#{enc(registration_id)}/remove", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
633
+ end
634
+
635
+ # Replace an approved 10DLC brand registration (us_ten_dlc_brand):
636
+ # archive it so the brand can be registered again (corrected legal
637
+ # details, a new owner of the EIN). The brand unlocks for
638
+ # sms.update_brand, and the new registration is a quote and its confirm
639
+ # (ten_dlc_brand_registration). Nothing changes at the carrier and
640
+ # nothing is charged here. Refused while a number on the brand isn't
641
+ # released or a 10DLC setup on it isn't removed (409 resource_in_use,
642
+ # with dependents). Pass an idempotency_key so a retry replaces once;
643
+ # one is generated when you don't.
644
+ def replace(registration_id, body = {}, idempotency_key: nil)
645
+ @http.request("POST", "/sms/registrations/#{enc(registration_id)}/replace", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
646
+ end
241
647
  end
242
648
 
243
649
  class Email < Base
244
- attr_reader :topics, :campaigns, :templates, :domains
650
+ # threads: inbox conversations (list, read, delete, reply).
651
+ attr_reader :topics, :campaigns, :templates, :domains, :threads
245
652
 
246
653
  def initialize(http)
247
654
  super
@@ -249,6 +656,7 @@ module Unitpost
249
656
  @campaigns = Campaigns.new(http)
250
657
  @templates = Templates.new(http)
251
658
  @domains = Domains.new(http)
659
+ @threads = EmailThreads.new(http)
252
660
  end
253
661
 
254
662
  # Send or schedule a transactional email. When no idempotency_key is
@@ -275,6 +683,23 @@ module Unitpost
275
683
  @http.request("POST", "/email/batches/#{enc(id)}/cancel")
276
684
  end
277
685
 
686
+ # Your batch sends, newest first (cursor-paginated), as the dashboard's
687
+ # Batches tab lists them. Each row is the same live rollup get_batch
688
+ # returns: how many emails it holds, when it's scheduled, a count per
689
+ # delivery status and how many are still cancelable.
690
+ def list_batches(limit: nil, after: nil, before: nil)
691
+ @http.request("GET", "/email/batches", query: list_params(limit: limit, after: after, before: before))
692
+ end
693
+
694
+ # filters: status, to, contact_id, campaign_id, batch_id, created_after,
695
+ # created_before, q (an exact recipient address, or part of the subject
696
+ # or the sender; at most 200 characters), source ("api", "smtp", "test",
697
+ # "batch", "campaign" or "reply"), outcome ("delivered", "opened",
698
+ # "clicked", "unsubscribed", "bounced", "complained", "failed" or
699
+ # "pending"; with campaign_id: who opened or clicked that campaign). A
700
+ # q, source or outcome value the list can't apply is ignored and named
701
+ # in the Unitpost-Warning response header; Unitpost-Strict: true
702
+ # refuses it instead.
278
703
  def list(limit: nil, after: nil, before: nil, **filters)
279
704
  @http.request("GET", "/email", query: list_params(limit: limit, after: after, before: before, **filters))
280
705
  end
@@ -287,14 +712,47 @@ module Unitpost
287
712
  @http.request("GET", "/email/#{enc(id)}")
288
713
  end
289
714
 
715
+ # One sent email's delivery events, oldest first, as the dashboard's
716
+ # email detail shows the timeline. Each event carries its detail in
717
+ # "data" under the webhook's names (data["bounce"]["diagnostic_code"],
718
+ # data["click"]["link"], data["complaint"]["feedback_type"], ...).
719
+ # Cursor-paginated: after / before take an emev_ id. Needs emails:read.
720
+ def list_events(id, limit: nil, after: nil, before: nil)
721
+ @http.request("GET", "/email/#{enc(id)}/events", query: list_params(limit: limit, after: after, before: before))
722
+ end
723
+
290
724
  def update(id, body)
291
725
  @http.request("PATCH", "/email/#{enc(id)}", body: body)
292
726
  end
293
727
 
728
+ # Send a failed email again on the same id, as the dashboard's Retry
729
+ # does. Only a one-off send whose failure was temporary is retried: a
730
+ # campaign recipient, a template test, a suppressed or rejected send, or a
731
+ # content error is a 409 saying why (send a new email instead). It passes
732
+ # the same checks as a new send: the sending domain, your plan and quota.
733
+ # It sends no body; follow the email with get.
734
+ #
735
+ # It sends real email, so the SDK generates an idempotency_key when you
736
+ # don't pass one, which makes an auto-retry safe. Pass your own to dedupe
737
+ # across separate retry calls. (`retry` is a Ruby keyword, so call it with
738
+ # a receiver: client.email.retry(id).)
739
+ def retry(id, idempotency_key: nil)
740
+ # No body: the route takes none, and nil sends nothing. It is passed as
741
+ # body: like every idempotent send, which sdk:check reads.
742
+ body = nil
743
+ @http.request("POST", "/email/#{enc(id)}/retry", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
744
+ end
745
+
294
746
  # Deliverability/engagement aggregates over a rolling window (days: 1–365,
295
- # defaults to 30 server-side).
296
- def stats(days: nil)
297
- @http.request("GET", "/email/stats", query: { days: days })
747
+ # defaults to 30 server-side) or a period: from: and to:, ISO 8601 with Z
748
+ # or an offset. Add grain: ("5m", "1h" or "1d", with from:/to:) and tz:
749
+ # (an IANA zone) for "series", the send volume per bucket. domain_id:
750
+ # (dom_…) counts one sending domain. A value the API can't apply is
751
+ # ignored and named in the Unitpost-Warning response header;
752
+ # Unitpost-Strict: true refuses it instead.
753
+ def stats(days: nil, from: nil, to: nil, grain: nil, tz: nil, domain_id: nil)
754
+ query = { days: days, from: from, to: to, grain: grain, tz: tz, domain_id: domain_id }
755
+ @http.request("GET", "/email/stats", query: query)
298
756
  end
299
757
 
300
758
  def received_list(limit: nil, after: nil, before: nil)
@@ -308,11 +766,22 @@ module Unitpost
308
766
  def received_attachment_url(id, attachment_id)
309
767
  @http.request("GET", "/email/received/#{enc(id)}/attachments/#{enc(attachment_id)}")
310
768
  end
769
+
770
+ # A signed URL to download the received message's original MIME (.eml),
771
+ # valid for about 5 minutes (expires_at), with its size_bytes. A body
772
+ # over 256 KB isn't inlined on received_get (its text and html are nil),
773
+ # so this is how to read it. A copy of one of your own sends
774
+ # (sent_by_us) is a 403. Needs emails:read.
775
+ def received_raw(id)
776
+ @http.request("GET", "/email/received/#{enc(id)}/raw")
777
+ end
311
778
  end
312
779
 
313
780
  class Contacts < Base
314
- def list(limit: nil, after: nil, before: nil)
315
- @http.request("GET", "/contacts", query: list_params(limit: limit, after: after, before: before))
781
+ # filters: q, status (subscribed|unsubscribed), phone (has|none),
782
+ # segment_id, segment_subscription (subscribed|opted_out).
783
+ def list(limit: nil, after: nil, before: nil, **filters)
784
+ @http.request("GET", "/contacts", query: list_params(limit: limit, after: after, before: before, **filters))
316
785
  end
317
786
 
318
787
  def list_all(**params)
@@ -350,6 +819,41 @@ module Unitpost
350
819
  def cancel_import(id)
351
820
  @http.request("POST", "/contacts/imports/#{enc(id)}/cancel")
352
821
  end
822
+
823
+ # Re-run a failed import from its stored rows (202); rows already added
824
+ # are skipped.
825
+ def retry_import(id)
826
+ @http.request("POST", "/contacts/imports/#{enc(id)}/retry")
827
+ end
828
+
829
+ # The contact's email addresses and phone numbers, with each one's status
830
+ # (one page, never has_more).
831
+ def addresses(id_or_email)
832
+ @http.request("GET", "/contacts/#{enc(id_or_email)}/addresses")
833
+ end
834
+
835
+ # The contact's most recent emails and texts, newest first (limit 1–100,
836
+ # default 25; no cursor).
837
+ def activity(id_or_email, limit: nil)
838
+ @http.request("GET", "/contacts/#{enc(id_or_email)}/activity", query: { limit: limit })
839
+ end
840
+
841
+ # The segments the contact is in, with its per-segment opt-out (not
842
+ # paginated). To add the contact to a static segment or remove it, use
843
+ # segments.add_member / segments.remove_member.
844
+ def list_segments(id_or_email)
845
+ @http.request("GET", "/contacts/#{enc(id_or_email)}/segments")
846
+ end
847
+
848
+ # Export contacts to a CSV file (202), as the Contacts page's Export
849
+ # does: every contact, or the ones the filters match (q, status, phone,
850
+ # segment_id, segment_subscription, as on list). It runs as a background
851
+ # job: follow it with jobs.get(job["id"]), then fetch the file with
852
+ # jobs.download(job["id"]). One export runs at a time: another while it
853
+ # runs is a 409 job_in_progress. segment_id also needs segments:read.
854
+ def export(body = {})
855
+ @http.request("POST", "/contacts/export", body: body)
856
+ end
353
857
  end
354
858
 
355
859
  class ContactFields < Base
@@ -383,11 +887,42 @@ module Unitpost
383
887
  end
384
888
 
385
889
  class Jobs < Base
890
+ # Your background jobs, newest first (cursor-paginated), as Settings →
891
+ # Bulk operations lists them: the kinds an API operation starts that your
892
+ # key may read. Filter with status (QUEUED, RUNNING, COMPLETED, FAILED,
893
+ # CANCELED) or kind ("contacts.export", "contact_field.delete", ...).
894
+ def list(status: nil, kind: nil, limit: nil, after: nil, before: nil)
895
+ @http.request("GET", "/jobs", query: list_params(limit: limit, after: after, before: before, status: status, kind: kind))
896
+ end
897
+
386
898
  # A background job: the 202 answer of an operation too large for one
387
899
  # request. Poll until `status` is COMPLETED, FAILED or CANCELED.
388
900
  def get(id)
389
901
  @http.request("GET", "/jobs/#{enc(id)}")
390
902
  end
903
+
904
+ # Stop a queued or running job. A running job stops after the part in
905
+ # flight; the work already done stays. A kind that can't stop half-way (a
906
+ # custom-field rename) is a 409 saying why. It sends no body.
907
+ def cancel(id)
908
+ @http.request("POST", "/jobs/#{enc(id)}/cancel")
909
+ end
910
+
911
+ # Resume a FAILED job from where it stopped (202): nothing it already
912
+ # processed runs again. Any other status is a 409. It sends no body.
913
+ # (`retry` is a Ruby keyword, so call it with a receiver:
914
+ # client.jobs.retry(id).)
915
+ def retry(id)
916
+ @http.request("POST", "/jobs/#{enc(id)}/retry")
917
+ end
918
+
919
+ # A finished job's file (a contacts export's CSV) as a signed url that
920
+ # expires in 5 minutes: fetch it right away, and call download again for
921
+ # a fresh one. A job that isn't COMPLETED, or a kind with no file, is a
922
+ # 409.
923
+ def download(id)
924
+ @http.request("GET", "/jobs/#{enc(id)}/download")
925
+ end
391
926
  end
392
927
 
393
928
  class Segments < Base
@@ -426,6 +961,36 @@ module Unitpost
426
961
  def remove_member(id, contact)
427
962
  @http.request("DELETE", "/segments/#{enc(id)}/contacts/#{enc(contact)}")
428
963
  end
964
+
965
+ # Opt a member (by id or email) out of this segment's sends without
966
+ # removing it ({ subscribed: false }), or back in, as the members table's
967
+ # toggle does. It stays a member. A dynamic segment has no per-segment
968
+ # opt-out (422).
969
+ def update_member(id, contact, body)
970
+ @http.request("PATCH", "/segments/#{enc(id)}/contacts/#{enc(contact)}", body: body)
971
+ end
972
+
973
+ # How many contacts a saved segment reaches: its members, the subscribed
974
+ # set a campaign would mail (0 means a campaign would send nothing), and a
975
+ # sample (which also needs contacts:read).
976
+ def preview(id)
977
+ @http.request("GET", "/segments/#{enc(id)}/preview")
978
+ end
979
+
980
+ # Count an unsaved dynamic filter ({ filter: ... }) before you create the
981
+ # segment, as the segment dialog's live count does: how many contacts
982
+ # match, how many of them a campaign would mail, and a sample (which also
983
+ # needs contacts:read). Nothing is saved.
984
+ def preview_filter(body)
985
+ @http.request("POST", "/segments/preview", body: body)
986
+ end
987
+
988
+ # The workspace's managed "All subscribed contacts" segment, the
989
+ # dashboard's "Everyone subscribed" campaign target: made the first time
990
+ # you ask (201), the same segment after that (200). It sends no body.
991
+ def all_contacts
992
+ @http.request("POST", "/segments/all-contacts")
993
+ end
429
994
  end
430
995
 
431
996
  class Topics < Base
@@ -453,6 +1018,17 @@ module Unitpost
453
1018
  @http.request("DELETE", "/email/topics/#{enc(id)}")
454
1019
  end
455
1020
 
1021
+ # Opt many contacts out of this topic as a background job (202, the
1022
+ # job): { contact_ids: [...] } or { emails: [...] } (up to 1,000, each a
1023
+ # contact of this workspace) or { segment_id: } (every member, however
1024
+ # many). Each is opted out as set_topic would, with its webhook only when
1025
+ # it was subscribed. Follow it with jobs.get(id). Pass an idempotency_key
1026
+ # so a retry answers the same job; one is generated when you don't.
1027
+ # There is no bulk opt-in.
1028
+ def opt_out(id, body, idempotency_key: nil)
1029
+ @http.request("POST", "/email/topics/#{enc(id)}/opt-out", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1030
+ end
1031
+
456
1032
  def list_topics(contact_id, limit: nil, after: nil, before: nil)
457
1033
  @http.request("GET", "/contacts/#{enc(contact_id)}/topics", query: list_params(limit: limit, after: after, before: before))
458
1034
  end
@@ -460,6 +1036,17 @@ module Unitpost
460
1036
  def set_topic(contact_id, body)
461
1037
  @http.request("POST", "/contacts/#{enc(contact_id)}/topics", body: body)
462
1038
  end
1039
+
1040
+ # Change a contact's preferences for several topics in one call
1041
+ # ({ topics: [{ topic_id:, subscribed: }] }, up to 50, each topic once);
1042
+ # topics left out keep theirs. Every topic is checked before any is set
1043
+ # (an unknown one is a 404 and nothing changes). Answers the resolved
1044
+ # preferences in the order sent
1045
+ # ({ "object" => "list", "has_more" => false, "data" => [...] }).
1046
+ # Idempotent.
1047
+ def update_topics(contact_id, body)
1048
+ @http.request("PATCH", "/contacts/#{enc(contact_id)}/topics", body: body)
1049
+ end
463
1050
  end
464
1051
 
465
1052
  class Campaigns < Base
@@ -506,6 +1093,19 @@ module Unitpost
506
1093
  @http.request("POST", "/email/campaigns/#{enc(id)}/resume")
507
1094
  end
508
1095
 
1096
+ # Move a scheduled campaign back to draft so it can be edited; clears its
1097
+ # send time.
1098
+ def unschedule(id)
1099
+ @http.request("POST", "/email/campaigns/#{enc(id)}/unschedule")
1100
+ end
1101
+
1102
+ # Copy a campaign into a new draft (201). Optional body `{ name: "..." }`.
1103
+ # Pass an idempotency_key so a retry returns the same copy; one is
1104
+ # generated when you don't.
1105
+ def duplicate(id, body = {}, idempotency_key: nil)
1106
+ @http.request("POST", "/email/campaigns/#{enc(id)}/duplicate", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1107
+ end
1108
+
509
1109
  def reschedule(id, body)
510
1110
  @http.request("POST", "/email/campaigns/#{enc(id)}/reschedule", body: body)
511
1111
  end
@@ -513,6 +1113,52 @@ module Unitpost
513
1113
  def validate(id)
514
1114
  @http.request("GET", "/email/campaigns/#{enc(id)}/validate")
515
1115
  end
1116
+
1117
+ # The campaign's results: delivered, unique opens and clicks,
1118
+ # unsubscribes, bounces, complaints and their rates. Every rate is nil
1119
+ # until something was sent; open and click rates are nil when that
1120
+ # tracking was off.
1121
+ def stats(id)
1122
+ @http.request("GET", "/email/campaigns/#{enc(id)}/stats")
1123
+ end
1124
+
1125
+ # stats for up to 100 campaigns in one read (1–100 ids). An id that isn't
1126
+ # one of this workspace's email campaigns is left out of data, never an
1127
+ # error; has_more is always false.
1128
+ def list_stats(ids)
1129
+ @http.request("GET", "/email/campaigns/stats", query: { ids: Array(ids).join(",") })
1130
+ end
1131
+
1132
+ # Who the campaign would reach if sent now, member by member: sendable,
1133
+ # missing_data, suppressed or excluded, with the reason. status filters
1134
+ # (default all); limit is 1–100 (default 50). Pass the page's next_cursor
1135
+ # as after for the next page (rows carry no id). A page can hold fewer
1136
+ # rows than limit while has_more is true.
1137
+ def list_recipients(id, status: nil, limit: nil, after: nil)
1138
+ @http.request("GET", "/email/campaigns/#{enc(id)}/recipients", query: { status: status, limit: limit, after: after })
1139
+ end
1140
+
1141
+ # After an automatic quality pause: the recipients whose message
1142
+ # hard-bounced or drew a spam complaint. They're already suppressed; this
1143
+ # is for cleaning the source list. Up to 10,000; has_more says it was cut
1144
+ # there.
1145
+ def list_affected(id)
1146
+ @http.request("GET", "/email/campaigns/#{enc(id)}/quality/affected")
1147
+ end
1148
+
1149
+ # After an automatic quality pause: take the flagged contacts out of the
1150
+ # campaign's static segment (needs segments:write too; a filter segment
1151
+ # is a 409). A repeat removes nothing. It doesn't resume the campaign.
1152
+ def remove_affected(id)
1153
+ @http.request("POST", "/email/campaigns/#{enc(id)}/quality/remove-affected")
1154
+ end
1155
+
1156
+ # Ask for the review a campaign needs before it can resume after a repeat
1157
+ # quality pause (resume answers 409 review_required until then). A repeat
1158
+ # answers already_requested: true and notifies no one.
1159
+ def request_review(id)
1160
+ @http.request("POST", "/email/campaigns/#{enc(id)}/quality/request-review")
1161
+ end
516
1162
  end
517
1163
 
518
1164
  class Templates < Base
@@ -541,12 +1187,110 @@ module Unitpost
541
1187
  end
542
1188
 
543
1189
  # Send ONE test of the template to body[:to] with sample variables.
1190
+ # Once a sending domain is verified it may go to anyone; until then only
1191
+ # to a member of your workspace.
544
1192
  def test_send(id, body)
545
1193
  @http.request("POST", "/email/templates/#{enc(id)}/test-send", body: body)
546
1194
  end
1195
+
1196
+ # The subject, html and text a send of this template would carry, with
1197
+ # your footer and branding, filled from variables (and from a contact's
1198
+ # fields with contact_id). Optional body
1199
+ # `{ variables: { ... }, subject: "...", contact_id: "con_..." }`; {}
1200
+ # renders with no variables. It sends and stores nothing, so it takes no
1201
+ # idempotency key. missing_variables lists the variables left without a
1202
+ # value: they render as a literal {{token}}, and a real send would refuse
1203
+ # them. Needs templates:read, and has its own per-workspace rate limit.
1204
+ def render(id, body = {})
1205
+ @http.request("POST", "/email/templates/#{enc(id)}/render", body: body)
1206
+ end
1207
+
1208
+ # Copy a template into a new draft (201). Optional body `{ name: "..." }`
1209
+ # (default: the original's name with " (copy)"); its subject, editor and
1210
+ # body carry over, its status, versions and usage don't. Pass an
1211
+ # idempotency_key so a retry returns the same copy; one is generated when
1212
+ # you don't.
1213
+ def duplicate(id, body = {}, idempotency_key: nil)
1214
+ @http.request("POST", "/email/templates/#{enc(id)}/duplicate", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1215
+ end
1216
+
1217
+ # Add one of the gallery's ready-made emails (unitpost.com/templates) to
1218
+ # your workspace as a draft Design template (201). body[:slug] names it
1219
+ # (optional :name); the ones marked for paid plans answer 403
1220
+ # limit_reached on the free plan. Pass an idempotency_key so a retry
1221
+ # returns the same template; one is generated when you don't.
1222
+ def from_library(body, idempotency_key: nil)
1223
+ @http.request("POST", "/email/templates/from-library", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1224
+ end
1225
+
1226
+ # What uses the template, and whether a change would be accepted now: the
1227
+ # campaigns that reference it, its live campaigns and automations, queued
1228
+ # sends, and can_edit_content / can_unpublish with the reason when not.
1229
+ # Read it before an edit or a delete: a content edit is refused while a
1230
+ # live campaign renders the template, and a delete while any campaign
1231
+ # uses it.
1232
+ def usage(id)
1233
+ @http.request("GET", "/email/templates/#{enc(id)}/usage")
1234
+ end
1235
+
1236
+ # The template's history, newest first: a version is added on every
1237
+ # publish and on every content save while it's published. limit is 1–100
1238
+ # (default 20). It pages by version number: pass the last row's version
1239
+ # (an integer, not an id) as after. There is no before.
1240
+ def list_versions(id, limit: nil, after: nil)
1241
+ @http.request("GET", "/email/templates/#{enc(id)}/versions", query: { limit: limit, after: after })
1242
+ end
1243
+
1244
+ # Put a version's subject and body back, as the editor's History →
1245
+ # Restore does. It is an update, so a system template, or one a live
1246
+ # campaign renders, is refused with a 409 naming why (usage says so up
1247
+ # front). On a published template the restore adds a new version; history
1248
+ # is never rewritten. It sends no body.
1249
+ def restore_version(id, version)
1250
+ @http.request("POST", "/email/templates/#{enc(id)}/versions/#{enc(version)}/restore")
1251
+ end
547
1252
  end
548
1253
 
549
- # Read-only Brand Kit profiles (voice, colors, pinned /img/{id} graphics).
1254
+ # Inbox conversations (/email/threads, thr_...): each received message and
1255
+ # the replies and forwards sent from it are one conversation, as Emails →
1256
+ # Received shows them.
1257
+ class EmailThreads < Base
1258
+ # Every conversation (Spam included), newest activity first. q searches
1259
+ # the subject, the sender and the opening words; limit is 1–100 (default
1260
+ # 50). Pass the page's next_cursor as after for the next page (not the
1261
+ # last row's id).
1262
+ def list(q: nil, limit: nil, after: nil)
1263
+ @http.request("GET", "/email/threads", query: { q: q, limit: limit, after: after })
1264
+ end
1265
+
1266
+ # One conversation, oldest message first: what you received (with bodies)
1267
+ # and what you sent from it (status and recipients, no body).
1268
+ def get(id)
1269
+ @http.request("GET", "/email/threads/#{enc(id)}")
1270
+ end
1271
+
1272
+ # Delete a conversation for good: its received messages are erased;
1273
+ # replies and forwards sent from it stay on your sent emails. It can't be
1274
+ # undone.
1275
+ def delete(id)
1276
+ @http.request("DELETE", "/email/threads/#{enc(id)}")
1277
+ end
1278
+
1279
+ # Reply, reply all or forward one received message of the conversation
1280
+ # (received_email_id): your text/html go on top and the original is
1281
+ # quoted under them. It sends now and marks the conversation read. It
1282
+ # sends real email, so pass an idempotency_key to make a retry safe; one
1283
+ # is generated when you don't.
1284
+ def reply(id, body, idempotency_key: nil)
1285
+ @http.request("POST", "/email/threads/#{enc(id)}/reply", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1286
+ end
1287
+ end
1288
+
1289
+ # Brand Kit profiles (voice, colors, pinned /img/{id} graphics), and the
1290
+ # imports that fill them from a website or the brand's own words. The reads
1291
+ # (list, get, get_import) need templates:read; the writes and starting,
1292
+ # accepting or canceling an import need branding:write, which no key
1293
+ # preset grants: tick it on the key.
550
1294
  class BrandKits < Base
551
1295
  def list(name: nil)
552
1296
  query = {}
@@ -557,6 +1301,81 @@ module Unitpost
557
1301
  def get(id)
558
1302
  @http.request("GET", "/brand-kits/#{enc(id)}")
559
1303
  end
1304
+
1305
+ # Create an empty profile (201): `{ name: ..., make_default: ... }`;
1306
+ # `name` is unique in the workspace. The first profile, or one with
1307
+ # make_default, becomes the default. At most five profiles
1308
+ # (403 limit_reached). Fill it with update or import.
1309
+ def create(body)
1310
+ @http.request("POST", "/brand-kits", body: body)
1311
+ end
1312
+
1313
+ # Edit a profile: only the fields you send change, a list replaces the
1314
+ # list, and nil or "" clears a text field. `graphics` pins library images
1315
+ # by `image_id` (img_...). `sync_visual` on the default profile also sets
1316
+ # the email branding's accent from its colors.
1317
+ def update(id, body)
1318
+ @http.request("PATCH", "/brand-kits/#{enc(id)}", body: body)
1319
+ end
1320
+
1321
+ # Delete a profile. When it was the default, the oldest remaining profile
1322
+ # becomes the default. The last profile can't be deleted (409): reset it
1323
+ # instead. Its pinned images stay in the library.
1324
+ def delete(id)
1325
+ @http.request("DELETE", "/brand-kits/#{enc(id)}")
1326
+ end
1327
+
1328
+ # Clear a profile's content (voice, colors, graphics, pages), keeping its
1329
+ # name and whether it's the default. It sends no body.
1330
+ def reset(id)
1331
+ @http.request("POST", "/brand-kits/#{enc(id)}/reset")
1332
+ end
1333
+
1334
+ # Make a profile the default: the one agents write with unless told
1335
+ # otherwise. It sends no body.
1336
+ def set_default(id)
1337
+ @http.request("POST", "/brand-kits/#{enc(id)}/set-default")
1338
+ end
1339
+
1340
+ # Add a graphic (201) from a public https image `url` (fetched once, no
1341
+ # redirects): `{ url: ..., role: ..., label: ... }`. It goes into the
1342
+ # image library, counted against its storage, and is pinned with its
1343
+ # `role` (default logo). To pin an image already in the library, update
1344
+ # the profile's `graphics`.
1345
+ def add_graphic(id, body)
1346
+ @http.request("POST", "/brand-kits/#{enc(id)}/graphics", body: body)
1347
+ end
1348
+
1349
+ # Build a profile from a website (`url`, or a bare domain) or the brand's
1350
+ # own words (`text`). It runs in the background, usually under a minute
1351
+ # (202): follow it with get_import. By default the result is applied when
1352
+ # it lands, to `brand_kit_id`, else the default profile, or a new one
1353
+ # when the default already has content. With `review: true` it stops at
1354
+ # a proposal (preview_ready) for accept_import; one review import is open
1355
+ # at a time, and a new one replaces it.
1356
+ def import(body)
1357
+ @http.request("POST", "/brand-kits/imports", body: body)
1358
+ end
1359
+
1360
+ # One import: its status, the proposal once it's ready, warnings and any
1361
+ # error.
1362
+ def get_import(id)
1363
+ @http.request("GET", "/brand-kits/imports/#{enc(id)}")
1364
+ end
1365
+
1366
+ # Apply a review import's proposal (preview_ready) to a profile: voice,
1367
+ # colors and pages, and its logos and backgrounds brought into the image
1368
+ # library and pinned. The body is optional: `brand_kit_id` applies it to
1369
+ # another profile, `name` names it, `sync_visual` also sets the email
1370
+ # branding's accent. To change other fields, accept and then update.
1371
+ def accept_import(id, body = {})
1372
+ @http.request("POST", "/brand-kits/imports/#{enc(id)}/accept", body: body)
1373
+ end
1374
+
1375
+ # Discard a review import's proposal or stop its crawl. It sends no body.
1376
+ def cancel_import(id)
1377
+ @http.request("POST", "/brand-kits/imports/#{enc(id)}/cancel")
1378
+ end
560
1379
  end
561
1380
 
562
1381
  class Domains < Base
@@ -592,6 +1411,41 @@ module Unitpost
592
1411
  def diagnose(id)
593
1412
  @http.request("GET", "/email/domains/#{enc(id)}/diagnose")
594
1413
  end
1414
+
1415
+ # Sender addresses (/email/senders, sndr_...): saved From addresses.
1416
+
1417
+ # Your saved From addresses, as the domain page lists them and the
1418
+ # dashboard's From pickers offer them: each a mailbox on one of your
1419
+ # domains, with its display name and from, the value to send with.
1420
+ # domain_id keeps one domain's. A sender can send once its domain can.
1421
+ def list_senders(domain_id: nil, limit: nil, after: nil, before: nil)
1422
+ @http.request("GET", "/email/senders", query: list_params(limit: limit, after: after, before: before, domain_id: domain_id))
1423
+ end
1424
+
1425
+ # Save a From address on one of your domains (201):
1426
+ # { address: ..., display_name: ... } (display_name is optional). The
1427
+ # domain may still be verifying. A mailbox already saved on that domain
1428
+ # is a 409, so a retry never saves it twice.
1429
+ def create_sender(body)
1430
+ @http.request("POST", "/email/senders", body: body)
1431
+ end
1432
+
1433
+ # One saved From address.
1434
+ def get_sender(id)
1435
+ @http.request("GET", "/email/senders/#{enc(id)}")
1436
+ end
1437
+
1438
+ # Change a sender's display name ({ display_name: ... }; nil or "" clears
1439
+ # it), the only field that changes: a different mailbox is a new sender.
1440
+ def update_sender(id, body)
1441
+ @http.request("PATCH", "/email/senders/#{enc(id)}", body: body)
1442
+ end
1443
+
1444
+ # Remove a saved From address from the pickers. Templates and campaigns
1445
+ # that send from it keep their From.
1446
+ def delete_sender(id)
1447
+ @http.request("DELETE", "/email/senders/#{enc(id)}")
1448
+ end
595
1449
  end
596
1450
 
597
1451
  class Webhooks < Base
@@ -628,16 +1482,43 @@ module Unitpost
628
1482
  @http.request("POST", "/webhooks/#{enc(id)}/rotate-secret")
629
1483
  end
630
1484
 
631
- def list_deliveries(id, limit: nil, after: nil, before: nil)
632
- @http.request("GET", "/webhooks/#{enc(id)}/deliveries", query: list_params(limit: limit, after: after, before: before))
1485
+ # The endpoint's delivery log, newest first (cursor-paginated). filters:
1486
+ # status (one or more of pending, queued, retrying, succeeded, failed,
1487
+ # exhausted, comma-separated, e.g. "failed,exhausted") and event_type
1488
+ # (e.g. "email.bounced"). The log ignored them before, so a value it
1489
+ # can't apply is ignored and named in the Unitpost-Warning response
1490
+ # header; Unitpost-Strict: true refuses it instead.
1491
+ def list_deliveries(id, limit: nil, after: nil, before: nil, **filters)
1492
+ @http.request("GET", "/webhooks/#{enc(id)}/deliveries", query: list_params(limit: limit, after: after, before: before, **filters))
633
1493
  end
634
1494
 
1495
+ # Same filters as list_deliveries.
635
1496
  def list_all_deliveries(id, **params)
636
1497
  paginate("/webhooks/#{enc(id)}/deliveries", params)
637
1498
  end
638
1499
 
1500
+ # Deliver one event to the endpoint again (202), as the dashboard's
1501
+ # Replay does. The same event goes out with the same id, so a receiver
1502
+ # that dedupes on it treats the replay as the delivery it already has.
1503
+ # The webhook must be enabled: a disabled or suspended one is a 409
1504
+ # (re-enable it with update first). Find deliveries with
1505
+ # list_deliveries. It sends no body.
1506
+ def replay_delivery(id, delivery_id)
1507
+ @http.request("POST", "/webhooks/#{enc(id)}/deliveries/#{enc(delivery_id)}/replay")
1508
+ end
1509
+
1510
+ # Deliver the backlog (202): the deliveries held while the webhook was
1511
+ # suspended (queued), as the dashboard's "Retry queued" does. With
1512
+ # { include_failed: true }, also the ones that failed for good (failed,
1513
+ # exhausted). The webhook must be enabled: a disabled or suspended one is
1514
+ # a 409 (re-enable it with update first); re-enabling never delivers the
1515
+ # backlog on its own. flushed counts the deliveries handed back.
1516
+ def flush(id, body = {})
1517
+ @http.request("POST", "/webhooks/#{enc(id)}/flush", body: body)
1518
+ end
1519
+
639
1520
  # Verify a delivery's signature and return the parsed event. Alias of
640
- # Unitpost.verify_webhook / Unitpost::Webhooks.verify for a Resend-style
1521
+ # Unitpost.verify_webhook / Unitpost::Webhooks.verify, callable as
641
1522
  # client.webhooks.verify(...). Raises Unitpost::WebhookVerificationError on
642
1523
  # a missing/invalid/stale signature.
643
1524
  def verify(payload:, secret:, headers:, tolerance_seconds: 300)
@@ -651,6 +1532,9 @@ module Unitpost
651
1532
  end
652
1533
 
653
1534
  class ApiKeys < Base
1535
+ # The workspace's API keys (prefix, scope, capabilities, last use; never
1536
+ # the secret). With an API key or an MCP sign-in it needs apikeys:read,
1537
+ # which no key preset includes.
654
1538
  def list(limit: nil, after: nil, before: nil)
655
1539
  @http.request("GET", "/api-keys", query: list_params(limit: limit, after: after, before: before))
656
1540
  end
@@ -666,13 +1550,49 @@ module Unitpost
666
1550
  def delete(id)
667
1551
  @http.request("DELETE", "/api-keys/#{enc(id)}")
668
1552
  end
1553
+
1554
+ # One key's last 24 hours: how many requests it made, how many were
1555
+ # answered 4xx, 5xx or 429, and when it was last used. Check it before
1556
+ # you revoke a key (is anything still calling with it?) or when an
1557
+ # integration's calls fail. Needs apikeys:read, which no key preset
1558
+ # includes.
1559
+ def usage(id)
1560
+ @http.request("GET", "/api-keys/#{enc(id)}/usage")
1561
+ end
1562
+ end
1563
+
1564
+ # The workspace's API request log: one row per call. Needs apikeys:read,
1565
+ # which no key preset includes.
1566
+ class Logs < Base
1567
+ # Your workspace's API request log, newest first (cursor-paginated, rlog_
1568
+ # ids): each call's method, path, status, time taken (duration_ms), the
1569
+ # API key that made it (api_key_id) and its x-request-id (request_id:
1570
+ # quote it to support). Never the caller's IP and never a body. filters:
1571
+ # status (a code such as 429, or a class: "2xx", "3xx", "4xx" or "5xx"),
1572
+ # api_key_id (key_...), method (GET, POST, PUT, PATCH or DELETE),
1573
+ # path_prefix (e.g. "/email/campaigns", at most 200 characters),
1574
+ # request_id (the x-request-id a response carried), created_after and
1575
+ # created_before (ISO 8601 with Z or an offset); an unknown filter is a
1576
+ # 422. Rows are kept 30 days. Needs apikeys:read, which no key preset
1577
+ # includes, and has its own per-workspace rate limit.
1578
+ def list(limit: nil, after: nil, before: nil, **filters)
1579
+ @http.request("GET", "/logs", query: list_params(limit: limit, after: after, before: before, **filters))
1580
+ end
669
1581
  end
670
1582
 
671
1583
  class Suppressions < Base
1584
+ # Your workspace's suppressed addresses, newest first (cursor-paginated).
1585
+ # filters: q (part of the address, at most 200 characters), reason
1586
+ # (bounce, complaint, unsubscribe, manual, import or api), created_after,
1587
+ # created_before (ISO 8601 with Z or an offset). scope is deprecated and
1588
+ # ignored. The list ignored these filters before, so a value it can't
1589
+ # apply is ignored and named in the Unitpost-Warning response header;
1590
+ # Unitpost-Strict: true refuses it instead.
672
1591
  def list(limit: nil, after: nil, before: nil, **filters)
673
1592
  @http.request("GET", "/suppressions", query: list_params(limit: limit, after: after, before: before, **filters))
674
1593
  end
675
1594
 
1595
+ # Same filters as list.
676
1596
  def list_all(**params)
677
1597
  paginate("/suppressions", params)
678
1598
  end
@@ -695,6 +1615,193 @@ module Unitpost
695
1615
  # absent while the automations/custom-events surface is behind the launch
696
1616
  # gate. Restore it (class Events + client wiring) when the surface ships.
697
1617
 
1618
+ # The workspace's image library: the images a template embeds. Each
1619
+ # image's `path` (`/img/...`) is what a template's `<Image src>` (or
1620
+ # `<img src>`) takes; `url` is its public address. Reads need
1621
+ # templates:read, writes templates:write.
1622
+ # Files (/files, file_ ids): bytes handed to the API for one purpose,
1623
+ # which an operation then takes by file_id (a brand document, the SMS
1624
+ # opt-in evidence on a quote or resubmission, a library image, the logo).
1625
+ # A file is private, metadata-only on the API, and expires 24 hours after
1626
+ # it is created; what uses it keeps its own copy. sms_* purposes need
1627
+ # sms:manage, image needs templates:write or branding:write (ADR-0159).
1628
+ class Files < Base
1629
+ # The workspace's unexpired files, newest first (cursor-paginated;
1630
+ # purpose filters).
1631
+ def list(limit: nil, after: nil, before: nil, purpose: nil)
1632
+ @http.request("GET", "/files", query: list_params(limit: limit, after: after, before: before, purpose: purpose))
1633
+ end
1634
+
1635
+ # Create a file (201) one of three ways: a public https `url` (fetched
1636
+ # once, no redirects, no private addresses), base64 `data` with its
1637
+ # `content_type` (up to about 4 MB), or neither, with `content_type` and
1638
+ # `size_bytes`: an upload session, whose `upload` says where to PUT the
1639
+ # bytes, with exactly `upload["headers"]`. The bytes decide the type.
1640
+ # Pass an idempotency_key so a retry makes one file; one is generated
1641
+ # when you don't.
1642
+ def create(body, idempotency_key: nil)
1643
+ @http.request("POST", "/files", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1644
+ end
1645
+
1646
+ # One file's metadata (never its bytes). Reading an awaiting_upload file
1647
+ # checks its upload, which makes it ready or failed.
1648
+ def get(id)
1649
+ @http.request("GET", "/files/#{enc(id)}")
1650
+ end
1651
+
1652
+ # Delete a file before it expires. What already used it keeps its copy.
1653
+ def delete(id)
1654
+ @http.request("DELETE", "/files/#{enc(id)}")
1655
+ end
1656
+ end
1657
+
1658
+ class LibraryImages < Base
1659
+ # The library, newest first (cursor-paginated).
1660
+ def list(limit: nil, after: nil, before: nil)
1661
+ @http.request("GET", "/library-images", query: list_params(limit: limit, after: after, before: before))
1662
+ end
1663
+
1664
+ def list_all(**params)
1665
+ paginate("/library-images", params)
1666
+ end
1667
+
1668
+ # Add an image (201) from a public https `url` (fetched once, no
1669
+ # redirects, no private addresses) or base64 `data` with its
1670
+ # `content_type`: PNG, JPEG, GIF or WebP up to 5 MB, counted against the
1671
+ # plan's image storage (403 limit_reached). Optional `filename` and
1672
+ # `alt`. Pass an idempotency_key so a retried upload stores one image;
1673
+ # one is generated when you don't.
1674
+ def create(body, idempotency_key: nil)
1675
+ @http.request("POST", "/library-images", body: body, idempotency_key: idempotency_key || SecureRandom.uuid)
1676
+ end
1677
+
1678
+ def get(id)
1679
+ @http.request("GET", "/library-images/#{enc(id)}")
1680
+ end
1681
+
1682
+ # Change the alt text the image suggests when it's inserted
1683
+ # (`{ alt: ... }`; nil or "" clears it).
1684
+ def update(id, body)
1685
+ @http.request("PATCH", "/library-images/#{enc(id)}", body: body)
1686
+ end
1687
+
1688
+ # Remove an image from the library. While a template, a campaign or sent
1689
+ # mail uses it, the answer is a 409 resource_in_use naming them
1690
+ # (`details`). `force: true` (sent as `?force=true`) deletes it anyway:
1691
+ # those emails then show a broken image wherever it isn't cached yet.
1692
+ def delete(id, force: false)
1693
+ @http.request("DELETE", "/library-images/#{enc(id)}", query: force ? { force: "true" } : nil)
1694
+ end
1695
+ end
1696
+
1697
+ # The look marketing emails' footer and the hosted unsubscribe page share,
1698
+ # as Settings → Brand shows it. Reading it needs templates:read; the writes
1699
+ # need branding:write, which no key preset grants: tick it on the key.
1700
+ class Branding < Base
1701
+ # Colors, font, company name and postal address, the unsubscribe page,
1702
+ # the footer, the logo; nil means the default.
1703
+ def get
1704
+ @http.request("GET", "/branding")
1705
+ end
1706
+
1707
+ # Change branding: only the fields you send change, and nil restores a
1708
+ # default. Hiding the "Sent with Unitpost" mark needs a paid plan
1709
+ # (403 limit_reached).
1710
+ def update(body)
1711
+ @http.request("PATCH", "/branding", body: body)
1712
+ end
1713
+
1714
+ # Replace the logo, from a public https `url` or base64 `data` (PNG,
1715
+ # JPEG, GIF or WebP, up to 5 MB).
1716
+ def set_logo(body)
1717
+ @http.request("PUT", "/branding/logo", body: body)
1718
+ end
1719
+
1720
+ # Clear the brand logo (the workspace image shows instead, else none).
1721
+ # It sends no body and answers the branding.
1722
+ def remove_logo
1723
+ @http.request("DELETE", "/branding/logo")
1724
+ end
1725
+ end
1726
+
1727
+ # The calling credential (whoami, which any valid credential may read),
1728
+ # the activity log (list_activity, which needs activity:read), and the
1729
+ # workspace's name and image. update, set_image and remove_image need
1730
+ # branding:write. No key preset grants either capability: tick it on the
1731
+ # key. Deleting the workspace stays in the dashboard.
1732
+ class Workspace < Base
1733
+ # Who is calling: the workspace, the credential (an API key or an OAuth
1734
+ # sign-in, never its secret), its capabilities and the workspace's rate
1735
+ # limit. Call it first to see what the credential may do: a call that
1736
+ # needs a capability it lacks answers 403 insufficient_scope. It needs no
1737
+ # capability: any valid credential may read it.
1738
+ def whoami
1739
+ @http.request("GET", "/whoami")
1740
+ end
1741
+
1742
+ # The workspace activity log, newest first (cursor-paginated, act_ ids):
1743
+ # what changed, when, who changed it (actor.name: a teammate, System,
1744
+ # Ask Unit) and, for a change made over the API, MCP or Ask Unit, how
1745
+ # (actor.via, with the API key). The rows the dashboard's Activity page
1746
+ # and each record's timeline show. filters: subject (contact, segment,
1747
+ # topic, field, template, component, campaign, email, domain,
1748
+ # sender_email, library_image, api_key, webhook, suppression, message,
1749
+ # handle or workspace), subject_id (with subject: one record's changes),
1750
+ # contact_id, campaign_id, q (part of the record's name or the actor's,
1751
+ # at most 200 characters) and channel ("email": without the SMS rows);
1752
+ # an unknown filter is a 422. Needs activity:read, which no key preset
1753
+ # includes: the log names your teammates.
1754
+ def list_activity(limit: nil, after: nil, before: nil, **filters)
1755
+ @http.request("GET", "/activity", query: list_params(limit: limit, after: after, before: before, **filters))
1756
+ end
1757
+
1758
+ # Same filters as list_activity.
1759
+ def list_all_activity(**params)
1760
+ paginate("/activity", params)
1761
+ end
1762
+
1763
+ # Rename the workspace (`{ name: ... }`).
1764
+ def update(body)
1765
+ @http.request("PATCH", "/workspace", body: body)
1766
+ end
1767
+
1768
+ # Replace the workspace image (its avatar in the dashboard, and the email
1769
+ # logo when there's no brand logo), from a public https `url` or base64
1770
+ # `data` (PNG, JPEG, GIF or WebP, up to 5 MB).
1771
+ def set_image(body)
1772
+ @http.request("PUT", "/workspace/image", body: body)
1773
+ end
1774
+
1775
+ # Clear the workspace image. It sends no body and answers the workspace.
1776
+ def remove_image
1777
+ @http.request("DELETE", "/workspace/image")
1778
+ end
1779
+ end
1780
+
1781
+ # The workspace's monthly spend caps and what each counted this UTC
1782
+ # calendar month. sms_purchases caps the SMS carrier purchases API keys and
1783
+ # apps confirm (sms.quotes.confirm). Reading needs sms:read, sms:purchase
1784
+ # or spend_caps:write; update needs spend_caps:write, which no key preset
1785
+ # includes and only the workspace owner can give a key.
1786
+ class SpendCaps < Base
1787
+ # { object: "spend_caps", sms_purchases: { cap_cents, max_cents,
1788
+ # spent_cents, period_start, period_end } }. A cap_cents of nil means
1789
+ # none, so every API purchase is refused with 403 api_spend_cap_not_set;
1790
+ # the cap that applies is the lower of cap_cents and max_cents.
1791
+ def get
1792
+ @http.request("GET", "/spend-caps")
1793
+ end
1794
+
1795
+ # Set caps: { sms_purchases: { cap_cents: <whole cents >= 0> | nil } }.
1796
+ # Only the caps you send change; nil clears it. A workspace its
1797
+ # organization pays for answers 403 billed_by_organization: its
1798
+ # organization sets the cap with sms_purchases_cap_cents on the
1799
+ # organization's workspace update.
1800
+ def update(body)
1801
+ @http.request("PATCH", "/spend-caps", body: body)
1802
+ end
1803
+ end
1804
+
698
1805
  class Usage < Base
699
1806
  # Current billing-period snapshot: plan, period window, emails sent, and
700
1807
  # (paid plans) the dollar sending wallet in integer USD cents.