@apet97/clockify-cli-115 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aleksandar Petković
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # @apet97/clockify-cli-115
2
+
3
+ Command-line interface for [Clockify](https://clockify.me/), built on
4
+ top of `clockify-sdk-ts-115`.
5
+
6
+ Two binaries, identical behavior:
7
+
8
+ - `clockify115` — full name
9
+ - `clk115` — short alias
10
+
11
+ ```sh
12
+ cd cli
13
+ npm install
14
+ npm run build
15
+ npm link
16
+ export CLOCKIFY_API_KEY=... # from Clockify > Profile > API Keys
17
+ export CLOCKIFY_WORKSPACE_ID=... # from a workspace URL
18
+
19
+ clk115 status
20
+ clk115 projects list --limit 5
21
+ clk115 start "WIP refactor" -p "Acme Corp"
22
+ clk115 stop
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ In precedence order (highest wins):
28
+
29
+ 1. **Command-line flags:** `--api-key`, `--workspace`, `--base-url`
30
+ 2. **Environment variables:** `CLOCKIFY_API_KEY`, `CLOCKIFY_WORKSPACE_ID`,
31
+ optional `CLOCKIFY_BASE_URL` for mock/replay or private gateway tests
32
+ 3. **Rc file:** `~/.clockifyrc.json` (or `clockifyrc.json` in
33
+ `$CLOCKIFY_HOME`)
34
+
35
+ Rc file shape:
36
+
37
+ ```json
38
+ {
39
+ "apiKey": "abcd1234…",
40
+ "workspaceId": "65b382b6…",
41
+ "baseUrl": "https://api.clockify.me/api/v1"
42
+ }
43
+ ```
44
+
45
+ Do not set `baseUrl` for normal Clockify use. It exists so tests can
46
+ point the CLI at `make mock-clockify` or a replay gateway without
47
+ touching production credentials.
48
+
49
+ ## Output modes
50
+
51
+ - **Default:** human-friendly tables via `cli-table3`.
52
+ - **`--output <mode>`:** `table`, `json`, or `ndjson`. `--json` is a
53
+ shortcut for `--output json`.
54
+ - **`--compact`:** single-line JSON without indentation.
55
+ - **`--select <path>`:** print a dot-path (e.g. `--select data.id` or
56
+ `--select 0.name`) before emitting JSON or NDJSON.
57
+
58
+ Errors go to stderr as `{"ok": false, "error": "..."}`; success-only
59
+ commands emit `{"ok": true, "message": "..."}`. `--no-color` disables ANSI
60
+ codes, and the CLI also auto-disables color when stdout is not a TTY.
61
+ Successful write commands in JSON and NDJSON include receipt fields:
62
+ `ok`, `action`, `entity`, `ids`, `changed`, `warnings`, and `next`.
63
+ Legacy top-level fields such as `id` remain for simple shell scripts.
64
+
65
+ ## Commands
66
+
67
+ <!-- BEGIN generated:cli-commands -->
68
+ | Command | What it does |
69
+ |---|---|
70
+ | `clk115 status` | Print workspace, current user, and running timer. |
71
+ | `clk115 doctor` | Check local CLI configuration without contacting Clockify. |
72
+ | `clk115 start [description] [-p project] [-t task] [--tag tag…] [--billable]` | Start a timer. Resolves project, task, and tag names to IDs. |
73
+ | `clk115 stop` | Stop the running timer for the current user. |
74
+ | `clk115 log <duration> <description> [-p project] [-t task] [--tag tag…] [--billable] [--end iso]` | Log a finished entry. Resolves project, task, and tag names to IDs. Duration accepts `1h30m`, `90m`, or `PT1H30M`. |
75
+ | `clk115 entries list [--limit N] [--page N] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--description text]` | List time entries for the current user. |
76
+ | `clk115 entries delete <id>` | Delete a time entry. |
77
+ | `clk115 projects list [--limit N] [--page N] [--name text] [--archived] [--client id]` | List projects. |
78
+ | `clk115 projects create <name> [--client id] [--color hex] [--billable]` | Create a project. |
79
+ | `clk115 projects get <id>` | Get one project by ID. |
80
+ | `clk115 projects update <id> [--name text] [--client id] [--color hex] [--note text] [--billable\|--no-billable] [--archived\|--no-archived]` | Update a project. |
81
+ | `clk115 projects delete <id>` | Delete a project (archives first; an active project cannot be deleted). |
82
+ | `clk115 clients list [--limit N] [--page N] [--name text] [--archived]` | List clients. |
83
+ | `clk115 clients create <name> [--note text]` | Create a client. |
84
+ | `clk115 clients get <id>` | Get one client by ID. |
85
+ | `clk115 clients update <id> [--name text] [--note text] [--address text] [--archived\|--no-archived]` | Update a client. |
86
+ | `clk115 clients delete <id>` | Delete a client (archives first; an active client cannot be deleted). |
87
+ | `clk115 tasks list <projectId> [--limit N] [--page N] [--name text]` | List tasks for a project. |
88
+ | `clk115 tasks create <projectId> <name> [--billable] [--estimate iso] [--assignee id…]` | Create a task under a project. |
89
+ | `clk115 tasks get <projectId> <id>` | Get one task by project ID and task ID. |
90
+ | `clk115 tasks update <projectId> <id> [--name text] [--status ACTIVE\|DONE] [--estimate iso] [--billable\|--no-billable] [--assignee id…]` | Update a task. |
91
+ | `clk115 tasks delete <projectId> <id>` | Delete a task (marks DONE first; an active task cannot be deleted). |
92
+ | `clk115 tags list [--limit N] [--page N] [--name text] [--archived]` | List tags. |
93
+ | `clk115 tags create <name>` | Create a tag. |
94
+ | `clk115 tags get <id>` | Get one tag by ID. |
95
+ | `clk115 tags update <id> [--name text] [--archived\|--no-archived]` | Update a tag. |
96
+ | `clk115 tags delete <id>` | Delete a tag. |
97
+ | `clk115 webhooks list [--type type]` | List outbound webhooks. |
98
+ | `clk115 webhooks create --name X --url U --event E [--trigger-source-type T --trigger-source ids]` | Create a webhook subscription. |
99
+ | `clk115 webhooks delete <id>` | Delete a webhook subscription. |
100
+ | `clk115 invoices list` | List invoices in the workspace. |
101
+ | `clk115 invoices create --client id --number N --currency USD --issued YYYY-MM-DD --due YYYY-MM-DD [--time-view-mode mode]` | Create an invoice draft. |
102
+ | `clk115 expenses list [--limit N] [--page N] [--start YYYY-MM-DD] [--end YYYY-MM-DD]` | List workspace expenses. |
103
+ | `clk115 expenses get <id>` | Get one expense by ID. |
104
+ | `clk115 expenses create --amount N --category id --date YYYY-MM-DD [--user id] [--project id] [--task id] [--notes text] [--billable\|--no-billable]` | Create an expense (scalar body; --user defaults to the API-key owner). |
105
+ | `clk115 expenses update <id> --amount N --category id --date YYYY-MM-DD --user id [--project id] [--task id] [--notes text] [--billable\|--no-billable]` | Update an expense (full replace of amount, category, date). |
106
+ | `clk115 expenses delete <id>` | Delete an expense. |
107
+ | `clk115 timeoff list [--page N] [--limit N] [--start date] [--end date] [--status APPROVED,PENDING,…] [--user ids]` | List time-off requests. |
108
+ | `clk115 timeoff submit --policy id --start date (--end date \| --days N) [--note text] [--half-day --half-day-period FIRST_HALF\|SECOND_HALF]` | Submit a time-off request against a policy. Provide --end (HOURS-unit policies) or --days (DAYS-unit policies). |
109
+ | `clk115 scheduling list [--limit N] [--page N] [--name text]` | List scheduling assignments. |
110
+ | `clk115 scheduling create --user id --project id --start date --end date --hours-per-day N [--task id --note text --billable --include-non-working-days --publish]` | Create a scheduling assignment. Drafts by default; pass `--publish` to publish. |
111
+ | `clk115 audit-log search --start RFC3339 --end RFC3339 --actions A,B,… [--authors ids --authors-mode CONTAINS\|DOES_NOT_CONTAIN --page N --limit N]` | Search the workspace audit log. Window must be ≤ 31 days. |
112
+ | `clk115 reports summary [--period p] [--from date] [--to date] [--groups PROJECT,TASK] [--billable] [--project name\|id…] [--client name\|id…]` | Summary report totals over a date range, grouped per --groups. Read-only. |
113
+ | `clk115 reports detailed [--period p] [--from date] [--to date] [--page N] [--page-size N]` | Detailed report listing individual time entries over a date range. Read-only. |
114
+ | `clk115 reports weekly [--period p] [--from date] [--to date] [--group USER\|PROJECT] [--subgroup TIME]` | Weekly report aggregating tracked time per week over a date range. Read-only. |
115
+ | `clk115 reports attendance [--period p] [--from date] [--to date]` | Attendance report of clock-in/out activity over a date range. Read-only. |
116
+ | `clk115 shared-reports list` | List the workspace's shared (public-link) reports. Read-only. |
117
+ | `clk115 shared-reports view <id> [--export-type JSON_V1\|JSON\|CSV\|XLSX\|PDF]` | View a shared report's rendered data by ID (not workspace-scoped). Read-only. |
118
+ | `clk115 shared-reports create --name X --type T --filter json [--public]` | Create a shared (public-link) report. |
119
+ | `clk115 shared-reports update <id> --name X --type T --filter json [--public]` | Replace a shared report by ID (full replace of name, type, and filter). |
120
+ | `clk115 shared-reports delete <id>` | Delete a shared report. |
121
+ | `clk115 users me` | Show the current authenticated user (the API-key owner). Read-only. |
122
+ | `clk115 users list [--limit N] [--page N] [--name text]` | List members of the workspace. Read-only. |
123
+ | `clk115 users invite <email> [--no-send-email]` | Invite (add) a user to the workspace by email. |
124
+ | `clk115 users update-profile <userId> [--name text] [--image-url url] [--remove-image] [--week-start day] [--work-capacity iso] [--working-days days…]` | Update one user's member profile. |
125
+ | `clk115 api <method> <path> [-q key=value…] [-H key=value…] [--body json\|@file\|-] [--all] [--page-size N] [--max-pages N] [--include-headers]` | Call a Clockify API path directly through the SDK client. Fills {workspaceId} from --workspace or CLOCKIFY_WORKSPACE_ID. |
126
+ | `clk115 completion [zsh\|bash\|fish]` | Print a shell completion script for zsh, bash, or fish. |
127
+ | `clk115 help [command]` | Print per-command help. |
128
+ | `clk115 --version` | Print CLI version. |
129
+ <!-- END generated:cli-commands -->
130
+
131
+ ## Examples
132
+
133
+ Start a timer with project / task by name:
134
+
135
+ ```sh
136
+ clk115 start "fix flaky test" -p "ACME Backend" -t "QA" --tag urgent
137
+ ```
138
+
139
+ Log a 90-minute entry that ended now:
140
+
141
+ ```sh
142
+ clk115 log 1h30m "RFC review"
143
+ ```
144
+
145
+ Log a 30-minute entry that ended yesterday at 17:00 UTC, in JSON for
146
+ piping into `jq`:
147
+
148
+ ```sh
149
+ clk115 --json log 30m "Daily standup" --end 2026-05-25T17:00:00Z | jq .id
150
+ ```
151
+
152
+ List the 50 most recent entries, filtered by description:
153
+
154
+ ```sh
155
+ clk115 entries list --limit 50 --description deploy
156
+ ```
157
+
158
+ Call a long-tail endpoint directly through the SDK client when no curated
159
+ command exists yet:
160
+
161
+ ```sh
162
+ clk115 api GET '/workspaces/{workspaceId}/tags' --query page-size=20 --output json
163
+ clk115 api GET '/workspaces/{workspaceId}/projects' --all --page-size 50 --output ndjson
164
+ clk115 api POST '/workspaces/{workspaceId}/tags' --body '{"name":"billable"}' --include-headers
165
+ ```
166
+
167
+ `{workspaceId}` is filled from `--workspace` or `CLOCKIFY_WORKSPACE_ID`.
168
+ `--all` walks `page`/`page-size` until a short or empty page (bounded by
169
+ `--max-pages`), and `--body` also accepts `@file` or `-` for stdin.
170
+
171
+ ## Shell completion
172
+
173
+ `clk115 completion <shell>` prints a completion script for `bash`, `zsh`, or
174
+ `fish` to stdout (it contacts nothing). Install it once into your shell's
175
+ completion location:
176
+
177
+ ```sh
178
+ # bash (Linux)
179
+ clk115 completion bash > ~/.local/share/bash-completion/completions/clk115
180
+
181
+ # zsh — write into a directory on your $fpath, then restart the shell
182
+ clk115 completion zsh > "${fpath[1]}/_clk115"
183
+
184
+ # fish
185
+ clk115 completion fish > ~/.config/fish/completions/clk115.fish
186
+ ```
187
+
188
+ For a one-off in the current shell: `source <(clk115 completion bash)`. The
189
+ `clockify115` binary accepts the same subcommand. See `examples/` for runnable
190
+ scripts.
191
+
192
+ ## Exit codes
193
+
194
+ - `0` — success
195
+ - `1` — any error (API failure, validation, missing config)
196
+ - `2` — commander argument error (unknown flag, missing required arg)
197
+
198
+ ## Development
199
+
200
+ ```sh
201
+ git clone https://github.com/apet97/clockify-ts-sdk
202
+ cd clockify-ts-sdk/cli
203
+ npm install
204
+ npm run dev -- status # via tsx, no build needed
205
+ npm test # unit tests across duration / config / output / CLI contract / mock server
206
+ npm run build # tsc → dist/
207
+ node dist/index.js status # smoke test (or invoke installed clk115/clockify115)
208
+ ```
209
+
210
+ `clockify-sdk-ts-115` is referenced as a `file:../wrapper` dev
211
+ dependency during local development and as a peer dependency for any
212
+ future published package.
213
+
214
+ ## License
215
+
216
+ MIT
package/dist/client.js ADDED
@@ -0,0 +1,10 @@
1
+ import { requireApiKey } from "./config.js";
2
+ export async function buildClient(config) {
3
+ const apiKey = requireApiKey(config);
4
+ const { createClockifyClient } = await import("clockify-sdk-ts-115");
5
+ return createClockifyClient({
6
+ apiKey,
7
+ allowInsecureBaseUrl: false,
8
+ ...(config.baseUrl !== undefined ? { environment: config.baseUrl } : {}),
9
+ });
10
+ }
@@ -0,0 +1,187 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { printJson, printNdjson } from "../output.js";
3
+ import { resolveBaseContext } from "./helpers.js";
4
+ const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
5
+ export const registerApiCommand = (program, services) => {
6
+ program
7
+ .command("api")
8
+ .description("Call a Clockify API path directly through the SDK client.")
9
+ .argument("<method>", "HTTP method: GET, POST, PUT, PATCH, or DELETE.")
10
+ .argument("<path>", "API path, e.g. /workspaces/{workspaceId}/tags.")
11
+ .option("-q, --query <key=value>", "Query parameter (repeatable).", collect, [])
12
+ .option("-H, --header <key=value>", "Request header (repeatable).", collect, [])
13
+ .option("--body <json|@file|->", "JSON body: inline, @file, or - for stdin.")
14
+ .option("--all", "Walk page/page-size pagination, honoring Last-Page when present.", false)
15
+ .option("--page-size <n>", "Page size for --all.", "50")
16
+ .option("--max-pages <n>", "Maximum pages for --all.", "20")
17
+ .option("--include-headers", "Include status and response headers in output.", false)
18
+ .action(async function (methodArg, pathArg, options) {
19
+ const { client, config, output } = await resolveBaseContext(this, services);
20
+ const method = methodArg.toUpperCase();
21
+ if (!METHODS.has(method)) {
22
+ throw new Error(`Unsupported method "${methodArg}". Use GET, POST, PUT, PATCH, or DELETE.`);
23
+ }
24
+ const path = resolvePath(pathArg, config.workspaceId);
25
+ const query = parsePairs(options.query);
26
+ const headers = parsePairs(options.header);
27
+ if (options.all) {
28
+ if (method !== "GET") {
29
+ throw new Error("--all is only supported for GET requests.");
30
+ }
31
+ const pageSize = parsePositiveInteger(options.pageSize, "--page-size");
32
+ const maxPages = parsePositiveInteger(options.maxPages, "--max-pages");
33
+ const items = await fetchAllPages(client, path, query, headers, pageSize, maxPages);
34
+ printApiOutput(items, output);
35
+ return;
36
+ }
37
+ const body = readBody(options.body);
38
+ const response = await client.fetch(buildPath(path, query), requestInit(method, headers, body));
39
+ const data = await readResponseData(response);
40
+ if (!response.ok && !options.includeHeaders) {
41
+ throw Object.assign(new Error(`HTTP ${response.status}: ${formatBody(data)}`), {
42
+ statusCode: response.status,
43
+ });
44
+ }
45
+ printApiOutput(responsePayload(response, data, options.includeHeaders), output);
46
+ });
47
+ };
48
+ function collect(value, previous) {
49
+ previous.push(value);
50
+ return previous;
51
+ }
52
+ function parsePairs(values) {
53
+ const result = {};
54
+ for (const value of values) {
55
+ const index = value.indexOf("=");
56
+ if (index <= 0) {
57
+ throw new Error(`Expected key=value, received "${value}".`);
58
+ }
59
+ const key = value.slice(0, index).trim();
60
+ if (!key) {
61
+ throw new Error(`Expected non-empty key in "${value}".`);
62
+ }
63
+ result[key] = value.slice(index + 1);
64
+ }
65
+ return result;
66
+ }
67
+ function resolvePath(path, workspaceId) {
68
+ if (!path.startsWith("/")) {
69
+ throw new Error("API path must start with /.");
70
+ }
71
+ if (path.includes("{workspaceId}")) {
72
+ if (!workspaceId) {
73
+ throw new Error("Path uses {workspaceId}; provide --workspace or CLOCKIFY_WORKSPACE_ID.");
74
+ }
75
+ return path.replaceAll("{workspaceId}", workspaceId);
76
+ }
77
+ return path;
78
+ }
79
+ function buildPath(path, query) {
80
+ const qIndex = path.indexOf("?");
81
+ const base = qIndex === -1 ? path : path.slice(0, qIndex);
82
+ const params = new URLSearchParams(qIndex === -1 ? "" : path.slice(qIndex + 1));
83
+ for (const [key, value] of Object.entries(query))
84
+ params.set(key, value);
85
+ const search = params.toString();
86
+ return search ? `${base}?${search}` : base;
87
+ }
88
+ function requestInit(method, headers, body) {
89
+ const merged = { ...headers };
90
+ const init = { method, headers: merged };
91
+ if (body !== undefined) {
92
+ init.body = body;
93
+ if (!Object.keys(merged).some((key) => key.toLowerCase() === "content-type")) {
94
+ merged["Content-Type"] = "application/json";
95
+ }
96
+ }
97
+ return init;
98
+ }
99
+ function readBody(body) {
100
+ if (body === undefined) {
101
+ return undefined;
102
+ }
103
+ if (body === "-") {
104
+ return readFileSync(0, "utf8");
105
+ }
106
+ if (body.startsWith("@")) {
107
+ return readFileSync(body.slice(1), "utf8");
108
+ }
109
+ return body;
110
+ }
111
+ function parsePositiveInteger(value, flag) {
112
+ const parsed = Number(value);
113
+ if (!Number.isInteger(parsed) || parsed <= 0) {
114
+ throw new Error(`${flag} must be a positive integer.`);
115
+ }
116
+ return parsed;
117
+ }
118
+ async function fetchAllPages(client, path, query, headers, pageSize, maxPages) {
119
+ const items = [];
120
+ for (let page = 1; page <= maxPages; page += 1) {
121
+ const pagePath = buildPath(path, { ...query, page: String(page), "page-size": String(pageSize) });
122
+ const response = await client.fetch(pagePath, requestInit("GET", headers));
123
+ const data = await readResponseData(response);
124
+ if (!response.ok) {
125
+ throw Object.assign(new Error(`HTTP ${response.status} on page ${page}: ${formatBody(data)}`), {
126
+ statusCode: response.status,
127
+ });
128
+ }
129
+ if (!Array.isArray(data)) {
130
+ throw new Error("--all expects each page to return a JSON array.");
131
+ }
132
+ const lastPage = parseLastPageHeader(response.headers.get("Last-Page"));
133
+ items.push(...data);
134
+ if (lastPage === true) {
135
+ break;
136
+ }
137
+ if (lastPage === false) {
138
+ continue;
139
+ }
140
+ if (data.length === 0 || data.length < pageSize) {
141
+ break;
142
+ }
143
+ }
144
+ return items;
145
+ }
146
+ function parseLastPageHeader(value) {
147
+ if (value == null)
148
+ return undefined;
149
+ const normalized = value.trim().toLowerCase();
150
+ if (normalized === "true")
151
+ return true;
152
+ if (normalized === "false")
153
+ return false;
154
+ return undefined;
155
+ }
156
+ function formatBody(data) {
157
+ return typeof data === "string" ? data : JSON.stringify(data);
158
+ }
159
+ async function readResponseData(response) {
160
+ const text = await response.text();
161
+ if (!text) {
162
+ return null;
163
+ }
164
+ try {
165
+ return JSON.parse(text);
166
+ }
167
+ catch {
168
+ return text;
169
+ }
170
+ }
171
+ function responsePayload(response, data, includeHeaders) {
172
+ if (!includeHeaders) {
173
+ return data;
174
+ }
175
+ return {
176
+ status: response.status,
177
+ headers: Object.fromEntries(response.headers.entries()),
178
+ data,
179
+ };
180
+ }
181
+ function printApiOutput(value, output) {
182
+ if (output.mode === "ndjson") {
183
+ printNdjson(value, output);
184
+ return;
185
+ }
186
+ printJson(value, output);
187
+ }
@@ -0,0 +1,50 @@
1
+ import { printRecords } from "../output.js";
2
+ import { clampPageSize, parseIntArg, resolveContext, splitList } from "./helpers.js";
3
+ export const registerAuditLogCommand = (program, services) => {
4
+ const audit = program.command("audit-log").description("Workspace audit log.");
5
+ audit
6
+ .command("search")
7
+ .description("Search the workspace audit log.")
8
+ .requiredOption("--start <date>", "Window start (RFC3339, e.g. 2026-05-01T00:00:00Z).")
9
+ .requiredOption("--end <date>", "Window end (RFC3339).")
10
+ .requiredOption("--actions <list>", "Comma-separated action names (e.g. CREATE_PROJECT,UPDATE_PROJECT).")
11
+ .option("--authors <ids>", "Comma-separated author IDs to include. Pass SYSTEM to include system audit events.")
12
+ .option("--authors-mode <mode>", "Author filter mode (CONTAINS|DOES_NOT_CONTAIN). Defaults to CONTAINS when authors are provided.", "CONTAINS")
13
+ .option("--page <n>", "Page number.", parseIntArg, 1)
14
+ .option("--limit <n>", "Items per page (default 50, max 200).", parseIntArg, 50)
15
+ .action(async function (opts) {
16
+ const { client, workspaceId, output } = await resolveContext(this, services);
17
+ const actions = splitList(opts.actions);
18
+ if (actions.length === 0) {
19
+ throw new Error("--actions must include at least one action name");
20
+ }
21
+ const authorIds = opts.authors ? splitList(opts.authors) : [];
22
+ const authors = {
23
+ authorIds,
24
+ contains: opts.authorsMode === "DOES_NOT_CONTAIN" ? "DOES_NOT_CONTAIN" : "CONTAINS",
25
+ };
26
+ const req = {
27
+ workspaceId,
28
+ start: opts.start,
29
+ end: opts.end,
30
+ actions,
31
+ authors,
32
+ page: opts.page,
33
+ "page-size": clampPageSize(opts.limit, 200),
34
+ };
35
+ const response = (await client.auditLogReport.search(req));
36
+ const items = Array.isArray(response) ? response : (response.entries ?? []);
37
+ const rows = items.map((raw) => {
38
+ const e = raw;
39
+ return {
40
+ id: e.id ?? "",
41
+ timestamp: e.timestamp ?? "",
42
+ action: e.action ?? "",
43
+ author: e.authorName ?? e.authorId ?? "",
44
+ entityType: e.entityType ?? "",
45
+ entityId: e.entityId ?? "",
46
+ };
47
+ });
48
+ printRecords(rows, output);
49
+ });
50
+ };
@@ -0,0 +1,139 @@
1
+ import { archiveThenDeleteClient } from "clockify-sdk-ts-115/ensure";
2
+ import { wireBody } from "clockify-sdk-ts-115/requests";
3
+ import { printObject, printRecords } from "../output.js";
4
+ import { printReceipt } from "../receipt.js";
5
+ import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
6
+ export const registerClientsCommand = (program, services) => {
7
+ const clients = program.command("clients").description("Manage clients.");
8
+ clients
9
+ .command("list")
10
+ .description("List clients in the workspace.")
11
+ .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
12
+ .option("--page <n>", "Page number.", parseIntArg, 1)
13
+ .option("--name <text>", "Filter by client name substring.")
14
+ .option("--archived", "Include archived clients.", false)
15
+ .action(async function (opts) {
16
+ const { client, workspaceId, output } = await resolveContext(this, services);
17
+ const req = {
18
+ workspaceId,
19
+ page: opts.page,
20
+ "page-size": clampPageSize(opts.limit, 200),
21
+ };
22
+ if (opts.name)
23
+ req.name = opts.name;
24
+ if (opts.archived)
25
+ req.archived = true;
26
+ const items = await client.clients.list(req);
27
+ const rows = items.map((raw) => {
28
+ const c = raw;
29
+ return {
30
+ id: c.id ?? "",
31
+ name: c.name ?? "",
32
+ note: c.note ?? "",
33
+ archived: c.archived === true,
34
+ };
35
+ });
36
+ printRecords(rows, output);
37
+ });
38
+ clients
39
+ .command("create")
40
+ .argument("<name>", "Client name.")
41
+ .option("--note <text>", "Client note.")
42
+ .description("Create a client in the workspace.")
43
+ .action(async function (name, opts) {
44
+ const { client, workspaceId, output } = await resolveContext(this, services);
45
+ const req = {
46
+ workspaceId,
47
+ body: { name, ...(opts.note !== undefined ? { note: opts.note } : {}) },
48
+ };
49
+ const created = (await client.clients.create(req));
50
+ const data = { id: created.id ?? "", name: created.name ?? "" };
51
+ printReceipt({
52
+ ok: true,
53
+ action: "clients.create",
54
+ entity: "client",
55
+ ids: { clientId: data.id },
56
+ data,
57
+ changed: { created: [{ type: "client", id: data.id, name: data.name }] },
58
+ next: [
59
+ {
60
+ command: `clk115 projects create <name> --client ${data.id}`,
61
+ reason: "Create a project for this client.",
62
+ },
63
+ ],
64
+ }, output);
65
+ });
66
+ clients
67
+ .command("get")
68
+ .argument("<id>", "Client ID.")
69
+ .description("Get one client by ID.")
70
+ .action(async function (id) {
71
+ const { client, workspaceId, output } = await resolveContext(this, services);
72
+ const result = await client.clients.get({ workspaceId, clientId: id });
73
+ printObject(result, output);
74
+ });
75
+ clients
76
+ .command("update")
77
+ .argument("<id>", "Client ID.")
78
+ .option("--name <text>", "New client name.")
79
+ .option("--note <text>", "Client note.")
80
+ .option("--address <text>", "Client address.")
81
+ .option("--archived", "Archive the client.")
82
+ .option("--no-archived", "Unarchive the client.")
83
+ .description("Update a client by ID.")
84
+ .action(async function (id, opts) {
85
+ const { client, workspaceId, output } = await resolveContext(this, services);
86
+ const body = {};
87
+ if (opts.name)
88
+ body.name = opts.name;
89
+ if (opts.note !== undefined)
90
+ body.note = opts.note;
91
+ if (opts.address !== undefined)
92
+ body.address = opts.address;
93
+ if (opts.archived !== undefined)
94
+ body.archived = opts.archived;
95
+ const req = wireBody({
96
+ workspaceId,
97
+ clientId: id,
98
+ body,
99
+ });
100
+ const updated = (await client.clients.update(req));
101
+ const data = { id: updated.id ?? id, name: updated.name ?? "" };
102
+ printReceipt({
103
+ ok: true,
104
+ action: "clients.update",
105
+ entity: "client",
106
+ ids: { clientId: data.id },
107
+ data,
108
+ changed: { updated: [{ type: "client", id: data.id, name: data.name }] },
109
+ next: [
110
+ {
111
+ command: `clk115 clients get ${data.id} --json`,
112
+ reason: "Verify the update.",
113
+ },
114
+ ],
115
+ }, output);
116
+ });
117
+ clients
118
+ .command("delete")
119
+ .argument("<id>", "Client ID.")
120
+ .description("Delete a client by ID (archives first; an active client cannot be deleted).")
121
+ .action(async function (id) {
122
+ const { client, workspaceId, output } = await resolveContext(this, services);
123
+ await archiveThenDeleteClient({ workspaceId, id, resource: client.clients });
124
+ printReceipt({
125
+ ok: true,
126
+ action: "clients.delete",
127
+ entity: "client",
128
+ ids: { clientId: id },
129
+ data: { id, deleted: true, message: `deleted client ${id}` },
130
+ changed: { deleted: [{ type: "client", id }] },
131
+ next: [
132
+ {
133
+ command: "clk115 clients list --json",
134
+ reason: "Verify the client no longer appears.",
135
+ },
136
+ ],
137
+ }, output);
138
+ });
139
+ };