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

Find a lead on the desk by name, email or phone #21

Merged opened this

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

Merged

mason/speed-to-lead:mason/19-find-a-lead-on-the-desk-by-name-email-or → main 2 commits fork

  • Merged. mason/19-find-a-lead-on-the-desk-by-name-email-or was merged into main as bc1891d.

Review

Sign in to review this change.
11 files changed +321 −28
README.md +6 −1
@@ -57,7 +57,12 @@ samples (step 1).
5757 the list narrow it: **Needs you** (a first reply or follow-up waiting),
5858 **In follow-up** (open, nothing waiting), **Closed** and **All**, each with
5959 its count (`/?show=needs|open|closed|all`; `GET /leads?show=…` and the MCP
60 `list_leads` tool take the same filter). Each row
60 `list_leads` tool take the same filter). The **search box** above the
61 links finds a lead by name, email or phone (`/?q=maria`; digits only for a
62 phone, so `555 0101` finds `(206) 555-0101`), case-insensitive, up to 80
63 characters, and combines with the view; "Clear" drops it. `GET /leads?q=…`
64 and the MCP `list_leads` tool take `q` too, and the terminal desk searches
65 with `/`. Each row
6166 shows the person's name, where they came from (Zillow, your website form,
6267 an open house, a referral), what they asked, and a **response clock**
6368 counting since they asked:
contract/openapi.json +15 −1
@@ -33,6 +33,15 @@
3333 ],
3434 "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)."
3535 }
36 },
37 {
38 "name": "q",
39 "in": "query",
40 "schema": {
41 "type": "string",
42 "maxLength": 80,
43 "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."
44 }
3645 }
3746 ],
3847 "responses": {
@@ -957,9 +966,13 @@
957966 ],
958967 "description": "The view listed."
959968 },
969 "q": {
970 "type": "string",
971 "description": "The search that narrowed the desk; empty when none."
972 },
960973 "counts": {
961974 "type": "object",
962 "description": "How many leads each view holds.",
975 "description": "How many leads each view holds, among those the search matched.",
963976 "properties": {
964977 "needs": {
965978 "type": "integer"
@@ -991,6 +1004,7 @@
9911004 "required": [
9921005 "record",
9931006 "show",
1007 "q",
9941008 "counts",
9951009 "leads"
9961010 ]
src/actions.ts +11 −2
@@ -20,6 +20,8 @@ import {
2020 detail,
2121 findLead,
2222 inView,
23 queryOf,
24 MAX_QUERY,
2325 insertLead,
2426 readyFor,
2527 redraftUnsent,
@@ -82,7 +84,7 @@ const stamp = (at?: Date): string => (at ?? new Date()).toISOString();
8284 export function listLeads(
8385 db: Database,
8486 who: Who,
85 input: { limit?: number; now?: number; show?: unknown } = {},
87 input: { limit?: number; now?: number; show?: unknown; q?: unknown } = {},
8688 ): Result<Desk> {
8789 // Leads are a team's desk, not anyone's own: anything but "yes" is a no.
8890 if (permit(who, "lead", "list") !== "yes")
@@ -92,10 +94,17 @@ export function listLeads(
9294 500,
9395 );
9496 const show = viewOf(input.show);
95 const all = desk(db, 500);
97 const q = queryOf(input.q);
98 if (q === undefined)
99 return fail(
100 "invalid",
101 `A search is plain text, up to ${MAX_QUERY} characters.`,
102 );
103 const all = desk(db, 500, q);
96104 return ok({
97105 record: responseRecord(db, input.now ?? Date.now()),
98106 show,
107 q,
99108 counts: countViews(all),
100109 leads: all.filter((l) => inView(l, show)).slice(0, limit),
101110 });
src/leads.ts +41 −5
@@ -110,6 +110,8 @@ export const countViews = (leads: readonly DeskLead[]): Record<View, number> =>
110110 export interface Desk {
111111 readonly record: ResponseRecord;
112112 readonly show: View;
113 /** The search that narrowed the desk; empty when none. */
114 readonly q: string;
113115 readonly counts: Record<View, number>;
114116 readonly leads: DeskLead[];
115117 }
@@ -151,8 +153,39 @@ export function detail(db: Database, id: number): LeadDetail | null {
151153 return found === null ? null : { ...found, messages: messagesOf(db, id) };
152154 }
153155
154 /** The desk, newest inquiry first. */
155 export function desk(db: Database, limit: number): DeskLead[] {
156 export const MAX_QUERY = 80;
157
158 /** What a door says about the search, in one place. */
159 export const Q_HELP =
160 "Narrow the desk to leads whose name or email holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters.";
161
162 /**
163 * A search from user text: trimmed, at most 80 characters, no control
164 * characters. `""` means no search; `undefined` means the text is refused.
165 */
166 export function queryOf(text: unknown): string | undefined {
167 if (text === undefined || text === null) return "";
168 if (typeof text !== "string") return undefined;
169 const q = text.trim();
170 if (q.length > MAX_QUERY || /[\x00-\x1f\x7f]/.test(q)) return undefined;
171 return q;
172 }
173
174 const likeOf = (text: string): string =>
175 `%${text.replace(/[\\%_]/g, "\\$&")}%`;
176
177 /** A phone's digits only, in SQL: the punctuation people type is dropped. */
178 const DIGITS = ["(", ")", "-", " ", ".", "+"].reduce(
179 (sql, ch) => `replace(${sql}, '${ch}', '')`,
180 "lead.phone",
181 );
182
183 /**
184 * The desk, newest inquiry first; with `q`, only leads whose name or email
185 * holds it, or whose phone holds its digits ("555 0101" finds "(206) 555-0101").
186 */
187 export function desk(db: Database, limit: number, q = ""): DeskLead[] {
188 const digits = /^[\d\s()+.\-]+$/.test(q) ? q.replace(/\D/g, "") : "";
156189 return db
157190 .query<
158191 LeadRecord & {
@@ -160,15 +193,18 @@ export function desk(db: Database, limit: number): DeskLead[] {
160193 ready_day: number | null;
161194 next_at: string | null;
162195 },
163 [number]
196 [number, string, string]
164197 >(
165198 `SELECT lead.*,
166199 (SELECT id FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_id,
167200 (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day,
168201 (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at
169 FROM lead ORDER BY created_at DESC, id DESC LIMIT ?1`,
202 FROM lead
203 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
204 OR (?3 <> '' AND ${DIGITS} LIKE ?3)
205 ORDER BY created_at DESC, id DESC LIMIT ?1`,
170206 )
171 .all(limit)
207 .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`)
172208 .map(({ ready_id, ready_day, next_at, ...row }) => ({
173209 ...lead(row),
174210 ready:
src/mcp.ts +7 −2
@@ -19,7 +19,7 @@ import {
1919 } from "./actions.ts";
2020 import { SOURCES } from "./drafts.ts";
2121 import { title } from "./env.ts";
22 import { VIEW_HELP, VIEWS } from "./leads.ts";
22 import { Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
2323 import { fields } from "./http.ts";
2424 import type { Who } from "./who.ts";
2525
@@ -53,10 +53,15 @@ export const tools: readonly Tool[] = [
5353 enum: [...VIEWS],
5454 description: VIEW_HELP,
5555 },
56 q: { type: "string", maxLength: 80, description: Q_HELP },
5657 },
5758 },
5859 run: (db, who, args) =>
59 listLeads(db, who, { limit: Number(args.limit ?? 200), show: args.show }),
60 listLeads(db, who, {
61 limit: Number(args.limit ?? 200),
62 show: args.show,
63 q: args.q,
64 }),
6065 },
6166 {
6267 name: "get_lead",
src/pages/desk.ts +22 −2
@@ -17,6 +17,7 @@ export function deskPage(input: {
1717 leads: readonly DeskLead[] | undefined;
1818 record?: ResponseRecord | undefined;
1919 show?: View | undefined;
20 q?: string | undefined;
2021 counts?: Record<View, number> | undefined;
2122 mayAdd: boolean;
2223 mayReset: boolean;
@@ -48,16 +49,23 @@ export function deskPage(input: {
4849 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0).length;
4950 const summary = `<p class="summary" aria-live="polite"><b>${waiting}</b> waiting for a first reply <span aria-hidden="true">·</span> <b>${due}</b> follow-up${due === 1 ? "" : "s"} due today</p>`;
5051 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>`;
52 const q = input.q ?? "";
5153 const views =
5254 counts === undefined
5355 ? ""
5456 : `<nav class="views" aria-label="Show">${VIEW_LABEL.map(
5557 ([view, label]) =>
56 `<a href="${view === "all" ? "/" : `/?show=${view}`}"${view === show ? ' aria-current="page"' : ""}>${label} <b>${counts[view]}</b></a>`,
58 `<a href="${viewHref(view, q)}"${view === show ? ' aria-current="page"' : ""}>${label} <b>${counts[view]}</b></a>`,
5759 ).join("")}</nav>`;
60 const search = `<form class="search" role="search" method="get" action="/">
61 ${show === "all" ? "" : `<input type="hidden" name="show" value="${show}">`}
62 <input class="input" type="search" name="q" value="${escape(q)}" maxlength="80" placeholder="Find by name, email or phone" aria-label="Find a lead by name, email or phone" autocomplete="off">
63 <button class="button button-quiet">Search</button>
64 </form>
65 ${q === "" ? "" : found(q, show, counts?.all ?? leads.length)}`;
5866 const list =
5967 leads.length === 0
60 ? `<p class="empty">${EMPTY[show]}</p>`
68 ? `<p class="empty">${q === "" ? EMPTY[show] : `No lead matches '${escape(q)}'${show === "all" ? "" : " in this view"}.`}</p>`
6169 : `<ul class="desk">${leads.map((lead) => row(lead, now)).join("")}</ul>`;
6270 return layout({
6371 who,
@@ -68,6 +76,7 @@ export function deskPage(input: {
6876 body: `<div id="desk" data-live="lead.added lead.changed">
6977 <div class="desk-head"><h1>Leads</h1>${summary}</div>
7078 ${record}
79 ${search}
7180 ${views}
7281 ${list}
7382 </div>
@@ -99,6 +108,17 @@ const example = `<div class="example" aria-label="Example lead">
99108 </div>
100109 </div>`;
101110
111 const found = (q: string, show: View, n: number): string =>
112 `<p class="found">${n} lead${n === 1 ? "" : "s"} match${n === 1 ? "es" : ""} “${escape(q)}” <a href="${viewHref(show, "")}">Clear</a></p>`;
113
114 const viewHref = (view: View, q: string): string => {
115 const params = new URLSearchParams();
116 if (view !== "all") params.set("show", view);
117 if (q !== "") params.set("q", q);
118 const query = params.toString();
119 return query === "" ? "/" : `/?${query}`;
120 };
121
102122 const VIEW_LABEL: readonly (readonly [View, string])[] = [
103123 ["needs", "Needs you"],
104124 ["open", "In follow-up"],
src/routes.ts +19 −7
@@ -47,7 +47,7 @@ import {
4747 staticFile,
4848 text,
4949 } from "./http.ts";
50 import { VIEW_HELP, VIEWS } from "./leads.ts";
50 import { MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
5151 import { events } from "./live.ts";
5252 import { rpc } from "./mcp.ts";
5353 import { deskPage } from "./pages/desk.ts";
@@ -146,6 +146,7 @@ const SHOW: Schema = {
146146 enum: [...VIEWS],
147147 description: VIEW_HELP,
148148 };
149 const Q: Schema = { type: "string", maxLength: MAX_QUERY, description: Q_HELP };
149150 export const DESK: Schema = {
150151 type: "object",
151152 properties: {
@@ -169,9 +170,10 @@ export const DESK: Schema = {
169170 required: ["days", "leads", "replied", "median_ms", "within_5_min_pct"],
170171 },
171172 show: { enum: [...VIEWS], description: "The view listed." },
173 q: { type: "string", description: "The search that narrowed the desk; empty when none." },
172174 counts: {
173175 type: "object",
174 description: "How many leads each view holds.",
176 description: "How many leads each view holds, among those the search matched.",
175177 properties: {
176178 needs: { type: "integer" },
177179 open: { type: "integer" },
@@ -182,7 +184,7 @@ export const DESK: Schema = {
182184 },
183185 leads: { type: "array", items: DESK_LEAD },
184186 },
185 required: ["record", "show", "counts", "leads"],
187 required: ["record", "show", "q", "counts", "leads"],
186188 };
187189 const NEW_LEAD: Schema = {
188190 type: "object",
@@ -323,9 +325,17 @@ export const routes: readonly Route[] = [
323325 path: "/",
324326 handle: (c) => {
325327 const { notice, clear } = readNotice(c.request);
326 const leads = listLeads(c.db, c.who, {
327 show: c.url.searchParams.get("show"),
328 const show = c.url.searchParams.get("show");
329 let leads = listLeads(c.db, c.who, {
330 show,
331 q: c.url.searchParams.get("q"),
328332 });
333 // A refused search still shows the desk, with the reason above it.
334 let refused: string | undefined;
335 if (!leads.ok && leads.error === "invalid") {
336 refused = leads.message;
337 leads = listLeads(c.db, c.who, { show });
338 }
329339 return html(
330340 deskPage({
331341 who: c.who,
@@ -333,10 +343,11 @@ export const routes: readonly Route[] = [
333343 leads: leads.ok ? leads.value.leads : undefined,
334344 record: leads.ok ? leads.value.record : undefined,
335345 show: leads.ok ? leads.value.show : undefined,
346 q: leads.ok ? leads.value.q : undefined,
336347 counts: leads.ok ? leads.value.counts : undefined,
337348 mayAdd: permit(c.who, "lead", "create") === "yes",
338349 mayReset: permit(c.who, "lead", "delete") === "yes",
339 notice,
350 notice: refused ?? notice,
340351 }),
341352 200,
342353 clear,
@@ -353,11 +364,12 @@ export const routes: readonly Route[] = [
353364 listLeads(c.db, c.who, {
354365 limit: whole(c.url.searchParams.get("limit")) ?? 200,
355366 show: c.url.searchParams.get("show"),
367 q: c.url.searchParams.get("q"),
356368 }),
357369 ),
358370 api: {
359371 summary: "The desk: your response record, and every lead, newest inquiry first.",
360 query: { limit: LIMIT, show: SHOW },
372 query: { limit: LIMIT, show: SHOW, q: Q },
361373 answer: DESK,
362374 },
363375 },
src/search.test.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * Finding a lead: name, email or phone, case-insensitive, narrowed by the
3 * view, refused when it is not plain short text, the same on every door.
4 */
5 import { expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { listLeads } from "./actions.ts";
10 import { openDb } from "./db.ts";
11 import { deskPage } from "./pages/desk.ts";
12 import { agent } from "./env.ts";
13 import { seed } from "./sample.ts";
14 import { insertLead, queryOf } from "./leads.ts";
15 import { plain, terminal } from "./terminal.ts";
16 import type { Who } from "./who.ts";
17
18 const alice: Who = { role: "user", id: "u1", name: "alice" };
19 const anon: Who = { role: "anon" };
20 const db = openDb(mkdtempSync(join(tmpdir(), "app-search-")));
21 seed(db, new Date());
22
23 const names = (input: { q?: unknown; show?: unknown }): string[] => {
24 const r = listLeads(db, alice, input);
25 if (!r.ok) throw new Error(r.message);
26 return r.value.leads.map((l) => l.name);
27 };
28
29 test("a name, an email or a phone finds the lead, in any case", () => {
30 expect(names({ q: "maria" })).toEqual(["Maria Gonzalez"]);
31 expect(names({ q: " GONZALEZ " })).toEqual(["Maria Gonzalez"]);
32 expect(names({ q: "david.chen@" })).toEqual(["David Chen"]);
33 expect(names({ q: "555 0101" })).toEqual(["Maria Gonzalez"]);
34 expect(names({ q: "(206) 555-0101" })).toEqual(["Maria Gonzalez"]);
35 expect(names({ q: "5550102" })).toEqual(["David Chen"]);
36 expect(names({ q: "nobody" })).toEqual([]);
37 });
38
39 test("no search is the whole desk", () => {
40 expect(names({}).length).toBe(12);
41 expect(names({ q: "" }).length).toBe(12);
42 });
43
44 test("a search combines with the view", () => {
45 expect(names({ q: "mar", show: "needs" })).toEqual(["Maria Gonzalez"]);
46 expect(names({ q: "mar" })).toEqual(["Maria Gonzalez", "Marcus Lee"]);
47 expect(names({ q: "mar", show: "closed" })).toEqual([]);
48 expect(names({ q: "grace", show: "closed" })).toEqual(["Grace Kim"]);
49 });
50
51 test("% and _ match themselves, not everything", () => {
52 insertLead(db, {
53 name: "Pat 100%_Real",
54 email: "[email protected]",
55 phone: "",
56 source: "website",
57 message: "Hello there, a question.",
58 consent: false,
59 }, new Date().toISOString(), agent);
60 expect(names({ q: "%" })).toEqual(["Pat 100%_Real"]);
61 expect(names({ q: "_" })).toEqual(["Pat 100%_Real"]);
62 expect(names({ q: "0%_R" })).toEqual(["Pat 100%_Real"]);
63 expect(names({ q: "'; DROP TABLE lead; --" })).toEqual([]);
64 });
65
66 test("a search is trimmed, short, and has no control characters", () => {
67 expect(queryOf(" x ")).toBe("x");
68 expect(queryOf("a".repeat(80))).toBe("a".repeat(80));
69 expect(queryOf("a".repeat(81))).toBeUndefined();
70 expect(queryOf("a\nb")).toBeUndefined();
71 expect(queryOf("a\x00b")).toBeUndefined();
72 expect(queryOf(5)).toBeUndefined();
73 const refused = listLeads(db, alice, { q: "a".repeat(81) });
74 expect(!refused.ok && refused.error).toBe("invalid");
75 });
76
77 test("signed out, a search is still the same refusal as the desk", () => {
78 const r = listLeads(db, anon, { q: "maria" });
79 expect(r.ok).toBe(false);
80 });
81
82 test("the page says how many matched, offers Clear, and says when none did", () => {
83 const r = listLeads(db, alice, { q: "maria" });
84 if (!r.ok) throw new Error(r.message);
85 const page = (v: typeof r.value) =>
86 deskPage({
87 who: alice,
88 agent,
89 leads: v.leads,
90 record: v.record,
91 show: v.show,
92 q: v.q,
93 counts: v.counts,
94 mayAdd: false,
95 mayReset: false,
96 });
97 const html = page(r.value);
98 expect(html).toContain('name="q" value="maria"');
99 expect(html).toContain("1 lead matches");
100 expect(html).toContain('href="/">Clear</a>');
101 expect(html).toContain("Maria Gonzalez");
102 expect(html).not.toContain("David Chen");
103 expect(html).toContain("/?q=maria");
104
105 const none = listLeads(db, alice, { q: "<b>x</b>", show: "needs" });
106 if (!none.ok) throw new Error(none.message);
107 const empty = page(none.value);
108 expect(empty).toContain("No lead matches '&lt;b&gt;x&lt;/b&gt;' in this view.");
109 expect(empty).not.toContain("<b>x</b>");
110 expect(empty).toContain('name="show" value="needs"');
111 expect(empty).toContain('href="/?show=needs">Clear</a>');
112 const plainNone = listLeads(db, alice, { q: "maria1" });
113 if (!plainNone.ok) throw new Error(plainNone.message);
114 expect(page(plainNone.value)).toContain("No lead matches 'maria1'.");
115 });
116
117 test("the terminal finds a lead with /", () => {
118 const t = terminal(db, alice);
119 const screen = () => t.screen(100).map(plain).join("\n");
120 expect(screen()).toContain("David Chen");
121 t.key("/");
122 for (const ch of "chen") t.key(ch);
123 t.key("\r");
124 expect(screen()).toContain("David Chen");
125 expect(screen()).not.toContain("Maria Gonzalez");
126 t.key("/");
127 for (let i = 0; i < 4; i++) t.key("\x7f");
128 for (const ch of "zzz") t.key(ch);
129 t.key("\r");
130 expect(screen()).toContain("No lead matches 'zzz'.");
131 t.key("/");
132 for (let i = 0; i < 3; i++) t.key("\x7f");
133 t.key("\r");
134 expect(screen()).toContain("Maria Gonzalez");
135 });
src/server.test.ts +19
@@ -603,3 +603,22 @@ test("the desk views: links with counts, aria-current, bad value is all, JSON ma
603603 expect(bad).toMatch(/<a href="\/"[^>]*aria-current="page">All/);
604604 expect(((await (await api("/leads?show=zzz", {}, alice)).json()) as { show: string }).show).toBe("all");
605605 });
606
607 test("GET /leads?q= is the desk's search as JSON, like the page", async () => {
608 const json = (await (await api("/leads?q=maria", {}, alice)).json()) as any;
609 expect(json.q).toBe("maria");
610 expect(json.leads.map((l: any) => l.name)).toEqual(["Maria Gonzalez"]);
611 const page = await (await api("/?q=maria", {}, alice)).text();
612 expect(page).toContain("Maria Gonzalez");
613 expect(page).not.toContain("David Chen");
614 expect((await api(`/leads?q=${"a".repeat(81)}`, {}, alice)).status).toBe(422);
615 const tooLong = await api(`/?q=${"a".repeat(81)}`, {}, alice);
616 expect(tooLong.status).toBe(200);
617 expect(await tooLong.text()).toContain("up to 80 characters");
618 const tool = await rpc(
619 { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_leads", arguments: { q: "555 0101" } } },
620 alice,
621 );
622 expect(JSON.stringify(tool)).toContain("Maria Gonzalez");
623 expect(JSON.stringify(tool)).not.toContain("David Chen");
624 });
src/terminal.ts +31 −8
@@ -5,7 +5,7 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · f view (needs/open/closed/all) · n log a lead · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email or phone · n log a lead · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · q qualified · x lost ·
1010 * D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
@@ -38,7 +38,7 @@ import { permit } from "./contract.ts";
3838 import { said as saidOf } from "./sentences.ts";
3939 import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts";
4040 import { ssh, title, where } from "./env.ts";
41 import { VIEWS, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
41 import { MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
4242 import { currentAgent } from "./profile.ts";
4343 import type { Who } from "./who.ts";
4444
@@ -104,6 +104,7 @@ const PROFILE_FIELDS = [
104104 type View =
105105 | { name: "desk" }
106106 | { name: "profile" }
107 | { name: "search"; typed: string }
107108 | { name: "activity"; sentOnly: boolean; before: number[] }
108109 | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> }
109110 | { name: "lead"; id: number }
@@ -144,12 +145,13 @@ export function terminal(
144145 let view: View = { name: "desk" };
145146 let cursor = 0;
146147 let show: DeskView = "all";
148 let q = "";
147149 let said = "";
148150 let done = false;
149151 const admin = (): boolean => permit(me, "lead", "delete") === "yes";
150152
151153 const leads = (): DeskLead[] => {
152 const listed = listLeads(db, me, { show });
154 const listed = listLeads(db, me, { show, q });
153155 return listed.ok ? listed.value.leads : [];
154156 };
155157 const lead = (id: number): LeadDetail | undefined => {
@@ -177,7 +179,7 @@ export function terminal(
177179 }
178180
179181 function deskScreen(): string[] {
180 const listed = listLeads(db, me, { show });
182 const listed = listLeads(db, me, { show, q });
181183 if (!listed.ok)
182184 return [listed.message, "", dim("esc quit")];
183185 const rows = listed.value.leads;
@@ -191,7 +193,9 @@ export function terminal(
191193 }).join(" "),
192194 "",
193195 ];
194 if (rows.length === 0) lines.push(dim(EMPTY[show]));
196 if (q !== "") lines.push(dim(`matching '${clean(q)}' · / to change, empty to clear`), "");
197 if (rows.length === 0)
198 lines.push(dim(q === "" ? EMPTY[show] : `No lead matches '${clean(q)}'.`));
195199 rows.forEach((l, i) => {
196200 const next =
197201 l.ready === null
@@ -207,7 +211,7 @@ export function terminal(
207211 lines.push(
208212 "",
209213 dim(
210 `j/k move · enter open · f view · n log a lead · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
214 `j/k move · enter open · f view · / find · n log a lead · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
211215 ),
212216 );
213217 return lines;
@@ -400,7 +404,9 @@ export function terminal(
400404 ? profileScreen()
401405 : view.name === "profile-edit"
402406 ? profileEditScreen(view)
403 : view.name === "lead"
407 : view.name === "search"
408 ? ["Find a lead by name, email or phone", "", `/ ${view.typed}▏`, "", dim("enter search · empty clears · esc cancel")]
409 : view.name === "lead"
404410 ? leadScreen(view.id, w)
405411 : view.name === "edit"
406412 ? leadScreen(view.id, w, view.text)
@@ -434,7 +440,8 @@ export function terminal(
434440 else if (input === "f") {
435441 show = VIEWS[(VIEWS.indexOf(show) + 1) % VIEWS.length]!;
436442 cursor = 0;
437 } else if (input === "n")
443 } else if (input === "/") view = { name: "search", typed: q };
444 else if (input === "n")
438445 view = { name: "add", step: 0, typed: "", fields: {} };
439446 else if (input === "p") view = { name: "profile" };
440447 else if (input === "a")
@@ -535,6 +542,22 @@ export function terminal(
535542 }
536543 return;
537544 }
545 case "search": {
546 if (input === "\x1b") view = { name: "desk" };
547 else if (input === "\r") {
548 const found = queryOf(view.typed);
549 if (found === undefined) said = `A search is plain text, up to ${MAX_QUERY} characters.`;
550 else {
551 q = found;
552 cursor = 0;
553 view = { name: "desk" };
554 }
555 } else {
556 const next = typing(view.typed, input);
557 if (next !== undefined) view = { ...view, typed: next };
558 }
559 return;
560 }
538561 case "add": {
539562 if (input === "\x1b") {
540563 said = "Nothing logged.";
static/app.css +15
@@ -591,6 +591,21 @@ label.check input {
591591 }
592592 }
593593
594 /* Finding a lead: one row that keeps its height whatever is typed. */
595 .search {
596 display: flex;
597 gap: var(--space-2);
598 margin: 0 0 var(--space-3);
599 }
600 .search .input {
601 flex: 1;
602 min-width: 0;
603 }
604 .found {
605 margin: 0 0 var(--space-3);
606 color: var(--color-muted);
607 }
608
594609 /* Activity. */
595610 .activity {
596611 list-style: none;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs