# niotio — command line client for the Niotio app

A small, dependency-free Go CLI for the Niotio survey REST API. Built to be driven
by humans *and* coding agents: every command supports `--json`, non-interactive
use is explicit (`--yes`), and exit codes are stable.

## Install

The CLI is served **by the Niotio app itself**, so installing needs no GitHub token
and no Go toolchain (the `stigsen/nps` repo is private):

**Recommended — curl | sh from the app** (checksum-verified prebuilt binary):
```bash
curl -fsSL https://niotio.dk/cli/install.sh | sh
```
The installer detects your OS/arch, verifies the sha256 against the app's
`/cli/manifest.json`, installs to `/usr/local/bin` (or `~/.local/bin`), and
pre-sets the API URL (`niotio config set-url https://niotio.dk`).
Override with `NPS_CLI_BASE_URL`, `NPS_CLI_BINDIR`, or skip the URL preset with
`NPS_CLI_NO_CONFIG=1`.

Published artifacts:
- `GET /cli/manifest.json` — version + artifact list (name/size/sha256)
- `GET /cli/checksums.txt`
- `GET /cli/download/niotio_{linux,darwin}_{amd64,arm64}.tar.gz`

They are produced by `scripts/cli-build.sh` (cross-compiles in a throwaway Go
container) and published to the host dir configured by `nps.cli.dist-dir`.

**Alternative — build from a clone** (needs Go 1.23+, always current):
```bash
git clone https://github.com/stigsen/nps.git
cd nps/cli && go build -o "$HOME/.local/bin/niotio" ./cmd/nps
```

## Release

Artifacts are produced by `scripts/cli-build.sh` — it cross-compiles linux/darwin
× amd64/arm64 in a throwaway Go container and writes the tarballs, `checksums.txt`
and `manifest.json` to `nps.cli.dist-dir` (default `/var/lib/nps/cli-dist`), which
the app serves at `/cli/download`.

Two ways to publish:
- **CI (preferred):** push a tag `cli/v1.2.3` (or run the `cli-publish` workflow
  manually). It builds the artifacts and rsyncs them to the host. Requires repo
  secrets `CLI_DEPLOY_HOST`, `CLI_DEPLOY_USER`, `CLI_DEPLOY_SSH_KEY` (and optional
  `CLI_DEPLOY_PATH`, default `/var/lib/nps/cli-dist`).
- **On the host:** run `scripts/cli-build.sh` (writes straight to the served dir).

End users update with `niotio update` (`--check` to only report). It reads
`/cli/manifest.json` from the configured app, verifies the artifact's sha256 and
atomically replaces the running binary. `niotio doctor` also nudges when a newer
build is available.

## Configure

API tokens are created in the app under **Settings → API tokens** (shown once).

```bash
niotio config set-url   https://niotio.dk --profile prod
niotio config set-token <your-token>                --profile prod
niotio config use prod
niotio doctor          # config → health → auth
```

Config lives at `~/.config/niotio/config.toml`. Overrides (highest first):
`--url/--token` flags, then `NPS_URL`/`NPS_TOKEN`/`NPS_PROFILE` env vars, then
the active profile. Useful for CI/agents that shouldn't touch the config file.

## Global flags

| flag | meaning |
| --- | --- |
| `--json` | machine-readable output (recommended for agents) |
| `--profile <name>` | config profile to use |
| `--url <url>` / `--token <t>` | override the target |
| `--yes`, `-y` | confirm destructive actions non-interactively |
| `--timeout <secs>` | HTTP timeout (default 30s) |
| `-q`, `--quiet`, `--no-color` | output tweaks |

Global flags may appear anywhere: `niotio campaign list --json` works.

## Commands

```
# config / diagnostics
niotio config show | config path | config set-url <url> | config set-token <t> | config use <name>
niotio whoami          # verify token + show target
niotio doctor          # connectivity + auth checks
niotio version

# campaigns
niotio campaign list [--trash]
niotio campaign get <id>
niotio campaign create --name <n> [--description <d>] [--close-on <rfc3339>] [--test]
niotio campaign update <id> [--name ...] [--description ...] ...
niotio campaign delete <id>            # -> trash (needs --yes)
niotio campaign restore <id>
niotio campaign activate <id> | deactivate <id>
niotio campaign send <id>              # needs --yes
niotio campaign metrics <id>
niotio campaign respondents <id> [--page N] [--size N] [--search q] [--status s]
niotio campaign activity <id>
niotio campaign simulate <id> [--count N] [--ratings 9:5,3:2] [--spread-days N] [--danish-percent 0-100]   # test campaigns; --count N = N responses per rating (0-10), e.g. --count 5 = 55 responses
niotio campaign simulate-clear <id>    # needs --yes

# respondents / responses
niotio respondent add <campaignId> --email <e> [--name <n>] [--language en|da]
niotio respondent import <campaignId> --csv <file> [--dry-run]
niotio response submit --respondent-token <t> --rating <0-10> [--comment <c>]
    # `--survey-token` is an alias. Global `--token` is the API token, not the survey token.

# follow-up cases (a low rating can open a case per response)
niotio case list [--status open|new|in_progress|resolved|not_possible|all]
                 [--assignee mine|all|unassigned] [--campaign <id>]
niotio case counts             # open / overdue / mine / unassigned
niotio case show <id>
niotio case notes <id>         # note timeline (system notes are marked)
niotio case note <id> --text "..."
niotio case assign <id> --user <userId> | --unassign
niotio case status <id> <NEW|IN_PROGRESS|RESOLVED|NOT_POSSIBLE> [--outcome RETAINED|LOST|UNKNOWN]
# `niotio cases` is an alias for `niotio case list`

# comment tags (per-account vocabulary; SOURCE tells AI work from human work)
niotio tag list [--q <text>] [--source human|ai]
niotio tag create <name> [--color '#0d6efd']
niotio tag update <id|name> [--name <new>] [--color '#0d6efd']
niotio tag delete <id|name>            # strips it from every comment (needs --yes)
niotio tag add <id|name> --comment <commentId>      # keep the comment's other tags
niotio tag remove <id|name> --comment <commentId>
niotio tag ai-remove                   # drop every AI-applied assignment (needs --yes)
# `niotio tags` is an alias for `niotio tag list`

# comments (search by text, tag, rating, campaign; --ai = tags the model applied)
niotio comment list [--tag <name> | --tag-id <id>] [--ai | --human] [--q <text>]
                    [--rating <0-10>] [--min-rating <n>] [--max-rating <n>]
                    [--campaign <id>] [--from <YYYY-MM-DD>] [--to <YYYY-MM-DD>]
                    [--page <n>] [--size <n>]
niotio comment tags <commentId>         # the tags on one comment, with who applied each
niotio comment set-tags <commentId> <tag...>   # replace the whole set (needs --yes)
# `niotio comments` is an alias for `niotio comment list`

# metrics
niotio metrics        # account-wide NPS

# email usage (monthly quota, Europe/Copenhagen month)
niotio usage                # 412 of 1,000 used, 588 left, resets 1 Nov (6 days)
niotio usage --campaigns    # + per-campaign table (this month only; test campaigns excluded)
niotio usage --json         # GET /api/v1/usage/email shape: {plan, period, emails, campaigns?}
                            # plan values: FREE, START, PRO, BUSINESS, INTERNAL (TEAM became PRO, ENTERPRISE became BUSINESS, #58)
```

## How-to guide

### 1. Get an API token

Open the app → **Settings → API tokens** and create one. The raw value is shown
**once** (only its SHA-256 hash is stored), so copy it now.

### 2. Configure the CLI

```bash
niotio config set-url   https://niotio.dk   # or --profile dev/local
niotio config set-token <your-token>
niotio config show                                    # token is masked
```

This writes `~/.config/niotio/config.toml`. For throwaway/CI use, skip the file and
use env vars instead:

