@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.
@@ -0,0 +1,137 @@
1
+ import { classifyClockifyBaseUrl } from "clockify-sdk-ts-115/create-client";
2
+ import { globalFlags, resolveFlags } from "../index.js";
3
+ import { printObject } from "../output.js";
4
+ import { rootProgram } from "./helpers.js";
5
+ const DEFAULT_CLOCKIFY_BASE_URL = "https://api.clockify.me/api/v1";
6
+ export const registerDoctorCommand = (program, services) => {
7
+ program
8
+ .command("doctor")
9
+ .description("Check local CLI configuration without contacting Clockify.")
10
+ .action(function () {
11
+ const root = rootProgram(this);
12
+ const flags = globalFlags(root);
13
+ const config = services.loadConfig(flags);
14
+ const output = resolveFlags(root);
15
+ printObject(buildDoctorReceipt(config, flags, process.env), output);
16
+ });
17
+ };
18
+ function buildDoctorReceipt(config, flags, env) {
19
+ const nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "0", 10);
20
+ const nodeOk = nodeMajor >= 20;
21
+ const apiKeySource = sourceFor("apiKey", config, flags, env);
22
+ const workspaceSource = sourceFor("workspaceId", config, flags, env);
23
+ const baseUrlSource = sourceFor("baseUrl", config, flags, env) ?? "default";
24
+ const apiKeyOk = isPresent(config.apiKey);
25
+ const workspaceOk = isPresent(config.workspaceId);
26
+ const baseUrl = config.baseUrl ?? DEFAULT_CLOCKIFY_BASE_URL;
27
+ const baseUrlClass = config.baseUrl ? classifyClockifyBaseUrl(baseUrl) : undefined;
28
+ const configOk = apiKeyOk && workspaceOk;
29
+ const ok = nodeOk && configOk;
30
+ return {
31
+ ok,
32
+ readiness: !nodeOk
33
+ ? "runtime_unsupported"
34
+ : configOk
35
+ ? "ready_for_status"
36
+ : "configuration_incomplete",
37
+ checks: {
38
+ node: {
39
+ ok: nodeOk,
40
+ status: nodeOk ? "supported" : "unsupported",
41
+ value: process.versions.node,
42
+ ...(nodeOk ? {} : { recovery: "Install Node.js 20 or newer before using @apet97/clockify-cli-115." }),
43
+ },
44
+ apiKey: {
45
+ ok: apiKeyOk,
46
+ status: apiKeyOk ? "present" : "missing",
47
+ ...(apiKeySource !== undefined ? { source: apiKeySource } : {}),
48
+ ...(apiKeyOk ? { value: "configured (redacted)" } : {}),
49
+ ...(apiKeyOk
50
+ ? {}
51
+ : { recovery: "Provide --api-key, set CLOCKIFY_API_KEY, or add apiKey to ~/.clockifyrc.json." }),
52
+ },
53
+ workspaceId: {
54
+ ok: workspaceOk,
55
+ status: workspaceOk ? "present" : "missing",
56
+ ...(workspaceSource !== undefined ? { source: workspaceSource } : {}),
57
+ ...(config.workspaceId !== undefined ? { value: maskId(config.workspaceId) ?? "" } : {}),
58
+ ...(workspaceOk
59
+ ? {}
60
+ : {
61
+ recovery: "Provide --workspace, set CLOCKIFY_WORKSPACE_ID, or add workspaceId to ~/.clockifyrc.json.",
62
+ }),
63
+ },
64
+ baseUrl: {
65
+ ok: baseUrlClass ? baseUrlClass.allowed : true,
66
+ status: config.baseUrl ? "override" : "default",
67
+ source: baseUrlSource,
68
+ value: baseUrl,
69
+ ...(config.baseUrl
70
+ ? {
71
+ recovery: baseUrlClass && !baseUrlClass.allowed
72
+ ? `${baseUrlClass.reason ?? "Base URL is outside the Clockify host allowlist."} The client will reject it — use the default Clockify API base URL, or a loopback host for mocks/replay.`
73
+ : "Use the default Clockify API base URL for real work; keep overrides for mocks or replay.",
74
+ }
75
+ : {}),
76
+ },
77
+ },
78
+ next: nextSteps({ nodeOk, apiKeyOk, workspaceOk, hasBaseUrlOverride: isPresent(config.baseUrl) }),
79
+ };
80
+ }
81
+ function nextSteps(input) {
82
+ const steps = [];
83
+ if (!input.nodeOk)
84
+ steps.push("Install Node.js 20 or newer.");
85
+ if (!input.apiKeyOk)
86
+ steps.push("Set CLOCKIFY_API_KEY or pass --api-key.");
87
+ if (!input.workspaceOk)
88
+ steps.push("Set CLOCKIFY_WORKSPACE_ID or pass --workspace.");
89
+ if (input.hasBaseUrlOverride) {
90
+ steps.push("Confirm CLOCKIFY_BASE_URL or --base-url is intentional before live work.");
91
+ }
92
+ if (steps.length === 0) {
93
+ steps.push("Run `clk115 status` to verify live Clockify access.");
94
+ steps.push("Run `clk115 --json status` when another tool needs a machine-readable receipt.");
95
+ }
96
+ return steps;
97
+ }
98
+ function sourceFor(field, config, flags, env) {
99
+ if (field === "apiKey") {
100
+ if (isPresent(flags.apiKey))
101
+ return "flag";
102
+ if (isPresent(env.CLOCKIFY_API_KEY))
103
+ return "env";
104
+ if (isPresent(config.apiKey))
105
+ return "rc";
106
+ return undefined;
107
+ }
108
+ if (field === "workspaceId") {
109
+ if (isPresent(flags.workspace))
110
+ return "flag";
111
+ if (isPresent(env.CLOCKIFY_WORKSPACE_ID))
112
+ return "env";
113
+ if (isPresent(config.workspaceId))
114
+ return "rc";
115
+ return undefined;
116
+ }
117
+ if (field === "baseUrl") {
118
+ if (isPresent(flags.baseUrl))
119
+ return "flag";
120
+ if (isPresent(env.CLOCKIFY_BASE_URL))
121
+ return "env";
122
+ if (isPresent(config.baseUrl))
123
+ return "rc";
124
+ return undefined;
125
+ }
126
+ return undefined;
127
+ }
128
+ function isPresent(value) {
129
+ return typeof value === "string" && value.trim().length > 0;
130
+ }
131
+ function maskId(value) {
132
+ if (!value)
133
+ return undefined;
134
+ if (value.length <= 10)
135
+ return "configured";
136
+ return `${value.slice(0, 4)}...${value.slice(-4)}`;
137
+ }
@@ -0,0 +1,67 @@
1
+ import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
+ import { printRecords } from "../output.js";
3
+ import { printReceipt } from "../receipt.js";
4
+ import { clampPageSize, parseIntArg, promoteDateBoundary, resolveContext } from "./helpers.js";
5
+ export const registerEntriesCommand = (program, services) => {
6
+ const entries = program.command("entries").description("Manage time entries.");
7
+ entries
8
+ .command("list")
9
+ .description("List the current user's time entries.")
10
+ .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
11
+ .option("--page <n>", "Page number (default 1).", parseIntArg, 1)
12
+ .option("--from <date>", "ISO 8601 start cutoff (inclusive).")
13
+ .option("--to <date>", "ISO 8601 end cutoff (inclusive).")
14
+ .option("--description <text>", "Filter by description substring.")
15
+ .action(async function (opts) {
16
+ const { client, workspaceId, output } = await resolveContext(this, services);
17
+ const user = await client.users.getCurrentUser();
18
+ const userId = entityId(user);
19
+ if (!userId) {
20
+ throw new Error("could not determine user ID");
21
+ }
22
+ const req = {
23
+ workspaceId,
24
+ userId,
25
+ page: opts.page,
26
+ "page-size": clampPageSize(opts.limit, 200),
27
+ };
28
+ if (opts.from)
29
+ req.start = promoteDateBoundary(opts.from, "from", "start");
30
+ if (opts.to)
31
+ req.end = promoteDateBoundary(opts.to, "to", "end");
32
+ if (opts.description)
33
+ req.description = opts.description;
34
+ const items = await client.timeEntries.listForUser(req);
35
+ const rows = items.map((raw) => {
36
+ const e = raw;
37
+ return {
38
+ id: e.id ?? "",
39
+ description: e.description ?? "",
40
+ project: e.projectId ?? "",
41
+ task: e.taskId ?? "",
42
+ billable: e.billable === true,
43
+ start: e.timeInterval?.start ?? "",
44
+ end: e.timeInterval?.end ?? "",
45
+ duration: e.timeInterval?.duration ?? "",
46
+ };
47
+ });
48
+ printRecords(rows, output);
49
+ });
50
+ entries
51
+ .command("delete")
52
+ .argument("<id>", "Time-entry ID.")
53
+ .description("Delete a time entry by ID.")
54
+ .action(async function (id) {
55
+ const { client, workspaceId, output } = await resolveContext(this, services);
56
+ await client.timeEntries.delete({ workspaceId, timeEntryId: id });
57
+ printReceipt({
58
+ ok: true,
59
+ action: "entries.delete",
60
+ entity: "time_entry",
61
+ ids: { entryId: id },
62
+ data: { id, deleted: true, message: `deleted time entry ${id}` },
63
+ changed: { deleted: [{ type: "time_entry", id }] },
64
+ next: [{ command: "clk115 entries list --json", reason: "Verify the entry no longer appears." }],
65
+ }, output);
66
+ });
67
+ };
@@ -0,0 +1,205 @@
1
+ import { entityId } from "clockify-sdk-ts-115/operation-receipt";
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, parseFloatArg, parseIntArg, promoteDateBoundary, resolveContext, } from "./helpers.js";
6
+ const EXPENSE_CHANGE_FIELDS = {
7
+ amount: "AMOUNT",
8
+ date: "DATE",
9
+ projectId: "PROJECT",
10
+ taskId: "TASK",
11
+ categoryId: "CATEGORY",
12
+ notes: "NOTES",
13
+ billable: "BILLABLE",
14
+ };
15
+ function expenseChangeFields(fields) {
16
+ return Object.entries(EXPENSE_CHANGE_FIELDS)
17
+ .filter(([key]) => fields[key] !== undefined)
18
+ .map(([, value]) => value);
19
+ }
20
+ export const registerExpensesCommand = (program, services) => {
21
+ const expenses = program.command("expenses").description("Inspect workspace expenses.");
22
+ expenses
23
+ .command("list")
24
+ .description("List expenses in the workspace.")
25
+ .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
26
+ .option("--page <n>", "Page number.", parseIntArg, 1)
27
+ .option("--start <date>", "Start of the date range (YYYY-MM-DD).")
28
+ .option("--end <date>", "End of the date range (YYYY-MM-DD).")
29
+ .action(async function (opts) {
30
+ const { client, workspaceId, output } = await resolveContext(this, services);
31
+ const req = {
32
+ workspaceId,
33
+ page: opts.page,
34
+ "page-size": clampPageSize(opts.limit, 200),
35
+ };
36
+ if (opts.start)
37
+ req.start = opts.start;
38
+ if (opts.end)
39
+ req.end = opts.end;
40
+ const response = (await client.expenses.list(wireBody(req)));
41
+ const items = (() => {
42
+ const inner = response.expenses;
43
+ if (Array.isArray(inner))
44
+ return inner;
45
+ if (inner && Array.isArray(inner.expenses))
46
+ return inner.expenses;
47
+ return [];
48
+ })();
49
+ const rows = items.map((raw) => {
50
+ const e = raw;
51
+ const category = typeof e.category === "object" && e.category !== null
52
+ ? (e.category.name ?? "")
53
+ : typeof e.category === "string"
54
+ ? e.category
55
+ : "";
56
+ return {
57
+ id: e.id ?? "",
58
+ date: e.date ?? "",
59
+ category,
60
+ projectId: e.projectId ?? "",
61
+ amount: e.total ?? e.amount ?? e.quantity ?? 0,
62
+ currency: e.currency ?? "",
63
+ billable: e.billable === true,
64
+ };
65
+ });
66
+ printRecords(rows, output);
67
+ });
68
+ expenses
69
+ .command("create")
70
+ .requiredOption("--amount <n>", "Amount.", parseFloatArg)
71
+ .requiredOption("--category <id>", "Expense category ID.")
72
+ .requiredOption("--date <date>", "Expense date (YYYY-MM-DD or ISO).")
73
+ .option("--user <id>", "Owning user ID (defaults to the API-key owner).")
74
+ .option("--project <id>", "Project ID.")
75
+ .option("--task <id>", "Task ID.")
76
+ .option("--notes <text>", "Notes.")
77
+ .option("--billable", "Mark as billable.")
78
+ .option("--no-billable", "Mark as non-billable.")
79
+ .description("Create an expense from amount, category, and date; defaults the user to the API-key owner.")
80
+ .action(async function (opts) {
81
+ const { client, workspaceId, output } = await resolveContext(this, services);
82
+ let userId = opts.user;
83
+ if (!userId) {
84
+ userId = entityId(await client.users.getCurrentUser());
85
+ if (!userId) {
86
+ throw new Error("could not determine user ID from getCurrentUser response; pass --user.");
87
+ }
88
+ }
89
+ const fields = {
90
+ amount: opts.amount,
91
+ categoryId: opts.category,
92
+ date: promoteDateBoundary(opts.date, "date", "start"),
93
+ };
94
+ if (opts.project)
95
+ fields.projectId = opts.project;
96
+ if (opts.task)
97
+ fields.taskId = opts.task;
98
+ if (opts.notes !== undefined)
99
+ fields.notes = opts.notes;
100
+ if (opts.billable !== undefined)
101
+ fields.billable = opts.billable;
102
+ const created = (await client.expenses.create({
103
+ ...fields,
104
+ userId,
105
+ workspaceId,
106
+ }));
107
+ const data = { id: created.id ?? "" };
108
+ printReceipt({
109
+ ok: true,
110
+ action: "expenses.create",
111
+ entity: "expense",
112
+ ids: { expenseId: data.id },
113
+ data,
114
+ changed: { created: [{ type: "expense", id: data.id }] },
115
+ next: [
116
+ {
117
+ command: `clk115 expenses get ${data.id} --json`,
118
+ reason: "Verify the new expense.",
119
+ },
120
+ ],
121
+ }, output);
122
+ });
123
+ expenses
124
+ .command("get")
125
+ .argument("<id>", "Expense ID.")
126
+ .description("Get one expense by ID.")
127
+ .action(async function (id) {
128
+ const { client, workspaceId, output } = await resolveContext(this, services);
129
+ const expense = await client.expenses.get({ workspaceId, expenseId: id });
130
+ printObject(expense, output);
131
+ });
132
+ expenses
133
+ .command("update")
134
+ .argument("<id>", "Expense ID.")
135
+ .requiredOption("--amount <n>", "Amount.", parseFloatArg)
136
+ .requiredOption("--category <id>", "Expense category ID.")
137
+ .requiredOption("--date <date>", "Expense date (YYYY-MM-DD or ISO).")
138
+ .requiredOption("--user <id>", "Owning user ID.")
139
+ .option("--project <id>", "Project ID.")
140
+ .option("--task <id>", "Task ID.")
141
+ .option("--notes <text>", "Notes.")
142
+ .option("--billable", "Mark as billable.")
143
+ .option("--no-billable", "Mark as non-billable.")
144
+ .description("Update an expense by ID (full replace of amount, category, date, plus any optional fields supplied).")
145
+ .action(async function (id, opts) {
146
+ const { client, workspaceId, output } = await resolveContext(this, services);
147
+ const fields = {
148
+ amount: opts.amount,
149
+ categoryId: opts.category,
150
+ date: promoteDateBoundary(opts.date, "date", "start"),
151
+ };
152
+ if (opts.project)
153
+ fields.projectId = opts.project;
154
+ if (opts.task)
155
+ fields.taskId = opts.task;
156
+ if (opts.notes !== undefined)
157
+ fields.notes = opts.notes;
158
+ if (opts.billable !== undefined)
159
+ fields.billable = opts.billable;
160
+ const updated = (await client.expenses.update({
161
+ ...fields,
162
+ changeFields: expenseChangeFields(fields),
163
+ userId: opts.user,
164
+ expenseId: id,
165
+ workspaceId,
166
+ }));
167
+ const data = { id: updated.id ?? id };
168
+ printReceipt({
169
+ ok: true,
170
+ action: "expenses.update",
171
+ entity: "expense",
172
+ ids: { expenseId: data.id },
173
+ data,
174
+ changed: { updated: [{ type: "expense", id: data.id }] },
175
+ next: [
176
+ {
177
+ command: `clk115 expenses get ${data.id} --json`,
178
+ reason: "Verify the update.",
179
+ },
180
+ ],
181
+ }, output);
182
+ });
183
+ expenses
184
+ .command("delete")
185
+ .argument("<id>", "Expense ID.")
186
+ .description("Delete an expense by ID.")
187
+ .action(async function (id) {
188
+ const { client, workspaceId, output } = await resolveContext(this, services);
189
+ await client.expenses.delete({ workspaceId, expenseId: id });
190
+ printReceipt({
191
+ ok: true,
192
+ action: "expenses.delete",
193
+ entity: "expense",
194
+ ids: { expenseId: id },
195
+ data: { id, deleted: true, message: `deleted expense ${id}` },
196
+ changed: { deleted: [{ type: "expense", id }] },
197
+ next: [
198
+ {
199
+ command: "clk115 expenses list --json",
200
+ reason: "Verify the expense no longer appears.",
201
+ },
202
+ ],
203
+ }, output);
204
+ });
205
+ };
@@ -0,0 +1,57 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { requireWorkspaceId } from "../config.js";
3
+ import { globalFlags, resolveFlags } from "../index.js";
4
+ export function parseIntArg(value) {
5
+ const parsed = Number.parseInt(value, 10);
6
+ if (!Number.isInteger(parsed) || parsed <= 0) {
7
+ throw new InvalidArgumentError("must be a positive integer.");
8
+ }
9
+ return parsed;
10
+ }
11
+ export function parseFloatArg(value) {
12
+ const parsed = Number.parseFloat(value);
13
+ if (!Number.isFinite(parsed) || parsed <= 0) {
14
+ throw new InvalidArgumentError("must be a positive number.");
15
+ }
16
+ return parsed;
17
+ }
18
+ export function clampPageSize(value, max) {
19
+ return Math.min(value, max);
20
+ }
21
+ export function splitList(value) {
22
+ return String(value)
23
+ .split(",")
24
+ .map((s) => s.trim())
25
+ .filter((s) => s.length > 0);
26
+ }
27
+ export function promoteDateBoundary(value, flag, edge) {
28
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
29
+ const probe = new Date(`${value}T00:00:00Z`);
30
+ if (Number.isNaN(probe.getTime()) || probe.toISOString().slice(0, 10) !== value) {
31
+ throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid calendar date (YYYY-MM-DD)`);
32
+ }
33
+ return edge === "start" ? `${value}T00:00:00Z` : `${value}T23:59:59Z`;
34
+ }
35
+ if (Number.isNaN(Date.parse(value))) {
36
+ throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid date (YYYY-MM-DD) or RFC3339 timestamp`);
37
+ }
38
+ return value;
39
+ }
40
+ export function rootProgram(cmd) {
41
+ let current = cmd;
42
+ while (current.parent != null) {
43
+ current = current.parent;
44
+ }
45
+ return current;
46
+ }
47
+ export async function resolveBaseContext(cmd, services) {
48
+ const program = rootProgram(cmd);
49
+ const config = services.loadConfig(globalFlags(program));
50
+ const client = await services.buildClient(config);
51
+ const output = resolveFlags(program);
52
+ return { client, config, output };
53
+ }
54
+ export async function resolveContext(cmd, services) {
55
+ const { client, config, output } = await resolveBaseContext(cmd, services);
56
+ return { client, workspaceId: requireWorkspaceId(config), output };
57
+ }
@@ -0,0 +1,81 @@
1
+ import { printRecords } from "../output.js";
2
+ import { printReceipt } from "../receipt.js";
3
+ import { resolveContext } from "./helpers.js";
4
+ export const registerInvoicesCommand = (program, services) => {
5
+ const invoices = program.command("invoices").description("Manage invoices.");
6
+ invoices
7
+ .command("list")
8
+ .description("List invoices in the workspace.")
9
+ .action(async function () {
10
+ const { client, workspaceId, output } = await resolveContext(this, services);
11
+ const response = (await client.invoices.list({ workspaceId }));
12
+ const items = response.invoices ?? [];
13
+ const rows = items.map((raw) => {
14
+ const inv = raw;
15
+ return {
16
+ id: inv.id ?? "",
17
+ number: inv.number ?? "",
18
+ client: inv.clientName ?? inv.clientId ?? "",
19
+ currency: inv.currency ?? "",
20
+ amount: inv.amount ?? 0,
21
+ status: inv.status ?? "",
22
+ issued: inv.issuedDate ?? "",
23
+ due: inv.dueDate ?? "",
24
+ };
25
+ });
26
+ printRecords(rows, output);
27
+ });
28
+ invoices
29
+ .command("create")
30
+ .description("Create an invoice draft.")
31
+ .requiredOption("--client <id>", "Client ID.")
32
+ .requiredOption("--number <text>", "Invoice number.")
33
+ .requiredOption("--currency <code>", "ISO currency code (e.g. USD, EUR).")
34
+ .requiredOption("--issued <date>", "Issued date (YYYY-MM-DD or RFC3339).")
35
+ .requiredOption("--due <date>", "Due date (YYYY-MM-DD or RFC3339).")
36
+ .option("--time-view-mode <mode>", "Time view mode (e.g. AGGREGATED_TIME_VIEW, DETAILED_TIME_VIEW).")
37
+ .action(async function (opts) {
38
+ const { client, workspaceId, output } = await resolveContext(this, services);
39
+ const body = {
40
+ clientId: opts.client,
41
+ number: opts.number,
42
+ currency: opts.currency,
43
+ issuedDate: normaliseInvoiceDate(opts.issued, "issued"),
44
+ dueDate: normaliseInvoiceDate(opts.due, "due"),
45
+ };
46
+ if (opts.timeViewMode)
47
+ body.timeViewMode = opts.timeViewMode;
48
+ const req = { workspaceId, body };
49
+ const created = (await client.invoices.create(req));
50
+ const data = {
51
+ id: created.id ?? "",
52
+ number: created.number ?? "",
53
+ status: created.status ?? "",
54
+ currency: created.currency ?? "",
55
+ amount: created.amount ?? 0,
56
+ };
57
+ printReceipt({
58
+ ok: true,
59
+ action: "invoices.create",
60
+ entity: "invoice",
61
+ ids: { invoiceId: data.id },
62
+ data,
63
+ changed: { created: [{ type: "invoice", id: data.id, name: data.number }] },
64
+ next: [
65
+ {
66
+ command: "clk115 invoices list --json",
67
+ reason: "Verify the invoice draft appears.",
68
+ },
69
+ ],
70
+ }, output);
71
+ });
72
+ };
73
+ function normaliseInvoiceDate(value, label) {
74
+ if (typeof value !== "string" || value.length === 0) {
75
+ throw new Error(`--${label} is required`);
76
+ }
77
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
78
+ return `${value}T00:00:00Z`;
79
+ }
80
+ return value;
81
+ }
@@ -0,0 +1,75 @@
1
+ import { parseDuration } from "../duration.js";
2
+ import { printReceipt } from "../receipt.js";
3
+ import { resolveContext } from "./helpers.js";
4
+ import { resolveProjectId, resolveTaskId, resolveTagIds } from "./resolve-refs.js";
5
+ export const registerLogCommand = (program, services) => {
6
+ program
7
+ .command("log")
8
+ .description("Log a finished time entry. Duration accepts 1h30m / 90m / PT1H30M.")
9
+ .argument("<duration>", "Duration like '1h30m', '45m', or ISO 8601 'PT1H30M'.")
10
+ .argument("<description>", "What you worked on.")
11
+ .option("-p, --project <name|id>", "Project name or ID.")
12
+ .option("-t, --task <name|id>", "Task name or ID.")
13
+ .option("--tag <name|id...>", "Tag name(s) or ID(s). Repeat the flag for multiple tags.")
14
+ .option("--billable", "Mark the entry as billable.", false)
15
+ .option("--end <iso>", "End timestamp (ISO 8601). Defaults to now.")
16
+ .action(async function (duration, description, opts) {
17
+ const { client, workspaceId, output } = await resolveContext(this, services);
18
+ if (opts.task && !opts.project) {
19
+ throw new Error("--task requires --project: a task entry must be scoped to its project.");
20
+ }
21
+ const projectId = opts.project
22
+ ? await resolveProjectId(client, workspaceId, opts.project)
23
+ : undefined;
24
+ const taskId = opts.task && projectId
25
+ ? await resolveTaskId(client, workspaceId, projectId, opts.task)
26
+ : undefined;
27
+ const tagIds = opts.tag && opts.tag.length > 0
28
+ ? await resolveTagIds(client, workspaceId, opts.tag)
29
+ : undefined;
30
+ const seconds = parseDuration(duration);
31
+ const endIso = opts.end ?? new Date().toISOString();
32
+ const endMs = Date.parse(endIso);
33
+ if (Number.isNaN(endMs)) {
34
+ throw new Error(`--end ${JSON.stringify(opts.end)} is not a valid ISO 8601 timestamp`);
35
+ }
36
+ const startIso = new Date(endMs - seconds * 1000).toISOString();
37
+ const body = {
38
+ start: startIso,
39
+ end: endIso,
40
+ description,
41
+ };
42
+ if (projectId)
43
+ body.projectId = projectId;
44
+ if (taskId)
45
+ body.taskId = taskId;
46
+ if (tagIds && tagIds.length > 0)
47
+ body.tagIds = tagIds;
48
+ if (opts.billable)
49
+ body.billable = true;
50
+ const req = { workspaceId, body };
51
+ const created = await client.timeEntries.create(req);
52
+ const entry = created;
53
+ const data = {
54
+ id: entry.id ?? "",
55
+ description: entry.description ?? "",
56
+ duration: entry.timeInterval?.duration ?? "",
57
+ start: startIso,
58
+ end: endIso,
59
+ };
60
+ printReceipt({
61
+ ok: true,
62
+ action: "entries.log",
63
+ entity: "time_entry",
64
+ ids: { entryId: data.id },
65
+ data,
66
+ changed: { created: [{ type: "time_entry", id: data.id }] },
67
+ next: [
68
+ {
69
+ command: "clk115 entries list --json",
70
+ reason: "Verify the entry appears in the expected date range.",
71
+ },
72
+ ],
73
+ }, output);
74
+ });
75
+ };