diff --git a/CHANGELOG.md b/CHANGELOG.md index 6900048..383795d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ All notable changes to the CLI are documented here. Releases are `v` tags on `main`. +## 0.3.0 - 2026-10-18 + +### Added + +- `fopost queue slots list · create · update · delete`, `queue next` and `queue preview` manage the posting queue, and `posts create --schedule queue` drops a post into the next free slot. +- `fopost posts unpublish` takes a live post down on every network; it confirms unless `--yes` is passed. +- `fopost connect-sessions create · get` mints a hosted connect link for one of your users and reads its status. +- `fopost webhooks deliveries list · get · redeliver` reads and replays a subscription's delivery log. +- `fopost automations versions list · get · restore` walks an automation's saved graphs and restores one as a new version. +- `fopost analytics inbox` prints the inbox roll-up. +- Requires `fopost-go` 0.4.0 (`Queue`, `ConnectSessions`, `Posts.Unpublish`, webhook deliveries, automation versions, `Analytics.Inbox`); the pin in `go.mod` must be re-pointed at the tag once it is released. + ## 0.2.0 - 2026-10-18 ### Removed diff --git a/CLAUDE.md b/CLAUDE.md index 076b5bd..60cda01 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ Guidance for Claude Code (claude.ai/code) when working in this repository. ## What This Is `github.com/fopost/fopost-cli` — the official FoPost command-line interface. It -builds a single static binary named `fopost` (version 0.2.0) that wraps the +builds a single static binary named `fopost` (version 0.3.0) that wraps the official Go SDK, `github.com/fopost/fopost-go`. It is distributed through a Homebrew tap, GitHub Releases, and `go install`; it is not a library and exports no public API. @@ -101,11 +101,11 @@ resolves it normally with no shim. It is currently pinned to a pseudo-version because the SDK has no `v*` tag yet; once it is tagged, bump `go.mod` to the released version. -The pin currently points at a commit on the SDK's `feature/broadcasts-sequences` -branch, which is stacked on `feature/contacts` and is what `fopost contacts`, -`fopost broadcasts` and `fopost sequences` need. Re-point it at `main` — or at -the tag — once those branches merge, or a `go get -u` will silently walk it -backwards. +The pin currently points at the head of the SDK's `feature/sdk-gaps` branch +(fopost/fopost-go#38), which is what `fopost queue`, `posts unpublish`, +`connect-sessions`, `webhooks deliveries`, `automations versions` and +`analytics inbox` need. Re-point it at the `v0.4.0` tag once that PR merges and +is tagged, or a `go get -u` will silently walk it backwards. `go.mod` declares `go 1.22`, which is why `golang.org/x/term` is pinned to `v0.27.0` — from `v0.34.0` it requires a newer toolchain. CI builds on 1.22 and @@ -121,7 +121,7 @@ go vet ./... gofmt -l . # must print nothing go run . --help # try the CLI without installing it -go build -ldflags "-X github.com/fopost/fopost-cli/internal/buildinfo.Version=0.2.0" -o fopost . +go build -ldflags "-X github.com/fopost/fopost-cli/internal/buildinfo.Version=0.3.0" -o fopost . ``` Tests never reach the network. They run the real cobra tree in-process through diff --git a/README.md b/README.md index eef6271..1a28449 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ Grab the archive for your platform from the `checksums.txt`, and put `fopost` on your `PATH`: ```bash -tar -xzf fopost_0.2.0_darwin_arm64.tar.gz +tar -xzf fopost_0.3.0_darwin_arm64.tar.gz sudo mv fopost /usr/local/bin/ fopost version ``` @@ -137,6 +137,10 @@ git log -1 --pretty=%s | \ Nothing reaches a platform without `--publish`, an explicit `posts publish`, or a schedule you set. +`--schedule queue` drops the post into the next free slot of the posting queue +instead of a fixed time. `fopost queue slots` manages the weekly slots, and +`fopost queue next` and `fopost queue preview` show when a queued post would go out. + ## Scripting with `--json` Every command takes `--json` and prints the resource instead of a table, so it @@ -239,8 +243,9 @@ fopost accounts list · get · rename · move · health · metrics · valid linkedin mentions reddit subreddits · rules · flairs · set-default fopost account-groups list · get · create · rename · set-members · delete -fopost posts list · get · create · publish · cancel · delete +fopost posts list · get · create · publish · cancel · unpublish · delete duplicate · preflight · deliveries +fopost queue slots (list · create · update · delete) · next · preview fopost media list · limits · upload · delete fopost labels list · create · delete fopost contacts list · get · conversations · import · delete @@ -254,9 +259,12 @@ fopost blog settings get · set · rotate-secret · test-website fopost blogs list · articles (list · get · create · update · delete) products (list · update) fopost analytics overview · top-posts · time-series · decay · frequency · timeline · - changes · collect-post · native-posts + changes · collect-post · native-posts · inbox fopost automations list · get · toggle · trigger · runs + versions list · get · restore fopost webhooks list · create · test · delete + deliveries list · get · redeliver +fopost connect-sessions create · get fopost activity list · audit fopost ads networks · tree · pause · resume · insights · leads · catalogs · library fopost completion bash · zsh · fish · powershell diff --git a/go.mod b/go.mod index 14188cd..53eef32 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/fopost/fopost-cli go 1.22 require ( - github.com/fopost/fopost-go v0.3.0 + github.com/fopost/fopost-go v0.3.1-0.20261018185422-4bdeedf09a93 github.com/spf13/cobra v1.10.2 golang.org/x/term v0.27.0 ) diff --git a/go.sum b/go.sum index 018416d..77b0d59 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/fopost/fopost-go v0.3.0 h1:HF8RGB+uO9SRXk+FWXLkrlzznN4Gl+SCxgQWV/TD3lY= -github.com/fopost/fopost-go v0.3.0/go.mod h1:Qz+7UCYTBnDEeZqB3VMrePxmYLVR9rFvx3+QWcKND8Q= +github.com/fopost/fopost-go v0.3.1-0.20261018185422-4bdeedf09a93 h1:CcVlEqyEa4w5GuUrtKekgcOjkc1sFWmQEpmRAoi47F4= +github.com/fopost/fopost-go v0.3.1-0.20261018185422-4bdeedf09a93/go.mod h1:Qz+7UCYTBnDEeZqB3VMrePxmYLVR9rFvx3+QWcKND8Q= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index 1358047..e534afa 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -5,7 +5,7 @@ import "runtime/debug" // Overridden at build time with -ldflags "-X ...buildinfo.Version=1.2.3". var ( - Version = "0.2.0" + Version = "0.3.0" Commit = "" Date = "" ) diff --git a/internal/cmd/analytics.go b/internal/cmd/analytics.go index 65972d9..c74e9c4 100644 --- a/internal/cmd/analytics.go +++ b/internal/cmd/analytics.go @@ -26,6 +26,7 @@ func newAnalyticsCmd(state *State) *cobra.Command { newAnalyticsChangesCmd(state), newAnalyticsCollectPostCmd(state), newAnalyticsNativePostsCmd(state), + newAnalyticsInboxCmd(state), ) return cmd } diff --git a/internal/cmd/analytics_inbox.go b/internal/cmd/analytics_inbox.go new file mode 100644 index 0000000..9009844 --- /dev/null +++ b/internal/cmd/analytics_inbox.go @@ -0,0 +1,64 @@ +package cmd + +import ( + "fmt" + + fopost "github.com/fopost/fopost-go" + "github.com/spf13/cobra" + + "github.com/fopost/fopost-cli/internal/output" +) + +func newAnalyticsInboxCmd(state *State) *cobra.Command { + params := &fopost.InboxAnalyticsParams{} + cmd := &cobra.Command{ + Use: "inbox", + Short: "Inbox volume, response time, and where it comes from", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := state.Client() + if err != nil { + return err + } + resolved, err := state.Resolved() + if err != nil { + return err + } + params.WorkspaceID = resolved.Workspace + inbox, err := client.Analytics.Inbox(cmd.Context(), params) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(inbox, func() { + median := "" + if inbox.Totals.MedianResponseMinutes != nil { + median = fmt.Sprintf("%.0f min", *inbox.Totals.MedianResponseMinutes) + } + printer.Fields([][2]string{ + {"Received", itoa(inbox.Totals.Received)}, + {"Sent", itoa(inbox.Totals.Sent)}, + {"Answered", itoa(inbox.Totals.Answered)}, + {"Open", itoa(inbox.Totals.Open)}, + {"Conversations", itoa(inbox.Totals.Conversations)}, + {"Median response", output.Dash(median)}, + {"Time zone", output.Dash(inbox.TimeZone)}, + }) + if len(inbox.ByPlatform) == 0 { + return + } + printer.Line("") + rows := make([][]string, 0, len(inbox.ByPlatform)) + for _, row := range inbox.ByPlatform { + rows = append(rows, []string{row.Platform, itoa(row.Received), itoa(row.Sent)}) + } + printer.Table([]string{"platform", "received", "sent"}, rows) + }) + }, + } + flags := cmd.Flags() + flags.StringVar(¶ms.AccountID, "account", "", "narrow to one account id") + flags.IntVar(¶ms.Days, "days", 0, "window length in days, 1 to 365 (the API defaults to 7)") + flags.StringVar(¶ms.TZ, "tz", "", "IANA zone the series and heatmap are bucketed in (default UTC)") + return cmd +} diff --git a/internal/cmd/analytics_inbox_test.go b/internal/cmd/analytics_inbox_test.go new file mode 100644 index 0000000..eb5265c --- /dev/null +++ b/internal/cmd/analytics_inbox_test.go @@ -0,0 +1,34 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestAnalyticsInboxPrintsTheTotals(t *testing.T) { + isolate(t) + api := newFakeAPI(t, func(w http.ResponseWriter, _ *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "totals": map[string]any{"received": 40, "sent": 12, "answered": 10, "open": 5, "conversations": 8, "median_response_minutes": 95.4}, + "deltas": map[string]any{}, "series": []any{}, + "by_platform": []map[string]any{{"platform": "linkedin", "received": 40, "sent": 12}}, + "by_type": []any{}, "by_account": []any{}, "response_time": []any{}, "heatmap": []any{}, + "time_zone": "UTC", + }}) + }) + configured(t, api.URL) + + stdout, stderr, code := run(t, "", "analytics", "inbox", "--days", "30", "--tz", "Europe/Zagreb") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + sent := api.find(t, "GET", "/analytics/inbox") + if sent.Query.Get("workspace_id") != "ws_1" || sent.Query.Get("days") != "30" || sent.Query.Get("tz") != "Europe/Zagreb" { + t.Fatalf("inbox sent query %v", sent.Query) + } + if !strings.Contains(stdout, "95 min") || !strings.Contains(stdout, "linkedin") { + t.Fatalf("inbox did not print the totals:\n%s", stdout) + } +} diff --git a/internal/cmd/automations.go b/internal/cmd/automations.go index bac820d..5ad89c9 100644 --- a/internal/cmd/automations.go +++ b/internal/cmd/automations.go @@ -4,8 +4,10 @@ import ( "encoding/json" "fmt" "os" + "strconv" "strings" + fopost "github.com/fopost/fopost-go" "github.com/spf13/cobra" "github.com/fopost/fopost-cli/internal/output" @@ -17,7 +19,7 @@ func newAutomationsCmd(state *State) *cobra.Command { cmd := &cobra.Command{ Use: "automations", Aliases: []string{"automation"}, - Short: "Inspect, toggle, and trigger automations", + Short: "Inspect, toggle, trigger, and restore automations", } cmd.AddCommand( newAutomationsListCmd(state), @@ -25,6 +27,7 @@ func newAutomationsCmd(state *State) *cobra.Command { newAutomationsToggleCmd(state), newAutomationsTriggerCmd(state), newAutomationsRunsCmd(state), + newAutomationsVersionsCmd(state), ) return cmd } @@ -215,3 +218,144 @@ func newAutomationsRunsCmd(state *State) *cobra.Command { cmd.Flags().IntVar(&perPage, "per-page", 0, "runs per page") return cmd } + +func newAutomationsVersionsCmd(state *State) *cobra.Command { + cmd := &cobra.Command{ + Use: "versions", + Aliases: []string{"version"}, + Short: "Walk and restore an automation's saved graphs", + } + cmd.AddCommand( + newAutomationsVersionsListCmd(state), + newAutomationsVersionsGetCmd(state), + newAutomationsVersionsRestoreCmd(state), + ) + return cmd +} + +func versionAuthor(author *fopost.AutomationVersionAuthor) string { + if author == nil { + return "" + } + return author.Name +} + +func parseVersion(value string) (int, error) { + version, err := strconv.Atoi(value) + if err != nil || version < 1 { + return 0, usageErrorf("version must be a positive number, got %q", value) + } + return version, nil +} + +func newAutomationsVersionsListCmd(state *State) *cobra.Command { + var page, perPage int + cmd := &cobra.Command{ + Use: "list ", + Short: "List an automation's saved versions, newest first", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := state.Client() + if err != nil { + return err + } + versions, err := client.Automations.ListVersions(cmd.Context(), args[0], page, perPage) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(versions, func() { + rows := make([][]string, 0, len(versions.Data)) + for _, version := range versions.Data { + rows = append(rows, []string{ + itoa(version.Version), + itoa(version.NodeCount), + "+" + itoa(len(version.NodesAdded)) + " -" + itoa(len(version.NodesRemoved)), + output.Dash(versionAuthor(version.CreatedBy)), + output.Stamp(version.CreatedAt.Time, version.CreatedAt.Raw), + output.Truncate(strValue(version.Note), 40), + }) + } + printer.Table([]string{"version", "nodes", "changed", "by", "saved", "note"}, rows) + if versions.Meta.Total > 0 { + printer.Line("") + printer.Line("Page %d of %d · %d version(s) total", max(versions.Meta.Page, 1), max(versions.Meta.TotalPages, 1), versions.Meta.Total) + } + }) + }, + } + cmd.Flags().IntVar(&page, "page", 0, "page number") + cmd.Flags().IntVar(&perPage, "per-page", 0, "versions per page") + return cmd +} + +func printGraph(printer *output.Printer, graph fopost.WorkflowGraph) { + rows := make([][]string, 0, len(graph.Nodes)) + for _, node := range graph.Nodes { + rows = append(rows, []string{itoa(node.Position), node.ID, node.Kind, output.Dash(strValue(node.Label))}) + } + printer.Table([]string{"position", "node id", "kind", "label"}, rows) +} + +func newAutomationsVersionsGetCmd(state *State) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Short: "Show one saved version with its nodes", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + number, err := parseVersion(args[1]) + if err != nil { + return err + } + client, err := state.Client() + if err != nil { + return err + } + version, err := client.Automations.GetVersion(cmd.Context(), args[0], number) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(version, func() { + printer.Fields([][2]string{ + {"Version", itoa(version.Version)}, + {"Saved", output.Stamp(version.CreatedAt.Time, version.CreatedAt.Raw)}, + {"By", output.Dash(versionAuthor(version.CreatedBy))}, + {"Note", output.Dash(strValue(version.Note))}, + {"Edges", itoa(len(version.Graph.Edges))}, + }) + if len(version.Graph.Nodes) == 0 { + return + } + printer.Line("") + printGraph(printer, version.Graph) + }) + }, + } +} + +func newAutomationsVersionsRestoreCmd(state *State) *cobra.Command { + return &cobra.Command{ + Use: "restore ", + Short: "Save a version's graph as a new version on top of the history", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + number, err := parseVersion(args[1]) + if err != nil { + return err + } + client, err := state.Client() + if err != nil { + return err + } + restored, err := client.Automations.RestoreVersion(cmd.Context(), args[0], number) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(restored, func() { + printer.Success("Restored version %d as version %d with %d step(s).", number, restored.Version, len(restored.Steps)) + }) + }, + } +} diff --git a/internal/cmd/automations_test.go b/internal/cmd/automations_test.go new file mode 100644 index 0000000..0868762 --- /dev/null +++ b/internal/cmd/automations_test.go @@ -0,0 +1,74 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestAutomationVersionsListGetRestore(t *testing.T) { + isolate(t) + api := newFakeAPI(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/automations/auto_1/versions": + json.NewEncoder(w).Encode(map[string]any{ + "data": []map[string]any{{ + "version": 3, "note": "Added the delay", "created_by": map[string]any{"name": "Ops"}, + "created_at": "2026-10-18T12:00:00Z", "node_count": 4, + "nodes_added": []map[string]any{{"id": "n4", "kind": "delay", "label": nil}}, "nodes_removed": []any{}, + }}, + "meta": map[string]any{"page": 1, "per_page": 20, "total": 3, "total_pages": 1}, + }) + case r.Method == http.MethodGet && r.URL.Path == "/automations/auto_1/versions/3": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "version": 3, "note": nil, "created_by": nil, "created_at": "2026-10-18T12:00:00Z", + "graph": map[string]any{ + "nodes": []map[string]any{{"id": "n1", "kind": "trigger", "label": "Start", "config": map[string]any{}, "position": 0}}, + "edges": []any{}, + }, + }}) + case r.Method == http.MethodPost && r.URL.Path == "/automations/auto_1/versions/3/restore": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "version": 4, "graph": map[string]any{"nodes": []any{}, "edges": []any{}}, + "steps": []map[string]any{{"position": 0, "node_id": "n1", "action_type": "send_email", "action_config": map[string]any{}}}, + }}) + default: + http.NotFound(w, r) + } + }) + configured(t, api.URL) + + stdout, stderr, code := run(t, "", "automations", "versions", "list", "auto_1", "--per-page", "20") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + if got := api.find(t, "GET", "/automations/auto_1/versions").Query.Get("per_page"); got != "20" { + t.Fatalf("list sent per_page=%q", got) + } + if !strings.Contains(stdout, "Added the delay") || !strings.Contains(stdout, "Ops") || !strings.Contains(stdout, "+1 -0") { + t.Fatalf("list did not print the version:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "automations", "versions", "get", "auto_1", "3") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "GET", "/automations/auto_1/versions/3") + if !strings.Contains(stdout, "trigger") || !strings.Contains(stdout, "Start") { + t.Fatalf("get did not print the nodes:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "automations", "versions", "restore", "auto_1", "3") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "POST", "/automations/auto_1/versions/3/restore") + if !strings.Contains(stdout, "version 4") { + t.Fatalf("restore did not print the new version:\n%s", stdout) + } + + if _, _, code := run(t, "", "automations", "versions", "get", "auto_1", "latest"); code != ExitUsage { + t.Fatalf("a non-numeric version exited %d, want %d", code, ExitUsage) + } +} diff --git a/internal/cmd/connect_sessions.go b/internal/cmd/connect_sessions.go new file mode 100644 index 0000000..2b8df98 --- /dev/null +++ b/internal/cmd/connect_sessions.go @@ -0,0 +1,118 @@ +package cmd + +import ( + "strings" + + fopost "github.com/fopost/fopost-go" + "github.com/spf13/cobra" + + "github.com/fopost/fopost-cli/internal/output" +) + +func init() { register(newConnectSessionsCmd) } + +func newConnectSessionsCmd(state *State) *cobra.Command { + cmd := &cobra.Command{ + Use: "connect-sessions", + Aliases: []string{"connect-session"}, + Short: "Mint and inspect hosted connect links", + Long: "A connect session is a single-use page, open for one hour, where one of your\n" + + "end users connects a social account into your workspace with no FoPost login.", + } + cmd.AddCommand( + newConnectSessionsCreateCmd(state), + newConnectSessionsGetCmd(state), + ) + return cmd +} + +func newConnectSessionsCreateCmd(state *State) *cobra.Command { + var ( + externalUserID string + platforms []string + redirectURL string + brandName string + brandLogoURL string + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Mint a hosted connect link for one of your users", + Long: "Mints a link and prints it once. --redirect-url must sit on a domain in the\n" + + "workspace redirect allowlist.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if externalUserID == "" { + return usageErrorf("--external-user-id is required") + } + if len(platforms) == 0 { + return usageErrorf("at least one --platform is required") + } + client, err := state.Client() + if err != nil { + return err + } + workspaceID, err := state.WorkspaceID("") + if err != nil { + return err + } + body := &fopost.CreateConnectSessionRequest{ + WorkspaceID: workspaceID, + ExternalUserID: externalUserID, + Platforms: platforms, + RedirectURL: redirectURL, + } + if brandName != "" || brandLogoURL != "" { + body.Branding = &fopost.CreateConnectSessionBranding{Name: brandName, LogoURL: brandLogoURL} + } + session, err := client.ConnectSessions.Create(cmd.Context(), body) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(session, func() { + printer.Success("Created connect session %s.", session.ID) + printer.Fields([][2]string{ + {"URL", session.URL}, + {"Platforms", strings.Join(session.Platforms, ", ")}, + {"Expires", output.Stamp(session.ExpiresAt.Time, session.ExpiresAt.Raw)}, + }) + }) + }, + } + cmd.Flags().StringVar(&externalUserID, "external-user-id", "", "your own id for the user (required)") + cmd.Flags().StringArrayVar(&platforms, "platform", nil, "network the user may pick (repeatable, at least one required)") + cmd.Flags().StringVar(&redirectURL, "redirect-url", "", "where to send the user once the account is connected") + cmd.Flags().StringVar(&brandName, "branding-name", "", "name the hosted page shows") + cmd.Flags().StringVar(&brandLogoURL, "branding-logo-url", "", "logo the hosted page shows") + return cmd +} + +func newConnectSessionsGetCmd(state *State) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Short: "Show a connect session's status and the account it connected", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := state.Client() + if err != nil { + return err + } + session, err := client.ConnectSessions.Get(cmd.Context(), args[0]) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(session, func() { + printer.Fields([][2]string{ + {"ID", session.ID}, + {"Status", session.Status}, + {"External user", session.ExternalUserID}, + {"Platforms", strings.Join(session.Platforms, ", ")}, + {"Account", output.Dash(strValue(session.AccountID))}, + {"Expires", output.Stamp(session.ExpiresAt.Time, session.ExpiresAt.Raw)}, + {"Used", output.Stamp(session.UsedAt.Time, session.UsedAt.Raw)}, + }) + }) + }, + } +} diff --git a/internal/cmd/connect_sessions_test.go b/internal/cmd/connect_sessions_test.go new file mode 100644 index 0000000..8c97171 --- /dev/null +++ b/internal/cmd/connect_sessions_test.go @@ -0,0 +1,62 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestConnectSessionsCreateAndGet(t *testing.T) { + isolate(t) + api := newFakeAPI(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost && r.URL.Path == "/connect-sessions": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "id": "cs_1", "status": "pending", "external_user_id": "user-42", + "platforms": []string{"linkedin", "bluesky"}, + "url": "https://connect.yourbrand.com/cs_1", "expires_at": "2026-10-18T13:00:00Z", + }}) + case r.Method == http.MethodGet && r.URL.Path == "/connect-sessions/cs_1": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "id": "cs_1", "status": "used", "external_user_id": "user-42", + "platforms": []string{"linkedin"}, "account_id": "acc_7", + "expires_at": "2026-10-18T13:00:00Z", "used_at": "2026-10-18T12:10:00Z", + }}) + default: + http.NotFound(w, r) + } + }) + configured(t, api.URL) + + stdout, stderr, code := run(t, "", "connect-sessions", "create", + "--external-user-id", "user-42", "--platform", "linkedin", "--platform", "bluesky", + "--redirect-url", "https://yourbrand.com/done", "--branding-name", "Your Brand", + "--branding-logo-url", "https://yourbrand.com/logo.png") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + sent := api.find(t, "POST", "/connect-sessions") + if sent.Body["workspaceId"] != "ws_1" || sent.Body["externalUserId"] != "user-42" || sent.Body["redirectUrl"] != "https://yourbrand.com/done" { + t.Fatalf("create sent %v", sent.Body) + } + if platforms, _ := sent.Body["platforms"].([]any); len(platforms) != 2 || platforms[1] != "bluesky" { + t.Fatalf("create sent platforms %v", sent.Body["platforms"]) + } + branding, _ := sent.Body["branding"].(map[string]any) + if branding["name"] != "Your Brand" || branding["logoUrl"] != "https://yourbrand.com/logo.png" { + t.Fatalf("create sent branding %v", sent.Body["branding"]) + } + if !strings.Contains(stdout, "https://connect.yourbrand.com/cs_1") { + t.Fatalf("create did not print the link:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "connect-sessions", "get", "cs_1") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "GET", "/connect-sessions/cs_1") + if !strings.Contains(stdout, "used") || !strings.Contains(stdout, "acc_7") { + t.Fatalf("get did not print the status and account:\n%s", stdout) + } +} diff --git a/internal/cmd/helpers.go b/internal/cmd/helpers.go index c6f1692..ad18f22 100644 --- a/internal/cmd/helpers.go +++ b/internal/cmd/helpers.go @@ -93,3 +93,11 @@ type deleted struct { Deleted bool `json:"deleted"` ID string `json:"id"` } + +// strValue reads an optional string the API may send as null. +func strValue(p *string) string { + if p == nil { + return "" + } + return *p +} diff --git a/internal/cmd/posts.go b/internal/cmd/posts.go index 6e0eae7..2a98978 100644 --- a/internal/cmd/posts.go +++ b/internal/cmd/posts.go @@ -26,6 +26,7 @@ func newPostsCmd(state *State) *cobra.Command { newPostsCreateCmd(state), newPostsPublishCmd(state), newPostsCancelCmd(state), + newPostsUnpublishCmd(state), newPostsDeleteCmd(state), newPostsDuplicateCmd(state), newPostsPreflightCmd(state), @@ -178,6 +179,7 @@ type createOptions struct { media []string files []string scheduleAt string + schedule string draft bool publish bool labels []string @@ -204,6 +206,7 @@ func newPostsCreateCmd(state *State) *cobra.Command { Example: strings.Join([]string{ " fopost posts create --account acc_1 --text \"Shipping today\" --publish", " fopost posts create --account acc_1 --text-file post.md --schedule-at \"2026-09-01 09:00\"", + " fopost posts create --account acc_1 --text \"Next free slot\" --schedule queue", " git log -1 --pretty=%s | fopost posts create --account acc_1 --text-file - --draft", }, "\n"), Args: cobra.NoArgs, @@ -219,6 +222,7 @@ func newPostsCreateCmd(state *State) *cobra.Command { flags.StringArrayVar(&opts.media, "media", nil, "local file to upload and attach (repeatable)") flags.StringArrayVar(&opts.files, "file", nil, "local file to send with the post (repeatable, up to 5)") flags.StringVar(&opts.scheduleAt, "schedule-at", "", "when to publish, RFC 3339 or \"2026-09-01 09:00\" in local time") + flags.StringVar(&opts.schedule, "schedule", "", "\"queue\" to publish at the next free queue slot") flags.BoolVar(&opts.draft, "draft", false, "save as a draft (the default when no schedule is given)") flags.BoolVar(&opts.publish, "publish", false, "publish immediately after creating") flags.StringArrayVar(&opts.labels, "label", nil, "label id to attach (repeatable)") @@ -236,6 +240,12 @@ func runPostsCreate(cmd *cobra.Command, state *State, opts *createOptions) error if opts.publish && opts.draft { return usageErrorf("--publish and --draft are alternatives; pass one") } + if opts.schedule != "" && opts.schedule != fopost.ScheduleQueue { + return usageErrorf("--schedule only accepts \"queue\"") + } + if opts.schedule != "" && (opts.scheduleAt != "" || opts.publish || opts.draft) { + return usageErrorf("--schedule queue is an alternative to --schedule-at, --publish, and --draft; pass one") + } text, err := readText(opts.text, opts.textFile, state.In) if err != nil { @@ -288,6 +298,10 @@ func runPostsCreate(cmd *cobra.Command, state *State, opts *createOptions) error body.Status = fopost.PostStatusScheduled body.ScheduleAt = scheduleAt } + if opts.schedule == fopost.ScheduleQueue { + body.Status = fopost.PostStatusScheduled + body.Schedule = fopost.ScheduleQueue + } files, closeFiles, err := openPostFiles(opts.files) if err != nil { @@ -452,6 +466,43 @@ func newPostsCancelCmd(state *State) *cobra.Command { return cmd } +func newPostsUnpublishCmd(state *State) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "unpublish ", + Short: "Take a live post down on every network", + Long: "Deletes the post on every network it is live on; the post stays as a record.\n" + + "A network that cannot delete a live post refuses the whole call.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if !yes { + if err := confirm(state, fmt.Sprintf("Unpublish post %s on every network? This cannot be undone.", args[0])); err != nil { + return err + } + } + client, err := state.Client() + if err != nil { + return err + } + result, err := client.Posts.Unpublish(cmd.Context(), args[0]) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(result, func() { + printer.Success("Unpublished %s on %d network(s). Post is %s.", args[0], len(result.Deliveries), output.Dash(result.PostStatus)) + rows := make([][]string, 0, len(result.Deliveries)) + for _, delivery := range result.Deliveries { + rows = append(rows, []string{delivery.AccountID, delivery.Platform, boolLabel(delivery.Removed, "removed", "kept")}) + } + printer.Table([]string{"account id", "platform", "result"}, rows) + }) + }, + } + cmd.Flags().BoolVarP(&yes, "yes", "y", false, "skip the confirmation prompt") + return cmd +} + func newPostsDeleteCmd(state *State) *cobra.Command { var yes bool cmd := &cobra.Command{ diff --git a/internal/cmd/posts_unpublish_test.go b/internal/cmd/posts_unpublish_test.go new file mode 100644 index 0000000..419fd00 --- /dev/null +++ b/internal/cmd/posts_unpublish_test.go @@ -0,0 +1,47 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestPostsUnpublishConfirmsAndPrintsEachNetwork(t *testing.T) { + isolate(t) + api := newFakeAPI(t, func(w http.ResponseWriter, _ *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "post_status": "unpublished", + "deliveries": []map[string]any{ + {"account_id": "acc_1", "platform": "linkedin", "removed": true}, + {"account_id": "acc_2", "platform": "bluesky", "removed": false}, + }, + }}) + }) + configured(t, api.URL) + + if _, _, code := run(t, "n\n", "posts", "unpublish", "post_1"); code != ExitUsage { + t.Fatalf("a declined prompt exited %d, want %d", code, ExitUsage) + } + if len(api.paths()) != 0 { + t.Fatalf("a declined prompt still sent %v", api.paths()) + } + + stdout, stderr, code := run(t, "", "posts", "unpublish", "post_1", "--yes") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "POST", "/posts/post_1/unpublish") + if !strings.Contains(stdout, "unpublished") || !strings.Contains(stdout, "linkedin") || !strings.Contains(stdout, "kept") { + t.Fatalf("unpublish did not print the outcome:\n%s", stdout) + } + + stdout, _, code = run(t, "", "posts", "unpublish", "post_1", "--yes", "--json") + if code != ExitOK { + t.Fatalf("exit = %d", code) + } + var result map[string]any + if err := json.Unmarshal([]byte(stdout), &result); err != nil || result["post_status"] != "unpublished" { + t.Fatalf("--json output is not the result: %v\n%s", err, stdout) + } +} diff --git a/internal/cmd/queue.go b/internal/cmd/queue.go new file mode 100644 index 0000000..df8ecd4 --- /dev/null +++ b/internal/cmd/queue.go @@ -0,0 +1,314 @@ +package cmd + +import ( + "fmt" + + fopost "github.com/fopost/fopost-go" + "github.com/spf13/cobra" + + "github.com/fopost/fopost-cli/internal/output" +) + +func init() { register(newQueueCmd) } + +func newQueueCmd(state *State) *cobra.Command { + cmd := &cobra.Command{ + Use: "queue", + Short: "Manage the posting queue and its weekly slots", + Long: "The posting queue is a set of weekly time slots. A post created with\n" + + "--schedule queue lands in the next free one.", + } + cmd.AddCommand( + newQueueSlotsCmd(state), + newQueueNextCmd(state), + newQueuePreviewCmd(state), + ) + return cmd +} + +func newQueueSlotsCmd(state *State) *cobra.Command { + cmd := &cobra.Command{ + Use: "slots", + Aliases: []string{"slot"}, + Short: "List, add, change, and remove queue slots", + } + cmd.AddCommand( + newQueueSlotsListCmd(state), + newQueueSlotsCreateCmd(state), + newQueueSlotsUpdateCmd(state), + newQueueSlotsDeleteCmd(state), + ) + return cmd +} + +var weekdayNames = []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} + +func weekdayLabel(weekday int) string { + if weekday < 0 || weekday >= len(weekdayNames) { + return itoa(weekday) + } + return weekdayNames[weekday] +} + +func accountLabel(id *string) string { + if id == nil { + return "all" + } + return *id +} + +func newQueueSlotsListCmd(state *State) *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "List the workspace's queue slots", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := state.Client() + if err != nil { + return err + } + workspaceID, err := state.WorkspaceID("") + if err != nil { + return err + } + slots, err := client.Queue.ListSlots(cmd.Context(), workspaceID) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(slots, func() { + rows := make([][]string, 0, len(slots)) + for _, slot := range slots { + rows = append(rows, []string{ + slot.ID, + weekdayLabel(slot.Weekday), + slot.Time, + slot.Timezone, + accountLabel(slot.AccountID), + }) + } + printer.Table([]string{"id", "weekday", "time", "timezone", "account"}, rows) + }) + }, + } +} + +func newQueueSlotsCreateCmd(state *State) *cobra.Command { + var ( + weekday int + at string + timezone string + account string + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Add a weekly queue slot", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if !cmd.Flags().Changed("weekday") { + return usageErrorf("--weekday is required") + } + if at == "" || timezone == "" { + return usageErrorf("--time and --timezone are required") + } + client, err := state.Client() + if err != nil { + return err + } + workspaceID, err := state.WorkspaceID("") + if err != nil { + return err + } + body := &fopost.CreateQueueSlotRequest{ + WorkspaceID: workspaceID, + Weekday: weekday, + Time: at, + Timezone: timezone, + } + if account != "" { + body.AccountID = fopost.String(account) + } + slot, err := client.Queue.CreateSlot(cmd.Context(), body) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(slot, func() { + printer.Success("Created slot %s: %s %s %s.", slot.ID, weekdayLabel(slot.Weekday), slot.Time, slot.Timezone) + }) + }, + } + cmd.Flags().IntVar(&weekday, "weekday", 0, "0 (Sunday) through 6 (Saturday) (required)") + cmd.Flags().StringVar(&at, "time", "", "HH:MM, 24-hour (required)") + cmd.Flags().StringVar(&timezone, "timezone", "", "IANA zone name, such as Europe/Zagreb (required)") + cmd.Flags().StringVar(&account, "account", "", "account id the slot applies to; omit for every account") + return cmd +} + +func printMoved(printer *output.Printer, moved []fopost.QueueMove) { + if len(moved) == 0 { + return + } + rows := make([][]string, 0, len(moved)) + for _, move := range moved { + rows = append(rows, []string{ + move.ID, + output.Stamp(move.From.Time, move.From.Raw), + output.Stamp(move.To.Time, move.To.Raw), + }) + } + printer.Table([]string{"post id", "from", "to"}, rows) +} + +func newQueueSlotsUpdateCmd(state *State) *cobra.Command { + var ( + weekday int + at string + timezone string + account string + ) + cmd := &cobra.Command{ + Use: "update ", + Short: "Change a queue slot; queued posts on it move with it", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + body := &fopost.UpdateQueueSlotRequest{Time: at, Timezone: timezone} + if cmd.Flags().Changed("weekday") { + body.Weekday = fopost.Int(weekday) + } + if cmd.Flags().Changed("account") { + if account == "" { + body.AccountID = nil + } else { + body.AccountID = fopost.String(account) + } + } + if body.Weekday == nil && at == "" && timezone == "" && !cmd.Flags().Changed("account") { + return usageErrorf("pass at least one of --weekday, --time, --timezone, or --account") + } + client, err := state.Client() + if err != nil { + return err + } + slot, err := client.Queue.UpdateSlot(cmd.Context(), args[0], body) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(slot, func() { + printer.Success("Updated slot %s: %s %s %s. Moved %d post(s).", slot.ID, weekdayLabel(slot.Weekday), slot.Time, slot.Timezone, len(slot.Moved)) + printMoved(printer, slot.Moved) + }) + }, + } + cmd.Flags().IntVar(&weekday, "weekday", 0, "0 (Sunday) through 6 (Saturday)") + cmd.Flags().StringVar(&at, "time", "", "HH:MM, 24-hour") + cmd.Flags().StringVar(&timezone, "timezone", "", "IANA zone name") + cmd.Flags().StringVar(&account, "account", "", "account id the slot applies to") + return cmd +} + +func newQueueSlotsDeleteCmd(state *State) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "delete ", + Short: "Remove a queue slot; queued posts on it move to the next free one", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if !yes { + if err := confirm(state, fmt.Sprintf("Delete slot %s? This cannot be undone.", args[0])); err != nil { + return err + } + } + client, err := state.Client() + if err != nil { + return err + } + result, err := client.Queue.DeleteSlot(cmd.Context(), args[0]) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(result, func() { + printer.Success("Deleted slot %s. Moved %d post(s).", args[0], len(result.Moved)) + printMoved(printer, result.Moved) + }) + }, + } + cmd.Flags().BoolVarP(&yes, "yes", "y", false, "skip the confirmation prompt") + return cmd +} + +type queueNext struct { + Next *fopost.Time `json:"next"` +} + +func newQueueNextCmd(state *State) *cobra.Command { + var account string + cmd := &cobra.Command{ + Use: "next", + Short: "Show when a post added to the queue now would go out", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := state.Client() + if err != nil { + return err + } + workspaceID, err := state.WorkspaceID("") + if err != nil { + return err + } + next, err := client.Queue.Next(cmd.Context(), workspaceID, account) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(queueNext{Next: next}, func() { + if next == nil { + printer.Line("No slot applies.") + return + } + printer.Line("%s", output.Stamp(next.Time, next.Raw)) + }) + }, + } + cmd.Flags().StringVar(&account, "account", "", "narrow to the slots for one account id") + return cmd +} + +func newQueuePreviewCmd(state *State) *cobra.Command { + var ( + account string + count int + ) + cmd := &cobra.Command{ + Use: "preview", + Short: "Show the next free queue times", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, err := state.Client() + if err != nil { + return err + } + workspaceID, err := state.WorkspaceID("") + if err != nil { + return err + } + times, err := client.Queue.Preview(cmd.Context(), workspaceID, account, count) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(times, func() { + rows := make([][]string, 0, len(times)) + for index, at := range times { + rows = append(rows, []string{itoa(index + 1), output.Stamp(at.Time, at.Raw)}) + } + printer.Table([]string{"#", "time"}, rows) + }) + }, + } + cmd.Flags().StringVar(&account, "account", "", "narrow to the slots for one account id") + cmd.Flags().IntVar(&count, "count", 0, "how many times to show (the API defaults to 5, at most 20)") + return cmd +} diff --git a/internal/cmd/queue_test.go b/internal/cmd/queue_test.go new file mode 100644 index 0000000..1dbc525 --- /dev/null +++ b/internal/cmd/queue_test.go @@ -0,0 +1,135 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestQueueSlotsAndPostsScheduleQueue(t *testing.T) { + isolate(t) + api := newFakeAPI(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost && r.URL.Path == "/queue/slots": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "id": "slot_1", "workspace_id": "ws_1", "account_id": nil, + "weekday": 2, "time": "09:00", "timezone": "Europe/Zagreb", + }}) + case r.Method == http.MethodPut && r.URL.Path == "/queue/slots/slot_1": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "id": "slot_1", "weekday": 0, "time": "10:30", "timezone": "Europe/Zagreb", + "moved": []map[string]any{{"id": "post_9", "from": "2026-10-20T07:00:00Z", "to": "2026-10-25T08:30:00Z"}}, + }}) + case r.Method == http.MethodDelete && r.URL.Path == "/queue/slots/slot_1": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"deleted": true, "moved": []any{}}}) + case r.URL.Path == "/queue/slots": + json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{ + {"id": "slot_1", "weekday": 2, "time": "09:00", "timezone": "Europe/Zagreb", "account_id": "acc_1"}, + }}) + case r.URL.Path == "/queue/next": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"next": "2026-10-20T07:00:00Z"}}) + case r.URL.Path == "/queue/preview": + json.NewEncoder(w).Encode(map[string]any{"data": []string{"2026-10-20T07:00:00Z", "2026-10-27T07:00:00Z"}}) + case r.Method == http.MethodPost && r.URL.Path == "/posts": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "id": "post_1", "status": "scheduled", "schedule_at": "2026-10-20T07:00:00Z", + }}) + default: + http.NotFound(w, r) + } + }) + configured(t, api.URL) + + stdout, stderr, code := run(t, "", "queue", "slots", "create", "--weekday", "2", "--time", "09:00", "--timezone", "Europe/Zagreb") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + created := api.find(t, "POST", "/queue/slots") + if created.Body["workspace_id"] != "ws_1" || created.Body["weekday"] != float64(2) || created.Body["time"] != "09:00" { + t.Fatalf("create sent %v", created.Body) + } + if _, present := created.Body["account_id"]; present { + t.Fatalf("create sent account_id for an every-account slot: %v", created.Body) + } + if !strings.Contains(stdout, "slot_1") || !strings.Contains(stdout, "Tue") { + t.Fatalf("create did not print the slot:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "queue", "slots", "list") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + if got := api.find(t, "GET", "/queue/slots").Query.Get("workspace_id"); got != "ws_1" { + t.Fatalf("list sent workspace_id=%q", got) + } + if !strings.Contains(stdout, "acc_1") { + t.Fatalf("list did not print the slot's account:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "queue", "slots", "update", "slot_1", "--weekday", "0", "--time", "10:30") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + updated := api.find(t, "PUT", "/queue/slots/slot_1") + // Sunday is 0, so the weekday must travel even though it is the zero value. + if updated.Body["weekday"] != float64(0) || updated.Body["time"] != "10:30" { + t.Fatalf("update sent %v", updated.Body) + } + if _, present := updated.Body["timezone"]; present { + t.Fatalf("update sent a timezone that was not passed: %v", updated.Body) + } + if !strings.Contains(stdout, "post_9") { + t.Fatalf("update did not print the moved post:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "queue", "slots", "delete", "slot_1", "--yes") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "DELETE", "/queue/slots/slot_1") + + stdout, stderr, code = run(t, "", "queue", "next", "--account", "acc_1") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + if got := api.find(t, "GET", "/queue/next").Query.Get("account_id"); got != "acc_1" { + t.Fatalf("next sent account_id=%q", got) + } + if !strings.Contains(stdout, "2026-10-20") { + t.Fatalf("next did not print the time:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "queue", "preview", "--count", "2") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + if got := api.find(t, "GET", "/queue/preview").Query.Get("count"); got != "2" { + t.Fatalf("preview sent count=%q", got) + } + if !strings.Contains(stdout, "2026-10-27") { + t.Fatalf("preview did not print the second time:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "posts", "create", "--account", "acc_1", "--text", "Next free slot", "--schedule", "queue") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + post := api.find(t, "POST", "/posts") + if post.Body["schedule"] != "queue" || post.Body["status"] != "scheduled" { + t.Fatalf("posts create sent %v", post.Body) + } + if _, present := post.Body["schedule_at"]; present { + t.Fatalf("posts create sent schedule_at alongside the queue: %v", post.Body) + } + if !strings.Contains(stdout, "Scheduled post_1") { + t.Fatalf("posts create did not report the schedule:\n%s", stdout) + } + + if _, _, code := run(t, "", "posts", "create", "--account", "acc_1", "--text", "x", "--schedule", "queue", "--publish"); code != ExitUsage { + t.Fatalf("--schedule queue with --publish exited %d, want %d", code, ExitUsage) + } + if _, _, code := run(t, "", "posts", "create", "--account", "acc_1", "--text", "x", "--schedule", "tomorrow"); code != ExitUsage { + t.Fatalf("--schedule tomorrow exited %d, want %d", code, ExitUsage) + } +} diff --git a/internal/cmd/webhooks.go b/internal/cmd/webhooks.go index 4aa75c1..257ee6f 100644 --- a/internal/cmd/webhooks.go +++ b/internal/cmd/webhooks.go @@ -23,6 +23,7 @@ func newWebhooksCmd(state *State) *cobra.Command { newWebhooksCreateCmd(state), newWebhooksTestCmd(state), newWebhooksDeleteCmd(state), + newWebhooksDeliveriesCmd(state), ) return cmd } @@ -166,3 +167,128 @@ func newWebhooksDeleteCmd(state *State) *cobra.Command { cmd.Flags().BoolVarP(&yes, "yes", "y", false, "skip the confirmation prompt") return cmd } + +func newWebhooksDeliveriesCmd(state *State) *cobra.Command { + cmd := &cobra.Command{ + Use: "deliveries", + Aliases: []string{"delivery"}, + Short: "Read and replay a subscription's delivery log", + } + cmd.AddCommand( + newWebhooksDeliveriesListCmd(state), + newWebhooksDeliveriesGetCmd(state), + newWebhooksDeliveriesRedeliverCmd(state), + ) + return cmd +} + +func responseStatus(status *int) string { + if status == nil { + return "" + } + return itoa(*status) +} + +func newWebhooksDeliveriesListCmd(state *State) *cobra.Command { + params := &fopost.ListWebhookDeliveriesParams{} + cmd := &cobra.Command{ + Use: "list ", + Short: "List recent delivery attempts, newest first", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := state.Client() + if err != nil { + return err + } + deliveries, err := client.Webhooks.ListDeliveries(cmd.Context(), args[0], params) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(deliveries, func() { + rows := make([][]string, 0, len(deliveries)) + for _, delivery := range deliveries { + rows = append(rows, []string{ + delivery.ID, + delivery.Event, + itoa(delivery.Attempt), + delivery.Status, + output.Dash(responseStatus(delivery.ResponseStatus)), + itoa(delivery.DurationMs) + "ms", + output.Stamp(delivery.CreatedAt.Time, delivery.CreatedAt.Raw), + }) + } + printer.Table([]string{"id", "event", "attempt", "status", "response", "duration", "sent"}, rows) + }) + }, + } + cmd.Flags().StringVar(¶ms.Status, "status", "", "success or failed") + cmd.Flags().IntVar(¶ms.Limit, "limit", 0, "how many to show, 1 to 200 (the API defaults to 50)") + return cmd +} + +func newWebhooksDeliveriesGetCmd(state *State) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Short: "Show one delivery attempt", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := state.Client() + if err != nil { + return err + } + delivery, err := client.Webhooks.GetDelivery(cmd.Context(), args[0], args[1]) + if err != nil { + return err + } + printer := state.Printer() + return printer.Value(delivery, func() { + snippet := strValue(delivery.ResponseSnippet) + printer.Fields([][2]string{ + {"ID", delivery.ID}, + {"Webhook", delivery.WebhookID}, + {"Event", delivery.Event}, + {"Delivery key", delivery.DeliveryKey}, + {"Attempt", itoa(delivery.Attempt)}, + {"Status", delivery.Status}, + {"Response", output.Dash(responseStatus(delivery.ResponseStatus))}, + {"Duration", itoa(delivery.DurationMs) + "ms"}, + {"Payload hash", delivery.PayloadHash}, + {"Next retry", output.Stamp(delivery.NextRetryAt.Time, delivery.NextRetryAt.Raw)}, + {"Sent", output.Stamp(delivery.CreatedAt.Time, delivery.CreatedAt.Raw)}, + }) + if snippet != "" { + printer.Line("") + printer.Line("%s", snippet) + } + }) + }, + } +} + +type redelivered struct { + Redelivered bool `json:"redelivered"` + WebhookID string `json:"webhook_id"` + DeliveryID string `json:"delivery_id"` +} + +func newWebhooksDeliveriesRedeliverCmd(state *State) *cobra.Command { + return &cobra.Command{ + Use: "redeliver ", + Short: "Send a delivery's event again as a new attempt", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + client, err := state.Client() + if err != nil { + return err + } + if err := client.Webhooks.Redeliver(cmd.Context(), args[0], args[1]); err != nil { + return err + } + printer := state.Printer() + return printer.Value(redelivered{Redelivered: true, WebhookID: args[0], DeliveryID: args[1]}, func() { + printer.Success("Queued delivery %s to be sent again.", args[1]) + }) + }, + } +} diff --git a/internal/cmd/webhooks_test.go b/internal/cmd/webhooks_test.go new file mode 100644 index 0000000..8db5f74 --- /dev/null +++ b/internal/cmd/webhooks_test.go @@ -0,0 +1,64 @@ +package cmd + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestWebhookDeliveriesListGetRedeliver(t *testing.T) { + isolate(t) + api := newFakeAPI(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/webhooks/wh_1/deliveries": + json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{ + "id": "del_1", "webhook_id": "wh_1", "event": "post.published", "delivery_key": "key_1", + "attempt": 2, "status": "failed", "response_status": 502, "response_snippet": "bad gateway", + "duration_ms": 340, "payload_hash": "abc", "created_at": "2026-10-18T12:00:00Z", + }}}) + case r.Method == http.MethodGet && r.URL.Path == "/webhooks/wh_1/deliveries/del_1": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{ + "id": "del_1", "webhook_id": "wh_1", "event": "post.published", "delivery_key": "key_1", + "attempt": 2, "status": "failed", "response_status": nil, "response_snippet": "no answer", + "duration_ms": 340, "payload_hash": "abc", "created_at": "2026-10-18T12:00:00Z", + }}) + case r.Method == http.MethodPost && r.URL.Path == "/webhooks/wh_1/deliveries/del_1/redeliver": + w.WriteHeader(http.StatusAccepted) + default: + http.NotFound(w, r) + } + }) + configured(t, api.URL) + + stdout, stderr, code := run(t, "", "webhooks", "deliveries", "list", "wh_1", "--status", "failed", "--limit", "10") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + listed := api.find(t, "GET", "/webhooks/wh_1/deliveries") + if listed.Query.Get("status") != "failed" || listed.Query.Get("limit") != "10" { + t.Fatalf("list sent query %v", listed.Query) + } + if !strings.Contains(stdout, "del_1") || !strings.Contains(stdout, "502") { + t.Fatalf("list did not print the delivery:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "webhooks", "deliveries", "get", "wh_1", "del_1") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "GET", "/webhooks/wh_1/deliveries/del_1") + if !strings.Contains(stdout, "key_1") || !strings.Contains(stdout, "no answer") { + t.Fatalf("get did not print the delivery:\n%s", stdout) + } + + stdout, stderr, code = run(t, "", "webhooks", "deliveries", "redeliver", "wh_1", "del_1", "--json") + if code != ExitOK { + t.Fatalf("exit = %d\n%s%s", code, stdout, stderr) + } + api.find(t, "POST", "/webhooks/wh_1/deliveries/del_1/redeliver") + var result map[string]any + if err := json.Unmarshal([]byte(stdout), &result); err != nil || result["redelivered"] != true || result["delivery_id"] != "del_1" { + t.Fatalf("--json output is not the acknowledgement: %v\n%s", err, stdout) + } +}