@infaris/calendar-cli 0.10.0 → 0.13.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/README.md CHANGED
@@ -324,8 +324,13 @@ infaris-calendar mail messages --search "offerte"
324
324
  infaris-calendar mail read 4812
325
325
  infaris-calendar mail draft --reply 4812 --body "<p>Dank je, klopt helemaal.</p>"
326
326
 
327
- # Change a draft: save the new version and remove the old one in one go
327
+ # Change only the text of a draft: recipients, thread, signature, quote and
328
+ # attachments stay. --attach adds a file, --note leaves a note for the reviewer.
328
329
  infaris-calendar mail drafts
330
+ infaris-calendar mail draft --edit 977 --body-file ./mail.md
331
+ infaris-calendar mail draft --edit 977 --attach offerte-v2.pdf --drop-attachments
332
+
333
+ # Or build the whole draft anew and remove the old one in one go
329
334
  infaris-calendar mail draft --replace 977 --to kees@example.com \
330
335
  --subject "Offerte v2" --body-file ./mail.html
331
336
 
@@ -333,8 +338,9 @@ infaris-calendar mail draft --replace 977 --to kees@example.com \
333
338
  infaris-calendar mail draft --to kees@example.com --body-file ./mail.html --dry-run
334
339
  infaris-calendar mail draft --to kees@example.com --body-file ./mail.md --preview /tmp/mail.html
335
340
 
336
- # Read the saved draft back to check it
337
- infaris-calendar mail read 978 --drafts
341
+ # Read the saved draft back to check it; --preview writes it as the recipient
342
+ # sees it (signature and inline images included) to render and look at
343
+ infaris-calendar mail read 978 --drafts --preview /tmp/draft.html
338
344
 
339
345
  # Many drafts at once (outreach): every draft is checked before any is saved
340
346
  cat > drafts.json <<'JSON'
@@ -369,6 +375,10 @@ infaris-calendar mail batch drafts.json --replace-map map.json --write-map map.j
369
375
  | `--folder <path>` | Folder of the original message (default `INBOX`) |
370
376
  | `--source-mailbox <id>` | Mailbox of the original (default: the draft mailbox) |
371
377
  | `--replace <uid>` | Replace an existing draft in Concepten |
378
+ | `--edit <uid>` | Change a draft in place: only what you pass changes; `--attach` adds files |
379
+ | `--mailbox <id>` | Mailbox of the draft to `--edit` |
380
+ | `--drop-attachments` | With `--edit`: remove the existing attachments |
381
+ | `--note <text>` | Private note for the reviewer (basis, what to check); shown in Calendar, never sent |
372
382
  | `--dry-run` | Print recipients, images and attachments without saving |
373
383
  | `--preview <file.html>` | Write the body with inline images to an HTML file; saves nothing |
374
384
  | `--no-inline-remote` | Keep `https://` images as links instead of embedding them |
@@ -394,7 +404,7 @@ Other `mail` commands, all read-only except `delete-draft` (removes a draft) and
394
404
  | `mail delete-draft <uid> [--mailbox]` (alias `draft-delete`) | Delete one draft, only from Concepten |
395
405
  | `mail messages [--mailbox] [--folder\|--sent] [--search] [--limit]` | List or search messages to find a UID |
396
406
  | `mail sent [--mailbox] [--search] [--limit]` | The newest messages in Verzonden |
397
- | `mail read <uid> [--mailbox] [--folder\|--drafts\|--sent]` | Show one message as text; never marks it read. With `--json` and `--drafts`/`--sent`: recipients incl. Bcc, subject, body and `signatureCount` |
407
+ | `mail read <uid> [--mailbox] [--folder\|--drafts\|--sent] [--preview f.html]` | Show one message as text; never marks it read. Attachments with type and size, inline images apart. With `--json` and `--drafts`/`--sent`: recipients incl. Bcc, subject, body, `signatureCount`, `agentDraft` and `note` |
398
408
  | `mail status <uid\|message-id> [--mailbox]` | Is it still a draft, really in Verzonden, or gone? |
399
409
  | `mail send [uids...] [--all-drafts [--filter q]] --yes` | Send existing drafts; see below |
400
410
 
@@ -547,6 +557,58 @@ without billing or a Guard license. Check returned `warning` values before
547
557
  retrying. Ticket creation reports its task number if a later upload fails;
548
558
  retry with `attach task`, not a second ticket.
549
559
 
560
+ ## Keeping the CRM tidy (0.13.0)
561
+
562
+ ```bash
563
+ infaris-crm list --email treffendenco.nl --include-archived --kind CLIENT --status PROSPECT
564
+ infaris-crm create --name "Vimexx" --kind SUPPLIER --dry-run # reports similar customers, writes nothing
565
+ infaris-crm update RELATION --name "New name" --legal-name "New name BV" --kind NETWORK --status ARCHIVED
566
+ infaris-crm archive RELATION
567
+ infaris-crm merge R-DUPLICATE --into R-LEADING --yes
568
+ infaris-crm contact-delete RELATION CONTACT_ID --yes
569
+ infaris-crm note RELATION --method EMAIL --at 2026-10-05T12:00:00+02:00 --source mail:ID --body-file n.md
570
+ infaris-crm tidy [--apply] [--include-archived]
571
+ ```
572
+
573
+ `create` answers 409 with the similar customers when the e-mail, website or name
574
+ already exists; `--allow-duplicate` creates anyway and `--dry-run` only reports. `list` hides
575
+ archived customers unless `--include-archived` or `--status` asks for them. `kind` is
576
+ `CLIENT` (default), `SUPPLIER`, `NETWORK`, `EVENT` or `EDUCATION`. `archive` and `update
577
+ --status ARCHIVED` refuse customers with a Stripe customer or Guard organization. `merge`
578
+ moves contacts and history and archives the duplicate; it refuses a duplicate with billing,
579
+ quotes, invoices or a Guard workspace and does not move Calendar tickets. `tidy` is a dry run
580
+ until `--apply`. Support must be deployed with these routes before the commands work.
581
+
582
+ ## Quotes in Support (0.12.0)
583
+
584
+ `infaris-crm quote` creates Guard quotes as drafts in Support, priced from the
585
+ live Infaris catalogue, and downloads the PDF Support renders. Acceptance stays
586
+ in Support, where it becomes the composed license and billing in Infaris.
587
+
588
+ ```bash
589
+ infaris-crm quote catalog --json # component ids, live prices, units
590
+ infaris-crm quote create --file offerte.json --customer RELATION --organization ORG_SLUG --logo logo.png --json
591
+ infaris-crm quote update Q-2026-0042 --file offerte.json --customer RELATION --json # drafts only
592
+ infaris-crm quote pdf Q-2026-0042 --out "Offerte Q-2026-0042.pdf"
593
+ infaris-crm quote send Q-2026-0042 # after the mail draft is ready
594
+ infaris-crm quote accept Q-2026-0042 --by "Name" --via email --variant option --yes # starts billing
595
+ infaris-crm quote show Q-2026-0042 --json # status, totals, prospectComponents
596
+ infaris-crm quote list RELATION --json
597
+ infaris-crm quote decline Q-2026-0042
598
+ ```
599
+
600
+ The quote file names components (`{"component": "website", "quantity": 5}`); a
601
+ `price` on a line or a `packagePrice` below the sum is reported back as a
602
+ deviation. `"optional": true` lines form the variant named by `optionLabel`.
603
+ The same file for the same relation derives the same idempotency key, so a
604
+ repeated `create` returns the existing quote; change a draft with `update`.
605
+ `quote accept` records the customer's acceptance exactly like the quote page
606
+ (same validation; repeating it changes nothing) and starts the license and
607
+ billing in Infaris, so it refuses without `--yes`. A refusal (Infaris, Stripe)
608
+ leaves the quote SENT with the reason in the error.
609
+ `prospectComponents` in the answer is the value for
610
+ `infaris-guard prospect --components`, so trial and quote hold the same.
611
+
550
612
  Use `infaris-crm login`, or `login link` / `login code <value>` for remote sessions.
551
613
  The logout affects both CLI tools. `INFARIS_CALENDAR_CONFIG_DIR` can select an
552
614
  isolated login directory for a separate profile or automation session. Override the CRM server with `INFARIS_CRM_URL`;
package/dist/api.js CHANGED
@@ -400,6 +400,8 @@ export async function listMailMessages(opts = {}) {
400
400
  export async function readMailMessage(uid, opts = {}) {
401
401
  const params = mailParams(opts);
402
402
  params.set("uid", String(uid));
403
+ if (opts.preview)
404
+ params.set("preview", "1");
403
405
  const { res } = await authedFetch(`/api/mail/messages?${params}`, {
404
406
  method: "GET",
405
407
  });
package/dist/auth.js CHANGED
@@ -330,6 +330,18 @@ async function refreshAccessToken(stale) {
330
330
  return rotate(creds);
331
331
  });
332
332
  }
