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

Let the agent set their name, brokerage and license from the app #8

Merged opened this

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

Merged

mason/speed-to-lead:mason/6-let-the-agent-set-their-name-brokerage-a → main 2 commits fork

  • Merged. mason/6-let-the-agent-set-their-name-brokerage-a was merged into main as 318c4c3.

Review

Sign in to review this change.
21 files changed +908 −19
AGENTS.md +2 −1
@@ -110,7 +110,8 @@ Speed to Lead is one realtor's desk. The concepts, one module each:
110110 drafts and schedules the cadence (days in `CADENCE`); `advance` makes a
111111 touch due on its day; `close` (qualified or lost) skips what is left.
112112 - `src/drafts.ts` — the words: templates filled from the inquiry and the
113 agent's profile (`agent` in `src/env.ts`), the signature every message
113 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
114 defaults of `agent` in `src/env.ts`), the signature every message
114115 carries, and the consent rule (`channelFor`: text only with written
115116 consent and a phone number). A trigger in `src/db.ts` holds that rule
116117 in the file as well.
README.md +16 −2
@@ -66,8 +66,15 @@ from the bottom of the desk, so the clocks read fresh for a demonstration.
6666
6767 ## Your profile
6868
69 Set these in the forge (Settings → App → Environment). Until you do, the
70 app uses a sample agent, Jordan Avery of Harbor & Pine Realty.
69 Open **Your profile** in the header (`/profile`) and fill in your name,
70 brokerage, license number, phone and email. An admin saves it; everyone
71 signed in can read it. The license number is required, because every
72 message shows it. Drafts you have not sent take the new profile at once;
73 messages already sent keep the signature they went out with.
74
75 Until you save one, the app uses these environment variables (forge
76 Settings → App → Environment) or, failing those, a sample agent, Jordan
77 Avery of Harbor & Pine Realty. Once a profile is saved it wins.
7178
7279 | variable | what it is |
7380 | ----------------- | ------------------------------- |
@@ -77,6 +84,13 @@ app uses a sample agent, Jordan Avery of Harbor & Pine Realty.
7784 | `AGENT_PHONE` | the phone number in your emails |
7885 | `AGENT_EMAIL` | the email address in your emails |
7986
87 In the terminal, press `p` on the desk to read it; an admin presses `e`
88 and types each field in turn (enter moves on, the last one saves).
89
90 A script reads it with `GET /profile` and an admin changes it with
91 `POST /profile` (JSON, all five fields); MCP has `get_profile` and
92 `set_profile`.
93
8094 ## For whoever connects it to a website
8195
8296 Every page has a JSON twin. Send `content-type: application/json` (or
contract.json +9
@@ -16,6 +16,15 @@
1616 "list": "user"
1717 }
1818 },
19 "profile": {
20 "can": {
21 "create": "nobody",
22 "read": "user",
23 "update": "admin",
24 "delete": "nobody",
25 "list": "nobody"
26 }
27 },
1928 "audit": {
2029 "api": "/api/audit",
2130 "can": {
contract/openapi.json +171
@@ -441,6 +441,177 @@
441441 }
442442 }
443443 },
444 "/profile": {
445 "get": {
446 "summary": "The agent whose desk this is: name, brokerage, license, phone and email. The AGENT_* environment variables until a profile is saved.",
447 "operationId": "getProfile",
448 "responses": {
449 "200": {
450 "description": "The agent whose desk this is: name, brokerage, license, phone and email. The AGENT_* environment variables until a profile is saved.",
451 "content": {
452 "application/json": {
453 "schema": {
454 "type": "object",
455 "properties": {
456 "id": {
457 "const": 1
458 },
459 "name": {
460 "type": "string",
461 "minLength": 1,
462 "maxLength": 120
463 },
464 "brokerage": {
465 "type": "string",
466 "minLength": 1,
467 "maxLength": 120
468 },
469 "license": {
470 "type": "string",
471 "minLength": 1,
472 "maxLength": 60,
473 "description": "Required: every message shows it."
474 },
475 "phone": {
476 "type": "string",
477 "description": "7 to 20 digits."
478 },
479 "email": {
480 "type": "string",
481 "format": "email"
482 }
483 },
484 "required": [
485 "id",
486 "name",
487 "brokerage",
488 "license",
489 "phone",
490 "email"
491 ]
492 }
493 }
494 }
495 },
496 "default": {
497 "description": "{ error, message }: why not",
498 "content": {
499 "application/json": {
500 "schema": {
501 "$ref": "#/components/schemas/Error"
502 }
503 }
504 }
505 }
506 }
507 },
508 "post": {
509 "summary": "Change the profile (admin only). Drafts not yet sent take it at once; messages already sent keep the signature they went out with. The license may not be blank.",
510 "operationId": "postProfile",
511 "requestBody": {
512 "required": true,
513 "content": {
514 "application/json": {
515 "schema": {
516 "type": "object",
517 "properties": {
518 "name": {
519 "type": "string",
520 "minLength": 1,
521 "maxLength": 120
522 },
523 "brokerage": {
524 "type": "string",
525 "minLength": 1,
526 "maxLength": 120
527 },
528 "license": {
529 "type": "string",
530 "minLength": 1,
531 "maxLength": 60,
532 "description": "Required: every message shows it."
533 },
534 "phone": {
535 "type": "string",
536 "description": "7 to 20 digits."
537 },
538 "email": {
539 "type": "string",
540 "format": "email"
541 }
542 },
543 "required": [
544 "name",
545 "brokerage",
546 "license",
547 "phone",
548 "email"
549 ]
550 }
551 }
552 }
553 },
554 "responses": {
555 "200": {
556 "description": "Change the profile (admin only). Drafts not yet sent take it at once; messages already sent keep the signature they went out with. The license may not be blank.",
557 "content": {
558 "application/json": {
559 "schema": {
560 "type": "object",
561 "properties": {
562 "id": {
563 "const": 1
564 },
565 "name": {
566 "type": "string",
567 "minLength": 1,
568 "maxLength": 120
569 },
570 "brokerage": {
571 "type": "string",
572 "minLength": 1,
573 "maxLength": 120
574 },
575 "license": {
576 "type": "string",
577 "minLength": 1,
578 "maxLength": 60,
579 "description": "Required: every message shows it."
580 },
581 "phone": {
582 "type": "string",
583 "description": "7 to 20 digits."
584 },
585 "email": {
586 "type": "string",
587 "format": "email"
588 }
589 },
590 "required": [
591 "id",
592 "name",
593 "brokerage",
594 "license",
595 "phone",
596 "email"
597 ]
598 }
599 }
600 }
601 },
602 "default": {
603 "description": "{ error, message }: why not",
604 "content": {
605 "application/json": {
606 "schema": {
607 "$ref": "#/components/schemas/Error"
608 }
609 }
610 }
611 }
612 }
613 }
614 },
444615 "/api/audit": {
445616 "get": {
446617 "summary": "The audit trail, newest first; `before` pages back by id.",
src/actions.ts +77 −3
@@ -10,7 +10,7 @@ import type { Database } from "bun:sqlite";
1010 import { record, type AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
1212 import { MAX_BODY, SOURCES, type Source } from "./drafts.ts";
13 import { agent } from "./env.ts";
13 import type { Agent } from "./env.ts";
1414 import {
1515 advance,
1616 clearLeads,
@@ -19,6 +19,7 @@ import {
1919 detail,
2020 insertLead,
2121 readyFor,
22 redraftUnsent,
2223 removeLead,
2324 send,
2425 type DeskLead,
@@ -26,6 +27,7 @@ import {
2627 type NewLead,
2728 } from "./leads.ts";
2829 import { emit } from "./live.ts";
30 import { currentAgent, storeAgent } from "./profile.ts";
2931 import { seed } from "./sample.ts";
3032 import type { Who } from "./who.ts";
3133
@@ -205,7 +207,7 @@ function add(
205207 return refuse(who, "Sign in to add a lead.", "You may not add a lead.");
206208 const read = readNewLead(input);
207209 if (!read.ok) return read;
208 const id = insertLead(db, read.value, stamp(at), agent);
210 const id = insertLead(db, read.value, stamp(at), currentAgent(db));
209211 const added = detail(db, id)!;
210212 emit("lead.added", { id });
211213 return ok(added);
@@ -249,7 +251,7 @@ function reply(
249251 `A${ready.channel === "text" ? " text" : "n email"} is 1 to ${max} characters.`,
250252 );
251253 const by = who.role === "anon" ? "" : who.name;
252 send(db, found.value, ready, body, by, stamp(at), agent);
254 send(db, found.value, ready, body, by, stamp(at), currentAgent(db));
253255 emit("lead.changed", { id: found.value.id });
254256 return ok(detail(db, found.value.id)!);
255257 }
@@ -366,6 +368,78 @@ export function resetSample(
366368 return result;
367369 }
368370
371 /** The agent whose desk this is, as a row of one: what every message is signed with. */
372 export type Profile = Agent & { readonly id: 1 };
373
374 export function getProfile(db: Database, who: Who): Result<Profile> {
375 if (permit(who, "profile", "read", { id: 1 }) !== "yes")
376 return refuse(
377 who,
378 "Sign in to read the profile.",
379 "You may not read the profile.",
380 );
381 return ok({ id: 1, ...currentAgent(db) });
382 }
383
384 /** What arrived for the profile, checked field by field: the agent to keep, or what is wrong. */
385 export function readAgent(input: Record<string, unknown>): Result<Agent> {
386 const text = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
387 const name = text(input.name);
388 const brokerage = text(input.brokerage);
389 const license = text(input.license);
390 const phone = text(input.phone);
391 const email = text(input.email);
392 if ([name, brokerage, license, phone, email].some((f) => hasControl(f, false)))
393 return fail(
394 "invalid",
395 "The profile is plain text: no control characters or line breaks.",
396 );
397 if (name.length === 0 || name.length > 120)
398 return fail("invalid", "Your name is 1 to 120 characters.");
399 if (brokerage.length === 0 || brokerage.length > 120)
400 return fail("invalid", "Your brokerage is 1 to 120 characters.");
401 if (license.length === 0 || license.length > 60)
402 return fail(
403 "invalid",
404 "Your license number is required, up to 60 characters: every message shows it.",
405 );
406 if (!PHONE.test(phone))
407 return fail("invalid", "A phone number is 7 to 20 digits.");
408 if (email.length > 254 || !EMAIL.test(email))
409 return fail("invalid", "An email address looks like [email protected].");
410 return ok({ name, brokerage, license, phone, email });
411 }
412
413 export const saveProfile = (
414 db: Database,
415 who: Who,
416 input: Record<string, unknown>,
417 at?: Date,
418 ): Result<Profile> =>
419 audited(db, who, "profile", "update", 1, change(db, who, input, at));
420
421 function change(
422 db: Database,
423 who: Who,
424 input: Record<string, unknown>,
425 at?: Date,
426 ): Result<Profile> {
427 if (permit(who, "profile", "update", { id: 1 }) !== "yes")
428 return refuse(
429 who,
430 "Sign in to change the profile.",
431 "Only an admin can change the profile.",
432 );
433 const read = readAgent(input);
434 if (!read.ok) return read;
435 db.transaction(() => {
436 storeAgent(db, read.value, who.role === "anon" ? "" : who.name, stamp(at));
437 redraftUnsent(db, read.value);
438 })();
439 emit("lead.changed", {});
440 return ok({ id: 1, ...read.value });
441 }
442
369443 /**
370444 * The audit trail, newest first, for whoever the table lets read it (an
371445 * admin, as the scaffold has it). `before` pages back by id. Audit rows name
src/contract.test.ts +17
@@ -13,8 +13,10 @@ import {
1313 deleteLead,
1414 getAudit,
1515 getLead,
16 getProfile,
1617 listAudit,
1718 listLeads,
19 saveProfile,
1820 setState,
1921 } from "./actions.ts";
2022 import { record } from "./audit.ts";
@@ -52,6 +54,13 @@ const aLead = (_authorId: string): number =>
5254 new Date().toISOString(),
5355 agent,
5456 );
57 const PROFILE = {
58 name: "Sam Realtor",
59 brokerage: "Sam & Co",
60 license: "CA DRE 01234567",
61 phone: "(555) 010-0000",
62 email: "[email protected]",
63 };
5564 const NEW = {
5665 name: "Lead",
5766 email: "[email protected]",
@@ -83,6 +92,14 @@ const doors: Record<
8392 setState(db, who, { id: aLead(authorId), state: "lost" }).ok,
8493 delete: (who, authorId) => deleteLead(db, who, { id: aLead(authorId) }).ok,
8594 },
95 // One profile, never created, listed or deleted: read it, and an admin changes it.
96 profile: {
97 read: (who) => getProfile(db, who).ok,
98 update: (who) => saveProfile(db, who, PROFILE).ok,
99 create: () => false,
100 list: () => false,
101 delete: () => false,
102 },
86103 // The trail is written by the app itself, never through a door: there
87104 // is no action that creates, changes or removes a row of it.
88105 audit: {
src/db.ts +12
@@ -82,6 +82,18 @@ export const migrations: string[] = [
8282 `CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
8383 // The scaffold's notes gave way to leads.
8484 `DROP TABLE note`,
85 // The agent whose desk this is, set from the app. One row at most; until
86 // it exists the AGENT_* environment variables are the profile.
87 `CREATE TABLE profile (
88 id INTEGER PRIMARY KEY CHECK (id = 1),
89 name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120),
90 brokerage TEXT NOT NULL CHECK (length(brokerage) BETWEEN 1 AND 120),
91 license TEXT NOT NULL CHECK (length(trim(license)) BETWEEN 1 AND 60),
92 phone TEXT NOT NULL CHECK (length(phone) BETWEEN 1 AND 40),
93 email TEXT NOT NULL CHECK (length(email) BETWEEN 3 AND 254),
94 updated_at TEXT NOT NULL,
95 updated_by TEXT NOT NULL
96 )`,
8597 ];
8698
8799 export function openDb(dir = dataDir): Database {
src/env.ts +3 −2
@@ -33,9 +33,10 @@ export const forgeUrl: string | undefined = process.env.FORGE_URL;
3333 export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? "";
3434
3535 /**
36 * The agent whose desk this is. Every message that goes out carries their
36 * The agent's profile until one is saved from the app (`src/profile.ts`
37 * holds the saved one, and wins). Every message that goes out carries their
3738 * name, brokerage and license number, as state advertising rules require.
38 * Set them in the forge (Settings → App → Environment); the defaults are
39 * Set these in the forge (Settings → App → Environment); the defaults are
3940 * the prototype's sample agent.
4041 */
4142 export const agent = {
src/leads.ts +23
@@ -215,6 +215,29 @@ export function send(
215215 })();
216216 }
217217
218 /**
219 * Words not yet sent are drafted again for `agent`: the profile changed, and
220 * nothing that has not gone out should still carry the old one. Sent
221 * messages are history and are never touched.
222 */
223 export function redraftUnsent(db: Database, agent: Agent): void {
224 const unsent = db
225 .query<{ id: number; lead_id: number; day: number; channel: Channel }, []>(
226 "SELECT id, lead_id, day, channel FROM message WHERE status IN ('draft', 'scheduled', 'due')",
227 )
228 .all();
229 db.transaction(() => {
230 for (const m of unsent) {
231 const found = findLead(db, m.lead_id)!;
232 db.query("UPDATE message SET body = ?1, signature = ?2 WHERE id = ?3").run(
233 draft(found, m.day, agent),
234 signature(m.channel, agent),
235 m.id,
236 );
237 }
238 })();
239 }
240
218241 /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */
219242 export function close(
220243 db: Database,
src/mcp.ts +26
@@ -10,7 +10,9 @@ import type { Database } from "bun:sqlite";
1010 import {
1111 addLead,
1212 getLead,
13 getProfile,
1314 listLeads,
15 saveProfile,
1416 sendReply,
1517 setState,
1618 type Result,
@@ -102,6 +104,30 @@ export const tools: readonly Tool[] = [
102104 run: (db, who, args) =>
103105 setState(db, who, { id: Number(args.id), state: args.state }),
104106 },
107 {
108 name: "get_profile",
109 description:
110 "The agent whose desk this is: name, brokerage, license, phone and email, as every message is signed.",
111 inputSchema: { type: "object", properties: {} },
112 run: (db, who) => getProfile(db, who),
113 },
114 {
115 name: "set_profile",
116 description:
117 "Change the agent's name, brokerage, license, phone and email (admin only). Unsent drafts take it at once; sent messages keep theirs.",
118 inputSchema: {
119 type: "object",
120 properties: {
121 name: { type: "string" },
122 brokerage: { type: "string" },
123 license: { type: "string" },
124 phone: { type: "string" },
125 email: { type: "string" },
126 },
127 required: ["name", "brokerage", "license", "phone", "email"],
128 },
129 run: (db, who, args) => saveProfile(db, who, args),
130 },
105131 ];
106132
107133 /** One JSON-RPC message in, an HTTP status and a body out (a notification gets 202 and no body). */
src/pages/desk.ts +5 −1
@@ -7,19 +7,22 @@ import { day, clock, consent, source, STATE_LABEL } from "./parts.ts";
77 import { layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 import type { DeskLead } from "../leads.ts";
10 import type { Agent } from "../env.ts";
1011 import type { Who } from "../who.ts";
1112
1213 export function deskPage(input: {
1314 who: Who;
15 agent: Agent;
1416 leads: readonly DeskLead[] | undefined;
1517 mayAdd: boolean;
1618 mayReset: boolean;
1719 notice?: string | undefined;
1820 }): string {
19 const { who, leads, notice } = input;
21 const { who, agent, leads, notice } = input;
2022 if (leads === undefined)
2123 return layout({
2224 who,
25 agent,
2326 path: "/",
2427 notice,
2528 body: `<section class="welcome">
@@ -38,6 +41,7 @@ export function deskPage(input: {
3841 : `<ul class="desk">${leads.map((lead) => row(lead, now)).join("")}</ul>`;
3942 return layout({
4043 who,
44 agent,
4145 path: "/",
4246 notice,
4347 heading: "Desk",
src/pages/layout.ts +10 −3
@@ -5,24 +5,31 @@
55 * card a chat app unfurls.
66 */
77
8 import { agent, description, publicOrigin, title } from "../env.ts";
8 import { description, publicOrigin, title } from "../env.ts";
9 import type { Agent } from "../env.ts";
910 import { asset, escape } from "../http.ts";
1011 import { token, tokensHref } from "../tokens.ts";
1112 import type { Who } from "../who.ts";
1213
14 // The name, brokerage and license are shown to everyone on purpose: they are
15 // the advertising disclosure the messages carry. Phone and email are not;
16 // they appear only on /profile, which needs a signed-in person.
1317 export function layout(input: {
1418 body: string;
1519 who: Who;
20 /** The agent whose desk it is: the profile as saved now. */
21 agent: Agent;
1622 path: string;
1723 heading?: string;
1824 notice?: string | undefined;
1925 }): string {
20 const { body, who, path, notice } = input;
26 const { body, who, agent, path, notice } = input;
2127 const name = input.heading === undefined ? title : `${input.heading} · ${title}`;
2228 const door =
2329 who.role === "anon"
2430 ? `<a class="button button-quiet" href="/__forge/signin?to=${escape(encodeURIComponent(path))}">Sign in</a>`
25 : `<span class="you">${escape(who.name)}</span>
31 : `<a class="button button-quiet" href="/profile">Your profile</a>
32 <span class="you">${escape(who.name)}</span>
2633 <a class="button button-quiet" href="/__forge/signout">Sign out</a>`;
2734 return `<!doctype html>
2835 <html lang="en">
src/pages/lead.ts +4 −1
@@ -7,6 +7,7 @@
77 import { channelFor, MAX_BODY } from "../drafts.ts";
88 import { escape } from "../http.ts";
99 import type { LeadDetail, Message } from "../leads.ts";
10 import type { Agent } from "../env.ts";
1011 import type { Who } from "../who.ts";
1112 import { layout } from "./layout.ts";
1213 import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts";
@@ -22,11 +23,12 @@ const words = (m: Pick<Message, "body" | "signature">): string =>
2223
2324 export function leadPage(input: {
2425 who: Who;
26 agent: Agent;
2527 lead: LeadDetail;
2628 mayUpdate: boolean;
2729 notice?: string | undefined;
2830 }): string {
29 const { who, lead, mayUpdate, notice } = input;
31 const { who, agent, lead, mayUpdate, notice } = input;
3032 const ready = lead.messages.find(
3133 (m) => m.status === "draft" || m.status === "due",
3234 );
@@ -112,6 +114,7 @@ export function leadPage(input: {
112114
113115 return layout({
114116 who,
117 agent,
115118 path,
116119 notice,
117120 heading: lead.name,
src/pages/profile.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * Your profile: the name, brokerage, license, phone and email every message
3 * is signed with. Everyone signed in reads it; an admin changes it in place.
4 */
5
6 import type { Profile } from "../actions.ts";
7 import { escape } from "../http.ts";
8 import type { Who } from "../who.ts";
9 import { layout } from "./layout.ts";
10
11 const FIELDS = [
12 { name: "name", label: "Name", type: "text", max: 120, auto: "name" },
13 { name: "brokerage", label: "Brokerage", type: "text", max: 120, auto: "organization" },
14 { name: "license", label: "License number", type: "text", max: 60, auto: "off" },
15 { name: "phone", label: "Phone", type: "tel", max: 20, auto: "tel" },
16 { name: "email", label: "Email", type: "email", max: 254, auto: "email" },
17 ] as const;
18
19 export function profilePage(input: {
20 who: Who;
21 profile: Profile;
22 mayUpdate: boolean;
23 notice?: string | undefined;
24 }): string {
25 const { who, profile, mayUpdate, notice } = input;
26 const body = mayUpdate
27 ? `<form class="card stack" method="post" action="/profile">
28 ${FIELDS.map(
29 (f) =>
30 `<label>${f.label} <input class="input" name="${f.name}" type="${f.type}" value="${escape(profile[f.name])}" required maxlength="${f.max}" autocomplete="${f.auto}"></label>`,
31 ).join("\n ")}
32 <button class="button">Save profile</button>
33 </form>`
34 : `<div class="card stack">
35 ${FIELDS.map((f) => `<p><span class="muted">${f.label}</span><br>${escape(profile[f.name])}</p>`).join("\n ")}
36 <p class="muted">Only an admin can change this.</p>
37 </div>`;
38 return layout({
39 who,
40 agent: profile,
41 path: "/profile",
42 notice,
43 heading: "Your profile",
44 body: `<p><a class="backlink" href="/">← All leads</a></p>
45 <h1>Your profile</h1>
46 <p class="muted">Every message you send is signed with this: your name, brokerage and license number, and how to reach you. Drafts not yet sent change the moment you save; messages already sent keep the signature they went out with.</p>
47 ${body}`,
48 });
49 }
src/profile.test.ts added +145
@@ -0,0 +1,145 @@
1 /**
2 * The agent's profile: the environment until one is saved, then the saved
3 * one — in the next draft, the unsent ones, and every screen — while what
4 * was already sent keeps the signature it went out with.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import {
11 addLead,
12 getProfile,
13 getLead,
14 saveProfile,
15 sendReply,
16 type Result,
17 } from "./actions.ts";
18 import { listAudit } from "./actions.ts";
19 import { openDb } from "./db.ts";
20 import { agent } from "./env.ts";
21 import { layout } from "./pages/layout.ts";
22 import { currentAgent } from "./profile.ts";
23 import type { Who } from "./who.ts";
24
25 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-profile-")));
26 const alice: Who = { role: "user", id: "u1", name: "alice" };
27 const root: Who = { role: "admin", id: "u0", name: "root" };
28 const anon: Who = { role: "anon" };
29 const must = <T>(r: Result<T>): T => {
30 if (!r.ok) throw new Error(`${r.error}: ${r.message}`);
31 return r.value;
32 };
33 const lead = {
34 name: "Maria Gonzalez",
35 email: "[email protected]",
36 phone: "(206) 555-0101",
37 source: "zillow",
38 message: "Could we see 418 Juniper Ln?",
39 consent: true,
40 };
41 const sam = {
42 name: "Sam Realtor",
43 brokerage: "Sam & Co",
44 license: "WA 99887",
45 phone: "(555) 010-0000",
46 email: "[email protected]",
47 };
48
49 test("before any save, the environment is the profile", () => {
50 const db = fresh();
51 expect(currentAgent(db)).toEqual(agent);
52 expect(must(getProfile(db, alice))).toEqual({ id: 1, ...agent });
53 const first = must(addLead(db, alice, lead)).messages[0]!;
54 expect(first.signature).toContain(agent.license);
55 });
56
57 test("saving changes the next draft's signature and the unsent ones, never a sent one", () => {
58 const db = fresh();
59 const a = must(addLead(db, alice, lead));
60 const sent = must(sendReply(db, alice, { id: a.id }));
61 const oldSignature = sent.messages[0]!.signature;
62 expect(oldSignature).toContain(agent.license);
63 const b = must(addLead(db, alice, { ...lead, email: "[email protected]" }));
64
65 expect(must(saveProfile(db, root, sam))).toEqual({ id: 1, ...sam });
66 expect(currentAgent(db)).toEqual(sam);
67
68 const next = must(addLead(db, alice, { ...lead, email: "[email protected]" }));
69 expect(next.messages[0]!.signature).toContain("WA 99887");
70 expect(next.messages[0]!.signature).not.toContain(agent.license);
71 // A draft written before the save is signed, and worded, as the saved profile.
72 const waiting = must(getLead(db, alice, { id: b.id })).messages[0]!;
73 expect(waiting.signature).toContain("WA 99887");
74 expect(waiting.body).toContain("Sam");
75 expect(waiting.body).toContain("Sam & Co");
76 // The follow-ups still to come as well.
77 const upcoming = must(getLead(db, alice, { id: a.id })).messages.filter((m) => m.status === "scheduled");
78 expect(upcoming.length).toBeGreaterThan(0);
79 for (const m of upcoming) expect(m.signature).toContain("WA 99887");
80 // What went out keeps what it went out with.
81 const history = must(getLead(db, alice, { id: a.id })).messages[0]!;
82 expect(history.status).toBe("sent");
83 expect(history.signature).toBe(oldSignature);
84 expect(history.signature).not.toContain("WA 99887");
85 // And what is sent after the save is signed with the new one.
86 const later = must(sendReply(db, alice, { id: b.id }));
87 expect(later.messages[0]!.signature).toContain("WA 99887");
88 });
89
90 test("every screen wears the saved profile", () => {
91 const db = fresh();
92 must(saveProfile(db, root, sam));
93 const page = layout({ body: "", who: alice, agent: currentAgent(db), path: "/" });
94 expect(page).toContain("Sam Realtor");
95 expect(page).toContain("WA 99887");
96 expect(page).toContain('href="/profile"');
97 });
98
99 test("a user may read the profile, not change it; a stranger may do neither", () => {
100 const db = fresh();
101 const refused = saveProfile(db, alice, sam);
102 expect(refused.ok).toBe(false);
103 if (!refused.ok) expect(refused.error).toBe("forbidden");
104 const stranger = saveProfile(db, anon, sam);
105 if (!stranger.ok) expect(stranger.error).toBe("signin_required");
106 expect(stranger.ok).toBe(false);
107 const read = getProfile(db, anon);
108 if (!read.ok) expect(read.error).toBe("signin_required");
109 expect(read.ok).toBe(false);
110 expect(currentAgent(db)).toEqual(agent);
111 });
112
113 test("the license may not be blank, and every field is checked", () => {
114 const db = fresh();
115 for (const bad of [
116 { license: "" },
117 { license: " " },
118 { license: "x".repeat(61) },
119 { license: undefined },
120 { name: "" },
121 { name: "A\x1b[2J" },
122 { brokerage: "Two\nLines" },
123 { phone: "call me" },
124 { email: "not-an-email" },
125 { email: "a@b" },
126 { name: "x".repeat(121) },
127 { name: 42 },
128 ]) {
129 const r = saveProfile(db, root, { ...sam, ...bad });
130 expect([JSON.stringify(bad), r.ok]).toEqual([JSON.stringify(bad), false]);
131 if (!r.ok) expect(r.error).toBe("invalid");
132 }
133 expect(currentAgent(db)).toEqual(agent);
134 });
135
136 test("changes are audited, refusals too", () => {
137 const db = fresh();
138 saveProfile(db, root, sam);
139 saveProfile(db, alice, sam);
140 const rows = must(listAudit(db, root)).filter((r) => r.resource === "profile");
141 expect(rows.map((r) => [r.verb, r.outcome, r.role])).toEqual([
142 ["update", "forbidden", "user"],
143 ["update", "ok", "admin"],
144 ]);
145 });
src/profile.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * The agent whose desk this is, kept in SQLite. Until a profile is saved
3 * the `AGENT_*` environment variables (`agent` in `src/env.ts`) speak for
4 * them; once one is saved, it wins. No permission is asked here: whether a
5 * person may change it is `actions.ts`'s question.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { agent as fromEnvironment, type Agent } from "./env.ts";
10
11 /** The saved profile, or the environment's until there is one. */
12 export function currentAgent(db: Database): Agent {
13 const saved = db
14 .query<Agent, []>(
15 "SELECT name, brokerage, license, phone, email FROM profile WHERE id = 1",
16 )
17 .get();
18 return saved ?? fromEnvironment;
19 }
20
21 /** Save `agent` as the profile, whoever it replaces. */
22 export function storeAgent(
23 db: Database,
24 agent: Agent,
25 by: string,
26 at: string,
27 ): void {
28 db.query(
29 `INSERT INTO profile (id, name, brokerage, license, phone, email, updated_at, updated_by)
30 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7)
31 ON CONFLICT (id) DO UPDATE SET name = ?1, brokerage = ?2, license = ?3,
32 phone = ?4, email = ?5, updated_at = ?6, updated_by = ?7`,
33 ).run(agent.name, agent.brokerage, agent.license, agent.phone, agent.email, at, by);
34 }
src/routes.ts +80
@@ -18,9 +18,11 @@ import {
1818 deleteLead,
1919 getAudit,
2020 getLead,
21 getProfile,
2122 listAudit,
2223 listLeads,
2324 resetSample,
25 saveProfile,
2426 sendReply,
2527 setState,
2628 tick,
@@ -48,6 +50,8 @@ import { rpc } from "./mcp.ts";
4850 import { deskPage } from "./pages/desk.ts";
4951 import { layout } from "./pages/layout.ts";
5052 import { leadPage } from "./pages/lead.ts";
53 import { profilePage } from "./pages/profile.ts";
54 import { currentAgent } from "./profile.ts";
5155 import { tokensCss } from "./tokens.ts";
5256 import type { Who } from "./who.ts";
5357
@@ -162,6 +166,23 @@ export const AUDIT_ROW: Schema = {
162166 },
163167 required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"],
164168 };
169 const PROFILE_FIELDS = {
170 name: { type: "string", minLength: 1, maxLength: 120 },
171 brokerage: { type: "string", minLength: 1, maxLength: 120 },
172 license: {
173 type: "string",
174 minLength: 1,
175 maxLength: 60,
176 description: "Required: every message shows it.",
177 },
178 phone: { type: "string", description: "7 to 20 digits." },
179 email: { type: "string", format: "email" },
180 } as const;
181 export const PROFILE: Schema = {
182 type: "object",
183 properties: { id: { const: 1 }, ...PROFILE_FIELDS },
184 required: ["id", ...Object.keys(PROFILE_FIELDS)],
185 };
165186 export const ERROR: Schema = {
166187 type: "object",
167188 properties: { error: { type: "string" }, message: { type: "string" } },
@@ -259,6 +280,7 @@ export const routes: readonly Route[] = [
259280 return html(
260281 deskPage({
261282 who: c.who,
283 agent: currentAgent(c.db),
262284 leads: leads.ok ? leads.value : undefined,
263285 mayAdd: permit(c.who, "lead", "create") === "yes",
264286 mayReset: permit(c.who, "lead", "delete") === "yes",
@@ -314,6 +336,7 @@ export const routes: readonly Route[] = [
314336 return html(
315337 layout({
316338 who: c.who,
339 agent: currentAgent(c.db),
317340 path: c.url.pathname,
318341 body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`,
319342 }),
@@ -323,6 +346,7 @@ export const routes: readonly Route[] = [
323346 return html(
324347 leadPage({
325348 who: c.who,
349 agent: currentAgent(c.db),
326350 lead: found.value,
327351 mayUpdate: permit(c.who, "lead", "update", { ...found.value }) === "yes",
328352 notice,
@@ -447,6 +471,62 @@ export const routes: readonly Route[] = [
447471 ),
448472 },
449473
474 // Whose desk it is: the name, brokerage and license every message is signed with.
475 {
476 method: "GET",
477 path: "/profile",
478 handle: (c) => {
479 const found = getProfile(c.db, c.who);
480 if (!browsing(c.request)) return answer(found);
481 const { notice, clear } = readNotice(c.request);
482 if (!found.ok)
483 return html(
484 layout({
485 who: c.who,
486 agent: currentAgent(c.db),
487 path: c.url.pathname,
488 body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`,
489 }),
490 STATUS[found.error],
491 );
492 return html(
493 profilePage({
494 who: c.who,
495 profile: found.value,
496 mayUpdate: permit(c.who, "profile", "update", { id: 1 }) === "yes",
497 notice,
498 }),
499 200,
500 clear,
501 );
502 },
503 api: {
504 summary:
505 "The agent whose desk this is: name, brokerage, license, phone and email. The AGENT_* environment variables until a profile is saved.",
506 answer: PROFILE,
507 },
508 },
509 {
510 method: "POST",
511 path: "/profile",
512 handle: (c) =>
513 posted(
514 c,
515 (input) => saveProfile(c.db, c.who, input),
516 () => ({ to: "/profile", said: "Saved. Drafts now carry this profile." }),
517 ),
518 api: {
519 summary:
520 "Change the profile (admin only). Drafts not yet sent take it at once; messages already sent keep the signature they went out with. The license may not be blank.",
521 body: {
522 type: "object",
523 properties: PROFILE_FIELDS,
524 required: Object.keys(PROFILE_FIELDS),
525 },
526 answer: PROFILE,
527 },
528 },
529
450530 // Who tried to change what: the audit trail, for whoever the table lets read it.
451531 {
452532 method: "GET",
src/sample.ts +3 −2
@@ -9,7 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import type { Source } from "./drafts.ts";
12 import { agent } from "./env.ts";
12 import { currentAgent } from "./profile.ts";
1313 import {
1414 advance,
1515 close,
@@ -78,7 +78,7 @@ export function seed(db: Database, now: Date): number {
7878 // Oldest first, so ids rise with time as they would have.
7979 for (const sample of [...SAMPLES].sort((a, b) => b.ago - a.ago)) {
8080 const asked = t - sample.ago;
81 const id = insertLead(db, sample, iso(asked), agent);
81 const id = insertLead(db, sample, iso(asked), currentAgent(db));
8282 if (sample.answeredIn !== undefined) {
8383 const replied = asked + sample.answeredIn;
8484 sendReady(db, id, iso(replied));
@@ -95,6 +95,7 @@ export function seed(db: Database, now: Date): number {
9595
9696 /** Send what is ready for a sample lead, as drafted, as the agent. */
9797 function sendReady(db: Database, id: number, at: string): void {
98 const agent = currentAgent(db);
9899 send(db, findLead(db, id)!, readyFor(db, id)!, readyFor(db, id)!.body, agent.name, at, agent);
99100 }
100101
src/server.test.ts +62
@@ -271,6 +271,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
271271 "add_lead",
272272 "send_reply",
273273 "mark_lead",
274 "get_profile",
275 "set_profile",
274276 ]);
275277 const call = (name: string, args: unknown, who = {}) =>
276278 rpc(
@@ -282,6 +284,16 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
282284 },
283285 who,
284286 );
287 // The profile over MCP: a stranger and a user are refused; an admin's change is what get_profile then says.
288 expect((await call("get_profile", {})).result.isError).toBe(true);
289 expect((await call("get_profile", {}, bob)).result.isError).toBeUndefined();
290 const mine = { name: "Mcp Agent", brokerage: "Tools Realty", license: "OR 4242", phone: "(555) 010-4242", email: "[email protected]" };
291 const userSet = await call("set_profile", mine, bob);
292 expect(userSet.result.isError).toBe(true);
293 expect(userSet.result.content[0].text).toContain("forbidden");
294 expect((await call("set_profile", { ...mine, license: "" }, root)).result.isError).toBe(true);
295 expect((await call("set_profile", mine, root)).result.isError).toBeUndefined();
296 expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine });
285297 const refused = await call("add_lead", NEW);
286298 expect(refused.result.isError).toBe(true);
287299 const added = await call("add_lead", { ...NEW, name: "Over MCP" }, root);
@@ -460,3 +472,53 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
460472 );
461473 }
462474 });
475
476 test("the profile is a page and a JSON twin: everyone in reads, only an admin saves", async () => {
477 const seen = await (await api("/profile", { headers: asJson }, alice)).json();
478 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "phone"]);
479 const page = await (await api("/profile", {}, alice)).text();
480 expect(page).toContain("Your profile");
481 expect(page).not.toContain('action="/profile"');
482 expect((await api("/profile", { redirect: "manual" })).status).toBe(401);
483
484 const sam = { name: "Sam Realtor", brokerage: "Sam & Co", license: "WA 99887", phone: "(555) 010-0000", email: "[email protected]" };
485 const refused = await api("/profile", { method: "POST", ...jsonBody(sam) }, alice);
486 expect(refused.status).toBe(403);
487 const blank = await api("/profile", { method: "POST", ...jsonBody({ ...sam, license: " " }) }, root);
488 expect(blank.status).toBe(422);
489 const saved = await api("/profile", { method: "POST", ...jsonBody(sam) }, root);
490 expect(saved.status).toBe(200);
491 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toEqual({ id: 1, ...sam });
492 const form_ = await api("/profile", {}, root);
493 expect(await form_.text()).toContain('action="/profile"');
494 const home = await (await api("/", {}, bob)).text();
495 expect(home).toContain("Sam Realtor");
496 expect(home).toContain("WA 99887");
497 // A form from another site changes nothing.
498 const cross = await api("/profile", { method: "POST", headers: { "sec-fetch-site": "cross-site" }, body: form({ ...sam, license: "EVIL" }) }, root);
499 expect(cross.status).toBe(403);
500 expect(((await (await api("/profile", { headers: asJson }, bob)).json()) as { license: string }).license).toBe("WA 99887");
501 const open = await (await api("/openapi.json", {}, root)).json() as { paths: Record<string, unknown> };
502 expect(Object.keys(open.paths["/profile"] as object).sort()).toEqual(["get", "post"]);
503 });
504
505 test("/profile answers each identity as the contract table says", async () => {
506 const { permit } = await import("./contract.ts");
507 const body = { name: "Table Test", brokerage: "Table Realty", license: "TT 1", phone: "(555) 010-1111", email: "[email protected]" };
508 const who = [
509 ["anon", {}, { role: "anon" } as const],
510 ["user", bob, { role: "user", id: "u2", name: "bob" } as const],
511 ["admin", root, { role: "admin", id: "u0", name: "root" } as const],
512 ] as const;
513 for (const [name, headers, identity] of who) {
514 const read = await api("/profile", { headers: asJson }, headers);
515 expect([name, "read", read.status === 200]).toEqual([name, "read", permit(identity, "profile", "read", { id: 1 }) === "yes"]);
516 if (read.status !== 200) expect(read.status).toBe(name === "anon" ? 401 : 403);
517 const write = await api("/profile", { method: "POST", ...jsonBody(body) }, headers);
518 expect([name, "update", write.status === 200]).toEqual([name, "update", permit(identity, "profile", "update", { id: 1 }) === "yes"]);
519 if (write.status !== 200) expect(write.status).toBe(name === "anon" ? 401 : 403);
520 }
521 // The verbs the table gives to nobody have no route at all.
522 for (const method of ["PATCH", "DELETE", "PUT"])
523 expect((await api("/profile", { method, ...jsonBody(body) }, root)).status).toBeGreaterThanOrEqual(400);
524 });
src/terminal.test.ts +66
@@ -202,3 +202,69 @@ test("clean keeps words and lines, drops every control", () => {
202202 expect(clean("one\r\ntwo")).toBe("one two");
203203 expect(clean("one\r\ntwo", false)).toBe("one\ntwo");
204204 });
205
206 const guest: Who = { role: "anon" };
207 const clear = (t: ReturnType<typeof terminal>, text: string): void => {
208 for (let i = 0; i < text.length; i++) t.key("\x7f");
209 };
210
211 test("p opens the profile: a guest is told to sign in, a user reads and cannot edit, an admin edits", () => {
212 const db = fresh();
213 const stranger = terminal(db, guest);
214 stranger.key("p");
215 expect(read(stranger)).toContain("Sign in to read the profile.");
216 expect(read(stranger)).not.toContain(agent.phone);
217 stranger.key("e");
218 expect(read(stranger)).not.toContain("editing");
219
220 const user = terminal(db, alice);
221 user.key("p");
222 expect(read(user)).toContain(agent.phone);
223 expect(read(user)).toContain(agent.email);
224 expect(read(user)).toContain("Only an admin can change it");
225 user.key("e");
226 expect(read(user)).toContain("Only an admin can change the profile.");
227 expect(read(user)).not.toContain("editing");
228 });
229
230 test("an admin edits the profile one field at a time; it is saved, audited and reaches the drafts", () => {
231 const db = fresh();
232 const t = terminal(db, root);
233 t.key("p");
234 expect(read(t)).toContain("e edit");
235 t.key("e");
236 const next = (current: string, text: string): void => {
237 clear(t, current);
238 type(t, text);
239 t.key("\r");
240 };
241 next(agent.name, "Sam Realtor");
242 next(agent.brokerage, "Sam & Co");
243 next(agent.license, "WA 99887");
244 next(agent.phone, "(555) 010-0000");
245 next(agent.email, "[email protected]");
246 expect(read(t)).toContain("Saved.");
247 expect(read(t)).toContain("WA 99887");
248 const saved = db.query<{ license: string }, []>("SELECT license FROM profile").get();
249 expect(saved?.license).toBe("WA 99887");
250 const id = (listLeads(db, root) as { ok: true; value: { id: number; state: string }[] }).value.find((l) => l.state === "new")!.id;
251 const lead = getLead(db, root, { id });
252 expect(lead.ok && lead.value.messages[0]!.signature).toContain("WA 99887");
253 const audit = db
254 .query<{ outcome: string }, []>("SELECT outcome FROM audit WHERE resource = 'profile'")
255 .all();
256 expect(audit.map((a) => a.outcome)).toEqual(["ok"]);
257 });
258
259 test("a blank license typed in the terminal is refused and nothing is saved", () => {
260 const db = fresh();
261 const t = terminal(db, root);
262 t.key("p");
263 t.key("e");
264 for (const current of [agent.name, agent.brokerage]) t.key("\r"), void current;
265 clear(t, agent.license);
266 t.key("\r");
267 for (let i = 0; i < 2; i++) t.key("\r");
268 expect(read(t)).toContain("license number is required");
269 expect(db.query("SELECT * FROM profile").all()).toHaveLength(0);
270 });
src/terminal.ts +94 −4
@@ -5,11 +5,13 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · n log a lead · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · n log a lead · p profile · 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
1212 * add one field at a time; enter next · esc cancel
13 * profile the name, brokerage and license every message carries ·
14 * e edit (admin): one field at a time, enter next, the last saves · esc back
1315 *
1416 * Nothing is sent from a screen that has not shown it: the lead screen
1517 * shows what they asked, the words going out, the signature under them,
@@ -21,16 +23,19 @@ import {
2123 addLead,
2224 deleteLead,
2325 getLead,
26 getProfile,
2427 listLeads,
2528 resetSample,
29 saveProfile,
2630 sendReply,
2731 setState,
2832 } from "./actions.ts";
2933 import { between, elapsed, tone } from "./clock.ts";
3034 import { permit } from "./contract.ts";
3135 import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts";
32 import { agent, ssh, title, where } from "./env.ts";
36 import { ssh, title, where } from "./env.ts";
3337 import type { DeskLead, LeadDetail, Message } from "./leads.ts";
38 import { currentAgent } from "./profile.ts";
3439 import type { Who } from "./who.ts";
3540
3641 const ESC = "\x1b[";
@@ -84,8 +89,18 @@ const ADD_FIELDS = [
8489 { key: "consent", label: "Written consent to be texted? y/n" },
8590 ] as const;
8691
92 const PROFILE_FIELDS = [
93 { key: "name", label: "Name" },
94 { key: "brokerage", label: "Brokerage" },
95 { key: "license", label: "License number (required: every message shows it)" },
96 { key: "phone", label: "Phone" },
97 { key: "email", label: "Email" },
98 ] as const;
99
87100 type View =
88101 | { name: "desk" }
102 | { name: "profile" }
103 | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> }
89104 | { name: "lead"; id: number }
90105 | { name: "edit"; id: number; text: string }
91106 | { name: "add"; step: number; typed: string; fields: Record<string, string> }
@@ -134,6 +149,7 @@ export function terminal(
134149 }
135150
136151 function header(): string[] {
152 const agent = currentAgent(db);
137153 return [
138154 `${bold(title)} ${clean(agent.name)} · ${clean(agent.brokerage)} ${dim(clean(where))} ${dim(me.role === "anon" ? "guest" : clean(me.name))}`,
139155 ssh === undefined ? "" : dim(`connect: ${ssh}`),
@@ -164,7 +180,7 @@ export function terminal(
164180 lines.push(
165181 "",
166182 dim(
167 `j/k move · enter open · n log a lead${admin() ? " · R restart the samples" : ""} · esc quit`,
183 `j/k move · enter open · n log a lead · p profile${admin() ? " · R restart the samples" : ""} · esc quit`,
168184 ),
169185 );
170186 return lines;
@@ -243,6 +259,32 @@ export function terminal(
243259 return lines;
244260 }
245261
262 /** Whether the table lets this person change the profile: only to leave out the hint. */
263 const mayEditProfile = (): boolean =>
264 permit(me, "profile", "update", { id: 1 }) === "yes";
265
266 function profileScreen(): string[] {
267 const found = getProfile(db, me);
268 if (!found.ok) return [found.message, "", dim("esc back")];
269 return [
270 bold("Your profile"),
271 "",
272 ...PROFILE_FIELDS.map((f) => `${f.label.split(" (")[0]!.padEnd(15)} ${clean(found.value[f.key])}`),
273 "",
274 dim(`Every message is signed with this.${mayEditProfile() ? " e edit ·" : " Only an admin can change it ·"} esc back`),
275 ];
276 }
277
278 function profileEditScreen(v: Extract<View, { name: "profile-edit" }>): string[] {
279 const lines = [bold("Your profile — editing"), ""];
280 PROFILE_FIELDS.forEach((field, i) => {
281 if (i < v.step) lines.push(`${field.label}: ${clean(v.fields[field.key] ?? "")}`);
282 if (i === v.step) lines.push(`${field.label}: ${clean(v.typed)}█`);
283 });
284 lines.push("", dim("enter next, the last one saves · esc cancel"));
285 return lines;
286 }
287
246288 function addScreen(v: Extract<View, { name: "add" }>): string[] {
247289 const lines = [bold("Log a lead by hand"), ""];
248290 ADD_FIELDS.forEach((field, i) => {
@@ -291,7 +333,11 @@ export function terminal(
291333 const body =
292334 view.name === "desk"
293335 ? deskScreen()
294 : view.name === "lead"
336 : view.name === "profile"
337 ? profileScreen()
338 : view.name === "profile-edit"
339 ? profileEditScreen(view)
340 : view.name === "lead"
295341 ? leadScreen(view.id, w)
296342 : view.name === "edit"
297343 ? leadScreen(view.id, w, view.text)
@@ -324,10 +370,54 @@ export function terminal(
324370 view = { name: "lead", id: rows[cursor]!.id };
325371 else if (input === "n")
326372 view = { name: "add", step: 0, typed: "", fields: {} };
373 else if (input === "p") view = { name: "profile" };
327374 else if (input === "R")
328375 view = { name: "confirm", what: "reset", back: view };
329376 return;
330377 }
378 case "profile": {
379 if (input === "\x1b" || input === "\x7f") view = { name: "desk" };
380 else if (input === "e") {
381 const found = getProfile(db, me);
382 if (!found.ok) said = found.message;
383 else if (!mayEditProfile()) said = "Only an admin can change the profile.";
384 else
385 view = {
386 name: "profile-edit",
387 step: 0,
388 typed: found.value[PROFILE_FIELDS[0].key],
389 fields: {},
390 };
391 }
392 return;
393 }
394 case "profile-edit": {
395 if (input === "\x1b") {
396 said = "Nothing changed.";
397 view = { name: "profile" };
398 } else if (input === "\r") {
399 const field = PROFILE_FIELDS[view.step]!;
400 const fields = { ...view.fields, [field.key]: view.typed.trim() };
401 const following = PROFILE_FIELDS[view.step + 1];
402 if (following !== undefined) {
403 const current = getProfile(db, me);
404 view = {
405 name: "profile-edit",
406 step: view.step + 1,
407 typed: current.ok ? current.value[following.key] : "",
408 fields,
409 };
410 } else {
411 const saved = saveProfile(db, me, fields);
412 said = saved.ok ? "Saved. Drafts now carry this profile." : saved.message;
413 view = { name: "profile" };
414 }
415 } else {
416 const next = typing(view.typed, input);
417 if (next !== undefined) view = { ...view, typed: next };
418 }
419 return;
420 }
331421 case "lead": {
332422 const id = view.id;
333423 const l = lead(id);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs