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
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/36-download-every-lead-and-its-status-as-a → main 3 commits fork 3 threads · 3 unresolved
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 | ||
| 276 | 276 | job gets "sign in first". Nothing depends on it: the app does the same |
| 277 | 277 | itself every hour. The whole API is described at `/openapi.json`, and the same |
| 278 | 278 | 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`). | |
| 280 | 280 | |
| 281 | 281 | ## From a terminal |
| 282 | 282 | |
| @@ -291,6 +291,7 @@ On the desk: | ||
| 291 | 291 | phone, source as a number, what they asked, consent `y` or `n`). |
| 292 | 292 | - `f` cycles the views (needs you, in follow-up, closed, all); the desk |
| 293 | 293 | shows the current one with its count. |
| 294 | - `x` shows the leads as CSV for the current view and search. | |
| 294 | 295 | - `R` restarts the sample leads from now (admins only; asks first). |
| 295 | 296 | - `esc` leaves. |
| 296 | 297 | |
| @@ -309,6 +310,15 @@ until you press a key on this screen: | ||
| 309 | 310 | - `D` removes the lead (admins only; asks first). |
| 310 | 311 | - `esc` goes back to the desk. |
| 311 | 312 | |
| 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 | ||
| 312 | 322 | ## Running it |
| 313 | 323 | |
| 314 | 324 | sh |
contract/openapi.json +53
| @@ -152,6 +152,59 @@ | ||
| 152 | 152 | } |
| 153 | 153 | } |
| 154 | 154 | }, |
| 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 | }, | |
| 155 | 208 | "/leads/{id}": { |
| 156 | 209 | "get": { |
| 157 | 210 | "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 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import { csvName, leadsCsv } from "./export.ts"; | |
| 10 | 11 | import { record, type Act, type AuditRow } from "./audit.ts"; |
| 11 | 12 | import { MAX_NOTE, outcomeOf } from "./calls.ts"; |
| 12 | 13 | import { permit } from "./contract.ts"; |
| @@ -27,6 +28,7 @@ import { | ||
| 27 | 28 | MAX_INBOUND, |
| 28 | 29 | MAX_QUERY, |
| 29 | 30 | insertLead, |
| 31 | lastMessages, | |
| 30 | 32 | updateContact, |
| 31 | 33 | optOut, |
| 32 | 34 | nextNeeding, |
| @@ -126,6 +128,29 @@ export function listLeads( | ||
| 126 | 128 | }); |
| 127 | 129 | } |
| 128 | 130 | |
| 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 | ||
| 129 | 154 | /** |
| 130 | 155 | * One lead, for `who` to do `verb` to. The door is asked before the row is |
| 131 | 156 | * 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 { | ||
| 12 | 12 | addLead, |
| 13 | 13 | addSampleInquiry, |
| 14 | 14 | deleteLead, |
| 15 | exportLeads, | |
| 15 | 16 | editLead, |
| 16 | 17 | getAudit, |
| 17 | 18 | getLead, |
| @@ -97,7 +98,12 @@ const doors: Record< | ||
| 97 | 98 | expect(addSampleInquiry(db, who).ok).toBe(added); |
| 98 | 99 | return added; |
| 99 | 100 | }, |
| 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 | }, | |
| 101 | 107 | read: (who, authorId) => getLead(db, who, { id: aLead(authorId) }).ok, |
| 102 | 108 | update: (who, authorId) => { |
| 103 | 109 | // 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 | ||
| 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&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 => { | ||
| 758 | 758 | export const clearLeads = (db: Database): void => { |
| 759 | 759 | db.exec("DELETE FROM lead"); |
| 760 | 760 | }; |
| 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"; | ||
| 10 | 10 | import { |
| 11 | 11 | addLead, |
| 12 | 12 | addSampleInquiry, |
| 13 | exportLeads, | |
| 13 | 14 | getLead, |
| 14 | 15 | getProfile, |
| 15 | 16 | listLeads, |
| @@ -72,6 +73,19 @@ export const tools: readonly Tool[] = [ | ||
| 72 | 73 | q: args.q, |
| 73 | 74 | }), |
| 74 | 75 | }, |
| 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 | }, | |
| 75 | 89 | { |
| 76 | 90 | name: "get_lead", |
| 77 | 91 | description: "One lead with every message: sent, drafted and upcoming.", |
src/openapi.ts +4 −4
| @@ -48,15 +48,15 @@ const within = (schema: Schema): Schema => | ||
| 48 | 48 | : value, |
| 49 | 49 | ]), |
| 50 | 50 | ); |
| 51 | const content = (schema: Schema) => ({ | |
| 52 | "application/json": { schema: named(schema) }, | |
| 51 | const content = (schema: Schema, media = "application/json") => ({ | |
| 52 | [media]: { schema: named(schema) }, | |
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | 55 | export function openapi(): Record<string, unknown> { |
| 56 | 56 | const paths: Record<string, Record<string, unknown>> = {}; |
| 57 | 57 | for (const route of routes) { |
| 58 | 58 | if (route.api === undefined) continue; |
| 59 | const { summary, body, answer, status, query } = route.api; | |
| 59 | const { summary, body, answer, status, query, media } = route.api; | |
| 60 | 60 | const path = route.path.replace(/:(\w+)/g, "{$1}"); |
| 61 | 61 | const params = [...route.path.matchAll(/:(\w+)/g)].map(([, name]) => ({ |
| 62 | 62 | name, |
| @@ -91,7 +91,7 @@ export function openapi(): Record<string, unknown> { | ||
| 91 | 91 | responses: { |
| 92 | 92 | [String(status ?? 200)]: { |
| 93 | 93 | description: summary, |
| 94 | content: content(answer), | |
| 94 | content: content(answer, media), | |
| 95 | 95 | }, |
| 96 | 96 | default: { |
| 97 | 97 | description: "{ error, message }: why not", |
src/pages/desk.ts +4
| @@ -82,6 +82,7 @@ export function deskPage(input: { | ||
| 82 | 82 | ${search} |
| 83 | 83 | ${views} |
| 84 | 84 | ${list} |
| 85 | <p class="export"><a href="${escape(exportHref(show, q))}" download>Download leads (CSV)</a></p> | |
| 85 | 86 | </div> |
| 86 | 87 | ${input.mayAdd ? `<form class="reset" method="post" action="/sample/inquiry"><button class="button button-quiet">Bring in a new inquiry</button></form>${addForm}` : ""} |
| 87 | 88 | ${ |
| @@ -122,6 +123,9 @@ const viewHref = (view: View, q: string): string => { | ||
| 122 | 123 | return query === "" ? "/" : `/?${query}`; |
| 123 | 124 | }; |
| 124 | 125 | |
| 126 | const exportHref = (view: View, q: string): string => | |
| 127 | viewHref(view, q).replace(/^\/\??/, "/leads.csv?").replace(/\?$/, ""); | |
| 128 | ||
| 125 | 129 | const VIEW_LABEL: readonly (readonly [View, string])[] = [ |
| 126 | 130 | ["needs", "Needs you"], |
| 127 | 131 | ["open", "In follow-up"], |
src/routes.ts +28
| @@ -23,6 +23,7 @@ import { | ||
| 23 | 23 | getLead, |
| 24 | 24 | getProfile, |
| 25 | 25 | listAudit, |
| 26 | exportLeads, | |
| 26 | 27 | listLeads, |
| 27 | 28 | resetSample, |
| 28 | 29 | saveProfile, |
| @@ -90,6 +91,8 @@ export interface Api { | ||
| 90 | 91 | readonly status?: number; |
| 91 | 92 | /** The query parameters it reads. */ |
| 92 | 93 | readonly query?: Readonly<Record<string, Schema>>; |
| 94 | /** The media type it answers in, when not JSON. */ | |
| 95 | readonly media?: string; | |
| 93 | 96 | } |
| 94 | 97 | |
| 95 | 98 | export interface Route { |
| @@ -487,6 +490,31 @@ export const routes: readonly Route[] = [ | ||
| 487 | 490 | answer: DESK, |
| 488 | 491 | }, |
| 489 | 492 | }, |
| 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 | }, | |
| 490 | 518 | { |
| 491 | 519 | method: "POST", |
| 492 | 520 | 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 () => | ||
| 283 | 283 | const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" }); |
| 284 | 284 | expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([ |
| 285 | 285 | "list_leads", |
| 286 | "export_leads", | |
| 286 | 287 | "get_lead", |
| 287 | 288 | "add_lead", |
| 288 | 289 | "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 | ||
| 350 | 350 | t.key("t"); // no longer offered |
| 351 | 351 | expect(read(t)).not.toContain("texting cannot"); |
| 352 | 352 | }); |
| 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 { | ||
| 30 | 30 | editLead, |
| 31 | 31 | getLead, |
| 32 | 32 | getProfile, |
| 33 | exportLeads, | |
| 33 | 34 | listLeads, |
| 34 | 35 | optOutTexts, |
| 35 | 36 | resetSample, |
| @@ -115,6 +116,7 @@ const PROFILE_FIELDS = [ | ||
| 115 | 116 | type View = |
| 116 | 117 | | { name: "desk" } |
| 117 | 118 | | { name: "profile" } |
| 119 | | { name: "export" } | |
| 118 | 120 | | { name: "search"; typed: string } |
| 119 | 121 | | { name: "activity"; sentOnly: boolean; before: number[] } |
| 120 | 122 | | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> } |
| @@ -252,12 +254,25 @@ export function terminal( | ||
| 252 | 254 | lines.push( |
| 253 | 255 | "", |
| 254 | 256 | 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`, | |
| 256 | 258 | ), |
| 257 | 259 | ); |
| 258 | 260 | return lines; |
| 259 | 261 | } |
| 260 | 262 | |
| 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 | ||
| 261 | 276 | /** Whether details can be corrected here: the table says yes and the lead is still open. */ |
| 262 | 277 | const mayEdit = (l: LeadDetail): boolean => |
| 263 | 278 | permit(me, "lead", "update", { ...l }) === "yes" && !CLOSED.includes(l.state); |
| @@ -480,7 +495,9 @@ export function terminal( | ||
| 480 | 495 | ? deskScreen() |
| 481 | 496 | : view.name === "activity" |
| 482 | 497 | ? activityScreen(view) |
| 483 | : view.name === "profile" | |
| 498 | : view.name === "export" | |
| 499 | ? exportScreen() | |
| 500 | : view.name === "profile" | |
| 484 | 501 | ? profileScreen() |
| 485 | 502 | : view.name === "profile-edit" |
| 486 | 503 | ? profileEditScreen(view) |
| @@ -561,6 +578,10 @@ export function terminal( | ||
| 561 | 578 | ? `${added.value.name} is on the desk; the clock is running.` |
| 562 | 579 | : added.message; |
| 563 | 580 | 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; | |
| 564 | 585 | } else if (input === "p") view = { name: "profile" }; |
| 565 | 586 | else if (input === "a") |
| 566 | 587 | view = { name: "activity", sentOnly: false, before: [] }; |
| @@ -585,6 +606,10 @@ export function terminal( | ||
| 585 | 606 | } |
| 586 | 607 | return; |
| 587 | 608 | } |
| 609 | case "export": { | |
| 610 | if (input === "\x1b" || input === "\x7f" || input === "q") view = { name: "desk" }; | |
| 611 | return; | |
| 612 | } | |
| 588 | 613 | case "profile": { |
| 589 | 614 | if (input === "\x1b" || input === "\x7f") view = { name: "desk" }; |
| 590 | 615 | else if (input === "e") { |
static/app.css +9
| @@ -619,6 +619,15 @@ label.check input { | ||
| 619 | 619 | margin: 0 0 var(); |
| 620 | 620 | color: var(); |
| 621 | 621 | } |
| 622 | .export { | |
| 623 | margin: var() 0 0; | |
| 624 | color: var(); | |
| 625 | } | |
| 626 | .export a { | |
| 627 | display: inline-block; | |
| 628 | padding: var() 0; | |
| 629 | color: inherit; | |
| 630 | } | |
| 622 | 631 | |
| 623 | 632 | /* Activity. */ |
| 624 | 633 | .activity { |
new above
offline
This assertion proves nothing. Seed a sent message and an inbound reply, then assert the latest timestamp.