Public: anyone can read this; the crew can change it.

Download every lead and its status as a spreadsheet the agent can open in Excel or import into their CRM #40

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/speed-to-lead:mason/36-download-every-lead-and-its-status-as-a → main 3 commits fork 3 threads · 3 unresolved

  • Merged. mason/36-download-every-lead-and-its-status-as-a was merged into main as c9ea383.

Review

Sign in to review this change.
15 files changed +458 −8
README.md +11 −1
@@ -276,7 +276,7 @@ like, but only as someone the forge has signed in — an unsigned scheduled
276276 job gets "sign in first". Nothing depends on it: the app does the same
277277 itself every hour. The whole API is described at `/openapi.json`, and the same
278278 actions are MCP tools at `POST /mcp` (`list_leads`, `get_lead`, `add_lead`,
279 `send_reply`, `mark_lead`).
279 `send_reply`, `mark_lead`, `export_leads`).
280280
281281 ## From a terminal
282282
@@ -291,6 +291,7 @@ On the desk:
291291 phone, source as a number, what they asked, consent `y` or `n`).
292292 - `f` cycles the views (needs you, in follow-up, closed, all); the desk
293293 shows the current one with its count.
294 - `x` shows the leads as CSV for the current view and search.
294295 - `R` restarts the sample leads from now (admins only; asks first).
295296 - `esc` leaves.
296297
@@ -309,6 +310,15 @@ until you press a key on this screen:
309310 - `D` removes the lead (admins only; asks first).
310311 - `esc` goes back to the desk.
311312
313 ## Taking your leads with you
314
315 Every lead and its status, as a spreadsheet, for whoever may list leads, with no cap on the count:
316
317 - **Desk:** the "Download leads (CSV)" link under the list; it keeps the current view and search. **HTTP:** `GET /leads.csv[?show=needs|open|closed|all][&q=…]` (anon gets 401). The response is `no-store`.
318 - **MCP:** the `export_leads` tool (`show`, `q`) returns `{ name, csv, count }`. **Terminal:** `x` on the desk shows the CSV for the current view and search on screen (`esc` goes back); download the file from the web desk.
319
320 Columns: name, email, phone, source, status, arrived at, first reply at, minutes to first reply, last message at (the later of a message sent and a reply from the lead), texts allowed. Times are ISO 8601. A field starting with `=`, `@`, `-`, `+`, tab or carriage return is prefixed with `'` so a spreadsheet never runs it as a formula; the one exception is a phone number written like `+1 206-555-0101` (a plus, then digits and the usual marks), which is kept as typed.
321
312322 ## Running it
313323
314324 ```sh
contract/openapi.json +53
@@ -152,6 +152,59 @@
152152 }
153153 }
154154 },
155 "/leads.csv": {
156 "get": {
157 "summary": "Every lead and its status as a spreadsheet (CSV), narrowed like the desk by show and q, with no cap on the count.",
158 "operationId": "getLeadsCsv",
159 "parameters": [
160 {
161 "name": "show",
162 "in": "query",
163 "schema": {
164 "enum": [
165 "needs",
166 "open",
167 "closed",
168 "all"
169 ],
170 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value)."
171 }
172 },
173 {
174 "name": "q",
175 "in": "query",
176 "schema": {
177 "type": "string",
178 "maxLength": 80,
179 "description": "Narrow the desk to leads whose name or email holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters."
180 }
181 }
182 ],
183 "responses": {
184 "200": {
185 "description": "Every lead and its status as a spreadsheet (CSV), narrowed like the desk by show and q, with no cap on the count.",
186 "content": {
187 "text/csv": {
188 "schema": {
189 "type": "string",
190 "description": "RFC 4180 CSV with a header row."
191 }
192 }
193 }
194 },
195 "default": {
196 "description": "{ error, message }: why not",
197 "content": {
198 "application/json": {
199 "schema": {
200 "$ref": "#/components/schemas/Error"
201 }
202 }
203 }
204 }
205 }
206 }
207 },
155208 "/leads/{id}": {
156209 "get": {
157210 "summary": "One lead, with every message: sent, drafted, and the follow-ups to come. Ask for application/json.",
src/actions.ts +25
@@ -7,6 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { csvName, leadsCsv } from "./export.ts";
1011 import { record, type Act, type AuditRow } from "./audit.ts";
1112 import { MAX_NOTE, outcomeOf } from "./calls.ts";
1213 import { permit } from "./contract.ts";
@@ -27,6 +28,7 @@ import {
2728 MAX_INBOUND,
2829 MAX_QUERY,
2930 insertLead,
31 lastMessages,
3032 updateContact,
3133 optOut,
3234 nextNeeding,
@@ -126,6 +128,29 @@ export function listLeads(
126128 });
127129 }
128130
131 /**
132 * Every lead the desk would show for `show` and `q`, as a spreadsheet: all of
133 * them, however many, under the same gate as the desk.
134 */
135 export function exportLeads(
136 db: Database,
137 who: Who,
138 input: { show?: unknown; q?: unknown; now?: Date } = {},
139 ): Result<{ name: string; csv: string; count: number }> {
140 if (permit(who, "lead", "list") !== "yes")
141 return refuse(who, "Sign in to take your leads.", "You may not take the leads.");
142 const q = queryOf(input.q);
143 if (q === undefined)
144 return fail("invalid", `A search is plain text, up to ${MAX_QUERY} characters.`);
145 const show = viewOf(input.show);
146 const leads = desk(db, -1, q).filter((l) => inView(l, show));
147 return ok({
148 name: csvName(input.now ?? new Date()),
149 csv: leadsCsv(leads, lastMessages(db)),
150 count: leads.length,
151 });
152 }
153
129154 /**
130155 * One lead, for `who` to do `verb` to. The door is asked before the row is
131156 * looked for, so whoever may not is told that and never learns whether the
src/contract.test.ts +7 −1
@@ -12,6 +12,7 @@ import {
1212 addLead,
1313 addSampleInquiry,
1414 deleteLead,
15 exportLeads,
1516 editLead,
1617 getAudit,
1718 getLead,
@@ -97,7 +98,12 @@ const doors: Record<
9798 expect(addSampleInquiry(db, who).ok).toBe(added);
9899 return added;
99100 },
100 list: (who) => listLeads(db, who).ok,
101 // The spreadsheet is the same cell through its own door (GET /leads.csv, the MCP tool export_leads, `x` in the terminal).
102 list: (who) => {
103 const listed = listLeads(db, who).ok;
104 expect(exportLeads(db, who).ok).toBe(listed);
105 return listed;
106 },
101107 read: (who, authorId) => getLead(db, who, { id: aLead(authorId) }).ok,
102108 update: (who, authorId) => {
103109 // Logging what a lead wrote back is the same cell, through its own door
src/export.test.ts added +182
@@ -0,0 +1,182 @@
1 /** Leads as a spreadsheet: the columns, the quoting, the formula guard, who may, and the narrowing. */
2 import { afterAll, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { exportLeads } from "./actions.ts";
7 import { COLUMNS, csvName, field, leadsCsv } from "./export.ts";
8 import { desk, insertLead, lastMessages, recordInbound } from "./leads.ts";
9 import { agent } from "./env.ts";
10 import { openDb } from "./db.ts";
11 import { seed } from "./sample.ts";
12 import { serve } from "./server.ts";
13 import { sign } from "./who.ts";
14
15 const KEY = "a-key-only-the-forge-holds";
16 const dir = mkdtempSync(join(tmpdir(), "app-export-"));
17 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
18 const base = `http://${server.hostname}:${server.port}`;
19 afterAll(() => server.stop(true));
20 const alice = (() => {
21 const identity = `u1|alice|user|${Date.now() + 600_000}`;
22 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
23 })();
24
25 /** RFC 4180 reader, to prove what the writer wrote comes back. */
26 const parse = (text: string): string[][] => {
27 const rows: string[][] = [];
28 let row: string[] = [];
29 let cell = "";
30 let quoted = false;
31 for (let i = 0; i < text.length; i++) {
32 const ch = text[i]!;
33 if (quoted) {
34 if (ch === '"' && text[i + 1] === '"') (cell += '"'), i++;
35 else if (ch === '"') quoted = false;
36 else cell += ch;
37 } else if (ch === '"') quoted = true;
38 else if (ch === ",") (row.push(cell), (cell = ""));
39 else if (ch === "\r" && text[i + 1] === "\n") (row.push(cell), rows.push(row), (row = []), (cell = ""), i++);
40 else cell += ch;
41 }
42 return rows;
43 };
44
45 const get = (path: string, who: Record<string, string> = alice) => fetch(base + path, { headers: who });
46
47 test("the download has the header, one row per lead, and the file headers", async () => {
48 const res = await get("/leads.csv");
49 expect(res.status).toBe(200);
50 expect(res.headers.get("content-type")).toBe("text/csv; charset=utf-8");
51 expect(res.headers.get("content-disposition")).toMatch(/^attachment; filename="leads-\d{4}-\d{2}-\d{2}\.csv"$/);
52 expect(res.headers.get("cache-control")).toBe("no-store");
53 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
54 expect(res.headers.get("content-security-policy")).toBeTruthy();
55 const rows = parse(await res.text());
56 expect(rows[0]).toEqual([...COLUMNS]);
57 const all = await (await get("/leads")).json();
58 expect(rows.length).toBe(1 + all.leads.length);
59 expect(all.leads.length).toBe(12);
60 expect(rows[1]!.length).toBe(COLUMNS.length);
61 expect(["yes", "no"]).toContain(rows[1]![9]!);
62 expect(["open", "qualified", "lost"]).toContain(rows[1]![4]!);
63 });
64
65 test("anon cannot download", async () => {
66 const res = await get("/leads.csv", {});
67 expect(res.status).toBe(401);
68 expect(res.headers.get("content-type")).not.toContain("csv");
69 });
70
71 test("show and q narrow the rows", async () => {
72 const all = parse(await (await get("/leads.csv")).text()).length - 1;
73 const closed = parse(await (await get("/leads.csv?show=closed")).text()).length - 1;
74 expect(closed).toBeLessThan(all);
75 const maria = parse(await (await get("/leads.csv?q=maria")).text());
76 expect(maria.length).toBe(2);
77 expect(maria[1]![0]).toBe("Maria Gonzalez");
78 });
79
80 test("a name with a comma, a quote and a newline round-trips", () => {
81 const db = openDb(mkdtempSync(join(tmpdir(), "app-export-db-")));
82 seed(db, new Date());
83 const lead = { ...desk(db, 1)[0]!, name: 'Smith, "Jo"\nJr' };
84 const rows = parse(leadsCsv([lead], new Map()));
85 expect(rows[1]![0]).toBe('Smith, "Jo"\nJr');
86 });
87
88 test("a field a spreadsheet would run is made text", () => {
89 for (const bad of ["=1+1", "+1 206", "-2", "@SUM(A1)", "\tx", "\rx"])
90 expect(field(bad).replace(/^"|"$/g, "")).toStartWith("'");
91 expect(field("=cmd")).toBe("'=cmd");
92 expect(field("plain")).toBe("plain");
93 });
94
95 test("a normal international phone survives; a plus that is not a phone does not", () => {
96 expect(field("+1 206-555-0101", true)).toBe("+1 206-555-0101");
97 expect(field("+44 (0) 20.7946.0000", true)).toBe("+44 (0) 20.7946.0000");
98 expect(field("+1 206", false)).toBe("'+1 206");
99 expect(field("+1+cmd|' /C calc'!A0", true)).toBe("'+1+cmd|' /C calc'!A0");
100 expect(field("-5", true)).toBe("'-5");
101 expect(field("=1+1", true)).toBe("'=1+1");
102 const db = openDb(mkdtempSync(join(tmpdir(), "app-export-db-")));
103 seed(db, new Date());
104 const lead = { ...desk(db, 1)[0]!, phone: "+1 206 555 0101" };
105 expect(parse(leadsCsv([lead], new Map()))[1]![2]).toBe("+1 206 555 0101");
106 });
107
outdated