```bash
export NPS_URL=https://niotio.dk
export NPS_TOKEN=<your-token>
```

### 3. Verify

```bash
niotio doctor     # checks: config → URL → token → /health → /api/campaigns auth
niotio whoami     # profile, URL, and whether the token is accepted
```

### 4. Common tasks

```bash
# Look around
niotio campaign list
niotio campaign list --trash
niotio campaign get 12
niotio campaign metrics 12
niotio campaign respondents 12 --size 100 --search jane
niotio campaign activity 12          # audit log
niotio metrics                        # account-wide NPS

# Run a survey
niotio campaign create --name "Q4 NPS" --description "Q4 customers" --test
niotio respondent add 12 --email jane@example.com --name "Jane" --language en
niotio respondent import 12 --csv respondents.csv --dry-run   # validate first
niotio respondent import 12 --csv respondents.csv
niotio campaign activate 12
niotio campaign send 12 --yes

# Simulate a run (testing/demos; test campaigns never email real people)
niotio campaign simulate 12 --count 40   # 40 responses per rating (0-10) = 440 total
niotio campaign simulate 12 --ratings 9:20,10:15,3:5
niotio campaign simulate 12 --count 40 --danish-percent 50   # mixed EN/DA respondents
niotio campaign simulate-clear 12 --yes

# Housekeeping
niotio campaign deactivate 12
niotio campaign delete 12 --yes       # → trash
niotio campaign restore 12
```

The CSV for `respondent import` takes `email,name,language`; a header row is
auto-detected and columns are matched by name, so order doesn't matter.

### Follow-up cases

A low rating can open a follow-up case for one response. `case list` defaults to
the **open cases assigned to you**; widen it with `--assignee all --status all`.

```bash
niotio case list                        # open cases assigned to me
niotio case list --assignee unassigned  # the queue nobody owns yet
niotio case note 7 --text "called the customer; follow up Friday"
niotio case status 7 RESOLVED --outcome RETAINED
```

`case assign 7 --user 3` hands a case to a teammate and `--unassign` returns it
to the unassigned queue. `case counts` prints one counter per line (open,
overdue, mine, unassigned), and every command supports `--json`.

`case list` and `case counts` still return HTTP 200 when the plan or campaign
has follow-up cases turned off — an empty list, or counters at zero. They do
not return 403. Operating on an existing case (`note`, `assign`, `status`)
answers `403 {"error":"followup_cases_disabled"}`, and the CLI reports that
message as-is.

### Comment tags