333
+ /** Credentials with a different refresh token than `used`, once another process saved them (max ~3 s). */
334
+ export async function awaitRotatedCredentials(used, { timeoutMs = 3_000, intervalMs = 200 } = {}) {
335
+ const deadline = Date.now() + timeoutMs;
336
+ for (;;) {
337
+ const current = loadCredentials();
338
+ if (current?.refreshToken && current.refreshToken !== used)
339
+ return current;
340
+ if (Date.now() >= deadline)
341
+ return null;
342
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
343
+ }
344
+ }
333
345
  async function rotate(creds) {
334
346
  if (!creds.refreshToken) {
335
347
  throw new Error("Your session has expired. Please run `infaris-calendar login` again.");
@@ -348,8 +360,19 @@ async function rotate(creds) {
348
360
  // error is worth retrying without a new sign-in.
349
361
  if (!/\((400|401)\)/.test(message))
350
362
  throw err;
363
+ // "Already used": a process outside our lock (an older CLI in another
364
+ // worktree shares this credentials file) rotated it a moment ago. Its new
365
+ // token lands in the file; take that instead of reporting a dead session.
366
+ if (/already been used/i.test(message)) {
367
+ const rotated = await awaitRotatedCredentials(creds.refreshToken);
368
+ if (rotated) {
369
+ return Date.now() + 30_000 < rotated.expiresAt ? rotated : rotate(rotated);
370
+ }
371
+ }
351
372
  throw new Error("Your session has expired. Please run `infaris-calendar login` again " +
352
- "(or `infaris-calendar login link` from an agent or SSH session).");
373
+ "(or `infaris-calendar login link` from an agent or SSH session). " +
374
+ "If this keeps happening, an older infaris-calendar in another worktree " +
375
+ "may share ~/.infaris/calendar and rotate the same session; update or remove it.");
353
376
  }
354
377
  const updated = toCredentials(creds.baseUrl, tokens);
355
378
  // Keep the old refresh token if the server did not send a new one.
@@ -0,0 +1,170 @@
1
+ import { Option } from "commander";
2
+ import { crmFetch } from "./crm-api.js";
3
+ export const RELATION_KINDS = [
4
+ "CLIENT",
5
+ "SUPPLIER",
6
+ "NETWORK",
7
+ "EVENT",
8
+ "EDUCATION",
9
+ ];
10
+ function output(value) {
11
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
12
+ }
13
+ const LEGAL_SUFFIX = /\s*[(,]?\s*(b\.?v\.?|v\.?o\.?f\.?|n\.?v\.?|c\.?v\.?|vof|bv|nv|eenmanszaak)\s*\)?\s*$/i;
14
+ /**
15
+ * Mirrors Support's normalizeRelationName: collapse whitespace and move a
16
+ * trailing legal form such as "(BV)" to the legal name.
17
+ */
18
+ export function tidyName(name, legalName) {
19
+ const collapsed = name.replace(/\s+/g, " ").trim();
20
+ const match = collapsed.match(LEGAL_SUFFIX);
21
+ const stripped = match ? collapsed.slice(0, match.index).trim() : collapsed;
22
+ if (!stripped)
23
+ return { name: collapsed, legalName };
24
+ const form = match?.[1]?.replace(/\./g, "").toUpperCase();
25
+ return {
26
+ name: stripped,
27
+ legalName: legalName ?? (form ? `${stripped} ${form}` : null),
28
+ };
29
+ }
30
+ /** The renames `tidy` would make; empty when every name is already clean. */
31
+ export function planTidy(items) {
32
+ const changes = [];
33
+ for (const item of items) {
34
+ const next = tidyName(item.name, item.legalName ?? null);
35
+ if (next.name === item.name && next.legalName === (item.legalName ?? null))
36
+ continue;
37
+ changes.push({
38
+ relationNumber: item.relationNumber,
39
+ from: item.name,
40
+ ...next,
41
+ });
42
+ }
43
+ return changes;
44
+ }
45
+ function patch(customer, body) {
46
+ return crmFetch(`/relations/${encodeURIComponent(customer)}`, {
47
+ method: "PATCH",
48
+ headers: { "content-type": "application/json" },
49
+ body: JSON.stringify(body),
50
+ });
51
+ }
52
+ export function registerAdminCommands(program) {
53
+ program
54
+ .command("update <customer>")
55
+ .description("Edit a customer's name, contact data, status or kind (pass only what changes)")
56
+ .option("--name <name>")
57
+ .option("--legal-name <name>")
58
+ .option("--email <email>")
59
+ .option("--phone <phone>")
60
+ .option("--website <url>")
61
+ .option("--contact-person <name>")
62
+ .addOption(new Option("--status <status>").choices([
63
+ "PROSPECT",
64
+ "ACTIVE",
65
+ "CHURNED",
66
+ "ARCHIVED",
67
+ ]))
68
+ .addOption(new Option("--kind <kind>").choices(RELATION_KINDS))
69
+ .option("--json", "Machine-readable output (default)")
70
+ .action(async (customer, opts) => {
71
+ const body = {};
72
+ if (opts.name !== undefined)
73
+ body.name = opts.name;
74
+ if (opts.legalName !== undefined)
75
+ body.legalName = opts.legalName;
76
+ if (opts.email !== undefined)
77
+ body.email = opts.email;
78
+ if (opts.phone !== undefined)
79
+ body.phone = opts.phone;
80
+ if (opts.website !== undefined)
81
+ body.website = opts.website;
82
+ if (opts.contactPerson !== undefined)
83
+ body.contactPerson = opts.contactPerson;
84
+ if (opts.status !== undefined)
85
+ body.status = opts.status;
86
+ if (opts.kind !== undefined)
87
+ body.kind = opts.kind;
88
+ if (!Object.keys(body).length)
89
+ throw new Error("Pass at least one field to change");
90
+ output(await patch(customer, body));
91
+ });
92
+ program
93
+ .command("archive <customer>")
94
+ .description("Archive a customer (hidden from list; history stays). Refused for billing or Guard customers")
95
+ .option("--json", "Machine-readable output (default)")
96
+ .action(async (customer) => {
97
+ output(await patch(customer, { status: "ARCHIVED" }));
98
+ });
99
+ program
100
+ .command("merge <duplicate>")
101
+ .description("Merge a duplicate dossier into the leading one: contacts and history move, the duplicate is archived")
102
+ .requiredOption("--into <customer>", "The dossier that stays")
103
+ .option("--yes", "Confirm the merge")
104
+ .option("--json", "Machine-readable output (default)")
105
+ .action(async (duplicate, opts) => {
106
+ if (!opts.yes)
107
+ throw new Error(`Merging moves all contacts and history of ${duplicate} into ${opts.into} and archives ${duplicate}. Repeat with --yes`);
108
+ output(await crmFetch(`/relations/${encodeURIComponent(duplicate)}/merge`, {
109
+ method: "POST",
110
+ headers: { "content-type": "application/json" },
111
+ body: JSON.stringify({ into: opts.into }),
112
+ }));
113
+ });
114
+ program
115
+ .command("contact-delete <customer> <contactId>")
116
+ .description("Delete a contact person; history entries keep the name but lose the link")
117
+ .option("--yes", "Confirm the deletion")
118
+ .action(async (customer, contactId, opts) => {
119
+ if (!opts.yes)
120
+ throw new Error("Repeat with --yes to delete the contact");
121
+ output(await crmFetch(`/relations/${encodeURIComponent(customer)}/contacts/${encodeURIComponent(contactId)}`, { method: "DELETE" }));
122
+ });
123
+ program
124
+ .command("tidy")
125
+ .description("Clean imported company names (line breaks, trailing (BV)/(VOF) moved to the legal name). Dry run unless --apply")
126
+ .option("--apply", "Write the renames")
127
+ .option("--include-archived", "Also tidy archived customers")
128
+ .action(async (opts) => {
129
+ const items = [];
130
+ for (let offset = 0;; offset += 100) {
131
+ const params = new URLSearchParams({
132
+ limit: "100",
133
+ offset: String(offset),
134
+ });
135
+ if (opts.includeArchived)
136
+ params.set("includeArchived", "1");
137
+ const page = (await crmFetch(`/relations?${params}`));
138
+ items.push(...page.items);
139
+ if (offset + 100 >= page.total)
140
+ break;
141
+ }
142
+ const changes = planTidy(items);
143
+ if (!opts.apply) {
144
+ output({ dryRun: true, checked: items.length, changes });
145
+ return;
146
+ }
147
+ const failed = [];
148
+ for (const change of changes) {
149
+ try {
150
+ await patch(change.relationNumber, {
151
+ name: change.name,
152
+ legalName: change.legalName,
153
+ });
154
+ }
155
+ catch (error) {
156
+ failed.push({
157
+ relationNumber: change.relationNumber,
158
+ error: error instanceof Error ? error.message : String(error),
159
+ });
160
+ }
161
+ }
162
+ output({
163
+ applied: changes.length - failed.length,
164
+ checked: items.length,
165
+ failed,
166
+ });
167
+ if (failed.length)
168
+ process.exitCode = 1;
169
+ });
170
+ }
package/dist/crm-api.js CHANGED
@@ -2,6 +2,10 @@ import { getValidCredentials } from "./auth.js";
2
2
  import { infarisEnv } from "./legacy.js";
3
3
  /** CRM shares Calendar's human PKCE login, not its service-to-service key. */
4
4
  export async function crmFetch(path, init = {}) {
5
+ return (await crmFetchRaw(path, init)).json();
6
+ }
7
+ /** As crmFetch, for a binary answer such as a quote PDF. */
8
+ export async function crmFetchRaw(path, init = {}) {
5
9
  const creds = await getValidCredentials();
6
10
  // A development Calendar login must never silently write to production CRM.
7
11
  const configured = infarisEnv("CRM_URL");
@@ -33,5 +37,5 @@ export async function crmFetch(path, init = {}) {
33
37
  const body = (await res.json().catch(() => ({})));
34
38
  throw new Error(`CRM request failed (${res.status}): ${body.error || res.statusText}${res.status === 401 ? ". Run infaris-crm login with an Infaris admin account." : ""}`);
35
39
  }
36
- return res.json();
40
+ return res;
37
41
  }
package/dist/crm-index.js CHANGED
@@ -4,12 +4,14 @@ import { Command, Option } from "commander";
4
4
  import { beginLogin, completeLogin, login, readLoginCode } from "./auth.js";
5
5
  import { clearCredentials, DEFAULT_BASE_URL } from "./config.js";
6
6
  import { crmFetch } from "./crm-api.js";
7
+ import { registerAdminCommands, RELATION_KINDS } from "./crm-admin.js";
8
+ import { registerQuoteCommands } from "./crm-quote.js";
7
9
  import { createTask, addTaskAttachment, listTeamMembers, listTasks, } from "./api.js";
8
10
  import { resolveAttendeeIds } from "./selectors.js";
9
11
  const program = new Command()
10
12
  .name("infaris-crm")
11
- .version("0.10.0")
12
- .description("Customer dossiers, contact people and contact history. Shares infaris-calendar login.");
13
+ .version("0.13.0")
14
+ .description("Customer dossiers, contact people, contact history and quotes. Shares infaris-calendar login.");
13
15
  function output(value) {
14
16
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
15
17
  }
@@ -39,17 +41,35 @@ program
39
41
  program
40
42
  .command("list")
41
43
  .description("Find customers (paginated)")
42
- .option("--search <text>")
44
+ .option("--search <text>", "Matches name, legal name, contact person, website, e-mail and relation number")
45
+ .option("--email <text>", "Find by e-mail address or domain (same as --search)")
46
+ .addOption(new Option("--status <status>").choices([
47
+ "PROSPECT",
48
+ "ACTIVE",
49
+ "CHURNED",
50
+ "ARCHIVED",
51
+ ]))
52
+ .addOption(new Option("--kind <kind>").choices(RELATION_KINDS))
53
+ .option("--include-archived", "Also list archived customers")
43
54
  .option("--limit <number>", "Page size, max 100", "25")
44
55
  .option("--offset <number>", "Page offset", "0")
45
56
  .option("--json", "Machine-readable output (default)")
46
57
  .action(async (opts) => {
58
+ if (opts.search && opts.email)
59
+ throw new Error("Choose --search or --email");
47
60
  const params = new URLSearchParams({
48
61
  limit: opts.limit,
49
62
  offset: opts.offset,
50
63
  });
51
- if (opts.search)
52
- params.set("search", opts.search);
64
+ const search = opts.search ?? opts.email;
65
+ if (search)
66
+ params.set("search", search);
67
+ if (opts.status)
68
+ params.set("status", opts.status);
69
+ if (opts.kind)
70
+ params.set("kind", opts.kind);
71
+ if (opts.includeArchived)
72
+ params.set("includeArchived", "1");
53
73
  output(await crmFetch(`/relations?${params}`));
54
74
  });
55
75
  program
@@ -61,6 +81,9 @@ program
61
81
  .option("--website <url>")
62
82
  .option("--contact-person <name>")
63
83
  .option("--note <text>")
84
+ .addOption(new Option("--kind <kind>", "What the relation is (default CLIENT; use SUPPLIER, NETWORK, EVENT or EDUCATION for non-customers)").choices(RELATION_KINDS))
85
+ .option("--dry-run", "Only report similar existing customers; write nothing")
86
+ .option("--allow-duplicate", "Create even if a customer with the same e-mail, site or name exists")
64
87
  .option("--json", "Machine-readable output (default)")
65
88
  .action(async (opts) => {
66
89
  output(await crmFetch("/relations", {
@@ -73,6 +96,9 @@ program
73
96
  website: opts.website,
74
97
  contactPerson: opts.contactPerson,
75
98
  initialNote: opts.note,
99
+ kind: opts.kind,
100
+ dryRun: opts.dryRun || undefined,
101
+ allowDuplicate: opts.allowDuplicate || undefined,
76
102
  }),
77
103
  }));
78
104
  });