This assertion proves nothing. Seed a sent message and an inbound reply, then assert the latest timestamp.

108 test("last message is the later of a sent message and a reply, whichever it is", () => {
109 const db = openDb(mkdtempSync(join(tmpdir(), "app-export-db-")));
110 const add = (name: string): number =>
111 insertLead(db, { name, email: "[email protected]", phone: "", source: "website", message: "Hi", consent: false }, "2026-11-01T09:00:00.000Z", agent);
112 const sentLater = add("A");
113 const repliedLater = add("B");
114 const quiet = add("C");
115 const sent = (id: number, at: string) =>
116 db.query("UPDATE message SET status = 'sent', sent_at = ?1 WHERE lead_id = ?2 AND day = 0").run(at, id);
117 const lead = (id: number) => desk(db, -1).find((l) => l.id === id)!;
118 sent(sentLater, "2026-11-01T12:00:00.000Z");
119 recordInbound(db, lead(sentLater), "email", "earlier reply", "2026-11-01T10:00:00.000Z", agent);
120 sent(repliedLater, "2026-11-01T10:00:00.000Z");
121 recordInbound(db, lead(repliedLater), "email", "later reply", "2026-11-01T13:00:00.000Z", agent);
122 const last = lastMessages(db);
123 expect(last.get(sentLater)).toBe("2026-11-01T12:00:00.000Z");
124 expect(last.get(repliedLater)).toBe("2026-11-01T13:00:00.000Z");
125 expect(last.has(quiet)).toBe(false);
126 });
127
128 test("every matching lead is exported, past 500", () => {
129 const db = openDb(mkdtempSync(join(tmpdir(), "app-export-db-")));
130 for (let i = 0; i < 520; i++)
131 insertLead(db, { name: `Lead ${i}`, email: `l${i}@example.com`, phone: "", source: "website", message: "Hi", consent: false }, "2026-11-01T09:00:00.000Z", agent);
132 const out = exportLeads(db, { role: "user", id: "u1", name: "alice" });
133 expect(out.ok && out.value.count).toBe(520);
134 expect(out.ok && parse(out.value.csv).length).toBe(521);
135 });
136
137 test("the action gates like the desk: anon is refused, a bad search is invalid", () => {
138 const db = openDb(mkdtempSync(join(tmpdir(), "app-export-db-")));
139 const anon = exportLeads(db, { role: "anon" });
140 expect(!anon.ok && anon.error).toBe("signin_required");
141 const bad = exportLeads(db, { role: "user", id: "u1", name: "alice" }, { q: "x".repeat(500) });
142 expect(!bad.ok && bad.error).toBe("invalid");
143 });
144
145 test("the MCP tool exports as the caller", async () => {
146 const call = (who: Record<string, string>) =>
147 fetch(base + "/mcp", {
148 method: "POST",
149 headers: { "content-type": "application/json", ...who },
150 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "export_leads", arguments: { q: "maria" } } }),
151 }).then((r) => r.json() as Promise<any>);
152 const ok = await call(alice);
153 const out = JSON.parse(ok.result.content[0].text);
154 expect(out.count).toBe(1);
155 expect(out.csv).toContain("Maria Gonzalez");
156 const refused = await call({});
157 expect(refused.result.isError).toBe(true);
158 });
159
160 test("minutes to first reply, texts allowed, and last message", () => {
161 const db = openDb(mkdtempSync(join(tmpdir(), "app-export-db-")));
162 seed(db, new Date());
163 const base = desk(db, 1)[0]!;
164 const lead = { ...base, created_at: "2026-11-02T10:00:00.000Z", replied_at: "2026-11-02T10:03:00.000Z", consent: true };
165 const row = parse(leadsCsv([lead], new Map([[lead.id, "2026-11-02T11:00:00.000Z"]])))[1]!;
166 expect(row.slice(5)).toEqual([
167 "2026-11-02T10:00:00.000Z",
168 "2026-11-02T10:03:00.000Z",
169 "3",
170 "2026-11-02T11:00:00.000Z",
171 "yes",
172 ]);
173 const waiting = parse(leadsCsv([{ ...lead, replied_at: null, consent: false }], new Map()))[1]!;
174 expect(waiting.slice(6)).toEqual(["", "", "", "no"]);
175 expect(csvName(new Date("2026-11-02T08:00:00Z"))).toBe("leads-2026-11-02.csv");
176 });
177
178 test("the desk links to the download, with its view and search", async () => {
179 const page = await (await get("/?show=closed&q=a")).text();
180 expect(page).toContain('href="/leads.csv?show=closed&amp;q=a"');
181 expect(await (await get("/")).text()).toContain('href="/leads.csv"');
182 });
src/export.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * Leads out as a spreadsheet: plain rows in, one CSV string out (RFC 4180).
3 * A field a spreadsheet would run as a formula is made text first.
4 */
5
6 import { between } from "./clock.ts";
7 import type { DeskLead } from "./leads.ts";
8
9 export const COLUMNS = [
10 "name",
11 "email",
12 "phone",
13 "source",
14 "status",
15 "arrived at",
16 "first reply at",
17 "minutes to first reply",
18 "last message at",
19 "texts allowed",
20 ] as const;
21
22 /** An international number, "+1 206-555-0101": a plus and then only digits and the marks people type. */
23 const PHONE = /^\+[\d\s().-]+$/;
24
25 /**
26 * One field: made inert if it starts like a formula, quoted if it needs it.
outdated

A leading + or - gets an apostrophe, so real phone numbers like +1 206... are altered in the CRM import. Exempt phone-shaped values.

27 * A phone number keeps its plus (`phone`), so a CRM imports it as typed;
28 * anything else after the plus is still guarded.
29 */
30 export function field(value: string, phone = false): string {
31 const safe = /^[=+\-@\t\r]/.test(value) && !(phone && PHONE.test(value)) ? `'${value}` : value;
32 return /[",\r\n]/.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
33 }
34
35 /** A lead's state as the agent thinks of it. */
36 const statusOf = (lead: DeskLead): string =>
37 lead.state === "qualified" || lead.state === "lost" ? lead.state : "open";
38
39 /**
40 * Every lead as a row under the header. `lastMessageAt` is when each lead
41 * last had a message sent or wrote back, by lead id.
42 */
43 export function leadsCsv(
44 leads: readonly DeskLead[],
45 lastMessageAt: ReadonlyMap<number, string>,
46 ): string {
47 const rows = leads.map((lead) => [
48 lead.name,
49 lead.email,
50 lead.phone,
51 lead.source,
52 statusOf(lead),
53 lead.created_at,
54 lead.replied_at ?? "",
55 lead.replied_at === null
56 ? ""
57 : String(Math.max(0, Math.round(between(lead.created_at, lead.replied_at) / 60_000))),
58 lastMessageAt.get(lead.id) ?? "",
59 lead.consent ? "yes" : "no",
60 ]);
61 return [COLUMNS, ...rows].map((row) => row.map((v, i) => field(v, COLUMNS[i] === "phone")).join(",")).join("\r\n") + "\r\n";
62 }
63
64 /** The file's name for a day: leads-2026-11-02.csv. */
65 export const csvName = (now: Date): string => `leads-${now.toISOString().slice(0, 10)}.csv`;
src/leads.ts +13
@@ -758,3 +758,16 @@ export const removeLead = (db: Database, id: number): void => {
758758 export const clearLeads = (db: Database): void => {
759759 db.exec("DELETE FROM lead");
760760 };
761
762 /** When each lead last had a message go out or wrote back, by lead id. */
763 export function lastMessages(db: Database): Map<number, string> {
764 const rows = db
765 .query<{ lead_id: number; at: string }, []>(
766 `SELECT lead_id, max(at) AS at FROM (
767 SELECT lead_id, sent_at AS at FROM message WHERE sent_at IS NOT NULL
768 UNION ALL SELECT lead_id, at FROM inbound
769 ) GROUP BY lead_id`,
770 )
771 .all();
772 return new Map(rows.map((r) => [r.lead_id, r.at]));
773 }
src/mcp.ts +14
@@ -10,6 +10,7 @@ import type { Database } from "bun:sqlite";
1010 import {
1111 addLead,
1212 addSampleInquiry,
13 exportLeads,
1314 getLead,
1415 getProfile,
1516 listLeads,
@@ -72,6 +73,19 @@ export const tools: readonly Tool[] = [
7273 q: args.q,
7374 }),
7475 },
76 {
77 name: "export_leads",
78 description:
79 "Every lead and its status as CSV text (RFC 4180, header row first, times in ISO 8601), all of them with no cap, optionally only one view or a search. Returns { name, csv, count }.",
80 inputSchema: {
81 type: "object",
82 properties: {
83 show: { enum: [...VIEWS], description: VIEW_HELP },
84 q: { type: "string", maxLength: 80, description: Q_HELP },
85 },
86 },
87 run: (db, who, args) => exportLeads(db, who, { show: args.show, q: args.q }),
88 },
7589 {
7690 name: "get_lead",
7791 description: "One lead with every message: sent, drafted and upcoming.",
src/openapi.ts +4 −4
@@ -48,15 +48,15 @@ const within = (schema: Schema): Schema =>
4848 : value,
4949 ]),
5050 );
51 const content = (schema: Schema) => ({
52 "application/json": { schema: named(schema) },
51 const content = (schema: Schema, media = "application/json") => ({
52 [media]: { schema: named(schema) },
5353 });
5454
5555 export function openapi(): Record<string, unknown> {
5656 const paths: Record<string, Record<string, unknown>> = {};
5757 for (const route of routes) {
5858 if (route.api === undefined) continue;
59 const { summary, body, answer, status, query } = route.api;
59 const { summary, body, answer, status, query, media } = route.api;
6060 const path = route.path.replace(/:(\w+)/g, "{$1}");
6161 const params = [...route.path.matchAll(/:(\w+)/g)].map(([, name]) => ({
6262 name,
@@ -91,7 +91,7 @@ export function openapi(): Record<string, unknown> {
9191 responses: {
9292 [String(status ?? 200)]: {
9393 description: summary,
94 content: content(answer),
94 content: content(answer, media),
9595 },
9696 default: {
9797 description: "{ error, message }: why not",
src/pages/desk.ts +4
@@ -82,6 +82,7 @@ export function deskPage(input: {
8282 ${search}
8383 ${views}
8484 ${list}
85 <p class="export"><a href="${escape(exportHref(show, q))}" download>Download leads (CSV)</a></p>
8586 </div>
8687 ${input.mayAdd ? `<form class="reset" method="post" action="/sample/inquiry"><button class="button button-quiet">Bring in a new inquiry</button></form>${addForm}` : ""}
8788 ${
@@ -122,6 +123,9 @@ const viewHref = (view: View, q: string): string => {
122123 return query === "" ? "/" : `/?${query}`;
123124 };
124125
126 const exportHref = (view: View, q: string): string =>
127 viewHref(view, q).replace(/^\/\??/, "/leads.csv?").replace(/\?$/, "");
128
125129 const VIEW_LABEL: readonly (readonly [View, string])[] = [
126130 ["needs", "Needs you"],
127131 ["open", "In follow-up"],
src/routes.ts +28
@@ -23,6 +23,7 @@ import {
2323 getLead,
2424 getProfile,
2525 listAudit,
26 exportLeads,
2627 listLeads,
2728 resetSample,
2829 saveProfile,
@@ -90,6 +91,8 @@ export interface Api {
9091 readonly status?: number;
9192 /** The query parameters it reads. */
9293 readonly query?: Readonly<Record<string, Schema>>;
94 /** The media type it answers in, when not JSON. */
95 readonly media?: string;
9396 }
9497
9598 export interface Route {
@@ -487,6 +490,31 @@ export const routes: readonly Route[] = [
487490 answer: DESK,
488491 },
489492 },
493 {
494 method: "GET",
495 path: "/leads.csv",
496 handle: (c) => {
497 const found = exportLeads(c.db, c.who, {
498 show: c.url.searchParams.get("show"),
499 q: c.url.searchParams.get("q"),
500 });
501 if (!found.ok) return answer(found);
502 return new Response(found.value.csv, {
503 headers: {
504 "content-type": "text/csv; charset=utf-8",
505 "content-disposition": `attachment; filename="${found.value.name}"`,
506 "cache-control": "no-store",
507 ...SECURITY,
508 },
509 });
510 },
511 api: {
512 summary: "Every lead and its status as a spreadsheet (CSV), narrowed like the desk by show and q, with no cap on the count.",
513 query: { show: SHOW, q: Q },
514 answer: { type: "string", description: "RFC 4180 CSV with a header row." },
515 media: "text/csv",
516 },
517 },
490518 {
491519 method: "POST",
492520 path: "/leads",
src/server.test.ts +1
@@ -283,6 +283,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
283283 const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" });
284284 expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([
285285 "list_leads",
286 "export_leads",
286287 "get_lead",
287288 "add_lead",
288289 "new_sample_inquiry",
src/terminal.test.ts +15
@@ -350,3 +350,18 @@ test("t asks, then y records that they asked to stop texts; any other key does n
350350 t.key("t"); // no longer offered
351351 expect(read(t)).not.toContain("texting cannot");
352352 });
353
354 test("x on the desk shows the leads as CSV, for those who may list; esc goes back", () => {
355 const db = fresh();
356 const t = terminal(db, alice);
357 t.key("x");
358 const screen = read(t);
359 expect(screen).toContain("12 leads as CSV");
360 expect(screen).toContain("name,email,phone,source,status");
361 expect(screen).toContain("Maria Gonzalez");
362 t.key("\x1b");
363 expect(read(t)).toContain("x export CSV");
364 const guest = terminal(db, { role: "anon" });
365 guest.key("x");
366 expect(read(guest)).not.toContain("as CSV");
367 });
src/terminal.ts +27 −2
@@ -30,6 +30,7 @@ import {
3030 editLead,
3131 getLead,
3232 getProfile,
33 exportLeads,
3334 listLeads,
3435 optOutTexts,
3536 resetSample,
@@ -115,6 +116,7 @@ const PROFILE_FIELDS = [
115116 type View =
116117 | { name: "desk" }
117118 | { name: "profile" }
119 | { name: "export" }
118120 | { name: "search"; typed: string }
119121 | { name: "activity"; sentOnly: boolean; before: number[] }
120122 | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> }
@@ -252,12 +254,25 @@ export function terminal(
252254 lines.push(
253255 "",
254256 dim(
255 `j/k move · enter open · f view · / find · n log a lead · i sample inquiry · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
257 `j/k move · enter open · f view · / find · n log a lead · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
256258 ),
257259 );
258260 return lines;
259261 }
260262
263 function exportScreen(): string[] {
264 const taken = exportLeads(db, me, { show, q });
265 if (!taken.ok) return [taken.message, "", dim("esc back")];
266 return [
267 bold(`${taken.value.count} lead${taken.value.count === 1 ? "" : "s"} as CSV`),
268 dim(`${taken.value.name} · the same file downloads from /leads.csv`),
269 "",
270 ...taken.value.csv.trimEnd().split("\r\n").map((line) => clean(line, false)),
271 "",
272 dim("esc back"),
273 ];
274 }
275
261276 /** Whether details can be corrected here: the table says yes and the lead is still open. */
262277 const mayEdit = (l: LeadDetail): boolean =>
263278 permit(me, "lead", "update", { ...l }) === "yes" && !CLOSED.includes(l.state);
@@ -480,7 +495,9 @@ export function terminal(
480495 ? deskScreen()
481496 : view.name === "activity"
482497 ? activityScreen(view)
483 : view.name === "profile"
498 : view.name === "export"
499 ? exportScreen()
500 : view.name === "profile"
484501 ? profileScreen()
485502 : view.name === "profile-edit"
486503 ? profileEditScreen(view)
@@ -561,6 +578,10 @@ export function terminal(
561578 ? `${added.value.name} is on the desk; the clock is running.`
562579 : added.message;
563580 if (added.ok) cursor = 0;
581 } else if (input === "x") {
582 const taken = exportLeads(db, me, { show, q });
583 if (taken.ok) view = { name: "export" };
584 else said = taken.message;
564585 } else if (input === "p") view = { name: "profile" };
565586 else if (input === "a")
566587 view = { name: "activity", sentOnly: false, before: [] };
@@ -585,6 +606,10 @@ export function terminal(
585606 }
586607 return;
587608 }
609 case "export": {
610 if (input === "\x1b" || input === "\x7f" || input === "q") view = { name: "desk" };
611 return;
612 }
588613 case "profile": {
589614 if (input === "\x1b" || input === "\x7f") view = { name: "desk" };
590615 else if (input === "e") {
static/app.css +9
@@ -619,6 +619,15 @@ label.check input {
619619 margin: 0 0 var(--space-3);
620620 color: var(--color-muted);
621621 }
622 .export {
623 margin: var(--space-4) 0 0;
624 color: var(--color-muted);
625 }
626 .export a {
627 display: inline-block;
628 padding: var(--space-2) 0;
629 color: inherit;
630 }
622631
623632 /* Activity. */
624633 .activity {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs