-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbroadcast.go
More file actions
441 lines (405 loc) · 16.1 KB
/
Copy pathbroadcast.go
File metadata and controls
441 lines (405 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package main
import (
"encoding/json"
"flag"
"fmt"
"net/url"
"os"
"strings"
)
// ─── broadcasts — full surface of /broadcasts and /broadcasts/<id> ───────────
//
// One command (`splashify broadcasts` for the list, `splashify broadcast`
// for everything per-id and create/cancel/restart/send-now/rebroadcast).
//
// READ:
// splashify broadcasts [--status …] [--search …] [--page N] [--limit N]
// splashify broadcast stats [--period 7d|30d|all]
// splashify broadcast <id> [--recompute]
// splashify broadcast <id> messages [--status … --channel … --page --limit --search --cumulative]
// splashify broadcast <id> cohorts cohort-counts (failed / sent / delivered / read)
// splashify broadcast <id> export [--status ALL|FAILED|DELIVERED|...] [--csv]
//
// WRITE (gated by subscription + wallet balance — see preflightBroadcast):
// splashify broadcast create … POST /app/broadcasts (WhatsApp or RCS)
// splashify broadcast <id> cancel
// splashify broadcast <id> restart
// splashify broadcast <id> send-now
// splashify broadcast <id> rebroadcast --cohort failed|sent|delivered|read|all [flags…]
//
// Before any write command that triggers actual sends, the CLI runs a
// preflight: hit /app/developer/cli-eligibility (subscription + WABA gate
// — same one cmdConnect uses) and /app/wallet/info. A subscription_expired
// account is refused with an upgrade prompt; an empty wallet is refused
// with a recharge prompt. --yes skips the balance soft-check (the backend
// still enforces it hard via "Insufficient balance" 4xx).
func cmdBroadcasts(args []string) error {
fs := flag.NewFlagSet("broadcasts", flag.ContinueOnError)
status := fs.String("status", "", "filter by status (scheduled, sending, completed, cancelled, paused, …)")
search := fs.String("search", "", "search by campaign name")
page := fs.String("page", "", "page number")
limit := fs.String("limit", "", "items per page")
if err := fs.Parse(args); err != nil {
return err
}
return runReq("GET", withQuery("/app/broadcasts", map[string]string{
"status": *status, "search": *search, "page": *page, "limit": *limit,
}), nil)
}
func cmdBroadcast(args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: splashify broadcast <id|stats|create> …")
}
switch args[0] {
case "stats":
fs := flag.NewFlagSet("broadcast stats", flag.ContinueOnError)
period := fs.String("period", "", "7d, 30d, 90d, all (default: all)")
if err := fs.Parse(args[1:]); err != nil {
return err
}
path := "/app/broadcasts/stats"
if *period != "" {
path += "?period=" + url.QueryEscape(*period)
}
return runReq("GET", path, nil)
case "create":
return cmdBroadcastCreate(args[1:])
}
// First arg is treated as a broadcast id; optional sub-action follows.
id := args[0]
if len(args) == 1 {
// `splashify broadcast <id> [--recompute]` lands here via reparse below.
return cmdBroadcastGet(id, nil)
}
switch args[1] {
case "messages":
return cmdBroadcastMessages(id, args[2:])
case "cohorts", "cohort-counts":
return runReq("GET", "/app/broadcasts/"+id+"/cohort-counts", nil)
case "progress", "watch", "stream":
return cmdBroadcastProgress(id, args[2:])
case "export":
return cmdBroadcastExport(id, args[2:])
case "cancel":
if err := preflightSend("broadcasts",false /*requireBalance*/); err != nil {
return err
}
return runReq("POST", "/app/broadcasts/"+id+"/cancel", nil)
case "restart":
if err := preflightSend("broadcasts",true); err != nil {
return err
}
return runReq("POST", "/app/broadcasts/"+id+"/restart", nil)
case "send-now":
if err := preflightSend("broadcasts",true); err != nil {
return err
}
return runReq("POST", "/app/broadcasts/"+id+"/send-now", nil)
case "rebroadcast":
return cmdBroadcastRebroadcast(id, args[2:])
default:
// Allow `broadcast <id> --recompute` by reparsing flags.
return cmdBroadcastGet(id, args[1:])
}
}
// ─── reads ───────────────────────────────────────────────────────────────────
func cmdBroadcastGet(id string, args []string) error {
fs := flag.NewFlagSet("broadcast get", flag.ContinueOnError)
recompute := fs.Bool("recompute", false, "ask backend to recompute stats")
if err := fs.Parse(args); err != nil {
return err
}
path := "/app/broadcasts/" + id
if *recompute {
path += "?recompute=true"
}
return runReq("GET", path, nil)
}
func cmdBroadcastMessages(id string, args []string) error {
fs := flag.NewFlagSet("broadcast messages", flag.ContinueOnError)
status := fs.String("status", "", "filter: SENT, DELIVERED, READ, FAILED, …")
channel := fs.String("channel", "", "filter: whatsapp, rcs")
page := fs.String("page", "", "page number")
limit := fs.String("limit", "", "items per page")
search := fs.String("search", "", "search by phone / contact name")
cumulative := fs.String("cumulative", "", "true|false — include earlier statuses (DELIVERED also includes READ)")
if err := fs.Parse(args); err != nil {
return err
}
return runReq("GET", withQuery("/app/broadcasts/"+id+"/messages", map[string]string{
"status": *status,
"channel": *channel,
"page": *page,
"limit": *limit,
"search": *search,
"cumulative": *cumulative,
}), nil)
}
func cmdBroadcastExport(id string, args []string) error {
fs := flag.NewFlagSet("broadcast export", flag.ContinueOnError)
status := fs.String("status", "ALL", "ALL, SENT, DELIVERED, READ, FAILED, …")
csv := fs.Bool("csv", false, "request format=csv (binary stream; pipe to a file)")
if err := fs.Parse(args); err != nil {
return err
}
q := map[string]string{"status": *status}
if *csv {
q["format"] = "csv"
}
return runReq("GET", withQuery("/app/broadcasts/"+id+"/export", q), nil)
}
// cmdBroadcastProgress streams the live progress of a broadcast via
// Server-Sent Events. The /broadcasts/<id>/progress endpoint is what the
// app's /broadcasts/<id>/progress page consumes — each event carries the
// running counts (sent/delivered/read/failed/pending) and a status
// string. The CLI prints one JSON object per event and exits when the
// broadcast reaches a terminal state (COMPLETED | CANCELLED | FAILED).
//
// splashify broadcast <id> progress follow until terminal
// splashify broadcast <id> progress --once print the first event and exit
// splashify broadcast <id> progress --max 10 stop after 10 events
func cmdBroadcastProgress(id string, args []string) error {
fs := flag.NewFlagSet("broadcast progress", flag.ContinueOnError)
once := fs.Bool("once", false, "print first event and exit (snapshot)")
max := fs.Int("max", 0, "stop after N events (0 = no cap)")
if err := fs.Parse(args); err != nil {
return err
}
cfg, err := requireConfig()
if err != nil {
return err
}
stop := func(parsed map[string]any) bool {
status, _ := parsed["status"].(string)
switch strings.ToUpper(status) {
case "COMPLETED", "CANCELLED", "FAILED":
return true
}
return false
}
return streamSSE(cfg.BaseURL, cfg.Token,
"/app/broadcasts/"+id+"/progress",
*once, *max, stop)
}
// ─── writes (preflight-gated) ────────────────────────────────────────────────
func cmdBroadcastCreate(args []string) error {
fs := flag.NewFlagSet("broadcast create", flag.ContinueOnError)
name := fs.String("name", "", "campaign name (required)")
desc := fs.String("description", "", "optional description")
// Template fields (required: name + category + language; ID is optional).
tmplID := fs.String("template-id", "", "template_id (optional — name+language is enough)")
tmplName := fs.String("template", "", "approved template name (required)")
tmplCat := fs.String("category", "", "template_category: MARKETING | UTILITY | AUTHENTICATION (required)")
tmplLang := fs.String("language", "en", "template_language code (default: en)")
tmplParams := fs.String("params", "", `JSON for template_params (per Meta Cloud API, e.g. {"components":[…]})`)
mediaURL := fs.String("media-url", "", "media URL for header media templates")
// Audience.
segmentIDs := fs.String("segment-ids", "", "comma-separated segment IDs")
contactIDs := fs.String("contact-ids", "", "comma-separated contact IDs")
// Scheduling + throttling.
sendType := fs.String("send-type", "now", "now | scheduled (default: now)")
scheduled := fs.String("scheduled-at", "", "ISO 8601 — required when --send-type=scheduled")
rateLimit := fs.Int("rate-limit", 0, "messages per second (0 = backend default)")
batchSize := fs.Int("batch-size", 0, "batch size for sending (0 = backend default)")
// RCS fallback for WhatsApp broadcasts, or pure-RCS mode.
rcsFbID := fs.String("rcs-fallback-template-id", "", "RCS fallback template id (WA→RCS fallback)")
rcsFbName := fs.String("rcs-fallback-template-name", "", "RCS fallback template name")
rcs := fs.Bool("rcs", false, "send as a pure-RCS broadcast (channel=rcs)")
// Preflight override.
yes := fs.Bool("yes", false, "skip the balance soft-check and confirmation prompt")
if err := fs.Parse(args); err != nil {
return err
}
if *name == "" || *tmplName == "" || *tmplCat == "" {
return fmt.Errorf(`usage: splashify broadcast create \
--name "May launch" --template <approved_name> \
--category MARKETING --language en \
[--template-id <id>] [--params '{"components":[…]}'] [--media-url …] \
[--segment-ids id1,id2 | --contact-ids id1,id2] \
[--send-type now|scheduled] [--scheduled-at 2026-06-01T10:00:00Z] \
[--rate-limit N] [--batch-size N] \
[--rcs-fallback-template-id <id> --rcs-fallback-template-name <name> | --rcs] \
[--yes]`)
}
if *segmentIDs == "" && *contactIDs == "" {
return fmt.Errorf("at least one of --segment-ids or --contact-ids is required")
}
if *sendType == "scheduled" && *scheduled == "" {
return fmt.Errorf("--scheduled-at is required when --send-type=scheduled")
}
// Preflight — subscription + non-zero wallet.
if !*yes {
if err := preflightSend("broadcasts",true); err != nil {
return err
}
}
body := map[string]any{
"name": *name,
"template_name": strings.ToLower(strings.TrimSpace(*tmplName)),
"template_category": strings.ToUpper(strings.TrimSpace(*tmplCat)),
"template_language": *tmplLang,
"send_type": *sendType,
}
if *desc != "" {
body["description"] = *desc
}
if *tmplID != "" {
body["template_id"] = *tmplID
}
if *tmplParams != "" {
var parsed any
if err := json.Unmarshal([]byte(*tmplParams), &parsed); err != nil {
return fmt.Errorf("--params must be valid JSON: %w", err)
}
body["template_params"] = parsed
}
if *mediaURL != "" {
body["media_url"] = *mediaURL
}
if *segmentIDs != "" {
body["segment_ids"] = splitTags(*segmentIDs)
}
if *contactIDs != "" {
body["contact_ids"] = splitTags(*contactIDs)
}
if *scheduled != "" {
body["scheduled_at"] = *scheduled
}
if *rateLimit > 0 {
body["rate_limit"] = *rateLimit
}
if *batchSize > 0 {
body["batch_size"] = *batchSize
}
if *rcsFbID != "" {
body["rcs_fallback_template_id"] = *rcsFbID
}
if *rcsFbName != "" {
body["rcs_fallback_template_name"] = *rcsFbName
}
if *rcs {
body["channel"] = "rcs"
body["channels"] = []string{"rcs"}
}
return runReq("POST", "/app/broadcasts", body)
}
func cmdBroadcastRebroadcast(id string, args []string) error {
fs := flag.NewFlagSet("broadcast rebroadcast", flag.ContinueOnError)
cohort := fs.String("cohort", "", "failed | sent | delivered | read | all (required)")
name := fs.String("name", "", "campaign name for the new broadcast")
tmplID := fs.String("template-id", "", "override template_id")
tmplName := fs.String("template", "", "override template_name")
tmplParams := fs.String("params", "", "JSON for template_params")
mediaURL := fs.String("media-url", "", "override media_url")
sendAt := fs.String("send-at", "", "ISO 8601 — schedule the rebroadcast (default: now)")
yes := fs.Bool("yes", false, "skip the balance soft-check")
if err := fs.Parse(args); err != nil {
return err
}
switch strings.ToLower(*cohort) {
case "failed", "sent", "delivered", "read", "all":
default:
return fmt.Errorf(`usage: splashify broadcast <id> rebroadcast --cohort failed|sent|delivered|read|all [flags…]`)
}
if !*yes {
if err := preflightSend("broadcasts",true); err != nil {
return err
}
}
body := map[string]any{"cohort": strings.ToLower(*cohort)}
if *name != "" {
body["name"] = *name
}
if *tmplID != "" {
body["template_id"] = *tmplID
}
if *tmplName != "" {
body["template_name"] = *tmplName
}
if *tmplParams != "" {
body["template_params"] = *tmplParams
}
if *mediaURL != "" {
body["media_url"] = *mediaURL
}
if *sendAt != "" {
body["send_at"] = *sendAt
}
return runReq("POST", "/app/broadcasts/"+id+"/rebroadcast", body)
}
// ─── preflight ───────────────────────────────────────────────────────────────
//
// preflightSend runs before any command that triggers actual sends/charges
// (broadcast create / send-now / restart / rebroadcast, call initiate, the
// calling send-* template-message commands). Two checks:
//
// 1. /app/developer/cli-eligibility — same gate cmdConnect uses. Refuses
// with the documented "upgrade your plan" / "no WABA" / "suspended"
// messages. SPLASHIFY_SKIP_ELIGIBILITY=1 still bypasses.
//
// 2. /app/wallet/info — fetches the user's wallet balance. When
// requireBalance is true we refuse if wallet_amount <= 0; otherwise
// we just show the current balance as context.
//
// `action` is the human-readable feature name woven into the refusal
// messages ("broadcasts", "calls", "templated call messages"). The
// backend always re-enforces both (subscription middleware and
// walletBilling.CheckBalance returning "Insufficient balance" 4xx) — this
// preflight is for fast, friendly UX, not security.
func preflightSend(action string, requireBalance bool) error {
if v := os.Getenv("SPLASHIFY_SKIP_PREFLIGHT"); v != "" && v != "0" && v != "false" {
fmt.Fprintln(os.Stderr, "note: SPLASHIFY_SKIP_PREFLIGHT is set — skipping preflight")
return nil
}
cfg, err := requireConfig()
if err != nil {
return err
}
api := newAPIClient(cfg.BaseURL, cfg.Token)
// 1. Subscription / eligibility
if v := os.Getenv("SPLASHIFY_SKIP_ELIGIBILITY"); v == "" || v == "0" || v == "false" {
elig, err := api.cliEligibility()
if err == nil && !elig.Eligible {
switch elig.Reason {
case "subscription_expired":
url := elig.UpgradeURL
if url == "" {
url = "https://app.splashifypro.com/settings/subscriptions"
}
return fmt.Errorf(`%s are unavailable — your trial has ended and there is no active paid plan on this account.
Upgrade your plan: %s
Once a plan is active, retry the command.`, action, url)
case "no_waba":
return fmt.Errorf("%s are unavailable — connect a WhatsApp Business Account first (https://app.splashifypro.com → WhatsApp → Connect Number)", action)
case "account_suspended":
return fmt.Errorf("%s are unavailable — your account is not active. Contact support", action)
}
}
}
// 2. Wallet balance
walletRaw, err := api.callRaw("GET", "/app/wallet/info", nil)
if err != nil {
fmt.Fprintln(os.Stderr, "note: could not fetch wallet balance —", err)
return nil
}
var wallet struct {
WalletAmount float64 `json:"wallet_amount"`
SpentBalance float64 `json:"spent_balance"`
CurrencyCode string `json:"currency_code"`
}
if err := json.Unmarshal(walletRaw, &wallet); err != nil {
fmt.Fprintln(os.Stderr, "note: wallet response unparsable, continuing")
return nil
}
sym := "₹"
if strings.EqualFold(wallet.CurrencyCode, "USD") {
sym = "$"
}
fmt.Fprintf(os.Stderr, "Wallet balance: %s%.2f\n", sym, wallet.WalletAmount)
if requireBalance && wallet.WalletAmount <= 0 {
return fmt.Errorf(`%s are unavailable — your wallet balance is %s%.2f.
Recharge: https://app.splashifypro.com/dashboard
(Or run with --yes to skip this soft-check; the backend still enforces it per-message.)`, action, sym, wallet.WalletAmount)
}
return nil
}