@@ -146,6 +172,7 @@ program
146
172
  ]))
147
173
  .option("--contact <id>", "Customer contact person id")
148
174
  .option("--at <iso>", "When the contact occurred (default now)")
175
+ .option("--source <ref>", "Where the note comes from, for example mail:<message id>")
149
176
  .option("--json", "Machine-readable output (default)")
150
177
  .action(async (customer, opts) => {
151
178
  if (opts.body !== undefined && opts.bodyFile !== undefined)
@@ -166,6 +193,7 @@ program
166
193
  contactMethod: opts.method,
167
194
  outcome: opts.outcome,
168
195
  contactId: opts.contact,
196
+ sourceRef: opts.source,
169
197
  occurredAt: opts.at || new Date().toISOString(),
170
198
  }),
171
199
  }));
@@ -192,6 +220,8 @@ program
192
220
  }),
193
221
  }));
194
222
  });
223
+ registerAdminCommands(program);
224
+ registerQuoteCommands(program);
195
225
  program.parseAsync(process.argv).catch((error) => {
196
226
  process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
197
227
  process.exitCode = 1;
@@ -0,0 +1,174 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { Option } from "commander";
5
+ import { crmFetch, crmFetchRaw } from "./crm-api.js";
6
+ /**
7
+ * `infaris-crm quote`: Guard quotes as DRAFTs in Support, priced from the
8
+ * live Infaris catalogue, with the PDF Support renders. Support owns the
9
+ * numbering, totals and acceptance; this only sends the draft.
10
+ */
11
+ const MAX_LOGO_BYTES = 256 * 1024;
12
+ /** PNG or JPEG file as a data URI; Support renders it on white in the PDF header. */
13
+ export function logoDataUri(path) {
14
+ const bytes = readFileSync(path);
15
+ if (bytes.length > MAX_LOGO_BYTES)
16
+ throw new Error(`Logo ${path} is larger than 256 kB; crop or compress it`);
17
+ const png = bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
18
+ const jpeg = bytes[0] === 0xff && bytes[1] === 0xd8;
19
+ if (!png && !jpeg)
20
+ throw new Error(`Logo ${path} must be a PNG or JPEG (convert an SVG first)`);
21
+ return `data:image/${png ? "png" : "jpeg"};base64,${bytes.toString("base64")}`;
22
+ }
23
+ /**
24
+ * The quote JSON with its logo inlined and an idempotency key: the same file
25
+ * for the same relation always gives the same key, so a repeated command
26
+ * returns the quote it already made instead of a second one.
27
+ */
28
+ export function readQuoteFile(path, overrides = {}) {
29
+ const text = readFileSync(path, "utf8");
30
+ const quote = JSON.parse(text);
31
+ if (!quote || typeof quote !== "object" || Array.isArray(quote))
32
+ throw new Error(`${path} must hold a JSON object`);
33
+ if (overrides.relation)
34
+ quote.relation = overrides.relation;
35
+ if (overrides.organization)
36
+ quote.organization = overrides.organization;
37
+ const relation = typeof quote.relation === "string" ? quote.relation.trim() : "";
38
+ const organization = typeof quote.organization === "string" ? quote.organization.trim() : "";
39
+ // With only the organization, Support uses the relation it is linked to (by its trial).
40
+ if (!relation && !organization)
41
+ throw new Error("Give the relation (--customer) or the organization (--organization)");
42
+ const logo = overrides.logo ?? (typeof quote.logo === "string" && !quote.logo.startsWith("data:") ? resolve(dirname(path), quote.logo) : undefined);
43
+ if (logo)
44
+ quote.logo = logoDataUri(logo);
45
+ quote.key =
46
+ overrides.key ??
47
+ (typeof quote.key === "string" && quote.key
48
+ ? quote.key
49
+ : `cli:${createHash("sha256").update(`${relation || `org:${organization}`}\n${text}`).digest("hex").slice(0, 40)}`);
50
+ return quote;
51
+ }
52
+ const json = (body) => ({
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify(body),
56
+ });
57
+ function output(value) {
58
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
59
+ }
60
+ const enc = encodeURIComponent;
61
+ /** A Support without the quote API answers 404 on its collection routes. */
62
+ async function quoteApi(call) {
63
+ try {
64
+ return await call();
65
+ }
66
+ catch (error) {
67
+ if (error instanceof Error && /\(404\): Not Found$|\(404\): $/.test(error.message))
68
+ throw new Error("Support has no quote API yet (deploy Support with /api/crm/quotes first)");
69
+ throw error;
70
+ }
71
+ }
72
+ export function registerQuoteCommands(program) {
73
+ const quote = program
74
+ .command("quote")
75
+ .description("Guard quotes in Support: draft from the catalogue, PDF, send, decline");
76
+ quote
77
+ .command("catalog")
78
+ .description("Quotable Infaris components with live prices (ids for the quote file)")
79
+ .option("--json", "Machine-readable output (default)")
80
+ .action(async () => output(await quoteApi(() => crmFetch("/quotes/catalog"))));
81
+ quote
82
+ .command("create")
83
+ .description("Create a DRAFT quote from a JSON file; repeating returns the same quote")
84
+ .requiredOption("--file <path>", "Quote JSON (see the guard-quote skill)")
85
+ .option("--customer <relation>", "Relation number or id; leave out to use the relation the organization is linked to")
86
+ .option("--organization <slug>", "Organization the license belongs to (overrides the file)")
87
+ .option("--logo <path>", "Customer logo, PNG or JPEG on white")
88
+ .option("--key <key>", "Idempotency key (default: derived from relation and file)")
89
+ .option("--json", "Machine-readable output (default)")
90
+ .action(async (opts) => {
91
+ const body = readQuoteFile(opts.file, {
92
+ relation: opts.customer,
93
+ organization: opts.organization,
94
+ key: opts.key,
95
+ logo: opts.logo,
96
+ });
97
+ output(await quoteApi(() => crmFetch("/quotes", json(body))));
98
+ });
99
+ quote
100
+ .command("update <number>")
101
+ .description("Replace the lines and texts of a DRAFT quote")
102
+ .requiredOption("--file <path>", "Quote JSON")
103
+ .option("--customer <relation>")
104
+ .option("--organization <slug>")
105
+ .option("--logo <path>")
106
+ .option("--json", "Machine-readable output (default)")
107
+ .action(async (number, opts) => {
108
+ const body = readQuoteFile(opts.file, {
109
+ relation: opts.customer,
110
+ organization: opts.organization,
111
+ logo: opts.logo,
112
+ });
113
+ output(await crmFetch(`/quotes/${enc(number)}`, { ...json(body), method: "PUT" }));
114
+ });
115
+ quote
116
+ .command("show <number>")
117
+ .description("Status, totals, lines and the --components value for the trial")
118
+ .option("--json", "Machine-readable output (default)")
119
+ .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}`)));
120
+ quote
121
+ .command("list <customer>")
122
+ .description("Quotes of a relation, newest first")
123
+ .option("--json", "Machine-readable output (default)")
124
+ .action(async (customer) => output(await crmFetch(`/quotes?${new URLSearchParams({ relation: customer })}`)));
125
+ quote
126
+ .command("pdf <number>")
127
+ .description("Download the PDF Support renders for the quote")
128
+ .requiredOption("--out <path>", "Where to write the PDF")
129
+ .action(async (number, opts) => {
130
+ const res = await crmFetchRaw(`/quotes/${enc(number)}/pdf`);
131
+ if (!res.headers.get("content-type")?.includes("application/pdf"))
132
+ throw new Error("Support did not return a PDF");
133
+ const bytes = Buffer.from(await res.arrayBuffer());
134
+ writeFileSync(opts.out, bytes);
135
+ output({ pdf: resolve(opts.out), bytes: bytes.length });
136
+ });
137
+ quote
138
+ .command("send <number>")
139
+ .description("Record the quote as SENT after confirmed sending; this command does not send email")
140
+ .option("--json", "Machine-readable output (default)")
141
+ .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}/send`, json({}))));
142
+ quote
143
+ .command("accept <number>")
144
+ .description("Record the customer's acceptance, as on the quote page; starts the license and billing in Infaris")
145
+ .requiredOption("--by <name>", "Who agreed on behalf of the customer")
146
+ .addOption(new Option("--via <channel>", "How the customer agreed")
147
+ .choices(["email", "signed_pdf", "verbal"])
148
+ .makeOptionMandatory())
149
+ .addOption(new Option("--variant <variant>", "base (Guard) or option (e.g. Guard met support); required with an option").choices([
150
+ "base",
151
+ "option",
152
+ ]))
153
+ .option("--document-url <url>", "https link to the signed copy or the acceptance mail")
154
+ .option("--dpa-signed", "The data processing agreement is signed")
155
+ .option("--yes", "Confirm: this starts real billing")
156
+ .option("--json", "Machine-readable output (default)")
157
+ .action(async (number, opts) => {
158
+ if (!opts.yes)
159
+ throw new Error("Accepting starts the license and billing in Infaris. Only with the customer's confirmed acceptance, then repeat with --yes.");
160
+ output(await crmFetch(`/quotes/${enc(number)}/accept`, json({
161
+ by: opts.by,
162
+ via: opts.via,
163
+ variant: opts.variant,
164
+ documentUrl: opts.documentUrl,
165
+ dpaSigned: Boolean(opts.dpaSigned),
166
+ confirm: true,
167
+ })));
168
+ });
169
+ quote
170
+ .command("decline <number>")
171
+ .description("Record that the customer declined")
172
+ .option("--json", "Machine-readable output (default)")
173
+ .action(async (number) => output(await crmFetch(`/quotes/${enc(number)}/decline`, json({}))));
174
+ }
package/dist/index.js CHANGED
@@ -25,7 +25,7 @@ const program = new Command();
25
25
  program
26
26
  .name("infaris-calendar")
27
27
  .description("Calendar CLI: agenda, tasks, mail drafts, and the urenstaat (hours).")
28
- .version("0.10.0");
28
+ .version("0.13.0");
29
29
  const loginCmd = program
30
30
  .command("login")
31
31
  .description("Sign in with Infaris in your browser and store a token")
@@ -866,6 +866,23 @@ function formatBytes(bytes) {
866
866
  ? `${(bytes / 1024 / 1024).toFixed(1)} MB`
867
867
  : `${Math.max(1, Math.round(bytes / 1024))} kB`;
868
868
  }
869
+ function escapeHtml(value) {
870
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
871
+ }
872
+ /** "Files:" for real attachments, "Inline:" for images in the text (older servers: names only). */
873
+ function describeAttachments(list) {
874
+ const files = list.map((a) => typeof a === "string" ? { filename: a, inline: false, label: a } : {
875
+ filename: a.filename,
876
+ inline: a.inline,
877
+ label: `${a.filename} (${a.contentType}, ${formatBytes(a.size)})`,
878
+ });
879
+ const attached = files.filter((f) => !f.inline).map((f) => f.label);
880
+ const inline = files.filter((f) => f.inline).map((f) => f.label);
881
+ return [
882
+ attached.length ? `Files: ${attached.join(", ")}` : "",
883
+ inline.length ? `Inline: ${inline.join(", ")}` : "",
884
+ ];
885
+ }
869
886
  mail
870
887
  .command("draft")
871
888
  .description([
@@ -892,6 +909,10 @@ mail
892
909
  .option("--source-mailbox <id>", "Mailbox id or address of the original (default: the draft mailbox)")
893
910
  .option("--no-forward-attachments", "Forward without the original attachments")
894
911
  .option("--replace <uid>", "Replace this existing draft in Concepten", parseUid)
912
+ .option("--edit <uid>", "Change this draft in place: only what you pass changes. New --body/--body-file replaces the text above the signature; recipients, subject, thread, signature, quote and attachments stay unless given; --attach adds files", parseUid)
913
+ .option("--mailbox <id>", "Mailbox (id, address or alias) of the draft to --edit")
914
+ .option("--drop-attachments", "With --edit: remove the draft's existing attachments")
915
+ .option("--note <text>", "Private note for whoever reviews the draft (what it is based on, what to check); shown in Calendar, never sent along")
895
916
  .option("--dry-run", "Check recipients, images and attachments without saving")
896
917
  .option("--preview <file.html>", "Write the body (images inline) to an HTML file to look at; implies --dry-run")
897
918
  .option("--no-inline-remote", "Keep https:// images as links instead of embedding them")
@@ -920,6 +941,10 @@ mail
920
941
  replace: opts.replace,
921
942
  inlineRemote: opts.inlineRemote,
922
943
  optimizeImages: opts.optimizeImages,
944
+ edit: opts.edit,
945
+ mailbox: opts.mailbox,
946
+ dropAttachments: opts.dropAttachments,
947
+ note: opts.note,
923
948
  }, process.cwd());
924
949
  for (const message of built.warnings)
925
950
  warn(message);
@@ -943,7 +968,7 @@ mail
943
968
  }
944
969
  });
945
970
  function printDraft(draft) {
946
- ok(`Draft ${draft.replaced ? `replaced (was ${draft.replaced}) ` : ""}saved in ${draft.folder} of ${draft.mailbox} (from ${draft.from})`);
971
+ ok(`Draft ${draft.edited ? `edited (was ${draft.edited}) ` : draft.replaced ? `replaced (was ${draft.replaced}) ` : ""}saved in ${draft.folder} of ${draft.mailbox} (from ${draft.from})`);
947
972
  const lines = [
948
973
  `To: ${draft.to.join(", ") || "-"}`,
949
974
  draft.cc.length ? `Cc: ${draft.cc.join(", ")}` : "",
@@ -955,7 +980,8 @@ function printDraft(draft) {
955
980
  draft.attachments.length
956
981
  ? `Files: ${draft.attachments.map((a) => `${a.filename} (${formatBytes(a.size)})`).join(", ")}`
957
982
  : "",
958
- draft.signature ? "" : "Signature: none",
983
+ draft.signature || draft.edited ? "" : "Signature: none",
984
+ draft.note ? `Note: ${draft.note}` : "",
959
985
  draft.url,
960
986
  ].filter(Boolean);
961
987
  process.stdout.write(lines.map((line) => ` ${line}\n`).join(""));
@@ -1101,7 +1127,7 @@ mail
1101
1127
  }
1102
1128
  process.stdout.write(`${list.folder} of ${list.mailbox}: ${list.total} draft(s)\n`);
1103
1129
  for (const d of list.drafts) {
1104
- process.stdout.write(` ${String(d.uid).padStart(6)} ${d.date?.slice(0, 16).replace("T", " ") ?? ""} ${d.to || "-"} ${d.subject}${d.hasAttachments ? " [bijlage]" : ""}\n`);
1130
+ process.stdout.write(` ${String(d.uid).padStart(6)} ${d.date?.slice(0, 16).replace("T", " ") ?? ""} ${d.to || "-"} ${d.subject}${d.hasAttachments ? " [bijlage]" : ""}${d.agentDraft ? " [agent]" : ""}\n`);
1105
1131
  }
1106
1132
  }
1107
1133
  catch (err) {
@@ -1328,6 +1354,7 @@ mail
1328
1354
  .option("--folder <path>", "Folder", "INBOX")
1329
1355
  .option("--drafts", "Read from Concepten (e.g. the uid `mail draft` returned)")
1330
1356
  .option("--sent", "Read from Verzonden")
1357
+ .option("--preview <file.html>", "Also write the message as the recipient sees it (signature and inline images included) to an HTML file, to render and look at")
1331
1358
  .option("--json", "Output as JSON")
1332
1359
  .action(async (uid, opts) => {
1333
1360
  try {
@@ -1335,9 +1362,18 @@ mail
1335
1362
  mailbox: opts.mailbox,
1336
1363
  folder: opts.folder,
1337
1364
  kind: opts.drafts ? "drafts" : opts.sent ? "sent" : undefined,
1365
+ preview: Boolean(opts.preview),
1338
1366
  });
1367
+ const { previewHtml, ...rest } = message;
1368
+ if (opts.preview) {
1369
+ if (!previewHtml) {
1370
+ throw new Error("This Calendar server does not support --preview yet");
1371
+ }
1372
+ writeFileSync(opts.preview, `<!doctype html><meta charset="utf-8"><title>${escapeHtml(rest.subject)}</title>${previewHtml}`);
1373
+ process.stderr.write(`Preview: ${resolvePath(opts.preview)}\n`);
1374
+ }
1339
1375
  if (opts.json) {
1340
- process.stdout.write(`${JSON.stringify({ ...where, message }, null, 2)}\n`);
1376
+ process.stdout.write(`${JSON.stringify({ ...where, message: rest }, null, 2)}\n`);
1341
1377
  return;
1342
1378
  }
1343
1379
  const head = [
@@ -1350,9 +1386,9 @@ mail
1350
1386
  message.signatureCount !== undefined
1351
1387
  ? `Signatures: ${message.signatureCount}`
1352
1388
  : "",
1353
- message.attachments.length
1354
- ? `Files: ${message.attachments.join(", ")}`
1355
- : "",
1389
+ message.agentDraft ? "Staged: by an agent" : "",
1390
+ message.note ? `Note: ${message.note}` : "",
1391
+ ...describeAttachments(message.attachments),
1356
1392
  ].filter(Boolean);
1357
1393
  process.stdout.write(`${head.join("\n")}\n\n${message.body}\n`);
1358
1394
  }
@@ -213,6 +213,12 @@ export async function buildDraft(spec, baseDir, deps = {}) {
213
213
  if ([reply, replyAll, forward].filter(Boolean).length > 1) {
214
214
  throw new Error("Use only one of reply, replyAll or forward");
215
215
  }
216
+ const edit = positiveUid(spec.edit, "edit");
217
+ if (edit && (reply || replyAll || forward || spec.replace !== undefined)) {
218
+ throw new Error("edit does not combine with reply, replyAll, forward or replace");
219
+ }
220
+ // Bij edit blijft de tekst staan tenzij je nieuwe tekst of plaatjes meegeeft.
221
+ const newText = spec.body !== undefined || spec.bodyFile !== undefined || (spec.images?.length ?? 0) > 0;
216
222
  let source = spec.body ?? "";
217
223
  let bodyDir = baseDir;
218
224
  if (spec.bodyFile === "-") {
@@ -270,7 +276,7 @@ export async function buildDraft(spec, baseDir, deps = {}) {
270
276
  cc: addressList(spec.cc),
271
277
  bcc: addressList(spec.bcc),
272
278
  subject: spec.subject,
273
- html,
279
+ html: edit && !newText ? undefined : html,
274
280
  fromAddress: spec.from,
275
281
  signature: spec.signature ?? true,
276
282
  optimizeImages: spec.optimizeImages ?? true,
@@ -282,8 +288,12 @@ export async function buildDraft(spec, baseDir, deps = {}) {
282
288
  ? { ...ref, uid: forward, attachments: spec.forwardAttachments ?? true }
283
289
  : undefined,
284
290
  replaceUid: positiveUid(spec.replace, "replace"),
291
+ editUid: edit,
292
+ mailbox: spec.mailbox,
293
+ dropAttachments: spec.dropAttachments || undefined,
294
+ note: spec.note,
285
295
  };
286
- if (!input.to?.length && !input.replyTo) {
296
+ if (!input.to?.length && !input.replyTo && !edit) {
287
297
  warnings.push("No recipient: the draft is saved without To");
288
298
  }
289
299
  return { input, html, images, totalBytes, warnings };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infaris/calendar-cli",
3
- "version": "0.10.0",
3
+ "version": "0.13.0",
4
4
  "description": "Command line interface for Calendar by Infaris: log in once on your device, read your agenda, manage work tasks, and fill the urenstaat from tasks, commits and PRs.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",