Public: anyone can read this; the crew can change it.
Let the agent set their name, brokerage and license from the app #8
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/6-let-the-agent-set-their-name-brokerage-a → main 2 commits fork
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: | ||
| 110 | 110 | drafts and schedules the cadence (days in `CADENCE`); `advance` makes a |
| 111 | 111 | touch due on its day; `close` (qualified or lost) skips what is left. |
| 112 | 112 | - `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 | |
| 114 | 115 | carries, and the consent rule (`channelFor`: text only with written |
| 115 | 116 | consent and a phone number). A trigger in `src/db.ts` holds that rule |
| 116 | 117 | 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. | ||
| 66 | 66 | |
| 67 | 67 | ## Your profile |
| 68 | 68 | |
| 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. | |
| 71 | 78 | |
| 72 | 79 | | variable | what it is | |
| 73 | 80 | | ----------------- | ------------------------------- | |
| @@ -77,6 +84,13 @@ app uses a sample agent, Jordan Avery of Harbor & Pine Realty. | ||
| 77 | 84 | | `AGENT_PHONE` | the phone number in your emails | |
| 78 | 85 | | `AGENT_EMAIL` | the email address in your emails | |
| 79 | 86 | |
| 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 | ||
| 80 | 94 | ## For whoever connects it to a website |
| 81 | 95 | |
| 82 | 96 | Every page has a JSON twin. Send `content-type: application/json` (or |
contract.json +9
| @@ -16,6 +16,15 @@ | ||
| 16 | 16 | "list": "user" |
| 17 | 17 | } |
| 18 | 18 | }, |
| 19 | "profile": { | |
| 20 | "can": { | |
| 21 | "create": "nobody", | |
| 22 | "read": "user", | |
| 23 | "update": "admin", | |
| 24 | "delete": "nobody", | |
| 25 | "list": "nobody" | |
| 26 | } | |
| 27 | }, | |
| 19 | 28 | "audit": { |
| 20 | 29 | "api": "/api/audit", |
| 21 | 30 | "can": { |
contract/openapi.json +171
| @@ -441,6 +441,177 @@ | ||
| 441 | 441 | } |
| 442 | 442 | } |
| 443 | 443 | }, |
| 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 | }, | |
| 444 | 615 | "/api/audit": { |
| 445 | 616 | "get": { |
| 446 | 617 | "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"; | ||
| 10 | 10 | import { record, type AuditRow } from "./audit.ts"; |
| 11 | 11 | import { permit } from "./contract.ts"; |
| 12 | 12 | import { MAX_BODY, SOURCES, type Source } from "./drafts.ts"; |
| 13 | import { agent } from "./env.ts"; | |
| 13 | import type { Agent } from "./env.ts"; | |
| 14 | 14 | import { |
| 15 | 15 | advance, |
| 16 | 16 | clearLeads, |
| @@ -19,6 +19,7 @@ import { | ||
| 19 | 19 | detail, |
| 20 | 20 | insertLead, |
| 21 | 21 | readyFor, |
| 22 | redraftUnsent, | |
| 22 | 23 | removeLead, |
| 23 | 24 | send, |
| 24 | 25 | type DeskLead, |
| @@ -26,6 +27,7 @@ import { | ||
| 26 | 27 | type NewLead, |
| 27 | 28 | } from "./leads.ts"; |
| 28 | 29 | import { emit } from "./live.ts"; |
| 30 | import { currentAgent, storeAgent } from "./profile.ts"; | |
| 29 | 31 | import { seed } from "./sample.ts"; |
| 30 | 32 | import type { Who } from "./who.ts"; |
| 31 | 33 | |
| @@ -205,7 +207,7 @@ function add( | ||
| 205 | 207 | return refuse(who, "Sign in to add a lead.", "You may not add a lead."); |
| 206 | 208 | const read = readNewLead(input); |
| 207 | 209 | 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)); | |
| 209 | 211 | const added = detail(db, id)!; |
| 210 | 212 | emit("lead.added", { id }); |
| 211 | 213 | return ok(added); |
| @@ -249,7 +251,7 @@ function reply( | ||
| 249 | 251 | `A${ready.channel === "text" ? " text" : "n email"} is 1 to ${max} characters.`, |
| 250 | 252 | ); |
| 251 | 253 | 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)); | |
| 253 | 255 | emit("lead.changed", { id: found.value.id }); |
| 254 | 256 | return ok(detail(db, found.value.id)!); |
| 255 | 257 | } |
| @@ -366,6 +368,78 @@ export function resetSample( | ||
| 366 | 368 | return result; |
| 367 | 369 | } |
| 368 | 370 | |
| 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 | ||
| 369 | 443 | /** |
| 370 | 444 | * The audit trail, newest first, for whoever the table lets read it (an |
| 371 | 445 | * admin, as the scaffold has it). `before` pages back by id. Audit rows name |
src/contract.test.ts +17
| @@ -13,8 +13,10 @@ import { | ||
| 13 | 13 | deleteLead, |
| 14 | 14 | getAudit, |
| 15 | 15 | getLead, |
| 16 | getProfile, | |
| 16 | 17 | listAudit, |
| 17 | 18 | listLeads, |
| 19 | saveProfile, | |
| 18 | 20 | setState, |
| 19 | 21 | } from "./actions.ts"; |
| 20 | 22 | import { record } from "./audit.ts"; |
| @@ -52,6 +54,13 @@ const aLead = (_authorId: string): number => | ||
| 52 | 54 | new Date().toISOString(), |
| 53 | 55 | agent, |
| 54 | 56 | ); |
| 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 | }; | |
| 55 | 64 | const NEW = { |
| 56 | 65 | name: "Lead", |
| 57 | 66 | email: "[email protected]", |
| @@ -83,6 +92,14 @@ const doors: Record< | ||
| 83 | 92 | setState(db, who, { id: aLead(authorId), state: "lost" }).ok, |
| 84 | 93 | delete: (who, authorId) => deleteLead(db, who, { id: aLead(authorId) }).ok, |
| 85 | 94 | }, |
| 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 | }, | |
| 86 | 103 | // The trail is written by the app itself, never through a door: there |
| 87 | 104 | // is no action that creates, changes or removes a row of it. |
| 88 | 105 | audit: { |
src/db.ts +12
| @@ -82,6 +82,18 @@ export const migrations: string[] = [ | ||
| 82 | 82 | `CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`, |
| 83 | 83 | // The scaffold's notes gave way to leads. |
| 84 | 84 | `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 | )`, | |
| 85 | 97 | ]; |
| 86 | 98 | |
| 87 | 99 | export function openDb(dir = dataDir): Database { |
src/env.ts +3 −2
| @@ -33,9 +33,10 @@ export const forgeUrl: string | undefined = process.env.FORGE_URL; | ||
| 33 | 33 | export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? ""; |
| 34 | 34 | |
| 35 | 35 | /** |
| 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 | |
| 37 | 38 | * 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 | |
| 39 | 40 | * the prototype's sample agent. |
| 40 | 41 | */ |
| 41 | 42 | export const agent = { |
src/leads.ts +23
| @@ -215,6 +215,29 @@ export function send( | ||
| 215 | 215 | })(); |
| 216 | 216 | } |
| 217 | 217 | |
| 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 | ||
| 218 | 241 | /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */ |
| 219 | 242 | export function close( |
| 220 | 243 | db: Database, |
src/mcp.ts +26
| @@ -10,7 +10,9 @@ import type { Database } from "bun:sqlite"; | ||
| 10 | 10 | import { |
| 11 | 11 | addLead, |
| 12 | 12 | getLead, |
| 13 | getProfile, | |
| 13 | 14 | listLeads, |
| 15 | saveProfile, | |
| 14 | 16 | sendReply, |
| 15 | 17 | setState, |
| 16 | 18 | type Result, |
| @@ -102,6 +104,30 @@ export const tools: readonly Tool[] = [ | ||
| 102 | 104 | run: (db, who, args) => |
| 103 | 105 | setState(db, who, { id: Number(args.id), state: args.state }), |
| 104 | 106 | }, |
| 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 | }, | |
| 105 | 131 | ]; |
| 106 | 132 | |
| 107 | 133 | /** 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"; | ||
| 7 | 7 | import { layout } from "./layout.ts"; |
| 8 | 8 | import { escape } from "../http.ts"; |
| 9 | 9 | import type { DeskLead } from "../leads.ts"; |
| 10 | import type { Agent } from "../env.ts"; | |
| 10 | 11 | import type { Who } from "../who.ts"; |
| 11 | 12 | |
| 12 | 13 | export function deskPage(input: { |
| 13 | 14 | who: Who; |
| 15 | agent: Agent; | |
| 14 | 16 | leads: readonly DeskLead[] | undefined; |
| 15 | 17 | mayAdd: boolean; |
| 16 | 18 | mayReset: boolean; |
| 17 | 19 | notice?: string | undefined; |
| 18 | 20 | }): string { |
| 19 | const { who, leads, notice } = input; | |
| 21 | const { who, agent, leads, notice } = input; | |
| 20 | 22 | if (leads === undefined) |
| 21 | 23 | return layout({ |
| 22 | 24 | who, |
| 25 | agent, | |
| 23 | 26 | path: "/", |
| 24 | 27 | notice, |
| 25 | 28 | body: `<section class="welcome"> |
| @@ -38,6 +41,7 @@ export function deskPage(input: { | ||
| 38 | 41 | : `<ul class="desk">${leads.map((lead) => row(lead, now)).join("")}</ul>`; |
| 39 | 42 | return layout({ |
| 40 | 43 | who, |
| 44 | agent, | |
| 41 | 45 | path: "/", |
| 42 | 46 | notice, |
| 43 | 47 | heading: "Desk", |
src/pages/layout.ts +10 −3
| @@ -5,24 +5,31 @@ | ||
| 5 | 5 | * card a chat app unfurls. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { agent, description, publicOrigin, title } from "../env.ts"; | |
| 8 | import { description, publicOrigin, title } from "../env.ts"; | |
| 9 | import type { Agent } from "../env.ts"; | |
| 9 | 10 | import { asset, escape } from "../http.ts"; |
| 10 | 11 | import { token, tokensHref } from "../tokens.ts"; |
| 11 | 12 | import type { Who } from "../who.ts"; |
| 12 | 13 | |
| 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. | |
| 13 | 17 | export function layout(input: { |
| 14 | 18 | body: string; |
| 15 | 19 | who: Who; |
| 20 | /** The agent whose desk it is: the profile as saved now. */ | |
| 21 | agent: Agent; | |
| 16 | 22 | path: string; |
| 17 | 23 | heading?: string; |
| 18 | 24 | notice?: string | undefined; |
| 19 | 25 | }): string { |
| 20 | const { body, who, path, notice } = input; | |
| 26 | const { body, who, agent, path, notice } = input; | |
| 21 | 27 | const name = input.heading === undefined ? title : `${input.heading} · ${title}`; |
| 22 | 28 | const door = |
| 23 | 29 | who.role === "anon" |
| 24 | 30 | ? `<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> | |
| 26 | 33 | <a class="button button-quiet" href="/__forge/signout">Sign out</a>`; |
| 27 | 34 | return `<!doctype html> |
| 28 | 35 | <html lang="en"> |
src/pages/lead.ts +4 −1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | import { channelFor, MAX_BODY } from "../drafts.ts"; |
| 8 | 8 | import { escape } from "../http.ts"; |
| 9 | 9 | import type { LeadDetail, Message } from "../leads.ts"; |
| 10 | import type { Agent } from "../env.ts"; | |
| 10 | 11 | import type { Who } from "../who.ts"; |
| 11 | 12 | import { layout } from "./layout.ts"; |
| 12 | 13 | import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts"; |
| @@ -22,11 +23,12 @@ const words = (m: Pick<Message, "body" | "signature">): string => | ||
| 22 | 23 | |
| 23 | 24 | export function leadPage(input: { |
| 24 | 25 | who: Who; |
| 26 | agent: Agent; | |
| 25 | 27 | lead: LeadDetail; |
| 26 | 28 | mayUpdate: boolean; |
| 27 | 29 | notice?: string | undefined; |
| 28 | 30 | }): string { |
| 29 | const { who, lead, mayUpdate, notice } = input; | |
| 31 | const { who, agent, lead, mayUpdate, notice } = input; | |
| 30 | 32 | const ready = lead.messages.find( |
| 31 | 33 | (m) => m.status === "draft" || m.status === "due", |
| 32 | 34 | ); |
| @@ -112,6 +114,7 @@ export function leadPage(input: { | ||
| 112 | 114 | |
| 113 | 115 | return layout({ |
| 114 | 116 | who, |
| 117 | agent, | |
| 115 | 118 | path, |
| 116 | 119 | notice, |
| 117 | 120 | 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 { | ||
| 18 | 18 | deleteLead, |
| 19 | 19 | getAudit, |
| 20 | 20 | getLead, |
| 21 | getProfile, | |
| 21 | 22 | listAudit, |
| 22 | 23 | listLeads, |
| 23 | 24 | resetSample, |
| 25 | saveProfile, | |
| 24 | 26 | sendReply, |
| 25 | 27 | setState, |
| 26 | 28 | tick, |
| @@ -48,6 +50,8 @@ import { rpc } from "./mcp.ts"; | ||
| 48 | 50 | import { deskPage } from "./pages/desk.ts"; |
| 49 | 51 | import { layout } from "./pages/layout.ts"; |
| 50 | 52 | import { leadPage } from "./pages/lead.ts"; |
| 53 | import { profilePage } from "./pages/profile.ts"; | |
| 54 | import { currentAgent } from "./profile.ts"; | |
| 51 | 55 | import { tokensCss } from "./tokens.ts"; |
| 52 | 56 | import type { Who } from "./who.ts"; |
| 53 | 57 | |
| @@ -162,6 +166,23 @@ export const AUDIT_ROW: Schema = { | ||
| 162 | 166 | }, |
| 163 | 167 | required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"], |
| 164 | 168 | }; |
| 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 | }; | |
| 165 | 186 | export const ERROR: Schema = { |
| 166 | 187 | type: "object", |
| 167 | 188 | properties: { error: { type: "string" }, message: { type: "string" } }, |
| @@ -259,6 +280,7 @@ export const routes: readonly Route[] = [ | ||
| 259 | 280 | return html( |
| 260 | 281 | deskPage({ |
| 261 | 282 | who: c.who, |
| 283 | agent: currentAgent(c.db), | |
| 262 | 284 | leads: leads.ok ? leads.value : undefined, |
| 263 | 285 | mayAdd: permit(c.who, "lead", "create") === "yes", |
| 264 | 286 | mayReset: permit(c.who, "lead", "delete") === "yes", |
| @@ -314,6 +336,7 @@ export const routes: readonly Route[] = [ | ||
| 314 | 336 | return html( |
| 315 | 337 | layout({ |
| 316 | 338 | who: c.who, |
| 339 | agent: currentAgent(c.db), | |
| 317 | 340 | path: c.url.pathname, |
| 318 | 341 | body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`, |
| 319 | 342 | }), |
| @@ -323,6 +346,7 @@ export const routes: readonly Route[] = [ | ||
| 323 | 346 | return html( |
| 324 | 347 | leadPage({ |
| 325 | 348 | who: c.who, |
| 349 | agent: currentAgent(c.db), | |
| 326 | 350 | lead: found.value, |
| 327 | 351 | mayUpdate: permit(c.who, "lead", "update", { ...found.value }) === "yes", |
| 328 | 352 | notice, |
| @@ -447,6 +471,62 @@ export const routes: readonly Route[] = [ | ||
| 447 | 471 | ), |
| 448 | 472 | }, |
| 449 | 473 | |
| 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 | ||
| 450 | 530 | // Who tried to change what: the audit trail, for whoever the table lets read it. |
| 451 | 531 | { |
| 452 | 532 | method: "GET", |
src/sample.ts +3 −2
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | 11 | import type { Source } from "./drafts.ts"; |
| 12 | import { agent } from "./env.ts"; | |
| 12 | import { currentAgent } from "./profile.ts"; | |
| 13 | 13 | import { |
| 14 | 14 | advance, |
| 15 | 15 | close, |
| @@ -78,7 +78,7 @@ export function seed(db: Database, now: Date): number { | ||
| 78 | 78 | // Oldest first, so ids rise with time as they would have. |
| 79 | 79 | for (const sample of [...SAMPLES].sort((a, b) => b.ago - a.ago)) { |
| 80 | 80 | const asked = t - sample.ago; |
| 81 | const id = insertLead(db, sample, iso(asked), agent); | |
| 81 | const id = insertLead(db, sample, iso(asked), currentAgent(db)); | |
| 82 | 82 | if (sample.answeredIn !== undefined) { |
| 83 | 83 | const replied = asked + sample.answeredIn; |
| 84 | 84 | sendReady(db, id, iso(replied)); |
| @@ -95,6 +95,7 @@ export function seed(db: Database, now: Date): number { | ||
| 95 | 95 | |
| 96 | 96 | /** Send what is ready for a sample lead, as drafted, as the agent. */ |
| 97 | 97 | function sendReady(db: Database, id: number, at: string): void { |
| 98 | const agent = currentAgent(db); | |
| 98 | 99 | send(db, findLead(db, id)!, readyFor(db, id)!, readyFor(db, id)!.body, agent.name, at, agent); |
| 99 | 100 | } |
| 100 | 101 |
src/server.test.ts +62
| @@ -271,6 +271,8 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 271 | 271 | "add_lead", |
| 272 | 272 | "send_reply", |
| 273 | 273 | "mark_lead", |
| 274 | "get_profile", | |
| 275 | "set_profile", | |
| 274 | 276 | ]); |
| 275 | 277 | const call = (name: string, args: unknown, who = {}) => |
| 276 | 278 | rpc( |
| @@ -282,6 +284,16 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 282 | 284 | }, |
| 283 | 285 | who, |
| 284 | 286 | ); |
| 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 }); | |
| 285 | 297 | const refused = await call("add_lead", NEW); |
| 286 | 298 | expect(refused.result.isError).toBe(true); |
| 287 | 299 | 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 | ||
| 460 | 472 | ); |
| 461 | 473 | } |
| 462 | 474 | }); |
| 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", () => { | ||
| 202 | 202 | expect(clean("one\r\ntwo")).toBe("one two"); |
| 203 | 203 | expect(clean("one\r\ntwo", false)).toBe("one\ntwo"); |
| 204 | 204 | }); |
| 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 @@ | ||
| 5 | 5 | * may — the hints only leave out keys the table would refuse. |
| 6 | 6 | * |
| 7 | 7 | * 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 | |
| 9 | 9 | * lead s approve and send · e edit, then send · q qualified · x lost · |
| 10 | 10 | * D remove (admin) · esc back |
| 11 | 11 | * edit type; enter is a new line · ctrl-d approve and send · esc cancel |
| 12 | 12 | * 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 | |
| 13 | 15 | * |
| 14 | 16 | * Nothing is sent from a screen that has not shown it: the lead screen |
| 15 | 17 | * shows what they asked, the words going out, the signature under them, |
| @@ -21,16 +23,19 @@ import { | ||
| 21 | 23 | addLead, |
| 22 | 24 | deleteLead, |
| 23 | 25 | getLead, |
| 26 | getProfile, | |
| 24 | 27 | listLeads, |
| 25 | 28 | resetSample, |
| 29 | saveProfile, | |
| 26 | 30 | sendReply, |
| 27 | 31 | setState, |
| 28 | 32 | } from "./actions.ts"; |
| 29 | 33 | import { between, elapsed, tone } from "./clock.ts"; |
| 30 | 34 | import { permit } from "./contract.ts"; |
| 31 | 35 | 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"; | |
| 33 | 37 | import type { DeskLead, LeadDetail, Message } from "./leads.ts"; |
| 38 | import { currentAgent } from "./profile.ts"; | |
| 34 | 39 | import type { Who } from "./who.ts"; |
| 35 | 40 | |
| 36 | 41 | const ESC = "\x1b["; |
| @@ -84,8 +89,18 @@ const ADD_FIELDS = [ | ||
| 84 | 89 | { key: "consent", label: "Written consent to be texted? y/n" }, |
| 85 | 90 | ] as const; |
| 86 | 91 | |
| 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 | ||
| 87 | 100 | type View = |
| 88 | 101 | | { name: "desk" } |
| 102 | | { name: "profile" } | |
| 103 | | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> } | |
| 89 | 104 | | { name: "lead"; id: number } |
| 90 | 105 | | { name: "edit"; id: number; text: string } |
| 91 | 106 | | { name: "add"; step: number; typed: string; fields: Record<string, string> } |
| @@ -134,6 +149,7 @@ export function terminal( | ||
| 134 | 149 | } |
| 135 | 150 | |
| 136 | 151 | function header(): string[] { |
| 152 | const agent = currentAgent(db); | |
| 137 | 153 | return [ |
| 138 | 154 | `${bold(title)} ${clean(agent.name)} · ${clean(agent.brokerage)} ${dim(clean(where))} ${dim(me.role === "anon" ? "guest" : clean(me.name))}`, |
| 139 | 155 | ssh === undefined ? "" : dim(`connect: ${ssh}`), |
| @@ -164,7 +180,7 @@ export function terminal( | ||
| 164 | 180 | lines.push( |
| 165 | 181 | "", |
| 166 | 182 | 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`, | |
| 168 | 184 | ), |
| 169 | 185 | ); |
| 170 | 186 | return lines; |
| @@ -243,6 +259,32 @@ export function terminal( | ||
| 243 | 259 | return lines; |
| 244 | 260 | } |
| 245 | 261 | |
| 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 | ||
| 246 | 288 | function addScreen(v: Extract<View, { name: "add" }>): string[] { |
| 247 | 289 | const lines = [bold("Log a lead by hand"), ""]; |
| 248 | 290 | ADD_FIELDS.forEach((field, i) => { |
| @@ -291,7 +333,11 @@ export function terminal( | ||
| 291 | 333 | const body = |
| 292 | 334 | view.name === "desk" |
| 293 | 335 | ? deskScreen() |
| 294 | : view.name === "lead" | |
| 336 | : view.name === "profile" | |
| 337 | ? profileScreen() | |
| 338 | : view.name === "profile-edit" | |
| 339 | ? profileEditScreen(view) | |
| 340 | : view.name === "lead" | |
| 295 | 341 | ? leadScreen(view.id, w) |
| 296 | 342 | : view.name === "edit" |
| 297 | 343 | ? leadScreen(view.id, w, view.text) |
| @@ -324,10 +370,54 @@ export function terminal( | ||
| 324 | 370 | view = { name: "lead", id: rows[cursor]!.id }; |
| 325 | 371 | else if (input === "n") |
| 326 | 372 | view = { name: "add", step: 0, typed: "", fields: {} }; |
| 373 | else if (input === "p") view = { name: "profile" }; | |
| 327 | 374 | else if (input === "R") |
| 328 | 375 | view = { name: "confirm", what: "reset", back: view }; |
| 329 | 376 | return; |
| 330 | 377 | } |
| 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 | } | |
| 331 | 421 | case "lead": { |
| 332 | 422 | const id = view.id; |
| 333 | 423 | const l = lead(id); |
new above
offline