Tags are per account and can be applied by a person or by the browser's built-in model
(the comment page's AI tagging). `SOURCE` in `tag list` is who created the tag, `AI` in the
list is how many of its comments the model applied, and a tag on a comment carries the same
`source` for whoever put it there — so model work is always separable and removable.

```bash
niotio tag list --source ai             # only tags the model created
niotio tag create Pris --color '#0d6efd'
niotio tag add Pris --comment 431       # keep the comment's other tags
niotio comment tags 431                 # what is on this comment, and who applied it
niotio comment list --tag Pris          # search comments by tag
niotio comment list --ai --max-rating 6 # only AI-tagged detractors
niotio comment set-tags 431 Pris Support --yes   # replace the whole set
niotio tag ai-remove --yes              # drop all AI assignments, keep human work
```

`--tag` takes a name (resolved case-insensitively inside your own vocabulary); `--tag-id`
takes an id. An unknown tag matches nothing rather than everything, and `tag add/remove`
needs editor access to the campaign behind the comment — a viewer gets a 404.

### 5. Scripting with `--json`

```bash
niotio campaign list --json | jq -r '.[] | "\(.id)\t\(.name)\t\(.npsScore)"'

id=$(niotio campaign create --name "agent-$(date +%s)" --test --json | jq -r .id)
niotio campaign simulate "$id" --count 50 --yes --json
niotio campaign metrics "$id" --json | jq '{nps:.npsScore, responses:.totalResponses}'
niotio campaign delete "$id" --yes
```

### 6. Built-in help

The CLI ships the same guide off-line:

```bash
niotio help                 # command list + getting started
niotio help examples        # cookbook (also: niotio examples)
niotio help config          # profiles, precedence, tokens
niotio help agents          # agent-specific guarantees and recipes
niotio help exit-codes      # exit code + JSON error contract
niotio help campaign list   # help for one command
```

The guide/help text is available in **English and Danish**: set `NPS_LANG=da`
(or use a `da_*` locale) for Danish. Command names, flags, JSON output and
errors always stay English, so scripts and agents are unaffected.

### 7. Troubleshooting

| symptom | fix |
| --- | --- |
| `no API URL configured` | run `niotio config set-url <url>` or set `NPS_URL` |
| `no API token configured` | run `niotio config set-token <t>` or set `NPS_TOKEN` |
| `HTTP 401` on any command | token invalid/revoked — regenerate in Settings |
| `refusing … without --yes` | mutating commands need `--yes` when not on a TTY |
| wrong target | check `niotio config show`; remember `--url/--token` > env > profile |

## How-to guide (dansk)

Kort dansk guide — den fulde, opdaterede version får du med `NPS_LANG=da niotio help`.

### 1. Hent et API-token
Åbn appen → **Indstillinger → API-tokens** og opret et. Det rå token vises kun
**én gang** (der gemmes kun en hash), så kopiér det med det samme.

### 2. Konfigurér
```bash
niotio config set-url   https://niotio.dk
niotio config set-token <dit-token>
niotio doctor
```
Til CI/engangsbrug: spring filen over og brug `NPS_URL` + `NPS_TOKEN`.

### 3. Almindelige opgaver
```bash
niotio campaign list                 # kampagner
niotio campaign get 12               # detaljer
niotio campaign metrics 12           # NPS for én kampagne
niotio metrics                        # NPS for hele kontoen
niotio usage                         # undersøgelses-e-mails brugt denne måned
niotio usage --campaigns             # + fordelt på kampagner
niotio campaign create --name "Q4 NPS" --test   # tørløb (sender ingen rigtig mail)
niotio respondent import 12 --csv respondenter.csv --dry-run
niotio campaign activate 12 && niotio campaign send 12 --yes

# simulér et forløb (godt til test/demo)
niotio campaign simulate 12 --count 40
niotio campaign simulate-clear 12 --yes
```

### 4. Scripting
Alle kommandoer understøtter `--json`: `niotio campaign metrics 12 --json`.
Destruktive kommandoer kræver `--yes` uden TTY. Exitkoder: `0` ok, `1` fejl,
`2` brugsfejl.

## Agent usage

```bash
export NPS_URL=https://niotio.dk
export NPS_TOKEN=...

# create a test campaign, seed it, read its NPS, tear it down
ID=$(niotio campaign create --name "agent-$RANDOM" --test --json | jq -r .id)
niotio campaign simulate "$ID" --count 40 --json
niotio campaign metrics "$ID" --json | jq '{nps: .npsScore, responses: .totalResponses}'
niotio campaign simulate-clear "$ID" --yes
niotio campaign delete "$ID" --yes
```

Exit codes: `0` success, `1` runtime/API error, `2` usage error. In `--json`
mode errors are emitted as `{"error": ..., "kind": "api|usage|error"}` on
stderr.

## Related docs

- REST API: https://niotio.dk/api/docs.md
- MCP server for AI agents: https://niotio.dk/mcp.md (same Bearer token as the CLI)

## Development

```bash
cd cli
gofmt -l .          # must be empty
go vet ./...
go build ./cmd/nps
go test ./...
goreleaser release --clean   # from cli/, publishes releases
```

CI (`.github/workflows/cli.yml`) runs gofmt/vet/test/build on changes under
`cli/`.

The CLI is exercised by `scripts/prod_smoke_test.sh` (read-only slice against a
live test campaign), per the repo's new-feature smoke-test contract.
