@infaris/calendar-cli 0.9.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,198 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { Command, Option } from "commander";
4
+ import { beginLogin, completeLogin, login, readLoginCode } from "./auth.js";
5
+ import { clearCredentials, DEFAULT_BASE_URL } from "./config.js";
6
+ import { crmFetch } from "./crm-api.js";
7
+ import { createTask, addTaskAttachment, listTeamMembers, listTasks, } from "./api.js";
8
+ import { resolveAttendeeIds } from "./selectors.js";
9
+ const program = new Command()
10
+ .name("infaris-crm")
11
+ .version("0.9.0")
12
+ .description("Customer dossiers, contact people and contact history. Shares infaris-calendar login.");
13
+ function output(value) {
14
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
15
+ }
16
+ const loginCommand = program
17
+ .command("login")
18
+ .option("--url <url>", "Calendar URL for the shared login", DEFAULT_BASE_URL)
19
+ .option("--manual", "Sign in on another device")
20
+ .action(async (opts) => {
21
+ const { credentials } = await login(opts.url, { manual: opts.manual });
22
+ output({ email: credentials.email });
23
+ });
24
+ loginCommand
25
+ .command("link")
26
+ .option("--url <url>", "Calendar URL", DEFAULT_BASE_URL)
27
+ .option("--new", "Discard a pending sign-in and start a fresh one")
28
+ .action((opts) => {
29
+ process.stdout.write(`${beginLogin(opts.url, { fresh: opts.new }).authUrl}\n`);
30
+ });
31
+ loginCommand.command("code [value]").action(async (value) => {
32
+ const { credentials } = await completeLogin(await readLoginCode(value));
33
+ output({ email: credentials.email });
34
+ });
35
+ program
36
+ .command("logout")
37
+ .description("Remove the shared Calendar/CRM login")
38
+ .action(() => clearCredentials());
39
+ program
40
+ .command("list")
41
+ .description("Find customers (paginated)")
42
+ .option("--search <text>")
43
+ .option("--limit <number>", "Page size, max 100", "25")
44
+ .option("--offset <number>", "Page offset", "0")
45
+ .option("--json", "Machine-readable output (default)")
46
+ .action(async (opts) => {
47
+ const params = new URLSearchParams({
48
+ limit: opts.limit,
49
+ offset: opts.offset,
50
+ });
51
+ if (opts.search)
52
+ params.set("search", opts.search);
53
+ output(await crmFetch(`/relations?${params}`));
54
+ });
55
+ program
56
+ .command("create")
57
+ .description("Create a prospect customer without billing or provisioning a Guard license")
58
+ .requiredOption("--name <name>")
59
+ .option("--email <email>")
60
+ .option("--phone <phone>")
61
+ .option("--website <url>")
62
+ .option("--contact-person <name>")
63
+ .option("--note <text>")
64
+ .option("--json", "Machine-readable output (default)")
65
+ .action(async (opts) => {
66
+ output(await crmFetch("/relations", {
67
+ method: "POST",
68
+ headers: { "content-type": "application/json" },
69
+ body: JSON.stringify({
70
+ name: opts.name,
71
+ email: opts.email,
72
+ phone: opts.phone,
73
+ website: opts.website,
74
+ contactPerson: opts.contactPerson,
75
+ initialNote: opts.note,
76
+ }),
77
+ }));
78
+ });
79
+ program
80
+ .command("show <customer>")
81
+ .description("Read customer, contacts, contact history, CRM owner and Calendar tickets")
82
+ .option("--include-done", "Include closed tickets")
83
+ .option("--entries-limit <number>", "Contact-history page size, max 200", "50")
84
+ .option("--entries-offset <number>", "Contact-history page offset", "0")
85
+ .option("--json", "Machine-readable output (default)")
86
+ .action(async (customer, opts) => {
87
+ const dossier = (await crmFetch(`/relations/${encodeURIComponent(customer)}?${new URLSearchParams({ entriesLimit: opts.entriesLimit, entriesOffset: opts.entriesOffset })}`));
88
+ // An unavailable Calendar fails loudly; an empty ticket list must mean no tickets.
89
+ const { tasks } = await listTasks({
90
+ relationNumber: dossier.relation.relationNumber,
91
+ includeDone: opts.includeDone,
92
+ });
93
+ output({ ...dossier, tasks });
94
+ });
95
+ program
96
+ .command("ticket <customer>")
97
+ .description("Create a Guard problem ticket linked to the canonical customer")
98
+ .requiredOption("--title <title>")
99
+ .option("--description <text>")
100
+ .option("--description-file <path>", "Read the problem brief from file, or '-' for stdin")
101
+ .option("--due <iso>")
102
+ .option("--assignee <people...>", "Assign by team name, email or id")
103
+ .option("--image <paths...>", "Attach screenshots or PDFs (max 10 MB each)")
104
+ .option("--json", "Machine-readable output (default)")
105
+ .action(async (customer, opts) => {
106
+ if (opts.description !== undefined && opts.descriptionFile !== undefined)
107
+ throw new Error("Choose --description or --description-file");
108
+ const description = opts.descriptionFile
109
+ ? readFileSync(opts.descriptionFile === "-" ? 0 : opts.descriptionFile, "utf8")
110
+ : opts.description;
111
+ const { relation } = (await crmFetch(`/relations/${encodeURIComponent(customer)}`));
112
+ const assigneeIds = opts.assignee
113
+ ? resolveAttendeeIds(opts.assignee, (await listTeamMembers()).members)
114
+ : undefined;
115
+ const { task, baseUrl } = await createTask({
116
+ title: opts.title,
117
+ description,
118
+ relationNumber: relation.relationNumber,
119
+ product: "pulseguard",
120
+ dueDate: opts.due,
121
+ assigneeIds,
122
+ });
123
+ const attachments = [];
124
+ for (const path of opts.image || []) {
125
+ try {
126
+ attachments.push((await addTaskAttachment(task.id, path)).attachment);
127
+ }
128
+ catch (error) {
129
+ throw new Error(`Ticket #${task.taskKey} was created at ${baseUrl}/t/${task.taskKey}. Upload failed; retry with infaris-calendar attach task --id ${task.taskKey}, not ticket. ${error instanceof Error ? error.message : error}`);
130
+ }
131
+ }
132
+ output({ task, attachments, url: `${baseUrl}/t/${task.taskKey}` });
133
+ });
134
+ program
135
+ .command("note <customer>")
136
+ .description("Append a note or contact moment to the customer log")
137
+ .option("--body <text>")
138
+ .option("--body-file <path>", "Read text from file, or '-' for stdin")
139
+ .addOption(new Option("--method <method>", "Creates a contact moment instead of a note").choices(["EMAIL", "PHONE", "MEETING", "VIDEO", "CHAT", "OTHER"]))
140
+ .addOption(new Option("--outcome <outcome>").choices([
141
+ "SPOKEN",
142
+ "NO_ANSWER",
143
+ "CALLBACK",
144
+ "INTERESTED",
145
+ "NOT_INTERESTED",
146
+ ]))
147
+ .option("--contact <id>", "Customer contact person id")
148
+ .option("--at <iso>", "When the contact occurred (default now)")
149
+ .option("--json", "Machine-readable output (default)")
150
+ .action(async (customer, opts) => {
151
+ if (opts.body !== undefined && opts.bodyFile !== undefined)
152
+ throw new Error("Choose --body or --body-file");
153
+ const body = opts.bodyFile
154
+ ? readFileSync(opts.bodyFile === "-" ? 0 : opts.bodyFile, "utf8")
155
+ : opts.body;
156
+ if (!body?.trim())
157
+ throw new Error("Pass --body or --body-file");
158
+ if (opts.outcome && !opts.method)
159
+ throw new Error("--outcome requires --method");
160
+ output(await crmFetch(`/relations/${encodeURIComponent(customer)}/entries`, {
161
+ method: "POST",
162
+ headers: { "content-type": "application/json" },
163
+ body: JSON.stringify({
164
+ kind: opts.method ? "CONTACT" : "NOTE",
165
+ body,
166
+ contactMethod: opts.method,
167
+ outcome: opts.outcome,
168
+ contactId: opts.contact,
169
+ occurredAt: opts.at || new Date().toISOString(),
170
+ }),
171
+ }));
172
+ });
173
+ program
174
+ .command("contact <customer>")
175
+ .description("Create or replace a customer contact person, without creating an Infaris account")
176
+ .requiredOption("--name <name>")
177
+ .option("--id <id>", "Existing contact id to replace")
178
+ .option("--email <email>")
179
+ .option("--phone <phone>")
180
+ .option("--role <role>")
181
+ .option("--json", "Machine-readable output (default)")
182
+ .action(async (customer, opts) => {
183
+ output(await crmFetch(`/relations/${encodeURIComponent(customer)}/contacts`, {
184
+ method: "POST",
185
+ headers: { "content-type": "application/json" },
186
+ body: JSON.stringify({
187
+ id: opts.id,
188
+ name: opts.name,
189
+ email: opts.email || null,
190
+ phone: opts.phone || null,
191
+ role: opts.role || null,
192
+ }),
193
+ }));
194
+ });
195
+ program.parseAsync(process.argv).catch((error) => {
196
+ process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
197
+ process.exitCode = 1;
198
+ });
package/dist/dates.js ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Small, dependency-free date helpers for the agenda commands.
3
+ *
4
+ * Inputs accepted everywhere a date/datetime is expected:
5
+ * - ISO 8601: 2026-06-30, 2026-06-30T14:00, 2026-06-30T14:00:00Z
6
+ * - "2026-06-30 14:00" (space instead of T)
7
+ * - relative keywords: now, today, tomorrow, yesterday
8
+ * - relative offsets: +3d, -1d, +2w, +1m (days / weeks / months)
9
+ * - "tomorrow 09:00", "today 14:30", "+1d 08:00"
10
+ *
11
+ * All parsing is done in the machine's local timezone (Europe/Amsterdam for the
12
+ * intended user), which is what people mean when they type "tomorrow at 9".
13
+ */
14
+ export function startOfDay(d) {
15
+ const x = new Date(d);
16
+ x.setHours(0, 0, 0, 0);
17
+ return x;
18
+ }
19
+ export function endOfDay(d) {
20
+ const x = new Date(d);
21
+ x.setHours(23, 59, 59, 999);
22
+ return x;
23
+ }
24
+ function addDays(d, n) {
25
+ const x = new Date(d);
26
+ x.setDate(x.getDate() + n);
27
+ return x;
28
+ }
29
+ function addMonths(d, n) {
30
+ const x = new Date(d);
31
+ x.setMonth(x.getMonth() + n);
32
+ return x;
33
+ }
34
+ /** First day of the week containing `d`. weekStartsOn: 0 = Sunday, 1 = Monday. */
35
+ function startOfWeek(d, weekStartsOn = 1) {
36
+ const x = startOfDay(d);
37
+ const day = (x.getDay() - weekStartsOn + 7) % 7;
38
+ return addDays(x, -day);
39
+ }
40
+ /**
41
+ * Parse a date/datetime string. Returns null when it can't be understood.
42
+ * Pure date keywords (today/tomorrow) resolve to the start of that day unless a
43
+ * time is appended.
44
+ */
45
+ export function parseDateInput(input, now = new Date()) {
46
+ if (!input)
47
+ return null;
48
+ const raw = input.trim();
49
+ const lower = raw.toLowerCase();
50
+ // "<keyword> HH:mm" — split off an optional trailing time.
51
+ const timeMatch = lower.match(/\s+(\d{1,2}):(\d{2})(?::(\d{2}))?$/);
52
+ let timePart = null;
53
+ let datePartLower = lower;
54
+ if (timeMatch) {
55
+ timePart = {
56
+ h: Number(timeMatch[1]),
57
+ m: Number(timeMatch[2]),
58
+ s: timeMatch[3] ? Number(timeMatch[3]) : 0,
59
+ };
60
+ datePartLower = lower.slice(0, timeMatch.index).trim();
61
+ }
62
+ let base = null;
63
+ if (datePartLower === "now") {
64
+ base = new Date(now);
65
+ }
66
+ else if (datePartLower === "today") {
67
+ base = startOfDay(now);
68
+ }
69
+ else if (datePartLower === "tomorrow") {
70
+ base = startOfDay(addDays(now, 1));
71
+ }
72
+ else if (datePartLower === "yesterday") {
73
+ base = startOfDay(addDays(now, -1));
74
+ }
75
+ else {
76
+ const offset = datePartLower.match(/^([+-]\d+)\s*([dwm])$/);
77
+ if (offset) {
78
+ const n = Number(offset[1]);
79
+ const unit = offset[2];
80
+ const ref = startOfDay(now);
81
+ base =
82
+ unit === "d" ? addDays(ref, n) : unit === "w" ? addDays(ref, n * 7) : addMonths(ref, n);
83
+ }
84
+ else {
85
+ // Fall back to native parsing. Accept a space between date and time.
86
+ const normalized = raw.replace(" ", "T");
87
+ const parsed = new Date(normalized);
88
+ if (!Number.isNaN(parsed.getTime()))
89
+ base = parsed;
90
+ }
91
+ }
92
+ if (!base)
93
+ return null;
94
+ if (timePart) {
95
+ base = new Date(base);
96
+ base.setHours(timePart.h, timePart.m, timePart.s, 0);
97
+ }
98
+ return base;
99
+ }
100
+ /** Resolve agenda command options into a concrete [start, end] window. */
101
+ export function resolveRange(opts, now = new Date(), weekStartsOn = 1) {
102
+ if (opts.from) {
103
+ const start = parseDateInput(opts.from, now);
104
+ if (!start)
105
+ throw new Error(`Invalid --from date: ${opts.from}`);
106
+ if (opts.to) {
107
+ const end = parseDateInput(opts.to, now);
108
+ if (!end)
109
+ throw new Error(`Invalid --to date: ${opts.to}`);
110
+ return { start, end: endOfDay(end) };
111
+ }
112
+ if (opts.days != null) {
113
+ const n = Number(opts.days);
114
+ if (!Number.isFinite(n) || n < 1)
115
+ throw new Error(`Invalid --days value: ${opts.days}`);
116
+ return { start: startOfDay(start), end: endOfDay(addDays(start, n - 1)) };
117
+ }
118
+ return { start: startOfDay(start), end: endOfDay(start) };
119
+ }
120
+ if (opts.tomorrow) {
121
+ const t = addDays(now, 1);
122
+ return { start: startOfDay(t), end: endOfDay(t) };
123
+ }
124
+ if (opts.week) {
125
+ const start = startOfWeek(now, weekStartsOn);
126
+ return { start, end: endOfDay(addDays(start, 6)) };
127
+ }
128
+ if (opts.month) {
129
+ const start = new Date(now.getFullYear(), now.getMonth(), 1);
130
+ const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
131
+ return { start: startOfDay(start), end: endOfDay(end) };
132
+ }
133
+ if (opts.days != null) {
134
+ const n = Number(opts.days);
135
+ if (!Number.isFinite(n) || n < 1)
136
+ throw new Error(`Invalid --days value: ${opts.days}`);
137
+ return { start: startOfDay(now), end: endOfDay(addDays(now, n - 1)) };
138
+ }
139
+ // Default: today.
140
+ return { start: startOfDay(now), end: endOfDay(now) };
141
+ }
142
+ const DATE_FMT = new Intl.DateTimeFormat("nl-NL", {
143
+ weekday: "short",
144
+ day: "numeric",
145
+ month: "short",
146
+ year: "numeric",
147
+ });
148
+ const TIME_FMT = new Intl.DateTimeFormat("nl-NL", {
149
+ hour: "2-digit",
150
+ minute: "2-digit",
151
+ });
152
+ export function formatDayHeading(d) {
153
+ return DATE_FMT.format(d);
154
+ }
155
+ export function formatTime(d) {
156
+ return TIME_FMT.format(d);
157
+ }
158
+ /** YYYY-MM-DD in local time, used to group events by day. */
159
+ export function localDayKey(d) {
160
+ const y = d.getFullYear();
161
+ const m = String(d.getMonth() + 1).padStart(2, "0");
162
+ const day = String(d.getDate()).padStart(2, "0");
163
+ return `${y}-${m}-${day}`;
164
+ }
@@ -0,0 +1,39 @@
1
+ import { endOfDay, parseDateInput, startOfDay } from "./dates.js";
2
+ /**
3
+ * Resolve CLI date input into the exact range sent to Calendar.
4
+ * For all-day events, --end is an inclusive calendar date.
5
+ */
6
+ export function resolveCreateEventTimes(opts, defaultDuration, now = new Date()) {
7
+ const parsedStart = parseDateInput(opts.start, now);
8
+ if (!parsedStart)
9
+ throw new Error(`Invalid --start: ${opts.start}`);
10
+ if (opts.allDay) {
11
+ const startTime = startOfDay(parsedStart);
12
+ const parsedEnd = opts.end ? parseDateInput(opts.end, now) : parsedStart;
13
+ if (!parsedEnd)
14
+ throw new Error(`Invalid --end: ${opts.end}`);
15
+ const endTime = endOfDay(parsedEnd);
16
+ if (endTime.getTime() < startTime.getTime()) {
17
+ throw new Error("End date must be on or after start date.");
18
+ }
19
+ return { startTime, endTime };
20
+ }
21
+ let endTime;
22
+ if (opts.end) {
23
+ const parsedEnd = parseDateInput(opts.end, now);
24
+ if (!parsedEnd)
25
+ throw new Error(`Invalid --end: ${opts.end}`);
26
+ endTime = parsedEnd;
27
+ }
28
+ else {
29
+ const minutes = opts.duration == null ? defaultDuration : Number(opts.duration);
30
+ if (!Number.isFinite(minutes) || minutes <= 0) {
31
+ throw new Error(`Invalid --duration: ${opts.duration}`);
32
+ }
33
+ endTime = new Date(parsedStart.getTime() + minutes * 60_000);
34
+ }
35
+ if (endTime.getTime() <= parsedStart.getTime()) {
36
+ throw new Error("End must be after start.");
37
+ }
38
+ return { startTime: parsedStart, endTime };
39
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Free/busy computation for the `free` command: given a list of events and a
3
+ * range, find open slots within working hours, in local time.
4
+ */
5
+ import { startOfDay } from "./dates.js";
6
+ /** Parse "HH:mm" into hours/minutes; throws on garbage. */
7
+ export function parseHm(input) {
8
+ const match = input.trim().match(/^(\d{1,2}):(\d{2})$/);
9
+ if (!match)
10
+ throw new Error(`Invalid time '${input}', expected HH:mm`);
11
+ const h = Number(match[1]);
12
+ const m = Number(match[2]);
13
+ if (h > 23 || m > 59)
14
+ throw new Error(`Invalid time '${input}'`);
15
+ return { h, m };
16
+ }
17
+ function mergeIntervals(intervals) {
18
+ if (intervals.length === 0)
19
+ return [];
20
+ const sorted = [...intervals].sort((a, b) => a.start - b.start);
21
+ const merged = [{ ...sorted[0] }];
22
+ for (let i = 1; i < sorted.length; i++) {
23
+ const last = merged[merged.length - 1];
24
+ const cur = sorted[i];
25
+ if (cur.start <= last.end) {
26
+ last.end = Math.max(last.end, cur.end);
27
+ }
28
+ else {
29
+ merged.push({ ...cur });
30
+ }
31
+ }
32
+ return merged;
33
+ }
34
+ export function computeFreeSlots(events, opts) {
35
+ const now = opts.now ?? new Date();
36
+ const minMs = opts.minMinutes * 60_000;
37
+ const slots = [];
38
+ const cursor = startOfDay(opts.rangeStart);
39
+ const lastDay = startOfDay(opts.rangeEnd);
40
+ while (cursor.getTime() <= lastDay.getTime()) {
41
+ const day = new Date(cursor);
42
+ cursor.setDate(cursor.getDate() + 1);
43
+ const dow = day.getDay();
44
+ if (!opts.includeWeekends && (dow === 0 || dow === 6))
45
+ continue;
46
+ const workStart = new Date(day);
47
+ workStart.setHours(opts.workStart.h, opts.workStart.m, 0, 0);
48
+ const workEnd = new Date(day);
49
+ workEnd.setHours(opts.workEnd.h, opts.workEnd.m, 0, 0);
50
+ // Clamp the working window to the requested range and to "now".
51
+ let windowStart = Math.max(workStart.getTime(), opts.rangeStart.getTime(), now.getTime());
52
+ const windowEnd = Math.min(workEnd.getTime(), opts.rangeEnd.getTime());
53
+ if (windowStart >= windowEnd)
54
+ continue;
55
+ // Build busy intervals overlapping this working window.
56
+ const busy = [];
57
+ for (const e of events) {
58
+ const s = new Date(e.startTime).getTime();
59
+ const en = new Date(e.endTime).getTime();
60
+ if (e.isAllDay) {
61
+ if (!opts.ignoreAllDay && s < windowEnd && en > windowStart) {
62
+ busy.push({ start: windowStart, end: windowEnd });
63
+ }
64
+ continue;
65
+ }
66
+ if (e.status === "cancelled")
67
+ continue;
68
+ if (s < windowEnd && en > windowStart) {
69
+ busy.push({ start: Math.max(s, windowStart), end: Math.min(en, windowEnd) });
70
+ }
71
+ }
72
+ const merged = mergeIntervals(busy);
73
+ let pointer = windowStart;
74
+ for (const interval of merged) {
75
+ if (interval.start - pointer >= minMs) {
76
+ slots.push(makeSlot(pointer, interval.start));
77
+ }
78
+ pointer = Math.max(pointer, interval.end);
79
+ }
80
+ if (windowEnd - pointer >= minMs) {
81
+ slots.push(makeSlot(pointer, windowEnd));
82
+ }
83
+ }
84
+ return slots;
85
+ }
86
+ function makeSlot(startMs, endMs) {
87
+ return {
88
+ start: new Date(startMs),
89
+ end: new Date(endMs),
90
+ minutes: Math.round((endMs - startMs) / 60_000),
91
+ };
92
+ }