Public: anyone can read this; the crew can change it.
Build speed-to-lead #2
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/1-build-speed-to-lead → main 4 commits fork 6 threads · 6 unresolved
AGENTS.md +37 −5
| @@ -30,8 +30,8 @@ preview at its own address, deployed from your branch as you push. | ||
| 30 | 30 | |
| 31 | 31 | One implementation, many doors. Every operation is a function in |
| 32 | 32 | `src/actions.ts` — `(db, who, input)` in, data or a named failure out — and |
| 33 | the page (`src/routes.ts`, `src/page.ts`), the JSON API (`src/routes.ts`), | |
| 34 | the MCP server (`src/mcp.ts`) and the terminal (`src/tty.ts`) call it. A | |
| 33 | the pages (`src/routes.ts`, `src/pages/`), the JSON API (`src/routes.ts`), | |
| 34 | the MCP server (`src/mcp.ts`) and the terminal (`src/terminal.ts`) call it. A | |
| 35 | 35 | door reads its wire format and shapes the answer; it decides nothing. A |
| 36 | 36 | rule in an action holds at every door at once; a rule anywhere else is a |
| 37 | 37 | bug waiting for the door you forgot. |
| @@ -79,8 +79,8 @@ To add a concept: | ||
| 79 | 79 | and a test in `src/actions.test.ts` for what the table cannot say. |
| 80 | 80 | - **A migration** — append to `migrations` in `src/db.ts`. Never edit one |
| 81 | 81 | that has run. `bun run src/db.ts --check` shows the version. |
| 82 | - **A page** — a row in `src/routes.ts` and a function in `src/page.ts`. | |
| 83 | With a second page, move them under `src/pages/` and keep one `layout`. | |
| 82 | - **A page** — a row in `src/routes.ts` and a file in `src/pages/` that | |
| 83 | renders through the one `layout` (`src/pages/layout.ts`). | |
| 84 | 84 | - **An API route** — a row in `src/routes.ts` that calls the action and |
| 85 | 85 | answers with `answer(...)`; the status follows the failure. Give it an |
| 86 | 86 | `api` entry beside it (a sentence, the body and answer as JSON Schema) |
| @@ -90,7 +90,7 @@ To add a concept: | ||
| 90 | 90 | names, so the door and the forge's probe find them. |
| 91 | 91 | - **A tool** — an entry in `tools` in `src/mcp.ts`: a name, one sentence, |
| 92 | 92 | a JSON schema, the action. |
| 93 | - **A terminal command** — a key in `src/tty.ts` that calls the action and | |
| 93 | - **A terminal command** — a key in `src/terminal.ts` that calls the action and | |
| 94 | 94 | reports on the status line. |
| 95 | 95 | - **Something live** — `emit(type, data)` in the action, and |
| 96 | 96 | `data-live="<types>"` on the region of the page that shows it. |
| @@ -101,6 +101,38 @@ To add a concept: | ||
| 101 | 101 | token; `src/design.test.ts` runs it, and holds every pair of colours a |
| 102 | 102 | person reads to 4.5:1 in both themes. |
| 103 | 103 | |
| 104 | ## This app | |
| 105 | ||
| 106 | Speed to Lead is one realtor's desk. The concepts, one module each: | |
| 107 | ||
| 108 | - `src/leads.ts` — leads and messages in SQLite, no permission asked: | |
| 109 | a lead arrives with its first reply drafted (day 0); sending that reply | |
| 110 | drafts and schedules the cadence (days in `CADENCE`); `advance` makes a | |
| 111 | touch due on its day; `close` (qualified or lost) skips what is left. | |
| 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 | |
| 114 | carries, and the consent rule (`channelFor`: text only with written | |
| 115 | consent and a phone number). A trigger in `src/db.ts` holds that rule | |
| 116 | in the file as well. | |
| 117 | - `src/clock.ts` — the response clock's two rules (green under 5 minutes, | |
| 118 | amber under an hour, red after). `static/clock.js` repeats them to tick | |
| 119 | in the browser; change both together. | |
| 120 | - `src/terminal.ts` — the terminal's screens and keys over the actions; | |
| 121 | `src/tty.ts` only wires it to the pty. Enter opens a lead; sending is a | |
| 122 | key pressed on the screen that shows the inquiry, the words, the | |
| 123 | signature and the channel. Never send from a screen that has not shown | |
| 124 | what goes. What the page can do, a key here can. | |
| 125 | - `src/live.ts` `watch` — the terminal is another process; the server | |
| 126 | notices its commits by `PRAGMA data_version` and emits `lead.changed`. | |
| 127 | - `src/sample.ts` — the twelve sample leads, laid out once on first boot | |
| 128 | and again, timed from now, by an admin's restart. | |
| 129 | ||
| 130 | Leads speak at `/leads` (the `lead` resource's `api`): the same path is the | |
| 131 | page for a browser and JSON for a script (`content-type` or `accept` | |
| 132 | `application/json`). Nothing is sent anywhere: "send" records the message | |
| 133 | as sent. Every message is approved by a person; an action never sends on | |
| 134 | its own, and a tool that sends says so. | |
| 135 | ||
| 104 | 136 | ## The bar |
| 105 | 137 | |
| 106 | 138 | - Security: every input is validated at the boundary and every output is |
README.md +153 −114
| @@ -1,125 +1,164 @@ | ||
| 1 | # speed-to-lead | |
| 1 | # Speed to Lead | |
| 2 | 2 | |
| 3 | Answer every new lead in under a minute: a desk of incoming leads with a response clock, a drafted personal reply to approve and send, and a 30-day follow-up cadence that never lets anyone sit untouched. | |
| 3 | Answer every new lead in under a minute, and never let anyone sit untouched | |
| 4 | for thirty days. | |
| 4 | 5 | |
| 5 | This is an app: the forge runs it. Production follows the default branch; | |
| 6 | every open pull gets a preview at its own address with its own copy of the | |
| 7 | data. Everything the app keeps lives under `FORGE_APP_DATA`, which is what | |
| 8 | makes "production data" and "preview data" two different things. | |
| 6 | An agent who replies within five minutes is far likelier to win the lead | |
| 7 | than one who replies in thirty — and most agents take hours. Speed to Lead | |
| 8 | puts every new inquiry on one screen with a clock running, has a personal | |
| 9 | reply already written for you, and keeps following up for a month until | |
| 10 | the person is qualified or gone. **You approve every message before it | |
| 11 | goes.** | |
| 12 | ||
| 13 | ## How it works | |
| 14 | ||
| 15 | **The desk** (the first screen) lists your leads, newest first. Each row | |
| 16 | shows the person's name, where they came from (Zillow, your website form, | |
| 17 | an open house, a referral), what they asked, and a **response clock** | |
| 18 | counting since they asked: | |
| 19 | ||
| 20 | - **green** — under 5 minutes. You're winning. | |
| 21 | - **amber** — under an hour. | |
| 22 | - **red** — over an hour. Answer this one now. | |
| 23 | ||
| 24 | Once you've replied, the clock stops and shows how long it took. | |
| 25 | ||
| 26 | **Tap a lead** to see what they wrote beside the reply drafted for them. | |
| 27 | The draft uses their first name, mentions where they found you, and answers | |
| 28 | what they asked about — a showing, selling their home, financing, | |
| 29 | relocating, a first purchase, price. Then: | |
| 30 | ||
| 31 | - **Approve and send** sends it as written. | |
| 32 | - **Edit** opens the text right there; change anything, then approve and send. | |
| 33 | ||
| 34 | **Text or email.** Each lead carries a badge: **Text OK** if they gave | |
| 35 | written consent to be texted, **Email only** if they didn't. The app never | |
| 36 | drafts a text to someone without that consent — it writes an email instead. | |
| 37 | ||
| 38 | **Your signature** goes on every message, and can't be edited off: your | |
| 39 | name, brokerage and license number, as state advertising rules require. | |
| 40 | Texts also say "Reply STOP to opt out." | |
| 41 | ||
| 42 | **The follow-up plan.** The moment your first reply goes out, the app | |
| 43 | drafts five follow-ups for **day 1, 3, 7, 14 and 30**. Each shows on the | |
| 44 | lead's page as upcoming; on its day it appears on the desk as ready, and | |
| 45 | you approve and send it like the first. **Mark qualified** or **Mark lost** | |
| 46 | takes a lead out of the plan. | |
| 47 | ||
| 48 | **Sample leads.** The app starts with twelve sample leads so you can see it | |
| 49 | work: two just in, two waiting a while, three gone red, and five already | |
| 50 | answered and partway through their follow-ups. An admin can restart them | |
| 51 | from the bottom of the desk, so the clocks read fresh for a demonstration. | |
| 52 | ||
| 53 | ## What is real and what is not, in this prototype | |
| 54 | ||
| 55 | - **Nothing is actually sent.** "Send" marks the message sent, shows it in | |
| 56 | the lead's history with the time and who approved it. No email or text | |
| 57 | leaves the app. | |
| 58 | - **No CRM import.** Leads arrive by the form on the desk ("Log a lead by | |
| 59 | hand") or by `POST /leads` (below), which a website form can call. | |
| 60 | - **No login of its own.** You sign in with the forge that runs the app. | |
| 61 | Anyone signed in can work the desk; only an admin can delete a lead or | |
| 62 | restart the samples. Someone not signed in sees only your name and a | |
| 63 | sign-in button. | |
| 64 | - **Drafts are templates**, filled from what the lead wrote and your | |
| 65 | profile. There is no AI writing them and no outside service called. | |
| 66 | ||
| 67 | ## Your profile | |
| 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. | |
| 71 | ||
| 72 | | variable | what it is | | |
| 73 | | ----------------- | ------------------------------- | | |
| 74 | | `AGENT_NAME` | your name | | |
| 75 | | `AGENT_BROKERAGE` | your brokerage | | |
| 76 | | `AGENT_LICENSE` | your license number, as shown | | |
| 77 | | `AGENT_PHONE` | the phone number in your emails | | |
| 78 | | `AGENT_EMAIL` | the email address in your emails | | |
| 79 | ||
| 80 | ## For whoever connects it to a website | |
| 81 | ||
| 82 | Every page has a JSON twin. Send `content-type: application/json` (or | |
| 83 | `accept: application/json`) as someone the forge has signed in: | |
| 84 | ||
| 85 | sh | |
| 86 | # a new lead (consent: written consent to be texted) | |
| 87 | curl -X POST https://<app>/leads -H 'content-type: application/json' \ | |
| 88 | -d '{"name":"Maria Gonzalez","email":"[email protected]","phone":"(206) 555-0101", | |
| 89 | "source":"zillow","message":"Can we see 418 Juniper Ln?","consent":true}' | |
| 90 | ||
| 91 | curl https://<app>/leads # the desk | |
| 92 | curl https://<app>/leads/1 -H 'accept: application/json' # one lead, every message | |
| 93 | curl -X POST https://<app>/leads/1/reply -H 'content-type: application/json' -d '{}' | |
| 94 | curl -X POST https://<app>/leads/1/reply -H 'content-type: application/json' -d '{"body":"edited words"}' | |
| 95 | curl -X POST https://<app>/leads/1/state -H 'content-type: application/json' -d '{"state":"qualified"}' | |
| 96 | curl -X POST https://<app>/tick # the day turns: follow-ups come due | |
| 97 | ||
| 98 | ||
| 99 | `source` is `zillow`, `website`, `open_house` or `referral`. Names, | |
| 100 | emails, phones and messages are plain text: anything carrying control | |
| 101 | characters is turned away. `POST /tick` is safe to call as often as you | |
| 102 | like, but only as someone the forge has signed in — an unsigned scheduled | |
| 103 | job gets "sign in first". Nothing depends on it: the app does the same | |
| 104 | itself every hour. The whole API is described at `/openapi.json`, and the same | |
| 105 | actions are MCP tools at `POST /mcp` (`list_leads`, `get_lead`, `add_lead`, | |
| 106 | `send_reply`, `mark_lead`). | |
| 107 | ||
| 108 | ## From a terminal | |
| 109 | ||
| 110 | When the forge gives the app a terminal, the command to reach it is shown | |
| 111 | in the forge as `FORGE_APP_SSH`. It is the same desk, with the same clocks | |
| 112 | ticking, and anything done there shows on open web pages within a second. | |
| 113 | ||
| 114 | On the desk: | |
| 115 | ||
| 116 | - `j` / `k` (or the arrow keys) move between leads; **enter opens one**. | |
| 117 | - `n` logs a lead by hand: type each answer and press enter (name, email, | |
| 118 | phone, source as a number, what they asked, consent `y` or `n`). | |
| 119 | - `R` restarts the sample leads from now (admins only; asks first). | |
| 120 | - `esc` leaves. | |
| 121 | ||
| 122 | On a lead, you see what they asked, the reply exactly as it will go, your | |
| 123 | signature under it, and whether it goes by text or email. Nothing is sent | |
| 124 | until you press a key on this screen: | |
| 125 | ||
| 126 | - `s` approves and sends it as shown. | |
| 127 | - `e` lets you edit it first: type, enter for a new line, backspace to | |
| 128 | delete, then `ctrl-d` to approve and send — or `esc` to send nothing. | |
| 129 | - `q` marks the lead qualified, `x` lost. | |
| 130 | - `D` removes the lead (admins only; asks first). | |
| 131 | - `esc` goes back to the desk. | |
| 132 | ||
| 133 | ## Running it | |
| 9 | 134 | |
| 10 | 135 | sh |
| 11 | 136 | PORT=8080 FORGE_APP_DATA=./data bun run src/server.ts # run it here |
| 12 | bun test # what `forge.json`'s app.test runs on every push | |
| 137 | bun test # what forge.json's app.test runs | |
| 13 | 138 | FORGE_APP_DATA=./data bun run src/tty.ts # the terminal |
| 14 | 139 | FORGE_APP_DATA=./data bun run src/db.ts --check # schema version, integrity |
| 15 | 140 | bun run lint:design # no colour but the tokens' |
| 16 | bun run contract:emit # rewrite contract/openapi.json from the routes | |
| 141 | bun run contract:emit # rewrite contract/openapi.json | |
| 17 | 142 | |
| 18 | 143 | |
| 19 | `app.test` in `forge.json` runs beside `app.run` in every deploy, not before | |
| 20 | it: the preview comes up the moment the app answers, and says `live`, or | |
| 21 | `serving · tests failed` the moment the suite disagrees. | |
| 144 | No dependencies: Bun, its built-in SQLite, and one database file under | |
| 145 | `FORGE_APP_DATA`. `AGENTS.md` says how the code is shaped; `contract.json` | |
| 146 | says who may do what. | |
| 22 | 147 | |
| 23 | ## The shape | |
| 24 | ||
| 25 | One implementation, many doors. `src/actions.ts` is every operation as a | |
| 26 | plain function — `(db, who, input)` in, data or a named failure out — and | |
| 27 | the page, the JSON API, the MCP server and the terminal all call it and | |
| 28 | decide nothing themselves. `AGENTS.md` says how to add to it. | |
| 29 | ||
| 30 | | file | what it is | | |
| 31 | | ---------------------------------- | -------------------------------------------------------------- | | |
| 32 | | `src/actions.ts` | list, add, delete; the audit trail, read | | |
| 33 | | `contract.json` | who may do what: roles, and the least role each verb needs | | |
| 34 | | `src/contract.ts`, `src/can.ts` | the table, read at boot; the forge's evaluator, verbatim | | |
| 35 | | `src/security.ts` | the door: rationing, same origin, the table before the body | | |
| 36 | | `src/audit.ts` | every change and every refused one, as a row | | |
| 37 | | `src/who.ts` | who is asking, from the forge's signed headers | | |
| 38 | | `src/db.ts` | SQLite under `FORGE_APP_DATA`, WAL, forward-only migrations | | |
| 39 | | `src/live.ts` | the in-process bus and `GET /events` | | |
| 40 | | `src/mcp.ts` | the actions as MCP tools at `POST /mcp` | | |
| 41 | | `src/routes.ts` | every path, in one table, each API route described beside it | | |
| 42 | | `src/openapi.ts` | the routes as OpenAPI; committed at `contract/openapi.json` | | |
| 43 | | `src/page.ts` | the HTML, rendered on the server, with its share metadata | | |
| 44 | | `design/tokens.json`, `src/tokens.ts` | the look as data, light and dark; compiled to `/tokens.css` | | |
| 45 | | `src/http.ts` | the floor: headers, body cap, files | | |
| 46 | | `src/server.ts` | boot: open the database, serve | | |
| 47 | | `src/tty.ts` | the terminal, over the same actions | | |
| 48 | | `src/env.ts` | what the forge told this process | | |
| 49 | | `static/app.css`, `static/live.js` | the look in the tokens' words, and the list that stays current | | |
| 50 | ||
| 51 | ## What every app stands on | |
| 52 | ||
| 53 | - **The door.** Before a route sees a request, `src/security.ts` rations | |
| 54 | writes (and a stranger's API calls), refuses a write from another site, | |
| 55 | and turns away — before the body is read — anyone the table lets through | |
| 56 | a resource's door for no row at all: 401 for a stranger, 403 for anyone | |
| 57 | else. The action still decides about the real row. | |
| 58 | - **The audit trail.** Every change, and every change refused, is a row: | |
| 59 | who, which resource and verb, which row, when, and whether they were | |
| 60 | let. Admins read it at `GET /api/audit`. A row that cannot be written | |
| 61 | is a log line, never a failed request. | |
| 62 | - **The API, described.** `GET /openapi.json` is `contract/openapi.json`, | |
| 63 | written from the routes by `bun run contract:emit`; each operation names | |
| 64 | its cell of the table (`x-contract`). `bun test` fails while it is stale. | |
| 65 | - **Up, or not.** `GET /healthz` answers `{ ok, version, uptime }`; the | |
| 66 | forge waits on it before it sends anyone to a deploy. | |
| 67 | - **The look.** `design/tokens.json` holds every colour, space and size, | |
| 68 | light and dark; nothing else spells out a colour (`bun run lint:design`), | |
| 69 | and every pair a person reads meets 4.5:1 in both themes. | |
| 70 | - **The open web.** A shared link unfurls (description, Open Graph, a | |
| 71 | card); `/robots.txt` keeps crawlers to the page, and out of previews | |
| 72 | entirely; `/.well-known/security.txt` sends a reporter to the forge | |
| 73 | that runs the app. | |
| 74 | ||
| 75 | ## Who you are | |
| 76 | ||
| 77 | The forge says who is asking on every request it proxies, and the app | |
| 78 | verifies the signature (`src/who.ts`); nothing else is trusted. Three tiers: | |
| 79 | ||
| 80 | - **anon** — anyone. Reads. | |
| 81 | - **user** — signed in to the forge and able to see this app. Adds notes, as | |
| 82 | themselves, and removes their own. | |
| 83 | - **admin** — able to write this repository. Removes any note. | |
| 84 | ||
| 85 | "Sign in" is `/__forge/signin?to=<path>` and "Sign out" is | |
| 86 | `/__forge/signout`; the forge answers both on the app's own host, and | |
| 87 | `/__forge/report` too: it sends anyone, with no account, to report a | |
| 88 | problem on this app's repository, if that repository is public. | |
| 89 | ||
| 90 | ## Any interface | |
| 91 | ||
| 92 | The same actions, the same rules, at every door. A script is the person | |
| 93 | whose forge grant it carries; a bare script is anonymous. | |
| 94 | ||
| 95 | sh | |
| 96 | curl https://<app>/api/notes | |
| 97 | curl -X POST https://<app>/api/notes -H 'content-type: application/json' -d '{"body":"hi"}' | |
| 98 | curl -X DELETE https://<app>/api/notes/1 | |
| 99 | ||
| 100 | ||
| 101 | As an MCP server, for Claude Code or Claude Desktop — `list_notes`, | |
| 102 | `add_note`, `delete_note`: | |
| 103 | ||
| 104 | sh | |
| 105 | claude mcp add --transport http __TITLE__ https://<app>/mcp | |
| 106 | ||
| 107 | ||
| 108 | json | |
| 109 | { | |
| 110 | "mcpServers": { "__TITLE__": { "type": "http", "url": "https://<app>/mcp" } } | |
| 111 | } | |
| 112 | ||
| 113 | ||
| 114 | The page stays current over `/events`: a note someone else adds or removes | |
| 115 | appears without a reload. Without JavaScript it is the same page, one | |
| 116 | reload behind. | |
| 117 | ||
| 118 | The terminal opens with the exact command in `FORGE_APP_SSH` when the app | |
| 119 | runs (`ssh -p 2222 <name>@<forge>` — the app is the login name, the forge | |
| 120 | the host; `<name>--<pull>@<forge>` for a preview's). It is `src/tty.ts` on | |
| 121 | a real pty over the same data, as the account at the keyboard. | |
| 122 | ||
| 123 | The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV` (`production` or | |
| 124 | `preview`), `FORGE_APP_URL`, `FORGE_APP_COMMIT`, `FORGE_APP_SSH` and | |
| 125 | `FORGE_APP_IDENTITY_KEY` when it starts the app. `forge.json` says how. | |
| 148 | | file | what it is | | |
| 149 | | ------------------------------------- | ----------------------------------------------------------- | | |
| 150 | | `src/actions.ts` | every operation, asking `contract.json` who may | | |
| 151 | | `src/leads.ts` | leads and messages: arrive, send, follow up, close | | |
| 152 | | `src/drafts.ts` | the drafted words, the signature, the consent rule | | |
| 153 | | `src/clock.ts`, `static/clock.js` | the response clock: its colours, and its tick | | |
| 154 | | `src/sample.ts` | the twelve sample leads | | |
| 155 | | `src/pages/` | the desk and the lead page, server-rendered | | |
| 156 | | `src/routes.ts` | every path, each API route described beside it | | |
| 157 | | `src/security.ts`, `src/http.ts` | the door and the floor: rationing, same origin, headers | | |
| 158 | | `src/audit.ts` | every change and every refused one, as a row (admins read `/api/audit`) | | |
| 159 | | `src/who.ts`, `src/contract.ts` | who is asking, and what the table lets them do | | |
| 160 | | `src/db.ts` | SQLite under `FORGE_APP_DATA`, forward-only migrations | | |
| 161 | | `src/live.ts`, `static/live.js` | the page stays current over `/events`, terminal writes too | | |
| 162 | | `src/mcp.ts` | the same actions as MCP tools | | |
| 163 | | `src/terminal.ts`, `src/tty.ts` | the desk in a terminal: its screens and keys, and the pty | | |
| 164 | | `design/tokens.json` | the palette and type, light and dark | |
contract.json +6 −6
| @@ -6,14 +6,14 @@ | ||
| 6 | 6 | "admin": { "above": ["author"], "held": { "by": "identity", "role": "admin" } } |
| 7 | 7 | }, |
| 8 | 8 | "resources": { |
| 9 | "note": { | |
| 10 | "api": "/api/notes", | |
| 9 | "lead": { | |
| 10 | "api": "/leads", | |
| 11 | 11 | "can": { |
| 12 | 12 | "create": "user", |
| 13 | "read": "anon", | |
| 14 | "update": "author", | |
| 15 | "delete": "author", | |
| 16 | "list": "anon" | |
| 13 | "read": "user", | |
| 14 | "update": "user", | |
| 15 | "delete": "admin", | |
| 16 | "list": "user" | |
| 17 | 17 | } |
| 18 | 18 | }, |
| 19 | 19 | "audit": { |
contract/openapi.json +515 −49
| @@ -1,15 +1,15 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "openapi": "3.1.0", |
| 3 | 3 | "info": { |
| 4 | "title": "speed-to-lead", | |
| 4 | "title": "Speed to Lead", | |
| 5 | 5 | "version": "0.1.0", |
| 6 | 6 | "description": "Answer every new lead in under a minute: a desk of incoming leads with a response clock, a drafted personal reply to approve and send, and a 30-day follow-up cadence that never lets anyone sit untouched." |
| 7 | 7 | }, |
| 8 | 8 | "paths": { |
| 9 | "/api/notes": { | |
| 9 | "/leads": { | |
| 10 | 10 | "get": { |
| 11 | "summary": "The notes, newest first.", | |
| 12 | "operationId": "getApiNotes", | |
| 11 | "summary": "The desk: every lead, newest inquiry first.", | |
| 12 | "operationId": "getLeads", | |
| 13 | 13 | "parameters": [ |
| 14 | 14 | { |
| 15 | 15 | "name": "limit", |
| @@ -24,13 +24,13 @@ | ||
| 24 | 24 | ], |
| 25 | 25 | "responses": { |
| 26 | 26 | "200": { |
| 27 | "description": "The notes, newest first.", | |
| 27 | "description": "The desk: every lead, newest inquiry first.", | |
| 28 | 28 | "content": { |
| 29 | 29 | "application/json": { |
| 30 | 30 | "schema": { |
| 31 | 31 | "type": "array", |
| 32 | 32 | "items": { |
| 33 | "$ref": "#/components/schemas/Note" | |
| 33 | "$ref": "#/components/schemas/DeskLead" | |
| 34 | 34 | } |
| 35 | 35 | } |
| 36 | 36 | } |
| @@ -48,14 +48,14 @@ | ||
| 48 | 48 | } |
| 49 | 49 | }, |
| 50 | 50 | "x-contract": { |
| 51 | "resource": "note", | |
| 51 | "resource": "lead", | |
| 52 | 52 | "verb": "list", |
| 53 | "least": "anon" | |
| 53 | "least": "user" | |
| 54 | 54 | } |
| 55 | 55 | }, |
| 56 | 56 | "post": { |
| 57 | "summary": "Add a note as the person asking.", | |
| 58 | "operationId": "postApiNotes", | |
| 57 | "summary": "A new lead arrives (a website form can post here), with its first reply drafted.", | |
| 58 | "operationId": "postLeads", | |
| 59 | 59 | "requestBody": { |
| 60 | 60 | "required": true, |
| 61 | 61 | "content": { |
| @@ -63,14 +63,42 @@ | ||
| 63 | 63 | "schema": { |
| 64 | 64 | "type": "object", |
| 65 | 65 | "properties": { |
| 66 | "body": { | |
| 66 | "name": { | |
| 67 | 67 | "type": "string", |
| 68 | 68 | "minLength": 1, |
| 69 | "maxLength": 500 | |
| 69 | "maxLength": 120 | |
| 70 | }, | |
| 71 | "email": { | |
| 72 | "type": "string", | |
| 73 | "format": "email" | |
| 74 | }, | |
| 75 | "phone": { | |
| 76 | "type": "string", | |
| 77 | "description": "Optional; needed to text." | |
| 78 | }, | |
| 79 | "source": { | |
| 80 | "enum": [ | |
| 81 | "zillow", | |
| 82 | "website", | |
| 83 | "open_house", | |
| 84 | "referral" | |
| 85 | ] | |
| 86 | }, | |
| 87 | "message": { | |
| 88 | "type": "string", | |
| 89 | "minLength": 1, | |
| 90 | "maxLength": 2000 | |
| 91 | }, | |
| 92 | "consent": { | |
| 93 | "type": "boolean", | |
| 94 | "description": "Prior written consent to be texted. Without it, only email." | |
| 70 | 95 | } |
| 71 | 96 | }, |
| 72 | 97 | "required": [ |
| 73 | "body" | |
| 98 | "name", | |
| 99 | "email", | |
| 100 | "source", | |
| 101 | "message" | |
| 74 | 102 | ] |
| 75 | 103 | } |
| 76 | 104 | } |
| @@ -78,11 +106,11 @@ | ||
| 78 | 106 | }, |
| 79 | 107 | "responses": { |
| 80 | 108 | "201": { |
| 81 | "description": "Add a note as the person asking.", | |
| 109 | "description": "A new lead arrives (a website form can post here), with its first reply drafted.", | |
| 82 | 110 | "content": { |
| 83 | 111 | "application/json": { |
| 84 | 112 | "schema": { |
| 85 | "$ref": "#/components/schemas/Note" | |
| 113 | "$ref": "#/components/schemas/Lead" | |
| 86 | 114 | } |
| 87 | 115 | } |
| 88 | 116 | } |
| @@ -99,16 +127,16 @@ | ||
| 99 | 127 | } |
| 100 | 128 | }, |
| 101 | 129 | "x-contract": { |
| 102 | "resource": "note", | |
| 130 | "resource": "lead", | |
| 103 | 131 | "verb": "create", |
| 104 | 132 | "least": "user" |
| 105 | 133 | } |
| 106 | 134 | } |
| 107 | 135 | }, |
| 108 | "/api/notes/{id}": { | |
| 136 | "/leads/{id}": { | |
| 109 | 137 | "get": { |
| 110 | "summary": "One note.", | |
| 111 | "operationId": "getApiNotesId", | |
| 138 | "summary": "One lead, with every message: sent, drafted, and the follow-ups to come. Ask for application/json.", | |
| 139 | "operationId": "getLeadsId", | |
| 112 | 140 | "parameters": [ |
| 113 | 141 | { |
| 114 | 142 | "name": "id", |
| @@ -121,11 +149,11 @@ | ||
| 121 | 149 | ], |
| 122 | 150 | "responses": { |
| 123 | 151 | "200": { |
| 124 | "description": "One note.", | |
| 152 | "description": "One lead, with every message: sent, drafted, and the follow-ups to come. Ask for application/json.", | |
| 125 | 153 | "content": { |
| 126 | 154 | "application/json": { |
| 127 | 155 | "schema": { |
| 128 | "$ref": "#/components/schemas/Note" | |
| 156 | "$ref": "#/components/schemas/Lead" | |
| 129 | 157 | } |
| 130 | 158 | } |
| 131 | 159 | } |
| @@ -142,14 +170,14 @@ | ||
| 142 | 170 | } |
| 143 | 171 | }, |
| 144 | 172 | "x-contract": { |
| 145 | "resource": "note", | |
| 173 | "resource": "lead", | |
| 146 | 174 | "verb": "read", |
| 147 | "least": "anon" | |
| 175 | "least": "user" | |
| 148 | 176 | } |
| 149 | 177 | }, |
| 150 | 178 | "patch": { |
| 151 | "summary": "Change a note's words.", | |
| 152 | "operationId": "patchApiNotesId", | |
| 179 | "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state).", | |
| 180 | "operationId": "patchLeadsId", | |
| 153 | 181 | "parameters": [ |
| 154 | 182 | { |
| 155 | 183 | "name": "id", |
| @@ -167,14 +195,15 @@ | ||
| 167 | 195 | "schema": { |
| 168 | 196 | "type": "object", |
| 169 | 197 | "properties": { |
| 170 | "body": { | |
| 171 | "type": "string", | |
| 172 | "minLength": 1, | |
| 173 | "maxLength": 500 | |
| 198 | "state": { | |
| 199 | "enum": [ | |
| 200 | "qualified", | |
| 201 | "lost" | |
| 202 | ] | |
| 174 | 203 | } |
| 175 | 204 | }, |
| 176 | 205 | "required": [ |
| 177 | "body" | |
| 206 | "state" | |
| 178 | 207 | ] |
| 179 | 208 | } |
| 180 | 209 | } |
| @@ -182,11 +211,11 @@ | ||
| 182 | 211 | }, |
| 183 | 212 | "responses": { |
| 184 | 213 | "200": { |
| 185 | "description": "Change a note's words.", | |
| 214 | "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state).", | |
| 186 | 215 | "content": { |
| 187 | 216 | "application/json": { |
| 188 | 217 | "schema": { |
| 189 | "$ref": "#/components/schemas/Note" | |
| 218 | "$ref": "#/components/schemas/Lead" | |
| 190 | 219 | } |
| 191 | 220 | } |
| 192 | 221 | } |
| @@ -203,14 +232,14 @@ | ||
| 203 | 232 | } |
| 204 | 233 | }, |
| 205 | 234 | "x-contract": { |
| 206 | "resource": "note", | |
| 235 | "resource": "lead", | |
| 207 | 236 | "verb": "update", |
| 208 | "least": "author" | |
| 237 | "least": "user" | |
| 209 | 238 | } |
| 210 | 239 | }, |
| 211 | 240 | "delete": { |
| 212 | "summary": "Remove a note.", | |
| 213 | "operationId": "deleteApiNotesId", | |
| 241 | "summary": "Remove a lead and everything said to it.", | |
| 242 | "operationId": "deleteLeadsId", | |
| 214 | 243 | "parameters": [ |
| 215 | 244 | { |
| 216 | 245 | "name": "id", |
| @@ -223,7 +252,7 @@ | ||
| 223 | 252 | ], |
| 224 | 253 | "responses": { |
| 225 | 254 | "200": { |
| 226 | "description": "Remove a note.", | |
| 255 | "description": "Remove a lead and everything said to it.", | |
| 227 | 256 | "content": { |
| 228 | 257 | "application/json": { |
| 229 | 258 | "schema": { |
| @@ -252,9 +281,163 @@ | ||
| 252 | 281 | } |
| 253 | 282 | }, |
| 254 | 283 | "x-contract": { |
| 255 | "resource": "note", | |
| 284 | "resource": "lead", | |
| 256 | 285 | "verb": "delete", |
| 257 | "least": "author" | |
| 286 | "least": "admin" | |
| 287 | } | |
| 288 | } | |
| 289 | }, | |
| 290 | "/leads/{id}/reply": { | |
| 291 | "post": { | |
| 292 | "summary": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.", | |
| 293 | "operationId": "postLeadsIdReply", | |
| 294 | "parameters": [ | |
| 295 | { | |
| 296 | "name": "id", | |
| 297 | "in": "path", | |
| 298 | "required": true, | |
| 299 | "schema": { | |
| 300 | "type": "integer" | |
| 301 | } | |
| 302 | } | |
| 303 | ], | |
| 304 | "requestBody": { | |
| 305 | "required": true, | |
| 306 | "content": { | |
| 307 | "application/json": { | |
| 308 | "schema": { | |
| 309 | "type": "object", | |
| 310 | "properties": { | |
| 311 | "body": { | |
| 312 | "type": "string", | |
| 313 | "minLength": 1, | |
| 314 | "maxLength": 4000, | |
| 315 | "description": "The words, edited; the draft when left out. A text is at most 480 characters. The signature is added." | |
| 316 | } | |
| 317 | } | |
| 318 | } | |
| 319 | } | |
| 320 | } | |
| 321 | }, | |
| 322 | "responses": { | |
| 323 | "200": { | |
| 324 | "description": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.", | |
| 325 | "content": { | |
| 326 | "application/json": { | |
| 327 | "schema": { | |
| 328 | "$ref": "#/components/schemas/Lead" | |
| 329 | } | |
| 330 | } | |
| 331 | } | |
| 332 | }, | |
| 333 | "default": { | |
| 334 | "description": "{ error, message }: why not", | |
| 335 | "content": { | |
| 336 | "application/json": { | |
| 337 | "schema": { | |
| 338 | "$ref": "#/components/schemas/Error" | |
| 339 | } | |
| 340 | } | |
| 341 | } | |
| 342 | } | |
| 343 | } | |
| 344 | } | |
| 345 | }, | |
| 346 | "/leads/{id}/state": { | |
| 347 | "post": { | |
| 348 | "summary": "Mark a lead qualified or lost: it leaves the follow-up plan.", | |
| 349 | "operationId": "postLeadsIdState", | |
| 350 | "parameters": [ | |
| 351 | { | |
| 352 | "name": "id", | |
| 353 | "in": "path", | |
| 354 | "required": true, | |
| 355 | "schema": { | |
| 356 | "type": "integer" | |
| 357 | } | |
| 358 | } | |
| 359 | ], | |
| 360 | "requestBody": { | |
| 361 | "required": true, | |
| 362 | "content": { | |
| 363 | "application/json": { | |
| 364 | "schema": { | |
| 365 | "type": "object", | |
| 366 | "properties": { | |
| 367 | "state": { | |
| 368 | "enum": [ | |
| 369 | "qualified", | |
| 370 | "lost" | |
| 371 | ] | |
| 372 | } | |
| 373 | }, | |
| 374 | "required": [ | |
| 375 | "state" | |
| 376 | ] | |
| 377 | } | |
| 378 | } | |
| 379 | } | |
| 380 | }, | |
| 381 | "responses": { | |
| 382 | "200": { | |
| 383 | "description": "Mark a lead qualified or lost: it leaves the follow-up plan.", | |
| 384 | "content": { | |
| 385 | "application/json": { | |
| 386 | "schema": { | |
| 387 | "$ref": "#/components/schemas/Lead" | |
| 388 | } | |
| 389 | } | |
| 390 | } | |
| 391 | }, | |
| 392 | "default": { | |
| 393 | "description": "{ error, message }: why not", | |
| 394 | "content": { | |
| 395 | "application/json": { | |
| 396 | "schema": { | |
| 397 | "$ref": "#/components/schemas/Error" | |
| 398 | } | |
| 399 | } | |
| 400 | } | |
| 401 | } | |
| 402 | } | |
| 403 | } | |
| 404 | }, | |
| 405 | "/tick": { | |
| 406 | "post": { | |
| 407 | "summary": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.", | |
| 408 | "operationId": "postTick", | |
| 409 | "responses": { | |
| 410 | "200": { | |
| 411 | "description": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.", | |
| 412 | "content": { | |
| 413 | "application/json": { | |
| 414 | "schema": { | |
| 415 | "type": "object", | |
| 416 | "properties": { | |
| 417 | "leads": { | |
| 418 | "type": "array", | |
| 419 | "items": { | |
| 420 | "type": "integer" | |
| 421 | } | |
| 422 | } | |
| 423 | }, | |
| 424 | "required": [ | |
| 425 | "leads" | |
| 426 | ] | |
| 427 | } | |
| 428 | } | |
| 429 | } | |
| 430 | }, | |
| 431 | "default": { | |
| 432 | "description": "{ error, message }: why not", | |
| 433 | "content": { | |
| 434 | "application/json": { | |
| 435 | "schema": { | |
| 436 | "$ref": "#/components/schemas/Error" | |
| 437 | } | |
| 438 | } | |
| 439 | } | |
| 440 | } | |
| 258 | 441 | } |
| 259 | 442 | } |
| 260 | 443 | }, |
| @@ -463,39 +646,322 @@ | ||
| 463 | 646 | }, |
| 464 | 647 | "components": { |
| 465 | 648 | "schemas": { |
| 466 | "Note": { | |
| 649 | "Lead": { | |
| 467 | 650 | "type": "object", |
| 468 | 651 | "properties": { |
| 469 | 652 | "id": { |
| 470 | 653 | "type": "integer" |
| 471 | 654 | }, |
| 472 | "body": { | |
| 655 | "name": { | |
| 473 | 656 | "type": "string", |
| 474 | 657 | "minLength": 1, |
| 475 | "maxLength": 500 | |
| 658 | "maxLength": 120 | |
| 476 | 659 | }, |
| 477 | "author_id": { | |
| 660 | "email": { | |
| 661 | "type": "string", | |
| 662 | "format": "email" | |
| 663 | }, | |
| 664 | "phone": { | |
| 478 | 665 | "type": "string" |
| 479 | 666 | }, |
| 480 | "author_name": { | |
| 481 | "type": "string" | |
| 667 | "source": { | |
| 668 | "enum": [ | |
| 669 | "zillow", | |
| 670 | "website", | |
| 671 | "open_house", | |
| 672 | "referral" | |
| 673 | ] | |
| 674 | }, | |
| 675 | "message": { | |
| 676 | "type": "string", | |
| 677 | "minLength": 1, | |
| 678 | "maxLength": 2000 | |
| 679 | }, | |
| 680 | "consent": { | |
| 681 | "type": "boolean", | |
| 682 | "description": "Prior written consent to be texted. Without it, only email." | |
| 683 | }, | |
| 684 | "state": { | |
| 685 | "enum": [ | |
| 686 | "new", | |
| 687 | "contacted", | |
| 688 | "qualified", | |
| 689 | "lost" | |
| 690 | ] | |
| 482 | 691 | }, |
| 483 | 692 | "created_at": { |
| 484 | 693 | "type": "string", |
| 485 | 694 | "format": "date-time" |
| 486 | 695 | }, |
| 696 | "replied_at": { | |
| 697 | "type": [ | |
| 698 | "string", | |
| 699 | "null" | |
| 700 | ], | |
| 701 | "format": "date-time" | |
| 702 | }, | |
| 487 | 703 | "updated_at": { |
| 488 | 704 | "type": "string", |
| 489 | 705 | "format": "date-time" |
| 706 | }, | |
| 707 | "messages": { | |
| 708 | "type": "array", | |
| 709 | "items": { | |
| 710 | "type": "object", | |
| 711 | "properties": { | |
| 712 | "id": { | |
| 713 | "type": "integer" | |
| 714 | }, | |
| 715 | "lead_id": { | |
| 716 | "type": "integer" | |
| 717 | }, | |
| 718 | "day": { | |
| 719 | "enum": [ | |
| 720 | 0, | |
| 721 | 1, | |
| 722 | 3, | |
| 723 | 7, | |
| 724 | 14, | |
| 725 | 30 | |
| 726 | ], | |
| 727 | "description": "0 is the first reply." | |
| 728 | }, | |
| 729 | "channel": { | |
| 730 | "enum": [ | |
| 731 | "text", | |
| 732 | "email" | |
| 733 | ] | |
| 734 | }, | |
| 735 | "body": { | |
| 736 | "type": "string", | |
| 737 | "minLength": 1, | |
| 738 | "maxLength": 4000 | |
| 739 | }, | |
| 740 | "signature": { | |
| 741 | "type": "string" | |
| 742 | }, | |
| 743 | "status": { | |
| 744 | "enum": [ | |
| 745 | "draft", | |
| 746 | "scheduled", | |
| 747 | "due", | |
| 748 | "sent", | |
| 749 | "skipped" | |
| 750 | ] | |
| 751 | }, | |
| 752 | "due_at": { | |
| 753 | "type": "string", | |
| 754 | "format": "date-time" | |
| 755 | }, | |
| 756 | "sent_at": { | |
| 757 | "type": [ | |
| 758 | "string", | |
| 759 | "null" | |
| 760 | ], | |
| 761 | "format": "date-time" | |
| 762 | }, | |
| 763 | "sent_by": { | |
| 764 | "type": [ | |
| 765 | "string", | |
| 766 | "null" | |
| 767 | ] | |
| 768 | } | |
| 769 | }, | |
| 770 | "required": [ | |
| 771 | "id", | |
| 772 | "lead_id", | |
| 773 | "day", | |
| 774 | "channel", | |
| 775 | "body", | |
| 776 | "signature", | |
| 777 | "status", | |
| 778 | "due_at" | |
| 779 | ] | |
| 780 | } | |
| 781 | } | |
| 782 | }, | |
| 783 | "required": [ | |
| 784 | "id", | |
| 785 | "name", | |
| 786 | "email", | |
| 787 | "phone", | |
| 788 | "source", | |
| 789 | "message", | |
| 790 | "consent", | |
| 791 | "state", | |
| 792 | "created_at", | |
| 793 | "replied_at", | |
| 794 | "updated_at", | |
| 795 | "messages" | |
| 796 | ] | |
| 797 | }, | |
| 798 | "DeskLead": { | |
| 799 | "type": "object", | |
| 800 | "properties": { | |
| 801 | "id": { | |
| 802 | "type": "integer" | |
| 803 | }, | |
| 804 | "name": { | |
| 805 | "type": "string", | |
| 806 | "minLength": 1, | |
| 807 | "maxLength": 120 | |
| 808 | }, | |
| 809 | "email": { | |
| 810 | "type": "string", | |
| 811 | "format": "email" | |
| 812 | }, | |
| 813 | "phone": { | |
| 814 | "type": "string" | |
| 815 | }, | |
| 816 | "source": { | |
| 817 | "enum": [ | |
| 818 | "zillow", | |
| 819 | "website", | |
| 820 | "open_house", | |
| 821 | "referral" | |
| 822 | ] | |
| 823 | }, | |
| 824 | "message": { | |
| 825 | "type": "string", | |
| 826 | "minLength": 1, | |
| 827 | "maxLength": 2000 | |
| 828 | }, | |
| 829 | "consent": { | |
| 830 | "type": "boolean", | |
| 831 | "description": "Prior written consent to be texted. Without it, only email." | |
| 832 | }, | |
| 833 | "state": { | |
| 834 | "enum": [ | |
| 835 | "new", | |
| 836 | "contacted", | |
| 837 | "qualified", | |
| 838 | "lost" | |
| 839 | ] | |
| 840 | }, | |
| 841 | "created_at": { | |
| 842 | "type": "string", | |
| 843 | "format": "date-time" | |
| 844 | }, | |
| 845 | "replied_at": { | |
| 846 | "type": [ | |
| 847 | "string", | |
| 848 | "null" | |
| 849 | ], | |
| 850 | "format": "date-time" | |
| 851 | }, | |
| 852 | "updated_at": { | |
| 853 | "type": "string", | |
| 854 | "format": "date-time" | |
| 855 | }, | |
| 856 | "ready": { | |
| 857 | "type": [ | |
| 858 | "object", | |
| 859 | "null" | |
| 860 | ], | |
| 861 | "description": "The message ready to approve now, if any.", | |
| 862 | "properties": { | |
| 863 | "id": { | |
| 864 | "type": "integer" | |
| 865 | }, | |
| 866 | "day": { | |
| 867 | "type": "integer" | |
| 868 | } | |
| 869 | } | |
| 870 | }, | |
| 871 | "next_at": { | |
| 872 | "type": [ | |
| 873 | "string", | |
| 874 | "null" | |
| 875 | ], | |
| 876 | "format": "date-time" | |
| 490 | 877 | } |
| 491 | 878 | }, |
| 492 | 879 | "required": [ |
| 493 | 880 | "id", |
| 494 | "body", | |
| 495 | "author_id", | |
| 496 | "author_name", | |
| 881 | "name", | |
| 882 | "email", | |
| 883 | "phone", | |
| 884 | "source", | |
| 885 | "message", | |
| 886 | "consent", | |
| 887 | "state", | |
| 497 | 888 | "created_at", |
| 498 | "updated_at" | |
| 889 | "replied_at", | |
| 890 | "updated_at", | |
| 891 | "ready", | |
| 892 | "next_at" | |
| 893 | ] | |
| 894 | }, | |
| 895 | "Message": { | |
| 896 | "type": "object", | |
| 897 | "properties": { | |
| 898 | "id": { | |
| 899 | "type": "integer" | |
| 900 | }, | |
| 901 | "lead_id": { | |
| 902 | "type": "integer" | |
| 903 | }, | |
| 904 | "day": { | |
| 905 | "enum": [ | |
| 906 | 0, | |
| 907 | 1, | |
| 908 | 3, | |
| 909 | 7, | |
| 910 | 14, | |
| 911 | 30 | |
| 912 | ], | |
| 913 | "description": "0 is the first reply." | |
| 914 | }, | |
| 915 | "channel": { | |
| 916 | "enum": [ | |
| 917 | "text", | |
| 918 | "email" | |
| 919 | ] | |
| 920 | }, | |
| 921 | "body": { | |
| 922 | "type": "string", | |
| 923 | "minLength": 1, | |
| 924 | "maxLength": 4000 | |
| 925 | }, | |
| 926 | "signature": { | |
| 927 | "type": "string" | |
| 928 | }, | |
| 929 | "status": { | |
| 930 | "enum": [ | |
| 931 | "draft", | |
| 932 | "scheduled", | |
| 933 | "due", | |
| 934 | "sent", | |
| 935 | "skipped" | |
| 936 | ] | |
| 937 | }, | |
| 938 | "due_at": { | |
| 939 | "type": "string", | |
| 940 | "format": "date-time" | |
| 941 | }, | |
| 942 | "sent_at": { | |
| 943 | "type": [ | |
| 944 | "string", | |
| 945 | "null" | |
| 946 | ], | |
| 947 | "format": "date-time" | |
| 948 | }, | |
| 949 | "sent_by": { | |
| 950 | "type": [ | |
| 951 | "string", | |
| 952 | "null" | |
| 953 | ] | |
| 954 | } | |
| 955 | }, | |
| 956 | "required": [ | |
| 957 | "id", | |
| 958 | "lead_id", | |
| 959 | "day", | |
| 960 | "channel", | |
| 961 | "body", | |
| 962 | "signature", | |
| 963 | "status", | |
| 964 | "due_at" | |
| 499 | 965 | ] |
| 500 | 966 | }, |
| 501 | 967 | "AuditRow": { |
design/tokens.json +196 −36
| @@ -3,63 +3,182 @@ | ||
| 3 | 3 | "color": { |
| 4 | 4 | "$type": "color", |
| 5 | 5 | "bg": { |
| 6 | "$value": "#f6f6f3", | |
| 7 | "$extensions": { "mode": { "dark": "#131312" } } | |
| 6 | "$value": "#f6f3ec", | |
| 7 | "$extensions": { | |
| 8 | "mode": { | |
| 9 | "dark": "#111513" | |
| 10 | } | |
| 11 | } | |
| 8 | 12 | }, |
| 9 | 13 | "surface": { |
| 10 | "$value": "#ffffff", | |
| 11 | "$extensions": { "mode": { "dark": "#1d1d1b" } } | |
| 14 | "$value": "#fffdf8", | |
| 15 | "$extensions": { | |
| 16 | "mode": { | |
| 17 | "dark": "#181e1b" | |
| 18 | } | |
| 19 | } | |
| 12 | 20 | }, |
| 13 | 21 | "fg": { |
| 14 | "$value": "#1c1c1a", | |
| 15 | "$extensions": { "mode": { "dark": "#ecece7" } } | |
| 22 | "$value": "#1d2420", | |
| 23 | "$extensions": { | |
| 24 | "mode": { | |
| 25 | "dark": "#ebe7de" | |
| 26 | } | |
| 27 | } | |
| 16 | 28 | }, |
| 17 | 29 | "muted": { |
| 18 | "$value": "#6b6b65", | |
| 19 | "$extensions": { "mode": { "dark": "#9a9a93" } } | |
| 30 | "$value": "#596159", | |
| 31 | "$extensions": { | |
| 32 | "mode": { | |
| 33 | "dark": "#a1a89f" | |
| 34 | } | |
| 35 | } | |
| 20 | 36 | }, |
| 21 | 37 | "line": { |
| 22 | "$value": "#e3e3dd", | |
| 23 | "$extensions": { "mode": { "dark": "#2c2c29" } } | |
| 38 | "$value": "#e2dccf", | |
| 39 | "$extensions": { | |
| 40 | "mode": { | |
| 41 | "dark": "#2a322d" | |
| 42 | } | |
| 43 | } | |
| 24 | 44 | }, |
| 25 | 45 | "accent": { |
| 26 | "$value": "#2f5bea", | |
| 27 | "$extensions": { "mode": { "dark": "#7c96ff" } } | |
| 46 | "$value": "#1e5a44", | |
| 47 | "$extensions": { | |
| 48 | "mode": { | |
| 49 | "dark": "#86cfaa" | |
| 50 | } | |
| 51 | } | |
| 28 | 52 | }, |
| 29 | 53 | "accent-fg": { |
| 30 | 54 | "$value": "#ffffff", |
| 31 | "$extensions": { "mode": { "dark": "#0f1a4d" } } | |
| 55 | "$extensions": { | |
| 56 | "mode": { | |
| 57 | "dark": "#0c2219" | |
| 58 | } | |
| 59 | } | |
| 60 | }, | |
| 61 | "brass": { | |
| 62 | "$value": "#7a5a1c", | |
| 63 | "$extensions": { | |
| 64 | "mode": { | |
| 65 | "dark": "#d6b46c" | |
| 66 | } | |
| 67 | } | |
| 32 | 68 | }, |
| 33 | 69 | "danger": { |
| 34 | "$value": "#c2410c", | |
| 35 | "$extensions": { "mode": { "dark": "#fb923c" } } | |
| 70 | "$value": "#a8321f", | |
| 71 | "$extensions": { | |
| 72 | "mode": { | |
| 73 | "dark": "#f19580" | |
| 74 | } | |
| 75 | } | |
| 76 | }, | |
| 77 | "ok": { | |
| 78 | "$value": "#17683f", | |
| 79 | "$extensions": { | |
| 80 | "mode": { | |
| 81 | "dark": "#7fd6a1" | |
| 82 | } | |
| 83 | } | |
| 84 | }, | |
| 85 | "ok-bg": { | |
| 86 | "$value": "#e3f2e8", | |
| 87 | "$extensions": { | |
| 88 | "mode": { | |
| 89 | "dark": "#13291d" | |
| 90 | } | |
| 91 | } | |
| 92 | }, | |
| 93 | "warn": { | |
| 94 | "$value": "#8a5200", | |
| 95 | "$extensions": { | |
| 96 | "mode": { | |
| 97 | "dark": "#f2b85c" | |
| 98 | } | |
| 99 | } | |
| 100 | }, | |
| 101 | "warn-bg": { | |
| 102 | "$value": "#fbefd9", | |
| 103 | "$extensions": { | |
| 104 | "mode": { | |
| 105 | "dark": "#2d2312" | |
| 106 | } | |
| 107 | } | |
| 108 | }, | |
| 109 | "late": { | |
| 110 | "$value": "#b42318", | |
| 111 | "$extensions": { | |
| 112 | "mode": { | |
| 113 | "dark": "#ff8f84" | |
| 114 | } | |
| 115 | } | |
| 116 | }, | |
| 117 | "late-bg": { | |
| 118 | "$value": "#fbe6e3", | |
| 119 | "$extensions": { | |
| 120 | "mode": { | |
| 121 | "dark": "#33171a" | |
| 122 | } | |
| 123 | } | |
| 36 | 124 | }, |
| 37 | 125 | "toast-bg": { |
| 38 | "$value": "#1c1c1a", | |
| 39 | "$extensions": { "mode": { "dark": "#ecece7" } } | |
| 126 | "$value": "#1d2420", | |
| 127 | "$extensions": { | |
| 128 | "mode": { | |
| 129 | "dark": "#ebe7de" | |
| 130 | } | |
| 131 | } | |
| 40 | 132 | }, |
| 41 | 133 | "toast-fg": { |
| 42 | "$value": "#f6f6f3", | |
| 43 | "$extensions": { "mode": { "dark": "#131312" } } | |
| 134 | "$value": "#f6f3ec", | |
| 135 | "$extensions": { | |
| 136 | "mode": { | |
| 137 | "dark": "#111513" | |
| 138 | } | |
| 139 | } | |
| 44 | 140 | }, |
| 45 | 141 | "shadow": { |
| 46 | "$value": "#0000002e", | |
| 47 | "$extensions": { "mode": { "dark": "#00000080" } } | |
| 142 | "$value": "#1d24201f", | |
| 143 | "$extensions": { | |
| 144 | "mode": { | |
| 145 | "dark": "#00000080" | |
| 146 | } | |
| 147 | } | |
| 48 | 148 | } |
| 49 | 149 | }, |
| 50 | 150 | "space": { |
| 51 | 151 | "$type": "dimension", |
| 52 | "1": { "$value": "0.25rem" }, | |
| 53 | "2": { "$value": "0.5rem" }, | |
| 54 | "3": { "$value": "0.75rem" }, | |
| 55 | "4": { "$value": "1rem" }, | |
| 56 | "5": { "$value": "1.5rem" }, | |
| 57 | "6": { "$value": "2.5rem" } | |
| 152 | "1": { | |
| 153 | "$value": "0.25rem" | |
| 154 | }, | |
| 155 | "2": { | |
| 156 | "$value": "0.5rem" | |
| 157 | }, | |
| 158 | "3": { | |
| 159 | "$value": "0.75rem" | |
| 160 | }, | |
| 161 | "4": { | |
| 162 | "$value": "1rem" | |
| 163 | }, | |
| 164 | "5": { | |
| 165 | "$value": "1.5rem" | |
| 166 | }, | |
| 167 | "6": { | |
| 168 | "$value": "2.5rem" | |
| 169 | } | |
| 58 | 170 | }, |
| 59 | 171 | "radius": { |
| 60 | 172 | "$type": "dimension", |
| 61 | "md": { "$value": "10px" }, | |
| 62 | "pill": { "$value": "999px" } | |
| 173 | "md": { | |
| 174 | "$value": "10px" | |
| 175 | }, | |
| 176 | "pill": { | |
| 177 | "$value": "999px" | |
| 178 | }, | |
| 179 | "sm": { | |
| 180 | "$value": "6px" | |
| 181 | } | |
| 63 | 182 | }, |
| 64 | 183 | "size": { |
| 65 | 184 | "$type": "dimension", |
| @@ -70,26 +189,67 @@ | ||
| 70 | 189 | }, |
| 71 | 190 | "font": { |
| 72 | 191 | "$type": "fontFamily", |
| 192 | "display": { | |
| 193 | "$value": [ | |
| 194 | "Iowan Old Style", | |
| 195 | "Palatino Linotype", | |
| 196 | "Palatino", | |
| 197 | "Book Antiqua", | |
| 198 | "Georgia", | |
| 199 | "serif" | |
| 200 | ], | |
| 201 | "$description": "Headings and names: a warm book serif, the voice of a handwritten note." | |
| 202 | }, | |
| 73 | 203 | "sans": { |
| 74 | "$value": ["system-ui", "-apple-system", "Segoe UI", "sans-serif"] | |
| 204 | "$value": [ | |
| 205 | "Avenir Next", | |
| 206 | "Avenir", | |
| 207 | "Segoe UI", | |
| 208 | "Helvetica Neue", | |
| 209 | "system-ui", | |
| 210 | "sans-serif" | |
| 211 | ], | |
| 212 | "$description": "Everything else, and the clock's figures." | |
| 75 | 213 | }, |
| 76 | 214 | "mono": { |
| 77 | "$value": ["ui-monospace", "SFMono-Regular", "Menlo", "monospace"] | |
| 215 | "$value": [ | |
| 216 | "ui-monospace", | |
| 217 | "SFMono-Regular", | |
| 218 | "Menlo", | |
| 219 | "monospace" | |
| 220 | ] | |
| 78 | 221 | } |
| 79 | 222 | }, |
| 80 | 223 | "text": { |
| 81 | 224 | "$type": "dimension", |
| 82 | "sm": { "$value": "0.875rem" }, | |
| 225 | "sm": { | |
| 226 | "$value": "0.875rem" | |
| 227 | }, | |
| 83 | 228 | "base": { |
| 84 | 229 | "$value": "1rem", |
| 85 | 230 | "$description": "Never below 16px: a phone zooms into a smaller input." |
| 86 | 231 | }, |
| 87 | "lg": { "$value": "1.125rem" }, | |
| 88 | "xl": { "$value": "1.5rem" } | |
| 232 | "lg": { | |
| 233 | "$value": "1.125rem" | |
| 234 | }, | |
| 235 | "xl": { | |
| 236 | "$value": "1.5rem" | |
| 237 | }, | |
| 238 | "2xl": { | |
| 239 | "$value": "2rem" | |
| 240 | }, | |
| 241 | "clock": { | |
| 242 | "$value": "1.625rem", | |
| 243 | "$description": "The response clock: the hero of every row." | |
| 244 | } | |
| 89 | 245 | }, |
| 90 | 246 | "leading": { |
| 91 | 247 | "$type": "number", |
| 92 | "body": { "$value": 1.55 }, | |
| 93 | "tight": { "$value": 1.2 } | |
| 248 | "body": { | |
| 249 | "$value": 1.55 | |
| 250 | }, | |
| 251 | "tight": { | |
| 252 | "$value": 1.2 | |
| 253 | } | |
| 94 | 254 | } |
| 95 | 255 | } |
src/actions.test.ts +217 −35
| @@ -1,58 +1,240 @@ | ||
| 1 | /** | |
| 2 | * What the table cannot say: a lead is checked field by field, the first | |
| 3 | * reply is drafted and goes only when approved, the cadence follows it and | |
| 4 | * advances with the clock, and closing a lead ends it. | |
| 5 | */ | |
| 1 | 6 | import { expect, test } from "bun:test"; |
| 2 | 7 | import { mkdtempSync } from "node:fs"; |
| 3 | 8 | import { tmpdir } from "node:os"; |
| 4 | 9 | import { join } from "node:path"; |
| 5 | import { addNote, deleteNote, listNotes } from "./actions.ts"; | |
| 10 | import { | |
| 11 | addLead, | |
| 12 | getLead, | |
| 13 | listLeads, | |
| 14 | readNewLead, | |
| 15 | resetSample, | |
| 16 | sendReply, | |
| 17 | setState, | |
| 18 | sourceOf, | |
| 19 | tick, | |
| 20 | } from "./actions.ts"; | |
| 6 | 21 | import { openDb } from "./db.ts"; |
| 22 | import { agent } from "./env.ts"; | |
| 23 | import { SAMPLES } from "./sample.ts"; | |
| 7 | 24 | import type { Who } from "./who.ts"; |
| 8 | 25 | |
| 9 | 26 | const db = openDb(mkdtempSync(join(tmpdir(), "app-actions-"))); |
| 10 | 27 | const anon: Who = { role: "anon" }; |
| 11 | 28 | const alice: Who = { role: "user", id: "u1", name: "alice" }; |
| 12 | const bob: Who = { role: "user", id: "u2", name: "bob" }; | |
| 13 | 29 | const root: Who = { role: "admin", id: "u0", name: "root" }; |
| 30 | const T0 = new Date("2026-10-12T15:00:00.000Z"); | |
| 31 | const at = (days: number, minutes = 0): Date => | |
| 32 | new Date(T0.getTime() + days * 86_400_000 + minutes * 60_000); | |
| 14 | 33 | |
| 15 | test("anyone reads; only a signed-in person adds, as themselves", () => { | |
| 16 | expect(listNotes(db, anon)).toEqual({ ok: true, value: [] }); | |
| 17 | const refused = addNote(db, anon, { body: "hello" }); | |
| 18 | expect(refused.ok).toBe(false); | |
| 19 | if (!refused.ok) expect(refused.error).toBe("signin_required"); | |
| 20 | const added = addNote(db, alice, { body: " hello " }); | |
| 21 | expect(added.ok).toBe(true); | |
| 22 | if (!added.ok) return; | |
| 23 | expect(added.value.body).toBe("hello"); | |
| 24 | expect(added.value.author_id).toBe("u1"); | |
| 25 | expect(added.value.author_name).toBe("alice"); | |
| 26 | const all = listNotes(db, anon); | |
| 27 | expect(all.ok && all.value.length).toBe(1); | |
| 34 | const maria = { | |
| 35 | name: " Maria Gonzalez ", | |
| 36 | email: "[email protected]", | |
| 37 | phone: "(206) 555-0101", | |
| 38 | source: "Zillow", | |
| 39 | message: "Is 418 Juniper Ln still available? Could we see it this weekend?", | |
| 40 | consent: true, | |
| 41 | }; | |
| 42 | const must = <T>(r: { ok: true; value: T } | { ok: false; message: string }): T => { | |
| 43 | if (!r.ok) throw new Error(r.message); | |
| 44 | return r.value; | |
| 45 | }; | |
| 46 | ||
| 47 | test("a lead is checked at the boundary, field by field", () => { | |
| 48 | expect(must(readNewLead(maria))).toEqual({ | |
| 49 | name: "Maria Gonzalez", | |
| 50 | email: "[email protected]", | |
| 51 | phone: "(206) 555-0101", | |
| 52 | source: "zillow", | |
| 53 | message: maria.message, | |
| 54 | consent: true, | |
| 55 | }); | |
| 56 | for (const bad of [ | |
| 57 | { ...maria, name: "" }, | |
| 58 | { ...maria, email: "not an email" }, | |
| 59 | { ...maria, phone: "call me" }, | |
| 60 | { ...maria, source: "craigslist" }, | |
| 61 | { ...maria, message: "x".repeat(2001) }, | |
| 62 | { ...maria, message: 42 }, | |
| 63 | ]) { | |
| 64 | const r = readNewLead(bad); | |
| 65 | expect([bad, r.ok]).toEqual([bad, false]); | |
| 66 | if (!r.ok) expect(r.error).toBe("invalid"); | |
| 67 | } | |
| 68 | expect(sourceOf("Open house")).toBe("open_house"); | |
| 69 | expect(sourceOf("website form")).toBe("website"); | |
| 70 | // Consent is only ever a clear yes. | |
| 71 | expect(must(readNewLead({ ...maria, consent: "maybe" })).consent).toBe(false); | |
| 72 | expect(must(readNewLead({ ...maria, consent: undefined })).consent).toBe(false); | |
| 28 | 73 | }); |
| 29 | 74 | |
| 30 | test("a note is one to five hundred characters", () => { | |
| 31 | for (const body of ["", " ", "x".repeat(501)]) { | |
| 32 | const r = addNote(db, alice, { body }); | |
| 75 | test("a stranger may not see or add leads; a signed-in person may", () => { | |
| 76 | const r = addLead(db, anon, maria); | |
| 77 | expect(r.ok).toBe(false); | |
| 78 | if (!r.ok) expect(r.error).toBe("signin_required"); | |
| 79 | expect(listLeads(db, anon).ok).toBe(false); | |
| 80 | expect(listLeads(db, alice)).toEqual({ ok: true, value: [] }); | |
| 81 | }); | |
| 82 | ||
| 83 | test("control characters are refused at the boundary; a textarea's line breaks are kept", () => { | |
| 84 | for (const bad of [ | |
| 85 | { ...maria, name: "Eve\x1b[2J" }, | |
| 86 | { ...maria, name: "Eve\nNewline" }, | |
| 87 | { ...maria, email: "[email protected]\x07" }, | |
| 88 | { ...maria, phone: "555\x9b2J0101" }, | |
| 89 | { ...maria, message: "hi\x1b]52;c;aGk=\x07" }, | |
| 90 | { ...maria, message: "hidden\x1b[8m" }, | |
| 91 | { ...maria, message: "nul\x00" }, | |
| 92 | ]) { | |
| 93 | const r = readNewLead(bad); | |
| 94 | expect([bad, r.ok]).toEqual([bad, false]); | |
| 95 | if (!r.ok) expect(r.error).toBe("invalid"); | |
| 96 | } | |
| 97 | expect(must(readNewLead({ ...maria, message: "line one\r\nline two\tok" })).message).toBe( | |
| 98 | "line one\nline two\tok", | |
| 99 | ); | |
| 100 | // An edited reply is held to the same. | |
| 101 | const lead = must(addLead(db, alice, { ...maria, name: "Plain Text" }, at(0))); | |
| 102 | const r = sendReply(db, alice, { id: lead.id, body: "Hi\x1b[2J" }, at(0, 1)); | |
| 103 | expect(r.ok).toBe(false); | |
| 104 | if (!r.ok) expect(r.error).toBe("invalid"); | |
| 105 | expect(must(sendReply(db, alice, { id: lead.id, body: "Hi\r\nthere" }, at(0, 1))).messages[0]!.body).toBe("Hi\nthere"); | |
| 106 | }); | |
| 107 | ||
| 108 | test("a new lead arrives with its first reply drafted, signed, by text when they consented", () => { | |
| 109 | const lead = must(addLead(db, alice, maria, at(0))); | |
| 110 | expect(lead.state).toBe("new"); | |
| 111 | expect(lead.replied_at).toBeNull(); | |
| 112 | expect(lead.messages).toHaveLength(1); | |
| 113 | const [first] = lead.messages; | |
| 114 | expect(first!.day).toBe(0); | |
| 115 | expect(first!.status).toBe("draft"); | |
| 116 | expect(first!.channel).toBe("text"); | |
| 117 | expect(first!.body).toContain("Hi Maria"); | |
| 118 | expect(first!.body).toContain("418 Juniper Ln"); | |
| 119 | expect(first!.signature).toContain(agent.name); | |
| 120 | expect(first!.signature).toContain(agent.brokerage); | |
| 121 | expect(first!.signature).toContain(agent.license); | |
| 122 | expect(first!.signature).toContain("STOP"); | |
| 123 | }); | |
| 124 | ||
| 125 | test("approve and send: the reply goes, the clock stops, and the cadence is drafted", () => { | |
| 126 | const lead = must(addLead(db, alice, { ...maria, name: "Sam Ortiz" }, at(0))); | |
| 127 | const sent = must(sendReply(db, alice, { id: lead.id }, at(0, 1))); | |
| 128 | expect(sent.state).toBe("contacted"); | |
| 129 | expect(sent.replied_at).toBe(at(0, 1).toISOString()); | |
| 130 | const [first, ...touches] = sent.messages; | |
| 131 | expect(first!.status).toBe("sent"); | |
| 132 | expect(first!.sent_by).toBe("alice"); | |
| 133 | expect(first!.body).toBe(lead.messages[0]!.body); | |
| 134 | expect(touches.map((m) => [m.day, m.status])).toEqual([ | |
| 135 | [1, "scheduled"], | |
| 136 | [3, "scheduled"], | |
| 137 | [7, "scheduled"], | |
| 138 | [14, "scheduled"], | |
| 139 | [30, "scheduled"], | |
| 140 | ]); | |
| 141 | expect(touches[2]!.due_at).toBe(at(7, 1).toISOString()); | |
| 142 | // Nothing is ready until a touch's day comes. | |
| 143 | const early = sendReply(db, alice, { id: lead.id }, at(0, 2)); | |
| 144 | expect(early.ok).toBe(false); | |
| 145 | if (!early.ok) expect(early.error).toBe("invalid"); | |
| 146 | }); | |
| 147 | ||
| 148 | test("an edit is what goes out, with the signature still on it", () => { | |
| 149 | const lead = must(addLead(db, alice, { ...maria, name: "Ana Diaz" }, at(0))); | |
| 150 | const sent = must( | |
| 151 | sendReply(db, alice, { id: lead.id, body: " Hi Ana — free Saturday at 10? " }, at(0, 1)), | |
| 152 | ); | |
| 153 | expect(sent.messages[0]!.body).toBe("Hi Ana — free Saturday at 10?"); | |
| 154 | expect(sent.messages[0]!.signature).toContain(agent.license); | |
| 155 | const lead2 = must(addLead(db, alice, { ...maria, name: "Bo Lin" }, at(0))); | |
| 156 | for (const body of [" ", "x".repeat(481)]) { | |
| 157 | const r = sendReply(db, alice, { id: lead2.id, body }, at(0, 1)); | |
| 33 | 158 | expect(r.ok).toBe(false); |
| 34 | 159 | if (!r.ok) expect(r.error).toBe("invalid"); |
| 35 | 160 | } |
| 36 | 161 | }); |
| 37 | 162 | |
| 38 | test("only the author or an admin removes a note", () => { | |
| 39 | const mine = addNote(db, alice, { body: "mine" }); | |
| 40 | if (!mine.ok) throw new Error(mine.message); | |
| 41 | const byBob = deleteNote(db, bob, { id: mine.value.id }); | |
| 42 | expect(byBob.ok).toBe(false); | |
| 43 | if (!byBob.ok) expect(byBob.error).toBe("forbidden"); | |
| 44 | const byAnon = deleteNote(db, anon, { id: mine.value.id }); | |
| 45 | expect(byAnon.ok).toBe(false); | |
| 46 | if (!byAnon.ok) expect(byAnon.error).toBe("signin_required"); | |
| 47 | expect(deleteNote(db, alice, { id: mine.value.id }).ok).toBe(true); | |
| 48 | const gone = deleteNote(db, alice, { id: mine.value.id }); | |
| 49 | expect(gone.ok).toBe(false); | |
| 50 | if (!gone.ok) expect(gone.error).toBe("not_found"); | |
| 163 | test("no text is drafted without consent: email only, from first reply to last touch", () => { | |
| 164 | const lead = must( | |
| 165 | addLead(db, alice, { ...maria, name: "No Consent", consent: false }, at(0)), | |
| 166 | ); | |
| 167 | expect(lead.messages[0]!.channel).toBe("email"); | |
| 168 | const sent = must(sendReply(db, alice, { id: lead.id }, at(0, 1))); | |
| 169 | expect(sent.messages.every((m) => m.channel === "email")).toBe(true); | |
| 170 | // Consent without a number to text is still email. | |
| 171 | const noPhone = must( | |
| 172 | addLead(db, alice, { ...maria, name: "No Phone", phone: "" }, at(0)), | |
| 173 | ); | |
| 174 | expect(noPhone.messages[0]!.channel).toBe("email"); | |
| 175 | // And the file refuses a text for them, whatever asks. | |
| 176 | expect(() => | |
| 177 | db | |
| 178 | .query("UPDATE message SET channel = 'text' WHERE lead_id = ?1") | |
| 179 | .run(lead.id), | |
| 180 | ).toThrow("no consent to text"); | |
| 181 | }); | |
| 51 | 182 | |
| 52 | const bobs = addNote(db, bob, { body: "bob's" }); | |
| 53 | if (!bobs.ok) throw new Error(bobs.message); | |
| 54 | expect(deleteNote(db, root, { id: bobs.value.id }).ok).toBe(true); | |
| 55 | const odd = deleteNote(db, root, { id: 1.5 }); | |
| 183 | test("the day turns: a touch comes due on its day, once, and is sent when approved", () => { | |
| 184 | const lead = must(addLead(db, alice, { ...maria, name: "Cadence Test" }, at(0))); | |
| 185 | must(sendReply(db, alice, { id: lead.id }, at(0))); | |
| 186 | expect(must(tick(db, alice, at(0, 30))).leads).not.toContain(lead.id); | |
| 187 | expect(must(tick(db, alice, at(1, 1))).leads).toContain(lead.id); | |
| 188 | expect(must(tick(db, alice, at(1, 2))).leads).not.toContain(lead.id); | |
| 189 | const desk = must(listLeads(db, alice)).find((l) => l.id === lead.id)!; | |
| 190 | expect(desk.ready?.day).toBe(1); | |
| 191 | const sent = must(sendReply(db, alice, { id: lead.id }, at(1, 5))); | |
| 192 | expect(sent.messages.find((m) => m.day === 1)!.status).toBe("sent"); | |
| 193 | expect(sent.messages.find((m) => m.day === 3)!.status).toBe("scheduled"); | |
| 194 | const after = must(listLeads(db, alice)).find((l) => l.id === lead.id)!; | |
| 195 | expect(after.ready).toBeNull(); | |
| 196 | expect(after.next_at).toBe(at(3).toISOString()); | |
| 197 | expect(tick(db, anon, at(2)).ok).toBe(false); | |
| 198 | }); | |
| 199 | ||
| 200 | test("qualified or lost leaves the cadence", () => { | |
| 201 | const lead = must(addLead(db, alice, { ...maria, name: "Leaving" }, at(0))); | |
| 202 | must(sendReply(db, alice, { id: lead.id }, at(0))); | |
| 203 | must(tick(db, alice, at(3, 1))); | |
| 204 | const closed = must(setState(db, alice, { id: lead.id, state: "qualified" })); | |
| 205 | expect(closed.state).toBe("qualified"); | |
| 206 | expect( | |
| 207 | closed.messages.filter((m) => m.day > 0).map((m) => m.status), | |
| 208 | ).toEqual(["skipped", "skipped", "skipped", "skipped", "skipped"]); | |
| 209 | must(tick(db, alice, at(40))); | |
| 210 | expect(must(getLead(db, alice, { id: lead.id })).messages.some((m) => m.status === "due")).toBe(false); | |
| 211 | expect(sendReply(db, alice, { id: lead.id }).ok).toBe(false); | |
| 212 | const odd = setState(db, alice, { id: lead.id, state: "contacted" }); | |
| 56 | 213 | expect(odd.ok).toBe(false); |
| 57 | 214 | if (!odd.ok) expect(odd.error).toBe("invalid"); |
| 215 | const gone = setState(db, alice, { id: 999_999, state: "lost" }); | |
| 216 | expect(gone.ok).toBe(false); | |
| 217 | if (!gone.ok) expect(gone.error).toBe("not_found"); | |
| 218 | }); | |
| 219 | ||
| 220 | test("the sample desk: twelve leads, some red, some mid-cadence; only an admin restarts it", () => { | |
| 221 | const sampleDb = openDb(mkdtempSync(join(tmpdir(), "app-sample-"))); | |
| 222 | expect(resetSample(sampleDb, alice).ok).toBe(false); | |
| 223 | expect(must(resetSample(sampleDb, root, T0)).leads).toBe(12); | |
| 224 | const desk = must(listLeads(sampleDb, alice)); | |
| 225 | expect(desk).toHaveLength(SAMPLES.length); | |
| 226 | expect(desk[0]!.name).toBe("Maria Gonzalez"); | |
| 227 | const waited = desk | |
| 228 | .filter((l) => l.replied_at === null) | |
| 229 | .map((l) => T0.getTime() - Date.parse(l.created_at)); | |
| 230 | expect(waited.filter((ms) => ms >= 3_600_000).length).toBeGreaterThanOrEqual(3); | |
| 231 | expect(waited.filter((ms) => ms < 300_000).length).toBeGreaterThanOrEqual(2); | |
| 232 | expect(new Set(desk.map((l) => l.source)).size).toBe(4); | |
| 233 | expect(desk.some((l) => l.consent) && desk.some((l) => !l.consent)).toBe(true); | |
| 234 | expect(desk.filter((l) => l.ready !== null && l.ready.day > 0).length).toBeGreaterThanOrEqual(2); | |
| 235 | expect(desk.some((l) => l.state === "qualified")).toBe(true); | |
| 236 | // Every sample message obeys the consent rule too. | |
| 237 | for (const lead of desk) | |
| 238 | for (const m of must(getLead(sampleDb, alice, { id: lead.id })).messages) | |
| 239 | if (m.channel === "text") expect(lead.consent).toBe(true); | |
| 58 | 240 | }); |
src/actions.ts +265 −113
| @@ -9,18 +9,26 @@ | ||
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | import { record, type AuditRow } from "./audit.ts"; |
| 11 | 11 | import { permit } from "./contract.ts"; |
| 12 | import { MAX_BODY, SOURCES, type Source } from "./drafts.ts"; | |
| 13 | import { agent } from "./env.ts"; | |
| 14 | import { | |
| 15 | advance, | |
| 16 | clearLeads, | |
| 17 | close, | |
| 18 | desk, | |
| 19 | detail, | |
| 20 | insertLead, | |
| 21 | readyFor, | |
| 22 | removeLead, | |
| 23 | send, | |
| 24 | type DeskLead, | |
| 25 | type LeadDetail, | |
| 26 | type NewLead, | |
| 27 | } from "./leads.ts"; | |
| 12 | 28 | import { emit } from "./live.ts"; |
| 29 | import { seed } from "./sample.ts"; | |
| 13 | 30 | import type { Who } from "./who.ts"; |
| 14 | 31 | |
| 15 | export interface Note { | |
| 16 | readonly id: number; | |
| 17 | readonly body: string; | |
| 18 | readonly author_id: string; | |
| 19 | readonly author_name: string; | |
| 20 | readonly created_at: string; | |
| 21 | readonly updated_at: string; | |
| 22 | } | |
| 23 | ||
| 24 | 32 | export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid"; |
| 25 | 33 | export type Result<T> = |
| 26 | 34 | | { ok: true; value: T } |
| @@ -32,8 +40,6 @@ const fail = <T>(error: Failure, message: string): Result<T> => ({ | ||
| 32 | 40 | message, |
| 33 | 41 | }); |
| 34 | 42 | |
| 35 | export const BODY_MAX = 500; | |
| 36 | ||
| 37 | 43 | /** The refusal for a "no": who is not signed in is asked to; who is, is told. */ |
| 38 | 44 | const refuse = <T>(who: Who, signIn: string, no: string): Result<T> => |
| 39 | 45 | who.role === "anon" ? fail("signin_required", signIn) : fail("forbidden", no); |
| @@ -61,158 +67,304 @@ const audited = <T extends { readonly id: number }>( | ||
| 61 | 67 | return result; |
| 62 | 68 | }; |
| 63 | 69 | |
| 64 | export function listNotes( | |
| 70 | /** The clock the actions read: now, unless a test says otherwise. */ | |
| 71 | const stamp = (at?: Date): string => (at ?? new Date()).toISOString(); | |
| 72 | ||
| 73 | export function listLeads( | |
| 65 | 74 | db: Database, |
| 66 | 75 | who: Who, |
| 67 | 76 | input: { limit?: number } = {}, |
| 68 | ): Result<Note[]> { | |
| 77 | ): Result<DeskLead[]> { | |
| 78 | // Leads are a team's desk, not anyone's own: anything but "yes" is a no. | |
| 79 | if (permit(who, "lead", "list") !== "yes") | |
| 80 | return refuse(who, "Sign in to open the desk.", "You may not see the desk."); | |
| 69 | 81 | const limit = Math.min( |
| 70 | Math.max(Math.trunc(input.limit ?? 100) || 100, 1), | |
| 82 | Math.max(Math.trunc(input.limit ?? 200) || 200, 1), | |
| 71 | 83 | 500, |
| 72 | 84 | ); |
| 73 | // "yes" is every note. When the table gives `list` to a role a row holds | |
| 74 | // (`author`), the answer names the columns instead, and the list is the | |
| 75 | // notes that name whoever asks. The names are the contract's, checked when | |
| 76 | // it was read; the value is bound. | |
| 77 | const may = permit(who, "note", "list"); | |
| 78 | if (may === "no") | |
| 79 | return refuse(who, "Sign in to see notes.", "You may not see these notes."); | |
| 80 | if (may === "yes") | |
| 81 | return ok( | |
| 82 | db | |
| 83 | .query<Note, [number]>("SELECT * FROM note ORDER BY id DESC LIMIT ?1") | |
| 84 | .all(limit), | |
| 85 | ); | |
| 86 | const mine = may.where.map((column) => `${column} = ?2`).join(" OR "); | |
| 87 | return ok( | |
| 88 | db | |
| 89 | .query< | |
| 90 | Note, | |
| 91 | [number, string] | |
| 92 | >(`SELECT * FROM note WHERE ${mine} ORDER BY id DESC LIMIT ?1`) | |
| 93 | .all(limit, who.role === "anon" ? "" : who.id), | |
| 94 | ); | |
| 95 | } | |
| 96 | ||
| 97 | export const addNote = ( | |
| 98 | db: Database, | |
| 99 | who: Who, | |
| 100 | input: { body: string }, | |
| 101 | ): Result<Note> => | |
| 102 | audited(db, who, "note", "create", undefined, add(db, who, input)); | |
| 103 | ||
| 104 | function add(db: Database, who: Who, input: { body: string }): Result<Note> { | |
| 105 | // The table decides; the type only learns it here: whoever may create is | |
| 106 | // signed in, and carries a name to write beside the note. | |
| 107 | if (who.role === "anon" || permit(who, "note", "create") !== "yes") | |
| 108 | return refuse(who, "Sign in to add a note.", "You may not add a note."); | |
| 109 | const body = input.body.trim(); | |
| 110 | if (body.length === 0 || body.length > BODY_MAX) | |
| 111 | return fail("invalid", `A note is 1 to ${BODY_MAX} characters.`); | |
| 112 | const note = db | |
| 113 | .query< | |
| 114 | Note, | |
| 115 | [string, string, string] | |
| 116 | >("INSERT INTO note (body, author_id, author_name) VALUES (?1, ?2, ?3) RETURNING *") | |
| 117 | .get(body, who.id, who.name)!; | |
| 118 | emit("note.added", note); | |
| 119 | return ok(note); | |
| 85 | return ok(desk(db, limit)); | |
| 120 | 86 | } |
| 121 | 87 | |
| 122 | 88 | /** |
| 123 | * One note, for `who` to do `verb` to. The door is asked before the row is | |
| 89 | * One lead, for `who` to do `verb` to. The door is asked before the row is | |
| 124 | 90 | * looked for, so whoever may not is told that and never learns whether the |
| 125 | * row exists; whoever may, and asked for nothing, hears `not_found`. | |
| 91 | * lead exists; whoever may, and asked for nothing, hears `not_found`. | |
| 126 | 92 | */ |
| 127 | function noteFor( | |
| 93 | function leadFor( | |
| 128 | 94 | db: Database, |
| 129 | 95 | who: Who, |
| 130 | 96 | verb: "read" | "update" | "delete", |
| 131 | 97 | id: number, |
| 132 | 98 | said: { signIn: string; no: string }, |
| 133 | ): Result<Note> { | |
| 134 | const note = Number.isInteger(id) | |
| 135 | ? db.query<Note, [number]>("SELECT * FROM note WHERE id = ?1").get(id) | |
| 136 | : null; | |
| 137 | // With no row to show, the door is asked about a row of their own: whoever | |
| 138 | // could not pass even then is refused, and learns nothing about what | |
| 139 | // exists; whoever could is told there is no such note. | |
| 140 | const row: Readonly<Record<string, unknown>> = | |
| 141 | note === null ? { author_id: who.role === "anon" ? null : who.id } : { ...note }; | |
| 142 | if (permit(who, "note", verb, row) !== "yes") | |
| 99 | ): Result<LeadDetail> { | |
| 100 | const found = Number.isInteger(id) ? detail(db, id) : null; | |
| 101 | if (permit(who, "lead", verb, found === null ? {} : { ...found }) !== "yes") | |
| 143 | 102 | return refuse(who, said.signIn, said.no); |
| 144 | if (note !== null) return ok(note); | |
| 103 | if (found !== null) return ok(found); | |
| 145 | 104 | if (!Number.isInteger(id)) |
| 146 | return fail("invalid", "A note id is a whole number."); | |
| 147 | return fail("not_found", "No such note."); | |
| 105 | return fail("invalid", "A lead id is a whole number."); | |
| 106 | return fail("not_found", "No such lead."); | |
| 148 | 107 | } |
| 149 | 108 | |
| 150 | export function getNote( | |
| 109 | export const getLead = ( | |
| 151 | 110 | db: Database, |
| 152 | 111 | who: Who, |
| 153 | 112 | input: { id: number }, |
| 154 | ): Result<Note> { | |
| 155 | return noteFor(db, who, "read", input.id, { | |
| 156 | signIn: "Sign in to read this note.", | |
| 157 | no: "You may not read this note.", | |
| 113 | ): Result<LeadDetail> => | |
| 114 | leadFor(db, who, "read", input.id, { | |
| 115 | signIn: "Sign in to open this lead.", | |
| 116 | no: "You may not open this lead.", | |
| 117 | }); | |
| 118 | ||
| 119 | const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; | |
| 120 | const PHONE = /^\+?[\d\s().-]{7,20}$/; | |
| 121 | ||
| 122 | /** A source as people say it — "Open house", "website form" — or undefined. */ | |
| 123 | export function sourceOf(value: unknown): Source | undefined { | |
| 124 | const key = String(value ?? "") | |
| 125 | .trim() | |
| 126 | .toLowerCase() | |
| 127 | .replace(/[\s-]+/g, "_") | |
| 128 | .replace(/_form$/, ""); | |
| 129 | return (SOURCES as readonly string[]).includes(key) | |
| 130 | ? (key as Source) | |
| 131 | : undefined; | |
| 132 | } | |
| 133 | ||
| 134 | /** Consent as a form or a script says it; anything unclear is no. */ | |
| 135 | const consentOf = (value: unknown): boolean => | |
| 136 | value === true || value === "true" || value === "on" || value === "yes"; | |
| 137 | ||
| 138 | /** | |
| 139 | * Control characters — ESC, BEL and the rest of C0 and C1 — have no place in | |
| 140 | * what a person wrote, and in a terminal they are commands: clear the | |
| 141 | * screen, hide text, write the clipboard. A tab is allowed everywhere, a | |
| 142 | * line break only where text has lines. | |
| 143 | */ | |
| 144 | const CONTROL = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/; | |
| 145 | const LINE_BREAK = /\n/; | |
| 146 | /** Lines as a browser's textarea sends them (\r\n) or a script does (\n), as \n. */ | |
| 147 | const lines = (s: string): string => s.replace(/\r\n?/g, "\n"); | |
| 148 | export const hasControl = (s: string, multiline: boolean): boolean => | |
| 149 | CONTROL.test(s) || (!multiline && LINE_BREAK.test(s)); | |
| 150 | ||
| 151 | /** What arrived, checked field by field: a lead to keep, or what is wrong with it. */ | |
| 152 | export function readNewLead(input: Record<string, unknown>): Result<NewLead> { | |
| 153 | const text = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); | |
| 154 | const name = text(input.name); | |
| 155 | const email = text(input.email).toLowerCase(); | |
| 156 | const phone = text(input.phone); | |
| 157 | const message = lines(text(input.message)); | |
| 158 | const source = sourceOf(input.source); | |
| 159 | if ( | |
| 160 | [name, email, phone].some((field) => hasControl(field, false)) || | |
| 161 | hasControl(message, true) | |
| 162 | ) | |
| 163 | return fail( | |
| 164 | "invalid", | |
| 165 | "A lead's details are plain text: no control characters, and line breaks only in what they asked.", | |
| 166 | ); | |
| 167 | if (name.length === 0 || name.length > 120) | |
| 168 | return fail("invalid", "A name is 1 to 120 characters."); | |
| 169 | if (email.length > 254 || !EMAIL.test(email)) | |
| 170 | return fail("invalid", "An email address looks like [email protected]."); | |
| 171 | if (phone !== "" && !PHONE.test(phone)) | |
| 172 | return fail("invalid", "A phone number is 7 to 20 digits."); | |
| 173 | if (source === undefined) | |
| 174 | return fail( | |
| 175 | "invalid", | |
| 176 | "The source is one of zillow, website, open_house or referral.", | |
| 177 | ); | |
| 178 | if (message.length === 0 || message.length > 2000) | |
| 179 | return fail("invalid", "What they asked is 1 to 2000 characters."); | |
| 180 | return ok({ | |
| 181 | name, | |
| 182 | email, | |
| 183 | phone, | |
| 184 | source, | |
| 185 | message, | |
| 186 | consent: consentOf(input.consent), | |
| 158 | 187 | }); |
| 159 | 188 | } |
| 160 | 189 | |
| 161 | export const updateNote = ( | |
| 190 | export const addLead = ( | |
| 162 | 191 | db: Database, |
| 163 | 192 | who: Who, |
| 164 | input: { id: number; body: string }, | |
| 165 | ): Result<Note> => | |
| 166 | audited(db, who, "note", "update", input.id, update(db, who, input)); | |
| 193 | input: Record<string, unknown>, | |
| 194 | at?: Date, | |
| 195 | ): Result<LeadDetail> => | |
| 196 | audited(db, who, "lead", "create", undefined, add(db, who, input, at)); | |
| 167 | 197 | |
| 168 | function update( | |
| 198 | function add( | |
| 169 | 199 | db: Database, |
| 170 | 200 | who: Who, |
| 171 | input: { id: number; body: string }, | |
| 172 | ): Result<Note> { | |
| 173 | const found = noteFor(db, who, "update", input.id, { | |
| 174 | signIn: "Sign in to edit a note.", | |
| 175 | no: "Only the author or an admin can edit a note.", | |
| 201 | input: Record<string, unknown>, | |
| 202 | at?: Date, | |
| 203 | ): Result<LeadDetail> { | |
| 204 | if (permit(who, "lead", "create") !== "yes") | |
| 205 | return refuse(who, "Sign in to add a lead.", "You may not add a lead."); | |
| 206 | const read = readNewLead(input); | |
| 207 | if (!read.ok) return read; | |
| 208 | const id = insertLead(db, read.value, stamp(at), agent); | |
| 209 | const added = detail(db, id)!; | |
| 210 | emit("lead.added", { id }); | |
| 211 | return ok(added); | |
| 212 | } | |
| 213 | ||
| 214 | /** | |
| 215 | * Approve and send what is ready for this lead — the first reply, or the | |
| 216 | * earliest touch that is due — as drafted, or as the agent edited it. | |
| 217 | * Nothing goes out that a person did not approve, and the agent's | |
| 218 | * signature goes on everything that does. | |
| 219 | */ | |
| 220 | export const sendReply = ( | |
| 221 | db: Database, | |
| 222 | who: Who, | |
| 223 | input: { id: number; body?: string | undefined }, | |
| 224 | at?: Date, | |
| 225 | ): Result<LeadDetail> => | |
| 226 | audited(db, who, "lead", "update", input.id, reply(db, who, input, at)); | |
| 227 | ||
| 228 | function reply( | |
| 229 | db: Database, | |
| 230 | who: Who, | |
| 231 | input: { id: number; body?: string | undefined }, | |
| 232 | at?: Date, | |
| 233 | ): Result<LeadDetail> { | |
| 234 | const found = leadFor(db, who, "update", input.id, { | |
| 235 | signIn: "Sign in to reply.", | |
| 236 | no: "You may not reply to this lead.", | |
| 176 | 237 | }); |
| 177 | 238 | if (!found.ok) return found; |
| 178 | const body = input.body.trim(); | |
| 179 | if (body.length === 0 || body.length > BODY_MAX) | |
| 180 | return fail("invalid", `A note is 1 to ${BODY_MAX} characters.`); | |
| 181 | const note = db | |
| 182 | .query< | |
| 183 | Note, | |
| 184 | [string, number] | |
| 185 | >("UPDATE note SET body = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?2 RETURNING *") | |
| 186 | .get(body, found.value.id)!; | |
| 187 | emit("note.changed", note); | |
| 188 | return ok(note); | |
| 239 | const ready = readyFor(db, found.value.id); | |
| 240 | if (ready === null) | |
| 241 | return fail("invalid", "Nothing is waiting to go to this lead right now."); | |
| 242 | const body = lines(input.body ?? ready.body).trim(); | |
| 243 | if (hasControl(body, true)) | |
| 244 | return fail("invalid", "A message is plain text: no control characters."); | |
| 245 | const max = MAX_BODY[ready.channel]; | |
| 246 | if (body.length === 0 || body.length > max) | |
| 247 | return fail( | |
| 248 | "invalid", | |
| 249 | `A${ready.channel === "text" ? " text" : "n email"} is 1 to ${max} characters.`, | |
| 250 | ); | |
| 251 | const by = who.role === "anon" ? "" : who.name; | |
| 252 | send(db, found.value, ready, body, by, stamp(at), agent); | |
| 253 | emit("lead.changed", { id: found.value.id }); | |
| 254 | return ok(detail(db, found.value.id)!); | |
| 189 | 255 | } |
| 190 | 256 | |
| 191 | export const deleteNote = ( | |
| 257 | /** Qualified or lost: the lead leaves the cadence. */ | |
| 258 | export const setState = ( | |
| 259 | db: Database, | |
| 260 | who: Who, | |
| 261 | input: { id: number; state: unknown }, | |
| 262 | at?: Date, | |
| 263 | ): Result<LeadDetail> => | |
| 264 | audited(db, who, "lead", "update", input.id, mark(db, who, input, at)); | |
| 265 | ||
| 266 | function mark( | |
| 267 | db: Database, | |
| 268 | who: Who, | |
| 269 | input: { id: number; state: unknown }, | |
| 270 | at?: Date, | |
| 271 | ): Result<LeadDetail> { | |
| 272 | const found = leadFor(db, who, "update", input.id, { | |
| 273 | signIn: "Sign in to update this lead.", | |
| 274 | no: "You may not update this lead.", | |
| 275 | }); | |
| 276 | if (!found.ok) return found; | |
| 277 | if (input.state !== "qualified" && input.state !== "lost") | |
| 278 | return fail("invalid", "A lead is marked qualified or lost."); | |
| 279 | close(db, found.value.id, input.state, stamp(at)); | |
| 280 | emit("lead.changed", { id: found.value.id }); | |
| 281 | return ok(detail(db, found.value.id)!); | |
| 282 | } | |
| 283 | ||
| 284 | /** Remove one lead and everything said to it — a test entry, a spammer. */ | |
| 285 | export const deleteLead = ( | |
| 192 | 286 | db: Database, |
| 193 | 287 | who: Who, |
| 194 | 288 | input: { id: number }, |
| 195 | 289 | ): Result<{ id: number }> => |
| 196 | audited(db, who, "note", "delete", input.id, remove(db, who, input)); | |
| 290 | audited(db, who, "lead", "delete", input.id, remove(db, who, input)); | |
| 197 | 291 | |
| 198 | 292 | function remove( |
| 199 | 293 | db: Database, |
| 200 | 294 | who: Who, |
| 201 | 295 | input: { id: number }, |
| 202 | 296 | ): Result<{ id: number }> { |
| 203 | const found = noteFor(db, who, "delete", input.id, { | |
| 204 | signIn: "Sign in to remove a note.", | |
| 205 | no: "Only the author or an admin can remove a note.", | |
| 297 | const found = leadFor(db, who, "delete", input.id, { | |
| 298 | signIn: "Sign in to remove a lead.", | |
| 299 | no: "Only an admin can remove a lead.", | |
| 206 | 300 | }); |
| 207 | 301 | if (!found.ok) return found; |
| 208 | db.query("DELETE FROM note WHERE id = ?1").run(found.value.id); | |
| 209 | emit("note.removed", { id: found.value.id }); | |
| 302 | removeLead(db, found.value.id); | |
| 303 | emit("lead.changed", { id: found.value.id }); | |
| 210 | 304 | return ok({ id: found.value.id }); |
| 211 | 305 | } |
| 212 | 306 | |
| 213 | /** Whether `who` may remove `note`: the table's answer, for the page and the terminal to draw from. */ | |
| 214 | export const canDelete = (who: Who, note: Note): boolean => | |
| 215 | permit(who, "note", "delete", { ...note }) === "yes"; | |
| 307 | /** | |
| 308 | * The day turns: every touch whose day has come is due, ready to approve. | |
| 309 | * The forge may call it daily (`POST /tick`); the server also runs it on | |
| 310 | * its own every hour, so a missed call costs nothing. Running it twice | |
| 311 | * changes nothing the second time. | |
| 312 | */ | |
| 313 | export function tick( | |
| 314 | db: Database, | |
| 315 | who: Who, | |
| 316 | at?: Date, | |
| 317 | ): Result<{ leads: number[] }> { | |
| 318 | const result: Result<{ leads: number[] }> = | |
| 319 | permit(who, "lead", "update") === "yes" | |
| 320 | ? ok({ leads: turn(db, at) }) | |
| 321 | : refuse(who, "Sign in to advance the cadence.", "You may not."); | |
| 322 | record(db, { | |
| 323 | who, | |
| 324 | resource: "lead", | |
| 325 | verb: "update", | |
| 326 | target: "tick", | |
| 327 | outcome: result.ok ? "ok" : result.error, | |
| 328 | }); | |
| 329 | return result; | |
| 330 | } | |
| 331 | ||
| 332 | /** The clock's own turn, asked of no one: time passing is not a person. */ | |
| 333 | export function turn(db: Database, at?: Date): number[] { | |
| 334 | const leads = advance(db, stamp(at)); | |
| 335 | for (const id of leads) emit("lead.changed", { id }); | |
| 336 | return leads; | |
| 337 | } | |
| 338 | ||
| 339 | /** Put the sample leads back as they were, timed from now: for a demonstration. */ | |
| 340 | export function resetSample( | |
| 341 | db: Database, | |
| 342 | who: Who, | |
| 343 | at?: Date, | |
| 344 | ): Result<{ leads: number }> { | |
| 345 | const result: Result<{ leads: number }> = | |
| 346 | permit(who, "lead", "delete") === "yes" | |
| 347 | ? ok({ | |
| 348 | leads: db.transaction(() => { | |
| 349 | clearLeads(db); | |
| 350 | return seed(db, at ?? new Date()); | |
| 351 | })(), | |
| 352 | }) | |
| 353 | : refuse( | |
| 354 | who, | |
| 355 | "Sign in to reset the sample leads.", | |
| 356 | "Only an admin can reset the sample leads.", | |
| 357 | ); | |
| 358 | record(db, { | |
| 359 | who, | |
| 360 | resource: "lead", | |
| 361 | verb: "delete", | |
| 362 | target: "sample", | |
| 363 | outcome: result.ok ? "ok" : result.error, | |
| 364 | }); | |
| 365 | if (result.ok) emit("lead.added", {}); | |
| 366 | return result; | |
| 367 | } | |
| 216 | 368 | |
| 217 | 369 | /** |
| 218 | 370 | * The audit trail, newest first, for whoever the table lets read it (an |
src/audit.test.ts +36 −27
| @@ -7,7 +7,7 @@ import { afterAll, expect, spyOn, test } from "bun:test"; | ||
| 7 | 7 | import { mkdtempSync } from "node:fs"; |
| 8 | 8 | import { tmpdir } from "node:os"; |
| 9 | 9 | import { join } from "node:path"; |
| 10 | import { addNote } from "./actions.ts"; | |
| 10 | import { addLead } from "./actions.ts"; | |
| 11 | 11 | import type { AuditRow } from "./audit.ts"; |
| 12 | 12 | import { openDb } from "./db.ts"; |
| 13 | 13 | import { serve } from "./server.ts"; |
| @@ -18,6 +18,7 @@ const server = serve({ | ||
| 18 | 18 | port: 0, |
| 19 | 19 | dataDir: mkdtempSync(join(tmpdir(), "app-audit-")), |
| 20 | 20 | identityKey: KEY, |
| 21 | sample: false, | |
| 21 | 22 | }); |
| 22 | 23 | const base = `http://${server.hostname}:${server.port}`; |
| 23 | 24 | afterAll(() => server.stop(true)); |
| @@ -34,6 +35,12 @@ const as = ( | ||
| 34 | 35 | }; |
| 35 | 36 | }; |
| 36 | 37 | const alice = as("u1", "alice"); |
| 38 | const NEW = { | |
| 39 | name: "Kept Lead", | |
| 40 | email: "[email protected]", | |
| 41 | source: "website", | |
| 42 | message: "Hello there", | |
| 43 | }; | |
| 37 | 44 | const bob = as("u2", "bob"); |
| 38 | 45 | const root = as("u0", "root", "admin"); |
| 39 | 46 | const call = ( |
| @@ -50,27 +57,29 @@ const trail = async (): Promise<AuditRow[]> => | ||
| 50 | 57 | |
| 51 | 58 | test("an allowed change and a refused one each leave a row", async () => { |
| 52 | 59 | const made = await call( |
| 53 | "/api/notes", | |
| 54 | { method: "POST", body: JSON.stringify({ body: "kept" }) }, | |
| 60 | "/leads", | |
| 61 | { method: "POST", body: JSON.stringify(NEW) }, | |
| 55 | 62 | alice, |
| 56 | 63 | ); |
| 57 | 64 | expect(made.status).toBe(201); |
| 58 | const note = (await made.json()) as { id: number }; | |
| 65 | const lead = (await made.json()) as { id: number }; | |
| 59 | 66 | // Refused at the door: a stranger may create nothing. |
| 60 | 67 | expect( |
| 61 | ( | |
| 62 | await call("/api/notes", { | |
| 63 | method: "POST", | |
| 64 | body: JSON.stringify({ body: "x" }), | |
| 65 | }) | |
| 66 | ).status, | |
| 68 | (await call("/leads", { method: "POST", body: JSON.stringify(NEW) })) | |
| 69 | .status, | |
| 67 | 70 | ).toBe(401); |
| 68 | // Refused by the action: bob could delete a note of his own, not alice's. | |
| 71 | // Let through, and turned back by the action: a lead is qualified or lost, not "maybe". | |
| 69 | 72 | expect( |
| 70 | (await call(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status, | |
| 71 | ).toBe(403); | |
| 73 | ( | |
| 74 | await call( | |
| 75 | `/leads/${lead.id}/state`, | |
| 76 | { method: "POST", body: JSON.stringify({ state: "maybe" }) }, | |
| 77 | bob, | |
| 78 | ) | |
| 79 | ).status, | |
| 80 | ).toBe(422); | |
| 72 | 81 | // Refused as cross-site, before the table is asked. |
| 73 | const forged = await fetch(`${base}/api/notes/${note.id}`, { | |
| 82 | const forged = await fetch(`${base}/leads/${lead.id}`, { | |
| 74 | 83 | method: "DELETE", |
| 75 | 84 | headers: { ...alice, "sec-fetch-site": "cross-site" }, |
| 76 | 85 | }); |
| @@ -93,16 +102,16 @@ test("an allowed change and a refused one each leave a row", async () => { | ||
| 93 | 102 | { |
| 94 | 103 | who_name: "alice", |
| 95 | 104 | role: "user", |
| 96 | resource: "note", | |
| 105 | resource: "lead", | |
| 97 | 106 | verb: "create", |
| 98 | target: String(note.id), | |
| 107 | target: String(lead.id), | |
| 99 | 108 | allowed: 1, |
| 100 | 109 | outcome: "ok", |
| 101 | 110 | }, |
| 102 | 111 | { |
| 103 | 112 | who_name: null, |
| 104 | 113 | role: "anon", |
| 105 | resource: "note", | |
| 114 | resource: "lead", | |
| 106 | 115 | verb: "create", |
| 107 | 116 | target: null, |
| 108 | 117 | allowed: 0, |
| @@ -111,16 +120,16 @@ test("an allowed change and a refused one each leave a row", async () => { | ||
| 111 | 120 | { |
| 112 | 121 | who_name: "bob", |
| 113 | 122 | role: "user", |
| 114 | resource: "note", | |
| 115 | verb: "delete", | |
| 116 | target: String(note.id), | |
| 117 | allowed: 0, | |
| 118 | outcome: "forbidden", | |
| 123 | resource: "lead", | |
| 124 | verb: "update", | |
| 125 | target: String(lead.id), | |
| 126 | allowed: 1, | |
| 127 | outcome: "invalid", | |
| 119 | 128 | }, |
| 120 | 129 | { |
| 121 | 130 | who_name: "alice", |
| 122 | 131 | role: "user", |
| 123 | resource: "note", | |
| 132 | resource: "lead", | |
| 124 | 133 | verb: "delete", |
| 125 | 134 | target: null, |
| 126 | 135 | allowed: 0, |
| @@ -133,7 +142,7 @@ test("an allowed change and a refused one each leave a row", async () => { | ||
| 133 | 142 | |
| 134 | 143 | test("reading is not an event: a GET leaves no row", async () => { |
| 135 | 144 | const before = (await trail()).length; |
| 136 | await call("/api/notes"); | |
| 145 | await call("/leads", {}, alice); | |
| 137 | 146 | await call("/", {}, alice); |
| 138 | 147 | expect((await trail()).length).toBe(before); |
| 139 | 148 | }); |
| @@ -166,17 +175,17 @@ test("a trail that cannot be written is a log line, and the change still happens | ||
| 166 | 175 | db.exec("DROP TABLE audit"); |
| 167 | 176 | const said = spyOn(console, "error").mockImplementation(() => {}); |
| 168 | 177 | try { |
| 169 | const added = addNote( | |
| 178 | const added = addLead( | |
| 170 | 179 | db, |
| 171 | 180 | { role: "user", id: "u1", name: "alice" }, |
| 172 | { body: "still here" }, | |
| 181 | NEW, | |
| 173 | 182 | ); |
| 174 | 183 | expect(added.ok).toBe(true); |
| 175 | 184 | expect(said).toHaveBeenCalledTimes(1); |
| 176 | 185 | const line = JSON.parse(String(said.mock.calls[0]![0])); |
| 177 | 186 | expect(line.audit).toMatchObject({ |
| 178 | 187 | who_name: "alice", |
| 179 | resource: "note", | |
| 188 | resource: "lead", | |
| 180 | 189 | verb: "create", |
| 181 | 190 | allowed: 1, |
| 182 | 191 | outcome: "ok", |
src/clock.test.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { elapsed, tone } from "./clock.ts"; | |
| 3 | ||
| 4 | test("the clock reads like a person says it, and changes colour on time", () => { | |
| 5 | expect(elapsed(42_000)).toBe("0:42"); | |
| 6 | expect(elapsed(12 * 60_000 + 7_000)).toBe("12:07"); | |
| 7 | expect(elapsed(3 * 3_600_000 + 5 * 60_000)).toBe("3h 05m"); | |
| 8 | expect(elapsed(4 * 86_400_000 + 2 * 3_600_000)).toBe("4d 2h"); | |
| 9 | expect(elapsed(-5)).toBe("0:00"); | |
| 10 | expect(tone(4 * 60_000 + 59_000)).toBe("ok"); | |
| 11 | expect(tone(5 * 60_000)).toBe("warn"); | |
| 12 | expect(tone(59 * 60_000)).toBe("warn"); | |
| 13 | expect(tone(60 * 60_000)).toBe("late"); | |
| 14 | }); |
src/clock.ts added +29
| @@ -0,0 +1,29 @@ | ||
| 1 | /** | |
| 2 | * The response clock: how long a lead has waited for a first reply, said | |
| 3 | * the way a person reads it, and the colour that says whether that is | |
| 4 | * fine. Green under five minutes, amber under an hour, red after. | |
| 5 | * `static/clock.js` carries the same two rules to keep the clock ticking | |
| 6 | * in the browser; the page's first paint is this module's. | |
| 7 | */ | |
| 8 | ||
| 9 | export const GREEN_MS = 5 * 60_000; | |
| 10 | export const AMBER_MS = 60 * 60_000; | |
| 11 | ||
| 12 | export type Tone = "ok" | "warn" | "late"; | |
| 13 | ||
| 14 | export const tone = (ms: number): Tone => | |
| 15 | ms < GREEN_MS ? "ok" : ms < AMBER_MS ? "warn" : "late"; | |
| 16 | ||
| 17 | /** 0:42, 12:07, 3h 05m, 4d 2h. */ | |
| 18 | export function elapsed(ms: number): string { | |
| 19 | const s = Math.max(0, Math.floor(ms / 1000)); | |
| 20 | if (s < 3600) | |
| 21 | return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; | |
| 22 | if (s < 86_400) | |
| 23 | return `${Math.floor(s / 3600)}h ${String(Math.floor((s % 3600) / 60)).padStart(2, "0")}m`; | |
| 24 | return `${Math.floor(s / 86_400)}d ${Math.floor((s % 86_400) / 3600)}h`; | |
| 25 | } | |
| 26 | ||
| 27 | /** Milliseconds between two ISO stamps (or a stamp and now). */ | |
| 28 | export const between = (from: string, to: string | number = Date.now()): number => | |
| 29 | (typeof to === "number" ? to : Date.parse(to)) - Date.parse(from); |
src/contract.test.ts +37 −20
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Every door answers as the table says. The test acts as each identity the |
| 3 | * contract declares — on a note that names them and on one that names | |
| 3 | * contract declares — on a row that names them and on one that names | |
| 4 | 4 | * someone else — and calls the real actions. A rule written by hand in an |
| 5 | 5 | * action, or a cell changed without its door, fails here. |
| 6 | 6 | */ |
| @@ -9,13 +9,13 @@ import { mkdtempSync } from "node:fs"; | ||
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| 11 | 11 | import { |
| 12 | addNote, | |
| 13 | deleteNote, | |
| 12 | addLead, | |
| 13 | deleteLead, | |
| 14 | 14 | getAudit, |
| 15 | getNote, | |
| 15 | getLead, | |
| 16 | 16 | listAudit, |
| 17 | listNotes, | |
| 18 | updateNote, | |
| 17 | listLeads, | |
| 18 | setState, | |
| 19 | 19 | } from "./actions.ts"; |
| 20 | 20 | import { record } from "./audit.ts"; |
| 21 | 21 | import { actingAs, identities, table, type Verb } from "./can.ts"; |
| @@ -34,18 +34,35 @@ function whoIs(identity: string): Who { | ||
| 34 | 34 | return { role, id: actor.id, name: identity }; |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | const noteBy = (authorId: string): number => | |
| 38 | db | |
| 39 | .query< | |
| 40 | { id: number }, | |
| 41 | [string] | |
| 42 | >("INSERT INTO note (body, author_id, author_name) VALUES ('n', ?1, ?1) RETURNING id") | |
| 43 | .get(authorId)!.id; | |
| 37 | import { agent } from "./env.ts"; | |
| 38 | import { insertLead } from "./leads.ts"; | |
| 39 | ||
| 40 | // Leads name no one: they are the desk's, not a person's. `authorId` goes unused. | |
| 41 | const aLead = (_authorId: string): number => | |
| 42 | insertLead( | |
| 43 | db, | |
| 44 | { | |
| 45 | name: "Lead", | |
| 46 | email: "[email protected]", | |
| 47 | phone: "", | |
| 48 | source: "website", | |
| 49 | message: "Hello", | |
| 50 | consent: false, | |
| 51 | }, | |
| 52 | new Date().toISOString(), | |
| 53 | agent, | |
| 54 | ); | |
| 55 | const NEW = { | |
| 56 | name: "Lead", | |
| 57 | email: "[email protected]", | |
| 58 | source: "zillow", | |
| 59 | message: "Hello", | |
| 60 | }; | |
| 44 | 61 | |
| 45 | 62 | const auditRow = (): number => { |
| 46 | 63 | record(db, { |
| 47 | 64 | who: { role: "anon" }, |
| 48 | resource: "note", | |
| 65 | resource: "lead", | |
| 49 | 66 | verb: "create", |
| 50 | 67 | outcome: "signin_required", |
| 51 | 68 | }); |
| @@ -58,13 +75,13 @@ const doors: Record< | ||
| 58 | 75 | string, |
| 59 | 76 | Partial<Record<Verb, (who: Who, authorId: string) => boolean>> |
| 60 | 77 | > = { |
| 61 | note: { | |
| 62 | create: (who) => addNote(db, who, { body: "hello" }).ok, | |
| 63 | list: (who) => listNotes(db, who).ok, | |
| 64 | read: (who, authorId) => getNote(db, who, { id: noteBy(authorId) }).ok, | |
| 78 | lead: { | |
| 79 | create: (who) => addLead(db, who, NEW).ok, | |
| 80 | list: (who) => listLeads(db, who).ok, | |
| 81 | read: (who, authorId) => getLead(db, who, { id: aLead(authorId) }).ok, | |
| 65 | 82 | update: (who, authorId) => |
| 66 | updateNote(db, who, { id: noteBy(authorId), body: "changed" }).ok, | |
| 67 | delete: (who, authorId) => deleteNote(db, who, { id: noteBy(authorId) }).ok, | |
| 83 | setState(db, who, { id: aLead(authorId), state: "lost" }).ok, | |
| 84 | delete: (who, authorId) => deleteLead(db, who, { id: aLead(authorId) }).ok, | |
| 68 | 85 | }, |
| 69 | 86 | // The trail is written by the app itself, never through a door: there |
| 70 | 87 | // is no action that creates, changes or removes a row of it. |
src/db.ts +44
| @@ -38,6 +38,50 @@ export const migrations: string[] = [ | ||
| 38 | 38 | allowed INTEGER NOT NULL CHECK (allowed IN (0, 1)), |
| 39 | 39 | outcome TEXT NOT NULL |
| 40 | 40 | )`, |
| 41 | // The desk. A lead is one person who asked; `consent` is their prior | |
| 42 | // written consent to be texted — without it, we only email. | |
| 43 | `CREATE TABLE lead ( | |
| 44 | id INTEGER PRIMARY KEY, | |
| 45 | name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120), | |
| 46 | email TEXT NOT NULL CHECK (length(email) BETWEEN 3 AND 254), | |
| 47 | phone TEXT NOT NULL DEFAULT '', | |
| 48 | source TEXT NOT NULL CHECK (source IN ('zillow', 'website', 'open_house', 'referral')), | |
| 49 | message TEXT NOT NULL CHECK (length(message) BETWEEN 1 AND 2000), | |
| 50 | consent INTEGER NOT NULL CHECK (consent IN (0, 1)), | |
| 51 | state TEXT NOT NULL DEFAULT 'new' CHECK (state IN ('new', 'contacted', 'qualified', 'lost')), | |
| 52 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), | |
| 53 | replied_at TEXT, | |
| 54 | updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) | |
| 55 | )`, | |
| 56 | `CREATE INDEX lead_created ON lead (created_at)`, | |
| 57 | // Everything we say to a lead: day 0 is the first reply, then the | |
| 58 | // cadence's touches. Drafted by the app, sent only when a person approves. | |
| 59 | `CREATE TABLE message ( | |
| 60 | id INTEGER PRIMARY KEY, | |
| 61 | lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE, | |
| 62 | day INTEGER NOT NULL CHECK (day >= 0), | |
| 63 | channel TEXT NOT NULL CHECK (channel IN ('text', 'email')), | |
| 64 | body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 4000), | |
| 65 | signature TEXT NOT NULL, | |
| 66 | status TEXT NOT NULL CHECK (status IN ('draft', 'scheduled', 'due', 'sent', 'skipped')), | |
| 67 | due_at TEXT NOT NULL, | |
| 68 | sent_at TEXT, | |
| 69 | sent_by TEXT, | |
| 70 | UNIQUE (lead_id, day) | |
| 71 | )`, | |
| 72 | `CREATE INDEX message_due ON message (status, due_at)`, | |
| 73 | // The consent rule, held by the file itself as well as by the actions: | |
| 74 | // no text is ever written for a lead who has not agreed to be texted. | |
| 75 | `CREATE TRIGGER message_text_needs_consent BEFORE INSERT ON message | |
| 76 | WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0 | |
| 77 | BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`, | |
| 78 | `CREATE TRIGGER message_text_needs_consent_update BEFORE UPDATE OF channel ON message | |
| 79 | WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0 | |
| 80 | BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`, | |
| 81 | // What the app remembers about itself: whether the sample leads were laid out. | |
| 82 | `CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`, | |
| 83 | // The scaffold's notes gave way to leads. | |
| 84 | `DROP TABLE note`, | |
| 41 | 85 | ]; |
| 42 | 86 | |
| 43 | 87 | export function openDb(dir = dataDir): Database { |
src/design.test.ts +13 −3
| @@ -13,9 +13,9 @@ import { compile, flatten, token, tokens, tokensCss } from "./tokens.ts"; | ||
| 13 | 13 | test("the tokens compile: light on :root, dark for the system and for data-theme", () => { |
| 14 | 14 | expect(tokensCss).toContain(`--color-bg: ${token("color-bg")};`); |
| 15 | 15 | expect(tokensCss).toContain("--space-4: 1rem;"); |
| 16 | expect(tokensCss).toContain( | |
| 17 | '--font-sans: system-ui, -apple-system, "Segoe UI", sans-serif;', | |
| 18 | ); | |
| 16 | // A family with a space is quoted; a generic one is not. | |
| 17 | expect(tokensCss).toContain('--font-sans: "Avenir Next", Avenir,'); | |
| 18 | expect(tokensCss).toMatch(/--font-display: "Iowan Old Style".*, serif;/); | |
| 19 | 19 | expect(tokensCss).toContain("@media (prefers-color-scheme: dark)"); |
| 20 | 20 | expect(tokensCss).toContain(':root:not([data-theme="light"])'); |
| 21 | 21 | expect(tokensCss).toContain(':root[data-theme="dark"]'); |
| @@ -70,6 +70,16 @@ test("every pair a person reads is at least 4.5:1, in both themes", () => { | ||
| 70 | 70 | ["color-accent", "color-surface"], |
| 71 | 71 | ["color-accent-fg", "color-accent"], |
| 72 | 72 | ["color-toast-fg", "color-toast-bg"], |
| 73 | ["color-brass", "color-bg"], | |
| 74 | ["color-brass", "color-surface"], | |
| 75 | ["color-danger", "color-surface"], | |
| 76 | // The clock, in each of its colours, and the consent badges. | |
| 77 | ["color-ok", "color-ok-bg"], | |
| 78 | ["color-warn", "color-warn-bg"], | |
| 79 | ["color-late", "color-late-bg"], | |
| 80 | ["color-ok", "color-surface"], | |
| 81 | ["color-warn", "color-surface"], | |
| 82 | ["color-warn", "color-bg"], | |
| 73 | 83 | ] as const; |
| 74 | 84 | for (const mode of ["light", "dark"] as const) |
| 75 | 85 | for (const [fg, bg] of pairs) { |
src/drafts.test.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { | |
| 3 | addressIn, | |
| 4 | channelFor, | |
| 5 | draft, | |
| 6 | signature, | |
| 7 | topicOf, | |
| 8 | type Asker, | |
| 9 | } from "./drafts.ts"; | |
| 10 | import { agent } from "./env.ts"; | |
| 11 | ||
| 12 | const lead: Asker = { | |
| 13 | name: "Aisha Bello", | |
| 14 | phone: "(206) 555-0105", | |
| 15 | source: "zillow", | |
| 16 | message: "Pre-approved up to $550k. Looking for 3 bedrooms with a yard.", | |
| 17 | consent: false, | |
| 18 | }; | |
| 19 | ||
| 20 | test("the consent rule: text only with written consent and a number", () => { | |
| 21 | expect(channelFor({ consent: false, phone: "(206) 555-0105" })).toBe("email"); | |
| 22 | expect(channelFor({ consent: true, phone: "" })).toBe("email"); | |
| 23 | expect(channelFor({ consent: true, phone: "(206) 555-0105" })).toBe("text"); | |
| 24 | }); | |
| 25 | ||
| 26 | test("a draft answers what they asked, by name, in the agent's voice", () => { | |
| 27 | expect(topicOf(lead.message)).toBe("financing"); | |
| 28 | expect(topicOf("Are the sellers flexible on price?")).toBe("price"); | |
| 29 | expect(topicOf("What's my condo worth?")).toBe("selling"); | |
| 30 | expect(addressIn("Can I tour 92 Harbor View Dr this week?")).toBe("92 Harbor View Dr"); | |
| 31 | const email = draft(lead, 0, agent); | |
| 32 | expect(email).toStartWith("Hi Aisha,"); | |
| 33 | expect(email).toContain("Zillow"); | |
| 34 | expect(email).toContain("lenders"); | |
| 35 | const text = draft({ ...lead, consent: true }, 0, agent); | |
| 36 | expect(text).toContain(agent.brokerage); | |
| 37 | expect(text.length).toBeLessThan(480); | |
| 38 | for (const day of [1, 3, 7, 14, 30]) | |
| 39 | expect(draft(lead, day, agent)).toStartWith("Hi Aisha,"); | |
| 40 | }); | |
| 41 | ||
| 42 | test("every signature names the agent, the brokerage and the license", () => { | |
| 43 | for (const channel of ["text", "email"] as const) { | |
| 44 | const s = signature(channel, agent); | |
| 45 | for (const part of [agent.name, agent.brokerage, agent.license]) | |
| 46 | expect(s).toContain(part); | |
| 47 | } | |
| 48 | }); |
src/drafts.ts added +157
| @@ -0,0 +1,157 @@ | ||
| 1 | /** | |
| 2 | * What the app drafts for the agent to approve: the first reply and each | |
| 3 | * touch of the cadence, filled from what the lead asked and the agent's | |
| 4 | * profile. Plain functions, no sending — a person approves every word. | |
| 5 | * | |
| 6 | * The consent rule lives here first: a lead is texted only when they gave | |
| 7 | * prior written consent and a phone number; everyone else gets email. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Agent } from "./env.ts"; | |
| 11 | ||
| 12 | export type Channel = "text" | "email"; | |
| 13 | export type Source = "zillow" | "website" | "open_house" | "referral"; | |
| 14 | ||
| 15 | export const SOURCES: readonly Source[] = [ | |
| 16 | "zillow", | |
| 17 | "website", | |
| 18 | "open_house", | |
| 19 | "referral", | |
| 20 | ]; | |
| 21 | export const SOURCE_LABEL: Readonly<Record<Source, string>> = { | |
| 22 | zillow: "Zillow", | |
| 23 | website: "Website form", | |
| 24 | open_house: "Open house", | |
| 25 | referral: "Referral", | |
| 26 | }; | |
| 27 | ||
| 28 | /** The cadence: the days after the first reply that each get a touch. */ | |
| 29 | export const CADENCE: readonly number[] = [1, 3, 7, 14, 30]; | |
| 30 | ||
| 31 | /** How much a message may say, before the signature. */ | |
| 32 | export const MAX_BODY: Readonly<Record<Channel, number>> = { | |
| 33 | text: 480, | |
| 34 | email: 4000, | |
| 35 | }; | |
| 36 | ||
| 37 | export interface Asker { | |
| 38 | readonly name: string; | |
| 39 | readonly phone: string; | |
| 40 | readonly source: Source; | |
| 41 | readonly message: string; | |
| 42 | readonly consent: boolean; | |
| 43 | } | |
| 44 | ||
| 45 | /** Text only with consent and a number to text; otherwise, email. */ | |
| 46 | export const channelFor = (lead: Pick<Asker, "consent" | "phone">): Channel => | |
| 47 | lead.consent && lead.phone !== "" ? "text" : "email"; | |
| 48 | ||
| 49 | /** The line every outgoing message ends with: who sent it, under which license. */ | |
| 50 | export const signature = (channel: Channel, agent: Agent): string => | |
| 51 | channel === "text" | |
| 52 | ? `— ${agent.name}, ${agent.brokerage}, Lic. ${agent.license}. Reply STOP to opt out.` | |
| 53 | : `${agent.name}\n${agent.brokerage} · License ${agent.license}\n${agent.phone} · ${agent.email}`; | |
| 54 | ||
| 55 | type Topic = | |
| 56 | | "showing" | |
| 57 | | "selling" | |
| 58 | | "financing" | |
| 59 | | "relocating" | |
| 60 | | "first_time" | |
| 61 | | "price" | |
| 62 | | "general"; | |
| 63 | ||
| 64 | // What they asked about, by the words they used. The first that fits wins. | |
| 65 | const TOPICS: readonly [Topic, RegExp][] = [ | |
| 66 | ["selling", /\b(sell|selling|worth|home value|apprais\w*|list (my|our))\b/i], | |
| 67 | ["first_time", /\bfirst[- ]time\b/i], | |
| 68 | ["relocating", /\b(relocat|moving (from|to|here)|transfer)/i], | |
| 69 | ["price", /\b(flexible|negotia|offer|price drop|lower)/i], | |
| 70 | ["showing", /\b(see|tour|show|showing|visit|available|walk ?through)\b/i], | |
| 71 | ["financing", /\b(pre-?approv|mortgage|lender|loan|down payment|budget|\$\s?\d)/i], | |
| 72 | ]; | |
| 73 | export const topicOf = (message: string): Topic => | |
| 74 | TOPICS.find(([, words]) => words.test(message))?.[0] ?? "general"; | |
| 75 | ||
| 76 | const ADDRESS = | |
| 77 | /\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,3}(?:St|Street|Ln|Lane|Ave|Avenue|Rd|Road|Ct|Court|Dr|Drive|Way|Blvd|Pl|Place|Ter|Terrace|Cir|Circle)\b/; | |
| 78 | /** A street address in what they wrote, if there is one. */ | |
| 79 | export const addressIn = (message: string): string | undefined => | |
| 80 | ADDRESS.exec(message)?.[0]; | |
| 81 | ||
| 82 | export const firstName = (name: string): string => | |
| 83 | name.trim().split(/\s+/)[0] ?? name; | |
| 84 | ||
| 85 | const OPENER: Readonly<Record<Source, string>> = { | |
| 86 | zillow: "Thanks for reaching out on Zillow", | |
| 87 | website: "Thanks for your note through my website", | |
| 88 | open_house: "It was great to have you at the open house", | |
| 89 | referral: "Thank you for reaching out — referrals mean the world to me", | |
| 90 | }; | |
| 91 | ||
| 92 | function ask(topic: Topic, address: string | undefined, short: boolean): string { | |
| 93 | switch (topic) { | |
| 94 | case "showing": | |
| 95 | return short | |
| 96 | ? `I'd be glad to show you ${address ?? "the home"}. Would Saturday morning or Sunday afternoon work?` | |
| 97 | : `I'd be glad to show you ${address ?? "the home"} in person. I have openings this week and over the weekend — would Saturday morning or Sunday afternoon suit you better?`; | |
| 98 | case "selling": | |
| 99 | return short | |
| 100 | ? "I'd be happy to put together a free market analysis of your home. When could I stop by for 20 minutes?" | |
| 101 | : "I'd be happy to put together a free, no-pressure market analysis of your home, so you know exactly where it stands today. When would be a good time for a quick 20-minute walk-through?"; | |
| 102 | case "financing": | |
| 103 | return short | |
| 104 | ? "That's a great place to start. Which neighborhoods are you looking at? I'll send homes that fit." | |
| 105 | : "That's a great place to start. I'll pull together homes that fit your budget, and if it helps I can introduce you to a couple of lenders my clients trust. Which neighborhoods are you considering?"; | |
| 106 | case "relocating": | |
| 107 | return short | |
| 108 | ? "Moving is a lot — I'm glad to make it easier. Could we do a 15-minute call this week?" | |
| 109 | : "Moving to a new city is a lot, and I'm glad to make it easier. Could we set up a 15-minute call this week to talk through neighborhoods, schools and timing?"; | |
| 110 | case "first_time": | |
| 111 | return short | |
| 112 | ? "I work with first-time buyers all the time. Could we do a quick 15-minute call this week?" | |
| 113 | : "I work with first-time buyers all the time, and I'd love to walk you through how it all works, start to finish. Would a 15-minute call this week work for you?"; | |
| 114 | case "price": | |
| 115 | return short | |
| 116 | ? "Good question — let me find out and get back to you today." | |
| 117 | : "Good question — let me find out what I can and get back to you today. In the meantime, would you like to see it again, or a few similar homes nearby?"; | |
| 118 | case "general": | |
| 119 | return short | |
| 120 | ? "I'd love to help. When's a good time for a quick call?" | |
| 121 | : "I'd love to help. When's a good time for a quick call, so I can learn what you're looking for?"; | |
| 122 | } | |
| 123 | } | |
| 124 | ||
| 125 | const TOUCH: Readonly<Record<number, (first: string, topic: Topic) => string>> = { | |
| 126 | 1: (first) => | |
| 127 | `Hi ${first}, just following up on my note yesterday. Happy to work around your schedule — what times are good for you?`, | |
| 128 | 3: (first, topic) => | |
| 129 | topic === "selling" | |
| 130 | ? `Hi ${first}, homes near you have been moving quickly this week. Would you like to see what sold nearby, and for how much?` | |
| 131 | : `Hi ${first}, a few new homes came on the market this week that might be a fit. Would you like me to send them over?`, | |
| 132 | 7: (first) => | |
| 133 | `Hi ${first}, I know things get busy. If now isn't the right time, no problem at all — just tell me when to check back.`, | |
| 134 | 14: (first) => | |
| 135 | `Hi ${first}, still here whenever you're ready. Is there anything I can look into for you — a neighborhood, a price range, a question about the process?`, | |
| 136 | 30: (first) => | |
| 137 | `Hi ${first}, it's been about a month, so I wanted to check in once more. If your plans have changed, I'd still be glad to help whenever the time is right.`, | |
| 138 | }; | |
| 139 | ||
| 140 | /** | |
| 141 | * The words for one message to `lead`: day 0 is the first reply, any other | |
| 142 | * day a touch of the cadence. The signature is not in here; it is added, | |
| 143 | * unchangeable, when the message goes out. | |
| 144 | */ | |
| 145 | export function draft(lead: Asker, day: number, agent: Agent): string { | |
| 146 | const channel = channelFor(lead); | |
| 147 | const first = firstName(lead.name); | |
| 148 | const topic = topicOf(lead.message); | |
| 149 | if (day === 0) { | |
| 150 | const address = addressIn(lead.message); | |
| 151 | if (channel === "text") | |
| 152 | return `Hi ${first}, it's ${firstName(agent.name)} with ${agent.brokerage}. ${OPENER[lead.source]}! ${ask(topic, address, true)}`; | |
| 153 | return `Hi ${first},\n\n${OPENER[lead.source]}. ${ask(topic, address, false)}\n\nTalk soon,`; | |
| 154 | } | |
| 155 | const touch = (TOUCH[day] ?? TOUCH[30]!)(first, topic); | |
| 156 | return channel === "text" ? touch : `${touch}\n\nBest,`; | |
| 157 | } |
src/env.ts +17 −1
| @@ -6,7 +6,8 @@ | ||
| 6 | 6 | |
| 7 | 7 | import pkg from "../package.json"; |
| 8 | 8 | |
| 9 | export const title: string = pkg.name; | |
| 9 | /** What a person sees the app called. */ | |
| 10 | export const title = "Speed to Lead"; | |
| 10 | 11 | /** The app's own version (package.json): what `/healthz` and `/openapi.json` say. */ |
| 11 | 12 | export const version: string = pkg.version ?? "0.0.0"; |
| 12 | 13 | /** When this process started, for `/healthz`'s uptime. */ |
| @@ -30,3 +31,18 @@ export const publicOrigin: string = new URL( | ||
| 30 | 31 | export const forgeUrl: string | undefined = process.env.FORGE_URL; |
| 31 | 32 | /** The key the forge signs identities with (`who.ts`). Unset, everyone is anonymous. */ |
| 32 | 33 | export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? ""; |
| 34 | ||
| 35 | /** | |
| 36 | * The agent whose desk this is. Every message that goes out carries their | |
| 37 | * name, brokerage and license number, as state advertising rules require. | |
| 38 | * Set them in the forge (Settings → App → Environment); the defaults are | |
| 39 | * the prototype's sample agent. | |
| 40 | */ | |
| 41 | export const agent = { | |
| 42 | name: process.env.AGENT_NAME || "Jordan Avery", | |
| 43 | brokerage: process.env.AGENT_BROKERAGE || "Harbor & Pine Realty", | |
| 44 | license: process.env.AGENT_LICENSE || "CA DRE 02145789", | |
| 45 | phone: process.env.AGENT_PHONE || "(555) 214-0187", | |
| 46 | email: process.env.AGENT_EMAIL || "[email protected]", | |
| 47 | } as const; | |
| 48 | export type Agent = typeof agent; |
src/http.ts +4 −4
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The floor every response stands on, and the few things a route needs to |
| 3 | * read a request safely. Nothing in here knows what a note is; who may | |
| 3 | * read a request safely. Nothing in here knows what a lead is; who may | |
| 4 | 4 | * come in at all is `security.ts`. |
| 5 | 5 | */ |
| 6 | 6 | |
| @@ -61,12 +61,12 @@ export const text = (body: string, status = 200): Response => | ||
| 61 | 61 | headers: { "content-type": "text/plain; charset=utf-8", ...SECURITY }, |
| 62 | 62 | }); |
| 63 | 63 | |
| 64 | /** Back to the page, with a word for it to show once (`readNotice`). */ | |
| 65 | export const back = (notice?: string): Response => | |
| 64 | /** Back to a page (the desk, unless said), with a word for it to show once (`readNotice`). */ | |
| 65 | export const back = (notice?: string, location = "/"): Response => | |
| 66 | 66 | new Response(null, { |
| 67 | 67 | status: 303, |
| 68 | 68 | headers: { |
| 69 | location: "/", | |
| 69 | location, | |
| 70 | 70 | ...SECURITY, |
| 71 | 71 | ...(notice === undefined |
| 72 | 72 | ? {} |
src/leads.ts added +258
| @@ -0,0 +1,258 @@ | ||
| 1 | /** | |
| 2 | * The desk's data: leads and what we say to them, read and written in | |
| 3 | * SQLite. No one is asked anything here — whether a person may is | |
| 4 | * `actions.ts`'s question, asked before any of these is called — so the | |
| 5 | * sample data (`sample.ts`) and the actions lay out leads the same way. | |
| 6 | * | |
| 7 | * A lead's life: it arrives with its first reply drafted (day 0). When that | |
| 8 | * reply goes out, the cadence's touches are drafted and scheduled for days | |
| 9 | * 1, 3, 7, 14 and 30 after it; `advance` makes each one due when its day | |
| 10 | * comes, and each is sent only when a person approves it. Marking a lead | |
| 11 | * qualified or lost takes it out of the cadence. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import { | |
| 16 | CADENCE, | |
| 17 | channelFor, | |
| 18 | draft, | |
| 19 | signature, | |
| 20 | type Channel, | |
| 21 | type Source, | |
| 22 | } from "./drafts.ts"; | |
| 23 | import type { Agent } from "./env.ts"; | |
| 24 | ||
| 25 | export type State = "new" | "contacted" | "qualified" | "lost"; | |
| 26 | export const CLOSED: readonly State[] = ["qualified", "lost"]; | |
| 27 | ||
| 28 | export interface Lead { | |
| 29 | readonly id: number; | |
| 30 | readonly name: string; | |
| 31 | readonly email: string; | |
| 32 | readonly phone: string; | |
| 33 | readonly source: Source; | |
| 34 | readonly message: string; | |
| 35 | /** Prior written consent to be texted. */ | |
| 36 | readonly consent: boolean; | |
| 37 | readonly state: State; | |
| 38 | readonly created_at: string; | |
| 39 | /** When the first reply went out; null while they wait. */ | |
| 40 | readonly replied_at: string | null; | |
| 41 | readonly updated_at: string; | |
| 42 | } | |
| 43 | ||
| 44 | export interface Message { | |
| 45 | readonly id: number; | |
| 46 | readonly lead_id: number; | |
| 47 | /** 0 is the first reply; any other is the cadence's day. */ | |
| 48 | readonly day: number; | |
| 49 | readonly channel: Channel; | |
| 50 | readonly body: string; | |
| 51 | readonly signature: string; | |
| 52 | readonly status: "draft" | "scheduled" | "due" | "sent" | "skipped"; | |
| 53 | readonly due_at: string; | |
| 54 | readonly sent_at: string | null; | |
| 55 | readonly sent_by: string | null; | |
| 56 | } | |
| 57 | ||
| 58 | export interface LeadDetail extends Lead { | |
| 59 | readonly messages: readonly Message[]; | |
| 60 | } | |
| 61 | ||
| 62 | /** A row of the desk: the lead, what is waiting on us, and when the next touch comes. */ | |
| 63 | export interface DeskLead extends Lead { | |
| 64 | /** The message ready to approve now — the first reply or a due touch — if any. */ | |
| 65 | readonly ready: { readonly id: number; readonly day: number } | null; | |
| 66 | /** When the next scheduled touch comes due, if one is. */ | |
| 67 | readonly next_at: string | null; | |
| 68 | } | |
| 69 | ||
| 70 | export interface NewLead { | |
| 71 | readonly name: string; | |
| 72 | readonly email: string; | |
| 73 | readonly phone: string; | |
| 74 | readonly source: Source; | |
| 75 | readonly message: string; | |
| 76 | readonly consent: boolean; | |
| 77 | } | |
| 78 | ||
| 79 | type LeadRecord = Omit<Lead, "consent"> & { consent: number }; | |
| 80 | const lead = (row: LeadRecord): Lead => ({ ...row, consent: row.consent === 1 }); | |
| 81 | ||
| 82 | const DAY_MS = 86_400_000; | |
| 83 | const later = (at: string, days: number): string => | |
| 84 | new Date(Date.parse(at) + days * DAY_MS).toISOString(); | |
| 85 | ||
| 86 | export const findLead = (db: Database, id: number): Lead | null => { | |
| 87 | const row = db | |
| 88 | .query<LeadRecord, [number]>("SELECT * FROM lead WHERE id = ?1") | |
| 89 | .get(id); | |
| 90 | return row === null ? null : lead(row); | |
| 91 | }; | |
| 92 | ||
| 93 | export const messagesOf = (db: Database, id: number): Message[] => | |
| 94 | db | |
| 95 | .query< | |
| 96 | Message, | |
| 97 | [number] | |
| 98 | >("SELECT * FROM message WHERE lead_id = ?1 ORDER BY day") | |
| 99 | .all(id); | |
| 100 | ||
| 101 | export function detail(db: Database, id: number): LeadDetail | null { | |
| 102 | const found = findLead(db, id); | |
| 103 | return found === null ? null : { ...found, messages: messagesOf(db, id) }; | |
| 104 | } | |
| 105 | ||
| 106 | /** The desk, newest inquiry first. */ | |
| 107 | export function desk(db: Database, limit: number): DeskLead[] { | |
| 108 | return db | |
| 109 | .query< | |
| 110 | LeadRecord & { | |
| 111 | ready_id: number | null; | |
| 112 | ready_day: number | null; | |
| 113 | next_at: string | null; | |
| 114 | }, | |
| 115 | [number] | |
| 116 | >( | |
| 117 | `SELECT lead.*, | |
| 118 | (SELECT id FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_id, | |
| 119 | (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day, | |
| 120 | (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at | |
| 121 | FROM lead ORDER BY created_at DESC, id DESC LIMIT ?1`, | |
| 122 | ) | |
| 123 | .all(limit) | |
| 124 | .map(({ ready_id, ready_day, next_at, ...row }) => ({ | |
| 125 | ...lead(row), | |
| 126 | ready: | |
| 127 | ready_id === null || ready_day === null | |
| 128 | ? null | |
| 129 | : { id: ready_id, day: ready_day }, | |
| 130 | next_at, | |
| 131 | })); | |
| 132 | } | |
| 133 | ||
| 134 | /** A lead arrives at `at`, with its first reply drafted. Returns its id. */ | |
| 135 | export function insertLead( | |
| 136 | db: Database, | |
| 137 | input: NewLead, | |
| 138 | at: string, | |
| 139 | agent: Agent, | |
| 140 | ): number { | |
| 141 | return db.transaction(() => { | |
| 142 | const { id } = db | |
| 143 | .query< | |
| 144 | { id: number }, | |
| 145 | [string, string, string, string, string, number, string] | |
| 146 | >( | |
| 147 | "INSERT INTO lead (name, email, phone, source, message, consent, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7) RETURNING id", | |
| 148 | ) | |
| 149 | .get( | |
| 150 | input.name, | |
| 151 | input.email, | |
| 152 | input.phone, | |
| 153 | input.source, | |
| 154 | input.message, | |
| 155 | input.consent ? 1 : 0, | |
| 156 | at, | |
| 157 | )!; | |
| 158 | const channel = channelFor(input); | |
| 159 | db.query( | |
| 160 | "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, 0, ?2, ?3, ?4, 'draft', ?5)", | |
| 161 | ).run(id, channel, draft(input, 0, agent), signature(channel, agent), at); | |
| 162 | return id; | |
| 163 | })(); | |
| 164 | } | |
| 165 | ||
| 166 | /** The message ready to approve now: the first reply, or the earliest due touch. */ | |
| 167 | export const readyFor = (db: Database, id: number): Message | null => | |
| 168 | db | |
| 169 | .query< | |
| 170 | Message, | |
| 171 | [number] | |
| 172 | >("SELECT * FROM message WHERE lead_id = ?1 AND status IN ('draft', 'due') ORDER BY day LIMIT 1") | |
| 173 | .get(id); | |
| 174 | ||
| 175 | /** | |
| 176 | * Send `message` with `body` (the draft, or the agent's edit of it), signed | |
| 177 | * as the agent is now. The first reply starts the cadence. | |
| 178 | */ | |
| 179 | export function send( | |
| 180 | db: Database, | |
| 181 | found: Lead, | |
| 182 | message: Message, | |
| 183 | body: string, | |
| 184 | by: string, | |
| 185 | at: string, | |
| 186 | agent: Agent, | |
| 187 | ): void { | |
| 188 | db.transaction(() => { | |
| 189 | db.query( | |
| 190 | "UPDATE message SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4 WHERE id = ?5", | |
| 191 | ).run(body, signature(message.channel, agent), at, by, message.id); | |
| 192 | if (message.day === 0) { | |
| 193 | db.query( | |
| 194 | "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2", | |
| 195 | ).run(at, found.id); | |
| 196 | const channel = channelFor(found); | |
| 197 | const open = !CLOSED.includes(found.state); | |
| 198 | for (const day of CADENCE) | |
| 199 | db.query( | |
| 200 | "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | |
| 201 | ).run( | |
| 202 | found.id, | |
| 203 | day, | |
| 204 | channel, | |
| 205 | draft(found, day, agent), | |
| 206 | signature(channel, agent), | |
| 207 | open ? "scheduled" : "skipped", | |
| 208 | later(at, day), | |
| 209 | ); | |
| 210 | } else | |
| 211 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run( | |
| 212 | at, | |
| 213 | found.id, | |
| 214 | ); | |
| 215 | })(); | |
| 216 | } | |
| 217 | ||
| 218 | /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */ | |
| 219 | export function close( | |
| 220 | db: Database, | |
| 221 | id: number, | |
| 222 | state: "qualified" | "lost", | |
| 223 | at: string, | |
| 224 | ): void { | |
| 225 | db.transaction(() => { | |
| 226 | db.query("UPDATE lead SET state = ?1, updated_at = ?2 WHERE id = ?3").run( | |
| 227 | state, | |
| 228 | at, | |
| 229 | id, | |
| 230 | ); | |
| 231 | db.query( | |
| 232 | "UPDATE message SET status = 'skipped' WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due')", | |
| 233 | ).run(id); | |
| 234 | })(); | |
| 235 | } | |
| 236 | ||
| 237 | /** Every scheduled touch whose day has come is due now. Returns the ids of the leads it touched. */ | |
| 238 | export function advance(db: Database, at: string): number[] { | |
| 239 | return db | |
| 240 | .query<{ lead_id: number }, [string]>( | |
| 241 | `UPDATE message SET status = 'due' | |
| 242 | WHERE status = 'scheduled' AND due_at <= ?1 | |
| 243 | AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted') | |
| 244 | RETURNING lead_id`, | |
| 245 | ) | |
| 246 | .all(at) | |
| 247 | .map((row) => row.lead_id) | |
| 248 | .filter((id, i, all) => all.indexOf(id) === i); | |
| 249 | } | |
| 250 | ||
| 251 | export const removeLead = (db: Database, id: number): void => { | |
| 252 | db.query("DELETE FROM lead WHERE id = ?1").run(id); | |
| 253 | }; | |
| 254 | ||
| 255 | /** Every lead, gone (their messages with them). */ | |
| 256 | export const clearLeads = (db: Database): void => { | |
| 257 | db.exec("DELETE FROM lead"); | |
| 258 | }; |
src/live.test.ts added +35
| @@ -0,0 +1,35 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { sendReply } from "./actions.ts"; | |
| 6 | import { openDb } from "./db.ts"; | |
| 7 | import { subscribe, watch, type LiveEvent } from "./live.ts"; | |
| 8 | import { seed } from "./sample.ts"; | |
| 9 | ||
| 10 | test("a write from another process on the same file reaches the bus", async () => { | |
| 11 | const dir = mkdtempSync(join(tmpdir(), "app-live-")); | |
| 12 | const server = openDb(dir); | |
| 13 | seed(server, new Date()); | |
| 14 | // The terminal: its own connection to the same file. | |
| 15 | const tty = openDb(dir); | |
| 16 | const heard: LiveEvent[] = []; | |
| 17 | const unsubscribe = subscribe((e) => heard.push(e)); | |
| 18 | const stop = watch(server, 20); | |
| 19 | try { | |
| 20 | await Bun.sleep(60); | |
| 21 | expect(heard).toEqual([]); | |
| 22 | const sent = sendReply(tty, { role: "user", id: "u1", name: "alice" }, { id: 12 }); | |
| 23 | expect(sent.ok).toBe(true); | |
| 24 | const before = heard.length; | |
| 25 | await Bun.sleep(80); | |
| 26 | // In a test the two connections share one bus, so the action's own | |
| 27 | // event ({ id }) arrives too; the watch's is the one that names no lead. | |
| 28 | const fromWatch = (e: LiveEvent) => | |
| 29 | e.type === "lead.changed" && Bun.deepEquals(e.data, {}); | |
| 30 | expect(heard.slice(before).filter(fromWatch)).toHaveLength(1); | |
| 31 | } finally { | |
| 32 | stop(); | |
| 33 | unsubscribe(); | |
| 34 | } | |
| 35 | }); |
src/live.ts +33 −2
| @@ -3,10 +3,14 @@ | ||
| 3 | 3 | * streams it to every open page as server-sent events, numbered, with the |
| 4 | 4 | * last hundred kept so a client that reconnects with `Last-Event-ID` (or |
| 5 | 5 | * `?since=`) hears what it missed. `static/live.js` turns the stream into |
| 6 | * DOM events. The bus is this process's: the terminal is another process, | |
| 7 | * and its writes show on the next load rather than live. | |
| 6 | * DOM events. The bus is this process's; the terminal is another process | |
| 7 | * on the same file, so `watch` notices its writes (SQLite's `data_version` | |
| 8 | * moves when another connection commits) and says so on the bus, and an | |
| 9 | * open page hears a send made over ssh within a second. | |
| 8 | 10 | */ |
| 9 | 11 | |
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | ||
| 10 | 14 | export interface LiveEvent { |
| 11 | 15 | readonly id: number; |
| 12 | 16 | readonly type: string; |
| @@ -79,3 +83,30 @@ export function events(request: Request): Response { | ||
| 79 | 83 | }, |
| 80 | 84 | }); |
| 81 | 85 | } |
| 86 | ||
| 87 | /** | |
| 88 | * Watch the database file for writes made by another process, and emit | |
| 89 | * `lead.changed` when one lands. `PRAGMA data_version` is SQLite's own | |
| 90 | * counter for exactly this: it moves when a commit from any other | |
| 91 | * connection lands, never for this connection's own (those emitted already). | |
| 92 | * One cheap read per interval. Returns the stop. | |
| 93 | */ | |
| 94 | export function watch(db: Database, everyMs = 1000): () => void { | |
| 95 | const version = (): number => | |
| 96 | db.query<{ data_version: number }, []>("PRAGMA data_version").get()! | |
| 97 | .data_version; | |
| 98 | let seen = version(); | |
| 99 | const timer = setInterval(() => { | |
| 100 | try { | |
| 101 | const now = version(); | |
| 102 | if (now === seen) return; | |
| 103 | seen = now; | |
| 104 | emit("lead.changed", {}); | |
| 105 | } catch { | |
| 106 | // A closed database is a stopped watch. | |
| 107 | clearInterval(timer); | |
| 108 | } | |
| 109 | }, everyMs); | |
| 110 | timer.unref(); | |
| 111 | return () => clearInterval(timer); | |
| 112 | } |
src/mcp.ts +65 −25
| @@ -7,7 +7,15 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import { addNote, deleteNote, listNotes, type Result } from "./actions.ts"; | |
| 10 | import { | |
| 11 | addLead, | |
| 12 | getLead, | |
| 13 | listLeads, | |
| 14 | sendReply, | |
| 15 | setState, | |
| 16 | type Result, | |
| 17 | } from "./actions.ts"; | |
| 18 | import { SOURCES } from "./drafts.ts"; | |
| 11 | 19 | import { title } from "./env.ts"; |
| 12 | 20 | import { fields } from "./http.ts"; |
| 13 | 21 | import type { Who } from "./who.ts"; |
| @@ -23,44 +31,76 @@ interface Tool { | ||
| 23 | 31 | ) => Result<unknown>; |
| 24 | 32 | } |
| 25 | 33 | |
| 34 | const ONE = { | |
| 35 | type: "object", | |
| 36 | properties: { id: { type: "integer" } }, | |
| 37 | required: ["id"], | |
| 38 | }; | |
| 39 | ||
| 26 | 40 | export const tools: readonly Tool[] = [ |
| 27 | 41 | { |
| 28 | name: "list_notes", | |
| 29 | description: "The notes, newest first.", | |
| 42 | name: "list_leads", | |
| 43 | description: | |
| 44 | "The desk: every lead, newest first, with what is ready to approve.", | |
| 45 | inputSchema: { | |
| 46 | type: "object", | |
| 47 | properties: { limit: { type: "integer", minimum: 1, maximum: 500 } }, | |
| 48 | }, | |
| 49 | run: (db, who, args) => | |
| 50 | listLeads(db, who, { limit: Number(args.limit ?? 200) }), | |
| 51 | }, | |
| 52 | { | |
| 53 | name: "get_lead", | |
| 54 | description: "One lead with every message: sent, drafted and upcoming.", | |
| 55 | inputSchema: ONE, | |
| 56 | run: (db, who, args) => getLead(db, who, { id: Number(args.id) }), | |
| 57 | }, | |
| 58 | { | |
| 59 | name: "add_lead", | |
| 60 | description: | |
| 61 | "A new lead arrives, with its first reply drafted. consent is prior written consent to be texted.", | |
| 30 | 62 | inputSchema: { |
| 31 | 63 | type: "object", |
| 32 | 64 | properties: { |
| 33 | limit: { | |
| 34 | type: "integer", | |
| 35 | minimum: 1, | |
| 36 | maximum: 500, | |
| 37 | description: "At most this many (100).", | |
| 38 | }, | |
| 65 | name: { type: "string" }, | |
| 66 | email: { type: "string" }, | |
| 67 | phone: { type: "string" }, | |
| 68 | source: { enum: SOURCES }, | |
| 69 | message: { type: "string" }, | |
| 70 | consent: { type: "boolean" }, | |
| 39 | 71 | }, |
| 72 | required: ["name", "email", "source", "message"], | |
| 40 | 73 | }, |
| 41 | run: (db, who, args) => | |
| 42 | listNotes(db, who, { limit: Number(args.limit ?? 100) }), | |
| 74 | run: (db, who, args) => addLead(db, who, args), | |
| 43 | 75 | }, |
| 44 | 76 | { |
| 45 | name: "add_note", | |
| 77 | name: "send_reply", | |
| 46 | 78 | description: |
| 47 | "Add a note as the signed-in person. Anonymous callers cannot.", | |
| 79 | "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. Only call this when the person has approved the words.", | |
| 48 | 80 | inputSchema: { |
| 49 | 81 | type: "object", |
| 50 | properties: { body: { type: "string", maxLength: 500 } }, | |
| 51 | required: ["body"], | |
| 52 | }, | |
| 53 | run: (db, who, args) => addNote(db, who, { body: String(args.body ?? "") }), | |
| 54 | }, | |
| 55 | { | |
| 56 | name: "delete_note", | |
| 57 | description: "Remove a note by id. Only its author or an admin can.", | |
| 58 | inputSchema: { | |
| 59 | type: "object", | |
| 60 | properties: { id: { type: "integer" } }, | |
| 82 | properties: { id: { type: "integer" }, body: { type: "string" } }, | |
| 61 | 83 | required: ["id"], |
| 62 | 84 | }, |
| 63 | run: (db, who, args) => deleteNote(db, who, { id: Number(args.id) }), | |
| 85 | run: (db, who, args) => | |
| 86 | sendReply(db, who, { | |
| 87 | id: Number(args.id), | |
| 88 | body: typeof args.body === "string" ? args.body : undefined, | |
| 89 | }), | |
| 90 | }, | |
| 91 | { | |
| 92 | name: "mark_lead", | |
| 93 | description: "Mark a lead qualified or lost; it leaves the follow-up plan.", | |
| 94 | inputSchema: { | |
| 95 | type: "object", | |
| 96 | properties: { | |
| 97 | id: { type: "integer" }, | |
| 98 | state: { enum: ["qualified", "lost"] }, | |
| 99 | }, | |
| 100 | required: ["id", "state"], | |
| 101 | }, | |
| 102 | run: (db, who, args) => | |
| 103 | setState(db, who, { id: Number(args.id), state: args.state }), | |
| 64 | 104 | }, |
| 65 | 105 | ]; |
| 66 | 106 |
src/openapi.test.ts +5
| @@ -10,6 +10,7 @@ import { join } from "node:path"; | ||
| 10 | 10 | import { emit, openapi } from "./openapi.ts"; |
| 11 | 11 | import { routes } from "./routes.ts"; |
| 12 | 12 | import { serve } from "./server.ts"; |
| 13 | import { sign } from "./who.ts"; | |
| 13 | 14 | |
| 14 | 15 | const committed = readFileSync( |
| 15 | 16 | new URL("../contract/openapi.json", import.meta.url), |
| @@ -65,10 +66,14 @@ test("GET /openapi.json serves the committed file", async () => { | ||
| 65 | 66 | port: 0, |
| 66 | 67 | dataDir: mkdtempSync(join(tmpdir(), "app-openapi-")), |
| 67 | 68 | identityKey: "k", |
| 69 | sample: false, | |
| 68 | 70 | }); |
| 69 | 71 | afterAll(() => server.stop(true)); |
| 72 | // The table opens no door to a stranger, so the description is for the signed-in. | |
| 73 | const identity = `u1|alice|user|${Date.now() + 60_000}`; | |
| 70 | 74 | const response = await fetch( |
| 71 | 75 | `http://${server.hostname}:${server.port}/openapi.json`, |
| 76 | { headers: { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k") } }, | |
| 72 | 77 | ); |
| 73 | 78 | expect(response.status).toBe(200); |
| 74 | 79 | expect(response.headers.get("content-type")).toContain("application/json"); |
src/openapi.ts +12 −2
| @@ -12,12 +12,22 @@ | ||
| 12 | 12 | |
| 13 | 13 | import { contract } from "./contract.ts"; |
| 14 | 14 | import { description, title, version } from "./env.ts"; |
| 15 | import { AUDIT_ROW, ERROR, NOTE, routes, type Schema } from "./routes.ts"; | |
| 15 | import { | |
| 16 | AUDIT_ROW, | |
| 17 | DESK_LEAD, | |
| 18 | ERROR, | |
| 19 | LEAD, | |
| 20 | MESSAGE, | |
| 21 | routes, | |
| 22 | type Schema, | |
| 23 | } from "./routes.ts"; | |
| 16 | 24 | import { doorOf } from "./security.ts"; |
| 17 | 25 | |
| 18 | 26 | // The shapes said once, under components, and referred to wherever they appear. |
| 19 | 27 | const NAMED = new Map<Schema, string>([ |
| 20 | [NOTE, "Note"], | |
| 28 | [LEAD, "Lead"], | |
| 29 | [DESK_LEAD, "DeskLead"], | |
| 30 | [MESSAGE, "Message"], | |
| 21 | 31 | [AUDIT_ROW, "AuditRow"], |
| 22 | 32 | [ERROR, "Error"], |
| 23 | 33 | ]); |
src/page.ts deleted −123
| @@ -1,123 +0,0 @@ | ||
| 1 | /** | |
| 2 | * The page, rendered on the server: the first paint is complete HTML, and | |
| 3 | * `static/live.js` keeps the notes fresh afterwards. When a second page | |
| 4 | * arrives, move `layout` to `src/pages/layout.ts` and give each page a file. | |
| 5 | */ | |
| 6 | ||
| 7 | import { canDelete, type Note } from "./actions.ts"; | |
| 8 | import { | |
| 9 | commit, | |
| 10 | description, | |
| 11 | env, | |
| 12 | publicOrigin, | |
| 13 | ssh, | |
| 14 | title, | |
| 15 | where, | |
| 16 | } from "./env.ts"; | |
| 17 | import { asset, escape } from "./http.ts"; | |
| 18 | import { token, tokensHref } from "./tokens.ts"; | |
| 19 | import type { Who } from "./who.ts"; | |
| 20 | ||
| 21 | /** | |
| 22 | * The frame every page shares: the tokens and the look, who you are, and | |
| 23 | * what a link to the page says when it is shared — a title, a sentence | |
| 24 | * and the address, for Open Graph and the card a chat app unfurls. | |
| 25 | */ | |
| 26 | export function layout(body: string, who: Who, path = "/"): string { | |
| 27 | const door = | |
| 28 | who.role === "anon" | |
| 29 | ? `<a class="button button-quiet" href="/__forge/signin?to=/">Sign in</a>` | |
| 30 | : `<span class="you"><b>${escape(who.name)}</b>${who.role === "admin" ? " · admin" : ""}</span> | |
| 31 | <a class="button button-quiet" href="/__forge/signout">Sign out</a>`; | |
| 32 | return `<!doctype html> | |
| 33 | <html lang="en"> | |
| 34 | <meta charset="utf-8"> | |
| 35 | <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 36 | <meta name="color-scheme" content="light dark"> | |
| 37 | <meta name="theme-color" content="${token("color-bg")}" media="(prefers-color-scheme: light)"> | |
| 38 | <meta name="theme-color" content="${token("color-bg", "dark")}" media="(prefers-color-scheme: dark)"> | |
| 39 | <link rel="icon" href="data:,"> | |
| 40 | <title>${escape(title)}</title> | |
| 41 | <meta name="description" content="${escape(description)}"> | |
| 42 | <meta property="og:type" content="website"> | |
| 43 | <meta property="og:site_name" content="${escape(title)}"> | |
| 44 | <meta property="og:title" content="${escape(title)}"> | |
| 45 | <meta property="og:description" content="${escape(description)}"> | |
| 46 | <meta property="og:url" content="${escape(publicOrigin + path)}"> | |
| 47 | <meta name="twitter:card" content="summary"> | |
| 48 | <meta name="twitter:title" content="${escape(title)}"> | |
| 49 | <meta name="twitter:description" content="${escape(description)}"> | |
| 50 | <link rel="stylesheet" href="${tokensHref}"> | |
| 51 | <link rel="stylesheet" href="${asset("app.css")}"> | |
| 52 | <script type="module" src="${asset("live.js")}"></script> | |
| 53 | <body> | |
| 54 | <div class="page"> | |
| 55 | <header class="head"> | |
| 56 | <div> | |
| 57 | <h1>${escape(title)}</h1> | |
| 58 | <p class="muted">${escape(description)}</p> | |
| 59 | </div> | |
| 60 | <nav class="row"> | |
| 61 | <span class="pill" data-env="${escape(env)}">${escape(where)}</span>${commit ? `<span class="muted mono">${escape(commit)}</span>` : ""} | |
| 62 | ${door} | |
| 63 | </nav> | |
| 64 | </header> | |
| 65 | <main>${body}</main> | |
| 66 | <footer class="muted"> | |
| 67 | ${ssh === undefined ? "" : `<p>Terminal: <code>${escape(ssh)}</code></p>`} | |
| 68 | <p>Also at <a href="/api/notes">/api/notes</a> (<a href="/openapi.json">described</a>) and <code>POST /mcp</code>, with the same rules.</p> | |
| 69 | <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p> | |
| 70 | </footer> | |
| 71 | </div> | |
| 72 | </body> | |
| 73 | </html> | |
| 74 | `; | |
| 75 | } | |
| 76 | ||
| 77 | export function home(input: { | |
| 78 | who: Who; | |
| 79 | notes: readonly Note[]; | |
| 80 | notice?: string | undefined; | |
| 81 | }): string { | |
| 82 | const { who, notes, notice } = input; | |
| 83 | const composer = | |
| 84 | who.role === "anon" | |
| 85 | ? `<p class="muted">Reading as a guest. <a href="/__forge/signin?to=/">Sign in</a> to add a note.</p>` | |
| 86 | : `<form class="row" method="post" action="/notes"> | |
| 87 | <input class="input" name="body" placeholder="Write a note" aria-label="New note" required maxlength="500" autocomplete="off" autofocus> | |
| 88 | <button class="button">Add</button> | |
| 89 | </form>`; | |
| 90 | const list = | |
| 91 | notes.length === 0 | |
| 92 | ? `<p class="empty">No notes yet. Notes written here stay in ${escape(where)} data.</p>` | |
| 93 | : `<ul class="list">${notes.map((note) => item(note, who)).join("")}</ul>`; | |
| 94 | return layout( | |
| 95 | `<section class="card">${composer}</section> | |
| 96 | <section id="notes" data-live="note.added note.removed">${list}</section> | |
| 97 | ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}</p>`}`, | |
| 98 | who, | |
| 99 | ); | |
| 100 | } | |
| 101 | ||
| 102 | const item = (note: Note, who: Who): string => `<li class="note"> | |
| 103 | <div> | |
| 104 | <p>${escape(note.body)}</p> | |
| 105 | <small class="muted">${escape(note.author_name)} · <time datetime="${escape(note.created_at)}">${ago(note.created_at)}</time></small> | |
| 106 | </div> | |
| 107 | ${ | |
| 108 | canDelete(who, note) | |
| 109 | ? `<form method="post" action="/notes/${note.id}/delete"><button class="button button-quiet" aria-label="Remove this note">Remove</button></form>` | |
| 110 | : "" | |
| 111 | } | |
| 112 | </li>`; | |
| 113 | ||
| 114 | const ago = (iso: string): string => { | |
| 115 | const s = Math.max(0, (Date.now() - Date.parse(iso)) / 1000); | |
| 116 | if (s < 60) return "just now"; | |
| 117 | if (s < 3600) return `${Math.floor(s / 60)}m ago`; | |
| 118 | if (s < 86400) return `${Math.floor(s / 3600)}h ago`; | |
| 119 | return new Date(iso).toLocaleDateString("en", { | |
| 120 | month: "short", | |
| 121 | day: "numeric", | |
| 122 | }); | |
| 123 | }; |
src/pages/desk.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | /** | |
| 2 | * The desk: every lead, newest first, each with what they asked and the | |
| 3 | * clock since they asked. One tap opens the lead with the reply drafted. | |
| 4 | */ | |
| 5 | ||
| 6 | import { day, clock, consent, source, STATE_LABEL } from "./parts.ts"; | |
| 7 | import { layout } from "./layout.ts"; | |
| 8 | import { escape } from "../http.ts"; | |
| 9 | import type { DeskLead } from "../leads.ts"; | |
| 10 | import type { Who } from "../who.ts"; | |
| 11 | ||
| 12 | export function deskPage(input: { | |
| 13 | who: Who; | |
| 14 | leads: readonly DeskLead[] | undefined; | |
| 15 | mayAdd: boolean; | |
| 16 | mayReset: boolean; | |
| 17 | notice?: string | undefined; | |
| 18 | }): string { | |
| 19 | const { who, leads, notice } = input; | |
| 20 | if (leads === undefined) | |
| 21 | return layout({ | |
| 22 | who, | |
| 23 | path: "/", | |
| 24 | notice, | |
| 25 | body: `<section class="welcome"> | |
| 26 | <h1>Every new lead answered in under a minute.</h1> | |
| 27 | <p>Your desk of incoming leads, a reply drafted for each one, and a 30-day follow-up plan so no one is left waiting. You approve every message before it goes.</p> | |
| 28 | <p><a class="button" href="/__forge/signin?to=%2F">Sign in to open your desk</a></p> | |
| 29 | </section>`, | |
| 30 | }); | |
| 31 | const now = Date.now(); | |
| 32 | const waiting = leads.filter((l) => l.ready?.day === 0).length; | |
| 33 | const due = leads.filter((l) => l.ready !== null && l.ready.day > 0).length; | |
| 34 | const summary = `<p class="summary" aria-live="polite"><b>${waiting}</b> waiting for a first reply <span aria-hidden="true">·</span> <b>${due}</b> follow-up${due === 1 ? "" : "s"} due today</p>`; | |
| 35 | const list = | |
| 36 | leads.length === 0 | |
| 37 | ? `<p class="empty">No leads yet. New inquiries appear here the moment they arrive.</p>` | |
| 38 | : `<ul class="desk">${leads.map((lead) => row(lead, now)).join("")}</ul>`; | |
| 39 | return layout({ | |
| 40 | who, | |
| 41 | path: "/", | |
| 42 | notice, | |
| 43 | heading: "Desk", | |
| 44 | body: `<div id="desk" data-live="lead.added lead.changed"> | |
| 45 | <div class="desk-head"><h1>Leads</h1>${summary}</div> | |
| 46 | ${list} | |
| 47 | </div> | |
| 48 | ${input.mayAdd ? addForm : ""} | |
| 49 | ${ | |
| 50 | input.mayReset | |
| 51 | ? `<form class="reset" method="post" action="/sample/reset"><button class="button button-quiet">Restart the sample leads from now</button></form>` | |
| 52 | : "" | |
| 53 | }`, | |
| 54 | }); | |
| 55 | } | |
| 56 | ||
| 57 | function status(lead: DeskLead): string { | |
| 58 | if (lead.state === "qualified" || lead.state === "lost") | |
| 59 | return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`; | |
| 60 | if (lead.ready?.day === 0) | |
| 61 | return `<span class="status" data-ready>Reply drafted — approve and send</span>`; | |
| 62 | if (lead.ready !== null) | |
| 63 | return `<span class="status" data-ready>Day ${lead.ready.day} follow-up ready</span>`; | |
| 64 | if (lead.next_at !== null) | |
| 65 | return `<span class="status">Next follow-up ${escape(day(lead.next_at))}</span>`; | |
| 66 | return `<span class="status">Follow-ups done</span>`; | |
| 67 | } | |
| 68 | ||
| 69 | const row = (lead: DeskLead, now: number): string => `<li> | |
| 70 | <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}> | |
| 71 | <span class="lead-main"> | |
| 72 | <span class="lead-name">${escape(lead.name)}</span> | |
| 73 | <span class="tags">${source(lead)}${consent(lead)}</span> | |
| 74 | <span class="ask">${escape(lead.message)}</span> | |
| 75 | ${status(lead)} | |
| 76 | </span> | |
| 77 | ${clock(lead, now)} | |
| 78 | </a> | |
| 79 | </li>`; | |
| 80 | ||
| 81 | const addForm = `<details class="card add"> | |
| 82 | <summary>Log a lead by hand</summary> | |
| 83 | <form class="stack" method="post" action="/leads"> | |
| 84 | <label>Name <input class="input" name="name" required maxlength="120" autocomplete="off"></label> | |
| 85 | <label>Email <input class="input" name="email" type="email" required maxlength="254" autocomplete="off"></label> | |
| 86 | <label>Phone <input class="input" name="phone" type="tel" maxlength="20" autocomplete="off"></label> | |
| 87 | <label>Source | |
| 88 | <select class="input" name="source"> | |
| 89 | <option value="website">Website form</option> | |
| 90 | <option value="zillow">Zillow</option> | |
| 91 | <option value="open_house">Open house</option> | |
| 92 | <option value="referral">Referral</option> | |
| 93 | </select> | |
| 94 | </label> | |
| 95 | <label>What they asked <textarea class="input" name="message" required maxlength="2000" rows="3"></textarea></label> | |
| 96 | <label class="check"><input type="checkbox" name="consent" value="yes"> They gave written consent to be texted</label> | |
| 97 | <button class="button">Add to the desk</button> | |
| 98 | </form> | |
| 99 | </details>`; |
src/pages/layout.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** | |
| 2 | * The frame every page shares: the tokens and the look, the agent whose | |
| 3 | * desk it is, who is signed in, and what a link to the page says when it | |
| 4 | * is shared — a title, a sentence and the address, for Open Graph and the | |
| 5 | * card a chat app unfurls. | |
| 6 | */ | |
| 7 | ||
| 8 | import { agent, description, publicOrigin, title } from "../env.ts"; | |
| 9 | import { asset, escape } from "../http.ts"; | |
| 10 | import { token, tokensHref } from "../tokens.ts"; | |
| 11 | import type { Who } from "../who.ts"; | |
| 12 | ||
| 13 | export function layout(input: { | |
| 14 | body: string; | |
| 15 | who: Who; | |
| 16 | path: string; | |
| 17 | heading?: string; | |
| 18 | notice?: string | undefined; | |
| 19 | }): string { | |
| 20 | const { body, who, path, notice } = input; | |
| 21 | const name = input.heading === undefined ? title : `${input.heading} · ${title}`; | |
| 22 | const door = | |
| 23 | who.role === "anon" | |
| 24 | ? `<a class="button button-quiet" href="/__forge/signin?to=${escape(encodeURIComponent(path))}">Sign in</a>` | |
| 25 | : `<span class="you">${escape(who.name)}</span> | |
| 26 | <a class="button button-quiet" href="/__forge/signout">Sign out</a>`; | |
| 27 | return `<!doctype html> | |
| 28 | <html lang="en"> | |
| 29 | <meta charset="utf-8"> | |
| 30 | <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 31 | <meta name="color-scheme" content="light dark"> | |
| 32 | <meta name="theme-color" content="${token("color-bg")}" media="(prefers-color-scheme: light)"> | |
| 33 | <meta name="theme-color" content="${token("color-bg", "dark")}" media="(prefers-color-scheme: dark)"> | |
| 34 | <link rel="icon" href="data:,"> | |
| 35 | <title>${escape(name)}</title> | |
| 36 | <meta name="description" content="${escape(description)}"> | |
| 37 | <meta property="og:type" content="website"> | |
| 38 | <meta property="og:site_name" content="${escape(title)}"> | |
| 39 | <meta property="og:title" content="${escape(`${title} · ${agent.name}`)}"> | |
| 40 | <meta property="og:description" content="${escape(description)}"> | |
| 41 | <meta property="og:url" content="${escape(publicOrigin + path)}"> | |
| 42 | <meta name="twitter:card" content="summary"> | |
| 43 | <meta name="twitter:title" content="${escape(`${title} · ${agent.name}`)}"> | |
| 44 | <meta name="twitter:description" content="${escape(description)}"> | |
| 45 | <link rel="stylesheet" href="${tokensHref}"> | |
| 46 | <link rel="stylesheet" href="${asset("app.css")}"> | |
| 47 | <script type="module" src="${asset("live.js")}"></script> | |
| 48 | <script type="module" src="${asset("clock.js")}"></script> | |
| 49 | <body> | |
| 50 | <div class="page"> | |
| 51 | <header class="head"> | |
| 52 | <a class="brand" href="/"> | |
| 53 | <span class="agent">${escape(agent.name)}</span> | |
| 54 | <span class="brokerage">${escape(agent.brokerage)}</span> | |
| 55 | </a> | |
| 56 | <nav class="row">${door}</nav> | |
| 57 | </header> | |
| 58 | <main>${body}</main> | |
| 59 | <footer class="muted"> | |
| 60 | <p>${escape(agent.name)} · ${escape(agent.brokerage)} · License ${escape(agent.license)}</p> | |
| 61 | <p>${escape(title)} — every message is approved by a person before it goes. <a href="/__forge/report">Report a problem</a></p> | |
| 62 | </footer> | |
| 63 | </div> | |
| 64 | ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}</p>`} | |
| 65 | </body> | |
| 66 | </html> | |
| 67 | `; | |
| 68 | } |
src/pages/lead.ts added +148
| @@ -0,0 +1,148 @@ | ||
| 1 | /** | |
| 2 | * One lead: what they asked beside what we are about to say, approve and | |
| 3 | * send in one tap or edit in place first, everything said so far, and the | |
| 4 | * follow-ups to come. | |
| 5 | */ | |
| 6 | ||
| 7 | import { channelFor, MAX_BODY } from "../drafts.ts"; | |
| 8 | import { escape } from "../http.ts"; | |
| 9 | import type { LeadDetail, Message } from "../leads.ts"; | |
| 10 | import type { Who } from "../who.ts"; | |
| 11 | import { layout } from "./layout.ts"; | |
| 12 | import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts"; | |
| 13 | ||
| 14 | const CHANNEL = { text: "text", email: "email" } as const; | |
| 15 | ||
| 16 | const titleOf = (m: Message): string => | |
| 17 | m.day === 0 ? "First reply" : `Day ${m.day} follow-up`; | |
| 18 | ||
| 19 | /** A message's words, line breaks kept, and the signature under them. */ | |
| 20 | const words = (m: Pick<Message, "body" | "signature">): string => | |
| 21 | `<p class="body">${escape(m.body)}</p><p class="sig">${escape(m.signature)}</p>`; | |
| 22 | ||
| 23 | export function leadPage(input: { | |
| 24 | who: Who; | |
| 25 | lead: LeadDetail; | |
| 26 | mayUpdate: boolean; | |
| 27 | notice?: string | undefined; | |
| 28 | }): string { | |
| 29 | const { who, lead, mayUpdate, notice } = input; | |
| 30 | const ready = lead.messages.find( | |
| 31 | (m) => m.status === "draft" || m.status === "due", | |
| 32 | ); | |
| 33 | const sent = lead.messages.filter((m) => m.status === "sent"); | |
| 34 | const cadence = lead.messages.filter((m) => m.day > 0); | |
| 35 | const closed = lead.state === "qualified" || lead.state === "lost"; | |
| 36 | const path = `/leads/${lead.id}`; | |
| 37 | const contact = [ | |
| 38 | `<a href="mailto:${escape(lead.email)}">${escape(lead.email)}</a>`, | |
| 39 | ...(lead.phone === "" | |
| 40 | ? [] | |
| 41 | : [`<a href="tel:${escape(lead.phone.replace(/[^\d+]/g, ""))}">${escape(lead.phone)}</a>`]), | |
| 42 | ].join(" · "); | |
| 43 | ||
| 44 | const draft = | |
| 45 | ready === undefined | |
| 46 | ? `<div class="pane ours"><h2>Nothing to send right now</h2><p class="muted">${ | |
| 47 | closed | |
| 48 | ? `Marked ${STATE_LABEL[lead.state].toLowerCase()}: out of the follow-up plan.` | |
| 49 | : lead.messages.some((m) => m.status === "scheduled") | |
| 50 | ? "The next follow-up is drafted below and comes due on its day." | |
| 51 | : "Every follow-up has gone out." | |
| 52 | }</p></div>` | |
| 53 | : `<div class="pane ours ready"> | |
| 54 | <h2>${titleOf(ready)} <span class="muted">· by ${CHANNEL[ready.channel]}</span></h2> | |
| 55 | <div class="draft-view">${words(ready)}</div> | |
| 56 | ${ | |
| 57 | mayUpdate | |
| 58 | ? `<div class="actions"> | |
| 59 | <form method="post" action="${path}/reply"><button class="button">Approve and send</button></form> | |
Low: "Approve and send" posts no message id, so |
||
| 60 | <details class="edit"> | |
| 61 | <summary class="button button-quiet">Edit</summary> | |
| 62 | <form class="stack" method="post" action="${path}/reply"> | |
| 63 | <label class="sr" for="body">Your ${titleOf(ready).toLowerCase()}</label> | |
| 64 | <textarea class="input" id="body" name="body" rows="${ready.channel === "text" ? 4 : 9}" maxlength="${MAX_BODY[ready.channel]}" required>${escape(ready.body)}</textarea> | |
| 65 | <p class="sig">${escape(ready.signature)}</p> | |
| 66 | <button class="button">Approve and send</button> | |
| 67 | </form> | |
| 68 | </details> | |
| 69 | </div>` | |
| 70 | : "" | |
| 71 | } | |
| 72 | ${ | |
| 73 | channelFor(lead) === "email" | |
| 74 | ? `<p class="hint">Email only: ${lead.consent ? "no phone number to text." : "they have not given written consent to be texted."}</p>` | |
| 75 | : "" | |
| 76 | } | |
| 77 | </div>`; | |
| 78 | ||
| 79 | const thread = | |
| 80 | sent.length === 0 | |
| 81 | ? "" | |
| 82 | : `<section class="card"><h2>Sent</h2><ol class="thread">${sent | |
| 83 | .map( | |
| 84 | (m) => `<li> | |
| 85 | <p class="meta">${titleOf(m)} · ${CHANNEL[m.channel]} · <time datetime="${escape(m.sent_at ?? "")}">${escape(when(m.sent_at ?? m.due_at))}</time>${m.sent_by ? ` · approved by ${escape(m.sent_by)}` : ""}</p> | |
| 86 | ${words(m)} | |
| 87 | </li>`, | |
| 88 | ) | |
| 89 | .join("")}</ol></section>`; | |
| 90 | ||
| 91 | const plan = | |
| 92 | cadence.length === 0 | |
| 93 | ? `<section class="card"><h2>Follow-up plan</h2><p class="muted">Day 1, 3, 7, 14 and 30 follow-ups are drafted the moment the first reply goes out.</p></section>` | |
| 94 | : `<section class="card"><h2>Follow-up plan</h2><ol class="plan">${cadence | |
| 95 | .map( | |
| 96 | (m) => `<li data-status="${m.status}"> | |
| 97 | <span class="plan-day">Day ${m.day}</span> | |
| 98 | <span class="plan-when">${escape(day(m.sent_at ?? m.due_at))}</span> | |
| 99 | <span class="plan-status">${PLAN[m.status]}</span> | |
| 100 | ${m.status === "scheduled" ? `<details class="peek"><summary>Preview</summary>${words(m)}</details>` : ""} | |
| 101 | </li>`, | |
| 102 | ) | |
| 103 | .join("")}</ol></section>`; | |
| 104 | ||
| 105 | const states = | |
| 106 | mayUpdate && !closed | |
| 107 | ? `<section class="states"> | |
| 108 | <form method="post" action="${path}/state"><input type="hidden" name="state" value="qualified"><button class="button button-quiet">Mark qualified</button></form> | |
| 109 | <form method="post" action="${path}/state"><input type="hidden" name="state" value="lost"><button class="button button-quiet">Mark lost</button></form> | |
| 110 | </section>` | |
| 111 | : ""; | |
| 112 | ||
| 113 | return layout({ | |
| 114 | who, | |
| 115 | path, | |
| 116 | notice, | |
| 117 | heading: lead.name, | |
| 118 | body: `<div id="lead" data-live="lead.changed"> | |
| 119 | <p><a class="backlink" href="/">← All leads</a></p> | |
| 120 | <header class="lead-head"> | |
| 121 | <div> | |
| 122 | <h1>${escape(lead.name)}</h1> | |
| 123 | <p class="tags">${source(lead)}${consent(lead)}<span class="chip" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span></p> | |
| 124 | <p class="contact">${contact}</p> | |
| 125 | </div> | |
| 126 | ${clock(lead)} | |
| 127 | </header> | |
| 128 | <div class="split"> | |
| 129 | <div class="pane theirs"> | |
| 130 | <h2>They asked <span class="muted">· <time datetime="${escape(lead.created_at)}">${escape(when(lead.created_at))}</time></span></h2> | |
| 131 | <blockquote>${escape(lead.message)}</blockquote> | |
| 132 | </div> | |
| 133 | ${draft} | |
| 134 | </div> | |
| 135 | ${thread} | |
| 136 | ${plan} | |
| 137 | ${states} | |
| 138 | </div>`, | |
| 139 | }); | |
| 140 | } | |
| 141 | ||
| 142 | const PLAN: Readonly<Record<Message["status"], string>> = { | |
| 143 | draft: "Drafted", | |
| 144 | scheduled: "Upcoming", | |
| 145 | due: "Ready to send", | |
| 146 | sent: "Sent", | |
| 147 | skipped: "Skipped", | |
| 148 | }; |
src/pages/parts.ts added +51
| @@ -0,0 +1,51 @@ | ||
| 1 | /** The pieces both pages draw: the clock, the source, the consent badge, a date. */ | |
| 2 | ||
| 3 | import { between, elapsed, tone } from "../clock.ts"; | |
| 4 | import { channelFor, SOURCE_LABEL } from "../drafts.ts"; | |
| 5 | import { escape } from "../http.ts"; | |
| 6 | import type { Lead } from "../leads.ts"; | |
| 7 | ||
| 8 | /** | |
| 9 | * The response clock. Waiting, it counts up from the inquiry | |
| 10 | * (`static/clock.js` keeps it ticking); answered, it holds how long the | |
| 11 | * first reply took. | |
| 12 | */ | |
| 13 | export function clock(lead: Lead, now = Date.now()): string { | |
| 14 | if (lead.replied_at !== null) { | |
| 15 | const took = between(lead.created_at, lead.replied_at); | |
| 16 | return `<span class="clock clock-done" data-tone="${tone(took)}"><small>answered in</small> <span class="clock-time">${elapsed(took)}</span></span>`; | |
| 17 | } | |
| 18 | const waited = between(lead.created_at, now); | |
| 19 | return `<span class="clock" data-tone="${tone(waited)}" data-since="${escape(lead.created_at)}" role="timer" aria-label="Waiting since the inquiry"><small>waiting</small> <span class="clock-time">${elapsed(waited)}</span></span>`; | |
| 20 | } | |
| 21 | ||
| 22 | export const source = (lead: Lead): string => | |
| 23 | `<span class="chip">${escape(SOURCE_LABEL[lead.source])}</span>`; | |
| 24 | ||
| 25 | export const consent = (lead: Lead): string => | |
| 26 | channelFor(lead) === "text" | |
| 27 | ? `<span class="badge" data-consent="text" title="They gave written consent to be texted">Text OK</span>` | |
| 28 | : `<span class="badge" data-consent="email" title="No written consent to text: email only">Email only</span>`; | |
| 29 | ||
| 30 | export const STATE_LABEL: Readonly<Record<Lead["state"], string>> = { | |
| 31 | new: "New", | |
| 32 | contacted: "In follow-up", | |
| 33 | qualified: "Qualified", | |
| 34 | lost: "Lost", | |
| 35 | }; | |
| 36 | ||
| 37 | /** "Tue, Oct 14", or with the time when it is today or soon. */ | |
| 38 | export const day = (iso: string): string => | |
| 39 | new Date(iso).toLocaleDateString("en-US", { | |
| 40 | weekday: "short", | |
| 41 | month: "short", | |
| 42 | day: "numeric", | |
| 43 | }); | |
| 44 | ||
| 45 | export const when = (iso: string): string => | |
| 46 | new Date(iso).toLocaleString("en-US", { | |
| 47 | month: "short", | |
| 48 | day: "numeric", | |
| 49 | hour: "numeric", | |
| 50 | minute: "2-digit", | |
| 51 | }); |
src/routes.ts +265 −75
| @@ -14,20 +14,25 @@ | ||
| 14 | 14 | import type { Database } from "bun:sqlite"; |
| 15 | 15 | import { existsSync, readFileSync } from "node:fs"; |
| 16 | 16 | import { |
| 17 | addNote, | |
| 18 | BODY_MAX, | |
| 19 | deleteNote, | |
| 17 | addLead, | |
| 18 | deleteLead, | |
| 20 | 19 | getAudit, |
| 21 | getNote, | |
| 20 | getLead, | |
| 22 | 21 | listAudit, |
| 23 | listNotes, | |
| 24 | updateNote, | |
| 22 | listLeads, | |
| 23 | resetSample, | |
| 24 | sendReply, | |
| 25 | setState, | |
| 26 | tick, | |
| 25 | 27 | type Failure, |
| 26 | 28 | type Result, |
| 27 | 29 | } from "./actions.ts"; |
| 30 | import { permit } from "./contract.ts"; | |
| 31 | import { CADENCE, MAX_BODY, SOURCES } from "./drafts.ts"; | |
| 28 | 32 | import { commit, env, forgeUrl, startedAt, version } from "./env.ts"; |
| 29 | 33 | import { |
| 30 | 34 | back, |
| 35 | escape, | |
| 31 | 36 | fields, |
| 32 | 37 | html, |
| 33 | 38 | json, |
| @@ -40,7 +45,9 @@ import { | ||
| 40 | 45 | } from "./http.ts"; |
| 41 | 46 | import { events } from "./live.ts"; |
| 42 | 47 | import { rpc } from "./mcp.ts"; |
| 43 | import { home } from "./page.ts"; | |
| 48 | import { deskPage } from "./pages/desk.ts"; | |
| 49 | import { layout } from "./pages/layout.ts"; | |
| 50 | import { leadPage } from "./pages/lead.ts"; | |
| 44 | 51 | import { tokensCss } from "./tokens.ts"; |
| 45 | 52 | import type { Who } from "./who.ts"; |
| 46 | 53 | |
| @@ -75,29 +82,69 @@ export interface Route { | ||
| 75 | 82 | } |
| 76 | 83 | |
| 77 | 84 | // The shapes the API speaks in, named once. |
| 78 | export const NOTE: Schema = { | |
| 85 | const STAMP: Schema = { type: "string", format: "date-time" }; | |
| 86 | export const MESSAGE: Schema = { | |
| 79 | 87 | type: "object", |
| 80 | 88 | properties: { |
| 81 | 89 | id: { type: "integer" }, |
| 82 | body: { type: "string", minLength: 1, maxLength: BODY_MAX }, | |
| 83 | author_id: { type: "string" }, | |
| 84 | author_name: { type: "string" }, | |
| 85 | created_at: { type: "string", format: "date-time" }, | |
| 86 | updated_at: { type: "string", format: "date-time" }, | |
| 90 | lead_id: { type: "integer" }, | |
| 91 | day: { enum: [0, ...CADENCE], description: "0 is the first reply." }, | |
| 92 | channel: { enum: ["text", "email"] }, | |
| 93 | body: { type: "string", minLength: 1, maxLength: MAX_BODY.email }, | |
| 94 | signature: { type: "string" }, | |
| 95 | status: { enum: ["draft", "scheduled", "due", "sent", "skipped"] }, | |
| 96 | due_at: STAMP, | |
| 97 | sent_at: { type: ["string", "null"], format: "date-time" }, | |
| 98 | sent_by: { type: ["string", "null"] }, | |
| 87 | 99 | }, |
| 88 | required: [ | |
| 89 | "id", | |
| 90 | "body", | |
| 91 | "author_id", | |
| 92 | "author_name", | |
| 93 | "created_at", | |
| 94 | "updated_at", | |
| 95 | ], | |
| 100 | required: ["id", "lead_id", "day", "channel", "body", "signature", "status", "due_at"], | |
| 96 | 101 | }; |
| 97 | const NOTE_BODY: Schema = { | |
| 102 | const LEAD_FIELDS = { | |
| 103 | id: { type: "integer" }, | |
| 104 | name: { type: "string", minLength: 1, maxLength: 120 }, | |
| 105 | email: { type: "string", format: "email" }, | |
| 106 | phone: { type: "string" }, | |
| 107 | source: { enum: SOURCES }, | |
| 108 | message: { type: "string", minLength: 1, maxLength: 2000 }, | |
| 109 | consent: { | |
| 110 | type: "boolean", | |
| 111 | description: "Prior written consent to be texted. Without it, only email.", | |
| 112 | }, | |
| 113 | state: { enum: ["new", "contacted", "qualified", "lost"] }, | |
| 114 | created_at: STAMP, | |
| 115 | replied_at: { type: ["string", "null"], format: "date-time" }, | |
| 116 | updated_at: STAMP, | |
| 117 | } as const; | |
| 118 | const LEAD_REQUIRED = Object.keys(LEAD_FIELDS); | |
| 119 | export const LEAD: Schema = { | |
| 98 | 120 | type: "object", |
| 99 | properties: { body: { type: "string", minLength: 1, maxLength: BODY_MAX } }, | |
| 100 | required: ["body"], | |
| 121 | properties: { ...LEAD_FIELDS, messages: { type: "array", items: MESSAGE } }, | |
| 122 | required: [...LEAD_REQUIRED, "messages"], | |
| 123 | }; | |
| 124 | export const DESK_LEAD: Schema = { | |
| 125 | type: "object", | |
| 126 | properties: { | |
| 127 | ...LEAD_FIELDS, | |
| 128 | ready: { | |
| 129 | type: ["object", "null"], | |
| 130 | description: "The message ready to approve now, if any.", | |
| 131 | properties: { id: { type: "integer" }, day: { type: "integer" } }, | |
| 132 | }, | |
| 133 | next_at: { type: ["string", "null"], format: "date-time" }, | |
| 134 | }, | |
| 135 | required: [...LEAD_REQUIRED, "ready", "next_at"], | |
| 136 | }; | |
| 137 | const NEW_LEAD: Schema = { | |
| 138 | type: "object", | |
| 139 | properties: { | |
| 140 | name: LEAD_FIELDS.name, | |
| 141 | email: LEAD_FIELDS.email, | |
| 142 | phone: { type: "string", description: "Optional; needed to text." }, | |
| 143 | source: LEAD_FIELDS.source, | |
| 144 | message: LEAD_FIELDS.message, | |
| 145 | consent: LEAD_FIELDS.consent, | |
| 146 | }, | |
| 147 | required: ["name", "email", "source", "message"], | |
| 101 | 148 | }; |
| 102 | 149 | export const AUDIT_ROW: Schema = { |
| 103 | 150 | type: "object", |
| @@ -126,6 +173,7 @@ const LIMIT: Schema = { | ||
| 126 | 173 | maximum: 500, |
| 127 | 174 | default: 100, |
| 128 | 175 | }; |
| 176 | const ID = (c: Context): number => Number(c.params.id); | |
| 129 | 177 | const list = (items: Schema): Schema => ({ type: "array", items }); |
| 130 | 178 | |
| 131 | 179 | const STATUS: Record<Failure, number> = { |
| @@ -145,8 +193,52 @@ const answer = <T>(result: Result<T>, status = 200): Response => | ||
| 145 | 193 | ); |
| 146 | 194 | |
| 147 | 195 | /** A result for a form: back to the page, with what went wrong if it did. */ |
| 148 | const done = <T>(result: Result<T>): Response => | |
| 149 | result.ok ? back() : back(result.message); | |
| 196 | const done = <T>(result: Result<T>, to = "/", said?: string): Response => | |
| 197 | result.ok ? back(said, to) : back(result.message, to); | |
| 198 | ||
| 199 | /** Did a script send this, and want JSON back? A browser's form never does. */ | |
| 200 | const scripted = (request: Request): boolean => | |
| 201 | (request.headers.get("content-type") ?? "").includes("application/json"); | |
| 202 | ||
| 203 | /** A browser asking for the page, rather than a script asking for data. */ | |
| 204 | const browsing = (request: Request): boolean => { | |
| 205 | const accept = request.headers.get("accept") ?? ""; | |
| 206 | return !accept.includes("application/json") || accept.includes("text/html"); | |
| 207 | }; | |
| 208 | ||
| 209 | /** The fields of a POST, from JSON or a form: `undefined` when too large. */ | |
| 210 | async function readFields( | |
| 211 | request: Request, | |
| 212 | ): Promise<Record<string, unknown> | undefined> { | |
| 213 | if (scripted(request)) { | |
| 214 | const body = await readJson(request); | |
| 215 | return body === undefined ? undefined : fields(body); | |
| 216 | } | |
| 217 | const form = await readForm(request); | |
| 218 | return form === undefined | |
| 219 | ? undefined | |
| 220 | : Object.fromEntries( | |
| 221 | [...form.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]), | |
| 222 | ); | |
| 223 | } | |
| 224 | ||
| 225 | /** One POST, answered for whoever sent it: JSON to a script, back to the page for a form. */ | |
| 226 | const posted = async <T>( | |
| 227 | c: Context, | |
| 228 | act: (input: Record<string, unknown>) => Result<T>, | |
| 229 | page: (value: T | undefined) => { to: string; said?: string }, | |
| 230 | status = 200, | |
| 231 | ): Promise<Response> => { | |
| 232 | const input = await readFields(c.request); | |
| 233 | if (input === undefined) | |
| 234 | return scripted(c.request) | |
| 235 | ? json({ error: "too_large" }, 413) | |
| 236 | : text("too large", 413); | |
| 237 | const result = act(input); | |
| 238 | if (scripted(c.request)) return answer(result, status); | |
| 239 | const { to, said } = page(result.ok ? result.value : undefined); | |
| 240 | return done(result, to, said); | |
| 241 | }; | |
| 150 | 242 | |
| 151 | 243 | /** A whole number from the query, or undefined. */ |
| 152 | 244 | const whole = (value: string | null): number | undefined => |
| @@ -157,98 +249,120 @@ const OPENAPI = new URL("../contract/openapi.json", import.meta.url); | ||
| 157 | 249 | const openapi = existsSync(OPENAPI) ? readFileSync(OPENAPI, "utf8") : undefined; |
| 158 | 250 | |
| 159 | 251 | export const routes: readonly Route[] = [ |
| 160 | // The page. Forms post and come back; the list stays live over /events. | |
| 252 | // The desk. Forms post and come back; the page stays live over /events. | |
| 161 | 253 | { |
| 162 | 254 | method: "GET", |
| 163 | 255 | path: "/", |
| 164 | 256 | handle: (c) => { |
| 165 | 257 | const { notice, clear } = readNotice(c.request); |
| 166 | const notes = listNotes(c.db, c.who); | |
| 258 | const leads = listLeads(c.db, c.who); | |
| 167 | 259 | return html( |
| 168 | home({ who: c.who, notes: notes.ok ? notes.value : [], notice }), | |
| 260 | deskPage({ | |
| 261 | who: c.who, | |
| 262 | leads: leads.ok ? leads.value : undefined, | |
| 263 | mayAdd: permit(c.who, "lead", "create") === "yes", | |
| 264 | mayReset: permit(c.who, "lead", "delete") === "yes", | |
| 265 | notice, | |
| 266 | }), | |
| 169 | 267 | 200, |
| 170 | 268 | clear, |
| 171 | 269 | ); |
| 172 | 270 | }, |
| 173 | 271 | }, |
| 174 | { | |
| 175 | method: "POST", | |
| 176 | path: "/notes", | |
| 177 | handle: async (c) => { | |
| 178 | const form = await readForm(c.request); | |
| 179 | if (form === undefined) return text("too large", 413); | |
| 180 | return done( | |
| 181 | addNote(c.db, c.who, { body: String(form.get("body") ?? "") }), | |
| 182 | ); | |
| 183 | }, | |
| 184 | }, | |
| 185 | { | |
| 186 | method: "POST", | |
| 187 | path: "/notes/:id/delete", | |
| 188 | handle: (c) => done(deleteNote(c.db, c.who, { id: Number(c.params.id) })), | |
| 189 | }, | |
| 190 | 272 | |
| 191 | // The JSON API: the same actions, the same identity, plain status codes. | |
| 273 | // Leads: the page for a browser and JSON for a script, at the same paths. | |
| 192 | 274 | { |
| 193 | 275 | method: "GET", |
| 194 | path: "/api/notes", | |
| 276 | path: "/leads", | |
| 195 | 277 | handle: (c) => |
| 196 | 278 | answer( |
| 197 | listNotes(c.db, c.who, { | |
| 198 | limit: Number(c.url.searchParams.get("limit") ?? 100), | |
| 279 | listLeads(c.db, c.who, { | |
| 280 | limit: whole(c.url.searchParams.get("limit")) ?? 200, | |
| 199 | 281 | }), |
| 200 | 282 | ), |
| 201 | 283 | api: { |
| 202 | summary: "The notes, newest first.", | |
| 284 | summary: "The desk: every lead, newest inquiry first.", | |
| 203 | 285 | query: { limit: LIMIT }, |
| 204 | answer: list(NOTE), | |
| 286 | answer: list(DESK_LEAD), | |
| 205 | 287 | }, |
| 206 | 288 | }, |
| 207 | 289 | { |
| 208 | 290 | method: "POST", |
| 209 | path: "/api/notes", | |
| 210 | handle: async (c) => { | |
| 211 | const body = await readJson(c.request); | |
| 212 | if (body === undefined) return json({ error: "too_large" }, 413); | |
| 213 | return answer( | |
| 214 | addNote(c.db, c.who, { body: String(fields(body).body ?? "") }), | |
| 291 | path: "/leads", | |
| 292 | handle: (c) => | |
| 293 | posted( | |
| 294 | c, | |
| 295 | (input) => addLead(c.db, c.who, input), | |
| 296 | (lead) => ({ to: lead === undefined ? "/" : `/leads/${lead.id}` }), | |
| 215 | 297 | 201, |
| 216 | ); | |
| 217 | }, | |
| 298 | ), | |
| 218 | 299 | api: { |
| 219 | summary: "Add a note as the person asking.", | |
| 220 | body: NOTE_BODY, | |
| 221 | answer: NOTE, | |
| 300 | summary: | |
| 301 | "A new lead arrives (a website form can post here), with its first reply drafted.", | |
| 302 | body: NEW_LEAD, | |
| 303 | answer: LEAD, | |
| 222 | 304 | status: 201, |
| 223 | 305 | }, |
| 224 | 306 | }, |
| 225 | 307 | { |
| 226 | 308 | method: "GET", |
| 227 | path: "/api/notes/:id", | |
| 228 | handle: (c) => answer(getNote(c.db, c.who, { id: Number(c.params.id) })), | |
| 229 | api: { summary: "One note.", answer: NOTE }, | |
| 309 | path: "/leads/:id", | |
| 310 | handle: (c) => { | |
| 311 | const found = getLead(c.db, c.who, { id: ID(c) }); | |
| 312 | if (!browsing(c.request)) return answer(found); | |
| 313 | if (!found.ok) | |
| 314 | return html( | |
| 315 | layout({ | |
| 316 | who: c.who, | |
| 317 | path: c.url.pathname, | |
| 318 | body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`, | |
| 319 | }), | |
| 320 | STATUS[found.error], | |
| 321 | ); | |
| 322 | const { notice, clear } = readNotice(c.request); | |
| 323 | return html( | |
| 324 | leadPage({ | |
| 325 | who: c.who, | |
| 326 | lead: found.value, | |
| 327 | mayUpdate: permit(c.who, "lead", "update", { ...found.value }) === "yes", | |
| 328 | notice, | |
| 329 | }), | |
| 330 | 200, | |
| 331 | clear, | |
| 332 | ); | |
| 333 | }, | |
| 334 | api: { | |
| 335 | summary: | |
| 336 | "One lead, with every message: sent, drafted, and the follow-ups to come. Ask for application/json.", | |
| 337 | answer: LEAD, | |
| 338 | }, | |
| 230 | 339 | }, |
| 231 | 340 | { |
| 232 | 341 | method: "PATCH", |
| 233 | path: "/api/notes/:id", | |
| 342 | path: "/leads/:id", | |
| 234 | 343 | handle: async (c) => { |
| 235 | 344 | const body = await readJson(c.request); |
| 236 | 345 | if (body === undefined) return json({ error: "too_large" }, 413); |
| 237 | 346 | return answer( |
| 238 | updateNote(c.db, c.who, { | |
| 239 | id: Number(c.params.id), | |
| 240 | body: String(fields(body).body ?? ""), | |
| 241 | }), | |
| 347 | setState(c.db, c.who, { id: ID(c), state: fields(body).state }), | |
| 242 | 348 | ); |
| 243 | 349 | }, |
| 244 | api: { summary: "Change a note's words.", body: NOTE_BODY, answer: NOTE }, | |
| 350 | api: { | |
| 351 | summary: "Mark a lead qualified or lost (the same as POST /leads/{id}/state).", | |
| 352 | body: { | |
| 353 | type: "object", | |
| 354 | properties: { state: { enum: ["qualified", "lost"] } }, | |
| 355 | required: ["state"], | |
| 356 | }, | |
| 357 | answer: LEAD, | |
| 358 | }, | |
| 245 | 359 | }, |
| 246 | 360 | { |
| 247 | 361 | method: "DELETE", |
| 248 | path: "/api/notes/:id", | |
| 249 | handle: (c) => answer(deleteNote(c.db, c.who, { id: Number(c.params.id) })), | |
| 362 | path: "/leads/:id", | |
| 363 | handle: (c) => answer(deleteLead(c.db, c.who, { id: ID(c) })), | |
| 250 | 364 | api: { |
| 251 | summary: "Remove a note.", | |
| 365 | summary: "Remove a lead and everything said to it.", | |
| 252 | 366 | answer: { |
| 253 | 367 | type: "object", |
| 254 | 368 | properties: { id: { type: "integer" } }, |
| @@ -256,6 +370,82 @@ export const routes: readonly Route[] = [ | ||
| 256 | 370 | }, |
| 257 | 371 | }, |
| 258 | 372 | }, |
| 373 | { | |
| 374 | method: "POST", | |
| 375 | path: "/leads/:id/reply", | |
| 376 | handle: (c) => | |
| 377 | posted( | |
| 378 | c, | |
| 379 | (input) => | |
| 380 | sendReply(c.db, c.who, { | |
| 381 | id: ID(c), | |
| 382 | body: typeof input.body === "string" ? input.body : undefined, | |
| 383 | }), | |
| 384 | () => ({ to: `/leads/${ID(c)}`, said: "Sent." }), | |
| 385 | ), | |
| 386 | api: { | |
| 387 | summary: | |
| 388 | "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.", | |
| 389 | body: { | |
| 390 | type: "object", | |
| 391 | properties: { | |
| 392 | body: { | |
| 393 | type: "string", | |
| 394 | minLength: 1, | |
| 395 | maxLength: MAX_BODY.email, | |
| 396 | description: `The words, edited; the draft when left out. A text is at most ${MAX_BODY.text} characters. The signature is added.`, | |
| 397 | }, | |
| 398 | }, | |
| 399 | }, | |
| 400 | answer: LEAD, | |
| 401 | }, | |
| 402 | }, | |
| 403 | { | |
| 404 | method: "POST", | |
| 405 | path: "/leads/:id/state", | |
| 406 | handle: (c) => | |
| 407 | posted( | |
| 408 | c, | |
| 409 | (input) => setState(c.db, c.who, { id: ID(c), state: input.state }), | |
| 410 | (lead) => ({ | |
| 411 | to: `/leads/${ID(c)}`, | |
| 412 | ...(lead === undefined ? {} : { said: `Marked ${lead.state}.` }), | |
| 413 | }), | |
| 414 | ), | |
| 415 | api: { | |
| 416 | summary: "Mark a lead qualified or lost: it leaves the follow-up plan.", | |
| 417 | body: { | |
| 418 | type: "object", | |
| 419 | properties: { state: { enum: ["qualified", "lost"] } }, | |
| 420 | required: ["state"], | |
| 421 | }, | |
| 422 | answer: LEAD, | |
| 423 | }, | |
| 424 | }, | |
| 425 | { | |
| 426 | method: "POST", | |
| 427 | path: "/tick", | |
| 428 | handle: (c) => answer(tick(c.db, c.who)), | |
| 429 | api: { | |
| 430 | summary: | |
| 431 | "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.", | |
| 432 | answer: { | |
| 433 | type: "object", | |
| 434 | properties: { leads: list({ type: "integer" }) }, | |
| 435 | required: ["leads"], | |
| 436 | }, | |
| 437 | }, | |
| 438 | }, | |
| 439 | { | |
| 440 | method: "POST", | |
| 441 | path: "/sample/reset", | |
| 442 | handle: (c) => | |
| 443 | posted( | |
| 444 | c, | |
| 445 | () => resetSample(c.db, c.who), | |
| 446 | () => ({ to: "/", said: "The sample leads start again from now." }), | |
| 447 | ), | |
| 448 | }, | |
| 259 | 449 | |
| 260 | 450 | // Who tried to change what: the audit trail, for whoever the table lets read it. |
| 261 | 451 | { |
| @@ -405,7 +595,7 @@ export const routes: readonly Route[] = [ | ||
| 405 | 595 | handle: () => |
| 406 | 596 | text( |
| 407 | 597 | env === "production" |
| 408 | ? "User-agent: *\nDisallow: /api/\nDisallow: /mcp\nDisallow: /events\nDisallow: /__forge/\n" | |
| 598 | ? "User-agent: *\nDisallow: /api/\nDisallow: /leads\nDisallow: /mcp\nDisallow: /events\nDisallow: /__forge/\n" | |
| 409 | 599 | : "User-agent: *\nDisallow: /\n", |
| 410 | 600 | ), |
| 411 | 601 | }, |
src/sample.ts added +113
| @@ -0,0 +1,113 @@ | ||
| 1 | /** | |
| 2 | * The sample desk the prototype ships with: twelve people, from every | |
| 3 | * source, timed from the moment they are laid out — two just in, two | |
| 4 | * waiting long enough to turn the clock amber, three gone red, and five | |
| 5 | * already answered and somewhere in their cadence. Laid out once, the | |
| 6 | * first time the app opens its database; `resetSample` lays them out again | |
| 7 | * from now, for a demonstration. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import type { Source } from "./drafts.ts"; | |
| 12 | import { agent } from "./env.ts"; | |
| 13 | import { | |
| 14 | advance, | |
| 15 | close, | |
| 16 | findLead, | |
| 17 | insertLead, | |
| 18 | readyFor, | |
| 19 | send, | |
| 20 | type NewLead, | |
| 21 | } from "./leads.ts"; | |
| 22 | ||
| 23 | interface Sample extends NewLead { | |
| 24 | /** How long ago they asked. */ | |
| 25 | readonly ago: number; | |
| 26 | /** How long the first reply took, when it has gone. */ | |
| 27 | readonly answeredIn?: number; | |
| 28 | /** The cadence days already sent. */ | |
| 29 | readonly touched?: readonly number[]; | |
| 30 | readonly closed?: "qualified" | "lost"; | |
| 31 | } | |
| 32 | ||
| 33 | const S = 1000; | |
| 34 | const M = 60 * S; | |
| 35 | const H = 60 * M; | |
| 36 | const D = 24 * H; | |
| 37 | ||
| 38 | let numbered = 0; | |
| 39 | const person = ( | |
| 40 | name: string, | |
| 41 | source: Source, | |
| 42 | consent: boolean, | |
| 43 | message: string, | |
| 44 | rest: Omit<Sample, keyof NewLead>, | |
| 45 | ): Sample => { | |
| 46 | const handle = name.toLowerCase().replace(/[^a-z]+/g, "."); | |
| 47 | return { | |
| 48 | name, | |
| 49 | email: `${handle}@example.com`, | |
| 50 | // 555-01xx: the numbers set aside for fiction. | |
| 51 | phone: `(206) 555-01${String(++numbered).padStart(2, "0")}`, | |
| 52 | source, | |
| 53 | message, | |
| 54 | consent, | |
| 55 | ...rest, | |
| 56 | }; | |
| 57 | }; | |
| 58 | ||
| 59 | export const SAMPLES: readonly Sample[] = [ | |
| 60 | person("Maria Gonzalez", "zillow", true, "Is 418 Juniper Ln still available? We'd love to see it this weekend if possible.", { ago: 40 * S }), | |
| 61 | person("David Chen", "website", false, "We're thinking about selling our townhouse in the spring. Any idea what it might be worth in today's market?", { ago: 3 * M + 10 * S }), | |
| 62 | person("Priya Raman", "open_house", true, "Loved the kitchen at Sunday's open house on Alder Ct. Are the sellers flexible on price at all?", { ago: 18 * M }), | |
| 63 | person("James O'Neill", "referral", false, "Sarah Patel said you helped her family relocate last year. We're moving from Denver in August and don't know the area.", { ago: 47 * M }), | |
| 64 | person("Aisha Bello", "zillow", false, "Pre-approved up to $550k. Looking for 3 bedrooms with a yard, ideally near good schools.", { ago: 2 * H + 12 * M }), | |
| 65 | person("Tom Becker", "website", true, "Do you work with first-time buyers? We have no idea where to start.", { ago: 5 * H + 30 * M }), | |
| 66 | person("Lena Novak", "open_house", false, "Signed in at the open house on Birch St. Could you send me the disclosures and HOA details?", { ago: 26 * H }), | |
| 67 | person("Marcus Lee", "zillow", true, "Can I tour 92 Harbor View Dr this week? Available most evenings after 6.", { ago: 2 * D + 3 * H, answeredIn: 48 * S, touched: [1] }), | |
| 68 | person("Rosa Alvarez", "referral", false, "My cousin Elena recommended you. We need a bigger place before the baby comes in March.", { ago: 4 * D + 2 * H, answeredIn: 3 * M + 20 * S, touched: [1] }), | |
| 69 | person("Ethan Brooks", "website", true, "What would my 2-bed condo on Seaview Ave sell for? Considering upsizing next year.", { ago: 8 * D + 5 * H, answeredIn: 2 * M + 5 * S, touched: [1, 3] }), | |
| 70 | person("Grace Kim", "zillow", false, "Is the price on 7 Larkspur Ct negotiable? We're pre-approved and ready to move.", { ago: 15 * D, answeredIn: 1 * M + 30 * S, touched: [1, 3, 7], closed: "qualified" }), | |
| 71 | person("Hannah Wright", "open_house", false, "Thanks for the tour of the Maple Ave home. Still deciding whether we want to stay in the city.", { ago: 31 * D, answeredIn: 4 * M + 15 * S, touched: [1, 3, 7, 14] }), | |
| 72 | ]; | |
| 73 | ||
| 74 | /** Lay the samples out as of `now`. Returns how many. */ | |
| 75 | export function seed(db: Database, now: Date): number { | |
| 76 | const t = now.getTime(); | |
| 77 | const iso = (ms: number): string => new Date(ms).toISOString(); | |
| 78 | // Oldest first, so ids rise with time as they would have. | |
| 79 | for (const sample of [...SAMPLES].sort((a, b) => b.ago - a.ago)) { | |
| 80 | const asked = t - sample.ago; | |
| 81 | const id = insertLead(db, sample, iso(asked), agent); | |
| 82 | if (sample.answeredIn !== undefined) { | |
| 83 | const replied = asked + sample.answeredIn; | |
| 84 | sendReady(db, id, iso(replied)); | |
| 85 | for (const day of sample.touched ?? []) { | |
| 86 | advance(db, iso(replied + day * D + 30 * M)); | |
| 87 | sendReady(db, id, iso(replied + day * D + 55 * M)); | |
| 88 | } | |
| 89 | } | |
| 90 | if (sample.closed !== undefined) close(db, id, sample.closed, iso(t - 2 * D)); | |
| 91 | } | |
| 92 | advance(db, iso(t)); | |
| 93 | return SAMPLES.length; | |
| 94 | } | |
| 95 | ||
| 96 | /** Send what is ready for a sample lead, as drafted, as the agent. */ | |
| 97 | function sendReady(db: Database, id: number, at: string): void { | |
| 98 | send(db, findLead(db, id)!, readyFor(db, id)!, readyFor(db, id)!.body, agent.name, at, agent); | |
| 99 | } | |
| 100 | ||
| 101 | /** The samples, the first time this database is opened and never again. */ | |
| 102 | export function seedOnce(db: Database, now = new Date()): void { | |
| 103 | db.transaction(() => { | |
| 104 | const done = db | |
| 105 | .query<{ value: string }, []>("SELECT value FROM meta WHERE key = 'sample'") | |
| 106 | .get(); | |
| 107 | if (done !== null) return; | |
| 108 | seed(db, now); | |
| 109 | db.query("INSERT INTO meta (key, value) VALUES ('sample', ?1)").run( | |
| 110 | now.toISOString(), | |
| 111 | ); | |
| 112 | })(); | |
| 113 | } |
src/security.test.ts +65 −34
| @@ -24,6 +24,7 @@ const server = serve({ | ||
| 24 | 24 | port: 0, |
| 25 | 25 | dataDir: mkdtempSync(join(tmpdir(), "app-door-")), |
| 26 | 26 | identityKey: KEY, |
| 27 | sample: false, | |
| 27 | 28 | }); |
| 28 | 29 | const base = `http://${server.hostname}:${server.port}`; |
| 29 | 30 | afterAll(() => server.stop(true)); |
| @@ -36,24 +37,18 @@ const as = (id: string, role: "user" | "admin"): Record<string, string> => { | ||
| 36 | 37 | }; |
| 37 | 38 | |
| 38 | 39 | test("a path is a resource's door by the contract's api, and nothing else is", () => { |
| 39 | expect(doorOf("GET", "/api/notes")).toEqual({ | |
| 40 | resource: "note", | |
| 41 | verb: "list", | |
| 42 | }); | |
| 43 | expect(doorOf("POST", "/api/notes")).toEqual({ | |
| 44 | resource: "note", | |
| 40 | expect(doorOf("GET", "/leads")).toEqual({ resource: "lead", verb: "list" }); | |
| 41 | expect(doorOf("POST", "/leads")).toEqual({ | |
| 42 | resource: "lead", | |
| 45 | 43 | verb: "create", |
| 46 | 44 | }); |
| 47 | expect(doorOf("GET", "/api/notes/7")).toEqual({ | |
| 48 | resource: "note", | |
| 49 | verb: "read", | |
| 50 | }); | |
| 51 | expect(doorOf("PATCH", "/api/notes/7")).toEqual({ | |
| 52 | resource: "note", | |
| 45 | expect(doorOf("GET", "/leads/7")).toEqual({ resource: "lead", verb: "read" }); | |
| 46 | expect(doorOf("PATCH", "/leads/7")).toEqual({ | |
| 47 | resource: "lead", | |
| 53 | 48 | verb: "update", |
| 54 | 49 | }); |
| 55 | expect(doorOf("DELETE", "/api/notes/7")).toEqual({ | |
| 56 | resource: "note", | |
| 50 | expect(doorOf("DELETE", "/leads/7")).toEqual({ | |
| 51 | resource: "lead", | |
| 57 | 52 | verb: "delete", |
| 58 | 53 | }); |
| 59 | 54 | expect(doorOf("GET", "/api/audit")).toEqual({ |
| @@ -61,11 +56,11 @@ test("a path is a resource's door by the contract's api, and nothing else is", ( | ||
| 61 | 56 | verb: "list", |
| 62 | 57 | }); |
| 63 | 58 | for (const [method, path] of [ |
| 64 | ["PUT", "/api/notes"], | |
| 65 | ["GET", "/api/notes/7/x"], | |
| 66 | ["GET", "/api/notesy"], | |
| 67 | ["GET", "/api/notes/"], | |
| 68 | ["POST", "/notes"], | |
| 59 | ["PUT", "/leads"], | |
| 60 | ["POST", "/leads/7/reply"], | |
| 61 | ["GET", "/leadsy"], | |
| 62 | ["GET", "/leads/"], | |
| 63 | ["POST", "/tick"], | |
| 69 | 64 | ] as const) |
| 70 | 65 | expect(doorOf(method, path)).toBeUndefined(); |
| 71 | 66 | }); |
| @@ -74,26 +69,27 @@ test("the door refuses only what no row would open", () => { | ||
| 74 | 69 | const anon = { role: "anon" } as const; |
| 75 | 70 | const alice = { role: "user", id: "u1", name: "alice" } as const; |
| 76 | 71 | const root = { role: "admin", id: "u0", name: "root" } as const; |
| 77 | expect(mayKnock(anon, "note", "list")).toBe(true); | |
| 78 | expect(mayKnock(anon, "note", "create")).toBe(false); | |
| 79 | expect(mayKnock(anon, "note", "delete")).toBe(false); | |
| 80 | // alice may delete a note of her own, so the door lets her ask; the action decides which. | |
| 81 | expect(mayKnock(alice, "note", "delete")).toBe(true); | |
| 72 | expect(mayKnock(anon, "lead", "list")).toBe(false); | |
| 73 | expect(mayKnock(anon, "lead", "create")).toBe(false); | |
| 74 | expect(mayKnock(alice, "lead", "read")).toBe(true); | |
| 75 | expect(mayKnock(alice, "lead", "update")).toBe(true); | |
| 76 | expect(mayKnock(alice, "lead", "delete")).toBe(false); | |
| 77 | expect(mayKnock(root, "lead", "delete")).toBe(true); | |
| 82 | 78 | expect(mayKnock(alice, "audit", "list")).toBe(false); |
| 83 | 79 | expect(mayKnock(root, "audit", "list")).toBe(true); |
| 84 | 80 | expect(mayKnock(root, "audit", "create")).toBe(false); |
| 85 | 81 | }); |
| 86 | 82 | |
| 87 | test("a stranger is refused /api before the body is read, when the contract closes it", async () => { | |
| 83 | test("a stranger is refused before the body is read, when the contract closes the door", async () => { | |
| 88 | 84 | // A body past the cap: read, it would be 413. The door answers first. |
| 89 | 85 | const huge = "x".repeat(128 * 1024); |
| 90 | const refused = await fetch(`${base}/api/notes`, { | |
| 86 | const refused = await fetch(`${base}/leads`, { | |
| 91 | 87 | method: "POST", |
| 92 | 88 | headers: { "content-type": "application/json" }, |
| 93 | 89 | body: huge, |
| 94 | 90 | }); |
| 95 | 91 | expect(refused.status).toBe(401); |
| 96 | const signedIn = await fetch(`${base}/api/notes`, { | |
| 92 | const signedIn = await fetch(`${base}/leads`, { | |
| 97 | 93 | method: "POST", |
| 98 | 94 | headers: { "content-type": "application/json", ...as("u1", "user") }, |
| 99 | 95 | body: huge, |
| @@ -103,15 +99,48 @@ test("a stranger is refused /api before the body is read, when the contract clos | ||
| 103 | 99 | error: "signin_required", |
| 104 | 100 | message: "Sign in first.", |
| 105 | 101 | }); |
| 102 | expect((await fetch(`${base}/leads`)).status).toBe(401); | |
| 106 | 103 | expect((await fetch(`${base}/api/audit`)).status).toBe(401); |
| 107 | 104 | expect((await fetch(`${base}/api/audit/1`)).status).toBe(401); |
| 108 | 105 | expect( |
| 109 | 106 | (await fetch(`${base}/api/audit`, { headers: as("u1", "user") })).status, |
| 110 | 107 | ).toBe(403); |
| 108 | expect( | |
| 109 | ( | |
| 110 | await fetch(`${base}/leads/1`, { | |
| 111 | method: "DELETE", | |
| 112 | headers: as("u1", "user"), | |
| 113 | }) | |
| 114 | ).status, | |
| 115 | ).toBe(403); | |
| 116 | // A person following a link is sent to sign in, not shown JSON. | |
| 117 | const followed = await fetch(`${base}/leads/1`, { | |
| 118 | headers: { accept: "text/html,application/xhtml+xml" }, | |
| 119 | redirect: "manual", | |
| 120 | }); | |
| 121 | expect(followed.status).toBe(303); | |
| 122 | expect(followed.headers.get("location")).toBe( | |
| 123 | "/__forge/signin?to=%2Fleads%2F1", | |
| 124 | ); | |
| 125 | expect(followed.headers.get("content-security-policy")).toContain( | |
| 126 | "default-src", | |
| 127 | ); | |
| 111 | 128 | // What the table opens stays open. |
| 112 | expect((await fetch(`${base}/api/notes`)).status).toBe(200); | |
| 113 | expect((await fetch(`${base}/api/notes/0`)).status).toBe(404); | |
| 114 | expect((await fetch(`${base}/openapi.json`)).status).toBe(200); | |
| 129 | const leads = await fetch(`${base}/leads`, { headers: as("u1", "user") }); | |
| 130 | expect(leads.status).toBe(200); | |
| 131 | expect( | |
| 132 | ( | |
| 133 | await fetch(`${base}/leads/0`, { | |
| 134 | headers: { accept: "application/json", ...as("u1", "user") }, | |
| 135 | }) | |
| 136 | ).status, | |
| 137 | ).toBe(404); | |
| 138 | // No door is open to a stranger, so neither is the API's description. | |
| 139 | expect((await fetch(`${base}/openapi.json`)).status).toBe(401); | |
| 140 | expect( | |
| 141 | (await fetch(`${base}/openapi.json`, { headers: as("u1", "user") })) | |
| 142 | .status, | |
| 143 | ).toBe(200); | |
| 115 | 144 | }); |
| 116 | 145 | |
| 117 | 146 | test("the API's description is shut to strangers when the table opens them no door", () => { |
| @@ -137,7 +166,8 @@ test("the API's description is shut to strangers when the table opens them no do | ||
| 137 | 166 | ); |
| 138 | 167 | if (!closed.ok) throw new Error(closed.problems.join("; ")); |
| 139 | 168 | expect(openToStrangers(closed.contract)).toBe(false); |
| 140 | expect(openToStrangers()).toBe(true); | |
| 169 | // This app's own table opens nothing to a stranger: leads are people's details. | |
| 170 | expect(openToStrangers()).toBe(false); | |
| 141 | 171 | }); |
| 142 | 172 | |
| 143 | 173 | test("strangers are rationed at the API, reads too", () => { |
| @@ -145,13 +175,14 @@ test("strangers are rationed at the API, reads too", () => { | ||
| 145 | 175 | const knock = () => |
| 146 | 176 | door( |
| 147 | 177 | db, |
| 148 | new Request("http://app/api/notes"), | |
| 149 | new URL("http://app/api/notes"), | |
| 178 | new Request("http://app/api/audit"), | |
| 179 | new URL("http://app/api/audit"), | |
| 150 | 180 | { role: "anon" }, |
| 151 | 181 | "203.0.113.7", |
| 152 | 182 | ); |
| 153 | 183 | const answers = Array.from({ length: STRANGERS.burst + 5 }, knock); |
| 154 | expect(answers.slice(0, STRANGERS.burst).every((a) => a === undefined)).toBe( | |
| 184 | // Turned away by the table (401) until the bucket is empty, then rationed. | |
| 185 | expect(answers.slice(0, STRANGERS.burst).every((a) => a?.status === 401)).toBe( | |
| 155 | 186 | true, |
| 156 | 187 | ); |
| 157 | 188 | expect(answers.at(-1)?.status).toBe(429); |
src/security.ts +22 −2
| @@ -24,7 +24,7 @@ import { record } from "./audit.ts"; | ||
| 24 | 24 | import { decide, VERBS, type Contract, type Verb } from "./can.ts"; |
| 25 | 25 | import { actorOf, contract } from "./contract.ts"; |
| 26 | 26 | import { publicOrigin } from "./env.ts"; |
| 27 | import { json, text } from "./http.ts"; | |
| 27 | import { html, json, SECURITY, text } from "./http.ts"; | |
| 28 | 28 | import type { Who } from "./who.ts"; |
| 29 | 29 | |
| 30 | 30 | // A browser on another site can make a person's browser POST here; it cannot |
| @@ -145,7 +145,9 @@ export function door( | ||
| 145 | 145 | const method = request.method === "HEAD" ? "GET" : request.method; |
| 146 | 146 | const writing = method !== "GET"; |
| 147 | 147 | const stranger = who.role === "anon"; |
| 148 | const found = doorOf(method, url.pathname); | |
| 148 | 149 | const api = |
| 150 | found !== undefined || | |
| 149 | 151 | url.pathname.startsWith("/api/") || |
| 150 | 152 | url.pathname === "/mcp" || |
| 151 | 153 | url.pathname === "/openapi.json"; |
| @@ -155,7 +157,6 @@ export function door( | ||
| 155 | 157 | if (stranger && api && !allow(`api:${from}`, STRANGERS)) |
| 156 | 158 | return text("too many requests", 429); |
| 157 | 159 | |
| 158 | const found = doorOf(method, url.pathname); | |
| 159 | 160 | if (writing && !sameOrigin(request)) { |
| 160 | 161 | record(db, { |
| 161 | 162 | who, |
| @@ -183,7 +184,26 @@ export function door( | ||
| 183 | 184 | : url.pathname.split("/").at(-1), |
| 184 | 185 | outcome, |
| 185 | 186 | }); |
| 187 | // A person following a link is sent to sign in, or told plainly; a | |
| 188 | // script hears JSON. Either way, nothing past the door is read. | |
| 189 | if (method === "GET" && wantsPage(request)) | |
| 190 | return stranger | |
| 191 | ? new Response(null, { | |
| 192 | status: 303, | |
| 193 | headers: { | |
| 194 | location: `/__forge/signin?to=${encodeURIComponent(url.pathname)}`, | |
| 195 | ...SECURITY, | |
| 196 | }, | |
| 197 | }) | |
| 198 | : html( | |
| 199 | `<!doctype html><meta charset="utf-8"><title>Not yours to open</title><p>You may not open this. <a href="/">Back to the desk</a></p>`, | |
| 200 | 403, | |
| 201 | ); | |
| 186 | 202 | return stranger |
| 187 | 203 | ? json({ error: outcome, message: "Sign in first." }, 401) |
| 188 | 204 | : json({ error: outcome, message: "You may not." }, 403); |
| 189 | 205 | } |
| 206 | ||
| 207 | /** A browser navigating: it asks for HTML first. */ | |
| 208 | const wantsPage = (request: Request): boolean => | |
| 209 | (request.headers.get("accept") ?? "").startsWith("text/html"); |
src/server.test.ts +213 −93
| @@ -2,7 +2,8 @@ import { afterAll, expect, test } from "bun:test"; | ||
| 2 | 2 | import { mkdtempSync } from "node:fs"; |
| 3 | 3 | import { tmpdir } from "node:os"; |
| 4 | 4 | import { join } from "node:path"; |
| 5 | import { env } from "./env.ts"; | |
| 5 | import { agent, env } from "./env.ts"; | |
| 6 | import { escape } from "./http.ts"; | |
| 6 | 7 | import { serve } from "./server.ts"; |
| 7 | 8 | import { sign } from "./who.ts"; |
| 8 | 9 | |
| @@ -34,6 +35,9 @@ const jsonBody = (body: unknown): RequestInit => ({ | ||
| 34 | 35 | headers: { "content-type": "application/json" }, |
| 35 | 36 | body: JSON.stringify(body), |
| 36 | 37 | }); |
| 38 | // alice writes a great deal here; each call is a fresh grant of hers, so | |
| 39 | // the per-person ration (tested on its own below) never trips the others. | |
| 40 | let grants = 0; | |
| 37 | 41 | const api = ( |
| 38 | 42 | path: string, |
| 39 | 43 | init: RequestInit = {}, |
| @@ -41,86 +45,215 @@ const api = ( | ||
| 41 | 45 | ) => |
| 42 | 46 | fetch(base + path, { |
| 43 | 47 | ...init, |
| 44 | headers: { ...(init.headers as Record<string, string>), ...who }, | |
| 48 | headers: { | |
| 49 | ...(init.headers as Record<string, string>), | |
| 50 | ...(who === alice ? as(`u1-${++grants}`, "alice") : who), | |
| 51 | }, | |
| 45 | 52 | }); |
| 46 | 53 | const rpc = (message: unknown, who: Record<string, string> = {}) => |
| 47 | 54 | api("/mcp", { method: "POST", ...jsonBody(message) }, who).then( |
| 48 | 55 | (r) => r.json() as Promise<any>, |
| 49 | 56 | ); |
| 50 | 57 | |
| 51 | test("the page knows who you are and offers the right door", async () => { | |
| 58 | const NEW = { | |
| 59 | name: "Nina Park", | |
| 60 | email: "[email protected]", | |
| 61 | phone: "(206) 555-0177", | |
| 62 | source: "website", | |
| 63 | message: "Could we see 12 Cedar Ln on Saturday?", | |
| 64 | consent: true, | |
| 65 | }; | |
| 66 | const form = (fields: Record<string, string>): FormData => { | |
| 67 | const f = new FormData(); | |
| 68 | for (const [k, v] of Object.entries(fields)) f.set(k, v); | |
| 69 | return f; | |
| 70 | }; | |
| 71 | const asJson = { accept: "application/json" }; | |
| 72 | type Lead = { | |
| 73 | id: number; | |
| 74 | state: string; | |
| 75 | replied_at: string | null; | |
| 76 | messages: { day: number; channel: string; status: string; body: string; signature: string }[]; | |
| 77 | }; | |
| 78 | const lead = async (id: number): Promise<Lead> => | |
| 79 | (await (await api(`/leads/${id}`, { headers: asJson }, alice)).json()) as Lead; | |
| 80 | const created = async (body: unknown = NEW): Promise<Lead> => { | |
| 81 | const response = await api("/leads", { method: "POST", ...jsonBody(body) }, alice); | |
| 82 | expect(response.status).toBe(201); | |
| 83 | return (await response.json()) as Lead; | |
| 84 | }; | |
| 85 | ||
| 86 | test("a guest sees who the desk belongs to and is asked to sign in; nothing about any lead", async () => { | |
| 52 | 87 | const guest = await (await fetch(base + "/")).text(); |
| 53 | expect(guest).toContain("<h1>"); | |
| 54 | expect(guest).toContain("/__forge/signin?to=/"); | |
| 88 | expect(guest).toContain(agent.name); | |
| 89 | expect(guest).toContain(escape(agent.brokerage)); | |
| 90 | expect(guest).toContain("/__forge/signin?to="); | |
| 55 | 91 | expect(guest).toContain('href="/__forge/report"'); |
| 56 | expect(guest).not.toContain('action="/notes"'); | |
| 57 | const signed = await (await api("/", {}, alice)).text(); | |
| 58 | expect(signed).toContain("<b>alice</b>"); | |
| 59 | expect(signed).toContain("/__forge/signout"); | |
| 60 | expect(signed).toContain('action="/notes"'); | |
| 92 | expect(guest).not.toContain("Maria Gonzalez"); | |
| 61 | 93 | }); |
| 62 | 94 | |
| 63 | test("a form post adds as the person; a guest is sent to sign in", async () => { | |
| 64 | const form = new FormData(); | |
| 65 | form.set("body", "hello from a form"); | |
| 66 | const refused = await api("/notes", { | |
| 67 | method: "POST", | |
| 68 | body: form, | |
| 69 | redirect: "manual", | |
| 70 | }); | |
| 71 | expect(refused.status).toBe(303); | |
| 72 | expect(refused.headers.get("set-cookie")).toContain("notice="); | |
| 73 | expect(refused.headers.get("set-cookie")).toContain("SameSite=Lax"); | |
| 74 | expect(await (await fetch(base + "/")).text()).not.toContain( | |
| 75 | "hello from a form", | |
| 95 | test("the desk: the sample leads, newest first, each with a source, consent and a clock", async () => { | |
| 96 | const page = await (await api("/", {}, alice)).text(); | |
| 97 | expect(page).toContain(agent.name); | |
| 98 | expect(page).toContain(escape(agent.brokerage)); | |
| 99 | expect(page).toContain("/__forge/signout"); | |
| 100 | expect(page.indexOf("Maria Gonzalez")).toBeLessThan(page.indexOf("Hannah Wright")); | |
| 101 | expect(page).toContain("James O'Neill"); | |
| 102 | for (const word of ["Zillow", "Website form", "Open house", "Referral", "Text OK", "Email only"]) | |
| 103 | expect([word, page.includes(word)]).toEqual([word, true]); | |
| 104 | for (const tone of ["ok", "warn", "late"]) | |
| 105 | expect([tone, page.includes(`data-tone="${tone}"`)]).toEqual([tone, true]); | |
| 106 | expect(page).toContain('data-since="'); | |
| 107 | expect(page).toContain('href="/leads/'); | |
| 108 | expect(page).toContain('action="/leads"'); | |
| 109 | // Only an admin may restart the sample. | |
| 110 | expect(page).not.toContain('action="/sample/reset"'); | |
| 111 | expect(await (await api("/", {}, root)).text()).toContain('action="/sample/reset"'); | |
| 112 | }); | |
| 113 | ||
| 114 | test("POST /leads: a lead arrives with its reply drafted; a stranger and a bad field are refused", async () => { | |
| 115 | const made = await created(); | |
| 116 | expect(made.state).toBe("new"); | |
| 117 | expect(made.messages).toHaveLength(1); | |
| 118 | expect(made.messages[0]!.status).toBe("draft"); | |
| 119 | expect(made.messages[0]!.body).toContain("12 Cedar Ln"); | |
| 120 | expect( | |
| 121 | (await api("/leads", { method: "POST", ...jsonBody(NEW) })).status, | |
| 122 | ).toBe(401); | |
| 123 | const bad = await api( | |
| 124 | "/leads", | |
| 125 | { method: "POST", ...jsonBody({ ...NEW, email: "nope" }) }, | |
| 126 | alice, | |
| 76 | 127 | ); |
| 128 | expect(bad.status).toBe(422); | |
| 129 | expect(((await bad.json()) as { error: string }).error).toBe("invalid"); | |
| 130 | // From the page's form: back to the lead, its reply ready. | |
| 77 | 131 | const posted = await api( |
| 78 | "/notes", | |
| 79 | { method: "POST", body: form, redirect: "manual" }, | |
| 132 | "/leads", | |
| 133 | { method: "POST", body: form({ ...NEW, name: "Form Person", consent: "yes" }), redirect: "manual" }, | |
| 80 | 134 | alice, |
| 81 | 135 | ); |
| 82 | 136 | expect(posted.status).toBe(303); |
| 83 | expect(posted.headers.get("set-cookie")).toBeNull(); | |
| 84 | const page = await (await api("/", {}, alice)).text(); | |
| 85 | expect(page).toContain("hello from a form"); | |
| 86 | expect(page).toContain("alice ·"); | |
| 137 | expect(posted.headers.get("location")).toMatch(/^\/leads\/\d+$/); | |
| 87 | 138 | }); |
| 88 | 139 | |
| 89 | test("the JSON API is the same actions with the same identity", async () => { | |
| 90 | const created = await api( | |
| 91 | "/api/notes", | |
| 92 | { method: "POST", ...jsonBody({ body: "over the api" }) }, | |
| 140 | test("the consent rule at the door: no text drafted without consent", async () => { | |
| 141 | const yes = await created({ ...NEW, name: "Texts OK", consent: true }); | |
| 142 | expect(yes.messages[0]!.channel).toBe("text"); | |
| 143 | const no = await created({ ...NEW, name: "Email Only", consent: false }); | |
| 144 | expect(no.messages[0]!.channel).toBe("email"); | |
| 145 | const unsaid = await created({ ...NEW, name: "Unsaid", consent: undefined }); | |
| 146 | expect(unsaid.messages[0]!.channel).toBe("email"); | |
| 147 | const page = await (await api(`/leads/${no.id}`, {}, alice)).text(); | |
| 148 | expect(page).toContain("Email only"); | |
| 149 | expect(page).toContain("not given written consent"); | |
| 150 | }); | |
| 151 | ||
| 152 | test("GET /leads/:id: the page, or JSON for a script", async () => { | |
| 153 | const made = await created({ ...NEW, name: "Page <b>Person</b>" }); | |
| 154 | const page = await (await api(`/leads/${made.id}`, {}, alice)).text(); | |
| 155 | expect(page).toContain("Page <b>Person</b>"); | |
| 156 | expect(page).not.toContain("<b>Person</b>"); | |
| 157 | expect(page).toContain(`action="/leads/${made.id}/reply"`); | |
| 158 | expect(page).toContain("Approve and send"); | |
| 159 | expect(page).toContain("Edit"); | |
| 160 | expect(page).toContain(escape(agent.license)); | |
| 161 | expect((await lead(made.id)).id).toBe(made.id); | |
| 162 | const missing = await api("/leads/999999", {}, alice); | |
| 163 | expect(missing.status).toBe(404); | |
| 164 | expect(missing.headers.get("content-type")).toContain("text/html"); | |
| 165 | const list = (await (await api("/leads", {}, alice)).json()) as { id: number }[]; | |
| 166 | expect(list.map((l) => l.id)).toContain(made.id); | |
| 167 | }); | |
| 168 | ||
| 169 | test("POST /leads/:id/reply: approve and send from the page, edited from the API, then the cadence", async () => { | |
| 170 | const one = await created({ ...NEW, name: "Approve Me" }); | |
| 171 | const sent = await api( | |
| 172 | `/leads/${one.id}/reply`, | |
| 173 | { method: "POST", body: form({}), redirect: "manual" }, | |
| 93 | 174 | alice, |
| 94 | 175 | ); |
| 95 | expect(created.status).toBe(201); | |
| 96 | const note = (await created.json()) as { id: number; author_name: string }; | |
| 97 | expect(note.author_name).toBe("alice"); | |
| 98 | const listed = (await (await fetch(base + "/api/notes")).json()) as { | |
| 99 | id: number; | |
| 100 | }[]; | |
| 101 | expect(listed.map((n) => n.id)).toContain(note.id); | |
| 176 | expect(sent.status).toBe(303); | |
| 177 | expect(sent.headers.get("location")).toBe(`/leads/${one.id}`); | |
| 178 | const after = await lead(one.id); | |
| 179 | expect(after.state).toBe("contacted"); | |
| 180 | expect(after.replied_at).not.toBeNull(); | |
| 181 | expect(after.messages.map((m) => [m.day, m.status])).toEqual([ | |
| 182 | [0, "sent"], | |
| 183 | [1, "scheduled"], | |
| 184 | [3, "scheduled"], | |
| 185 | [7, "scheduled"], | |
| 186 | [14, "scheduled"], | |
| 187 | [30, "scheduled"], | |
| 188 | ]); | |
| 189 | const page = await (await api(`/leads/${one.id}`, {}, alice)).text(); | |
| 190 | expect(page).toContain("approved by alice"); | |
| 191 | expect(page).toContain("Day 30"); | |
| 192 | ||
| 193 | const two = await created({ ...NEW, name: "Edit Me", consent: false }); | |
| 194 | const edited = await api( | |
| 195 | `/leads/${two.id}/reply`, | |
| 196 | { method: "POST", ...jsonBody({ body: "Hi Nina, Saturday at 10 works." }) }, | |
| 197 | alice, | |
| 198 | ); | |
| 199 | expect(edited.status).toBe(200); | |
| 200 | const done = (await edited.json()) as Lead; | |
| 201 | expect(done.messages[0]!.body).toBe("Hi Nina, Saturday at 10 works."); | |
| 202 | expect(done.messages[0]!.signature).toContain(agent.license); | |
| 203 | // Nothing more is ready today. | |
| 102 | 204 | expect( |
| 103 | (await api("/api/notes", { method: "POST", ...jsonBody({ body: "anon" }) })) | |
| 104 | .status, | |
| 105 | ).toBe(401); | |
| 106 | expect( | |
| 107 | (await api(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status, | |
| 108 | ).toBe(403); | |
| 109 | expect( | |
| 110 | (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status, | |
| 111 | ).toBe(200); | |
| 112 | expect( | |
| 113 | (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status, | |
| 114 | ).toBe(404); | |
| 115 | expect( | |
| 116 | ( | |
| 117 | await api( | |
| 118 | "/api/notes", | |
| 119 | { method: "POST", ...jsonBody({ body: "" }) }, | |
| 120 | alice, | |
| 121 | ) | |
| 122 | ).status, | |
| 205 | (await api(`/leads/${two.id}/reply`, { method: "POST", ...jsonBody({}) }, alice)).status, | |
| 123 | 206 | ).toBe(422); |
| 207 | expect( | |
| 208 | (await api(`/leads/${two.id}/reply`, { method: "POST", ...jsonBody({}) })).status, | |
| 209 | ).toBe(401); | |
| 210 | }); | |
| 211 | ||
| 212 | test("POST /leads/:id/state and PATCH /leads/:id: qualified or lost leaves the cadence", async () => { | |
| 213 | const one = await created({ ...NEW, name: "Qualify Me" }); | |
| 214 | await api(`/leads/${one.id}/reply`, { method: "POST", ...jsonBody({}) }, alice); | |
| 215 | const marked = await api( | |
| 216 | `/leads/${one.id}/state`, | |
| 217 | { method: "POST", body: form({ state: "qualified" }), redirect: "manual" }, | |
| 218 | alice, | |
| 219 | ); | |
| 220 | expect(marked.status).toBe(303); | |
| 221 | const after = await lead(one.id); | |
| 222 | expect(after.state).toBe("qualified"); | |
| 223 | expect(after.messages.filter((m) => m.day > 0).every((m) => m.status === "skipped")).toBe(true); | |
| 224 | const two = await created({ ...NEW, name: "Lose Me" }); | |
| 225 | const patched = await api( | |
| 226 | `/leads/${two.id}`, | |
| 227 | { method: "PATCH", ...jsonBody({ state: "lost" }) }, | |
| 228 | alice, | |
| 229 | ); | |
| 230 | expect(patched.status).toBe(200); | |
| 231 | expect(((await patched.json()) as Lead).state).toBe("lost"); | |
| 232 | expect( | |
| 233 | (await api(`/leads/${two.id}/state`, { method: "POST", ...jsonBody({ state: "new" }) }, alice)).status, | |
| 234 | ).toBe(422); | |
| 235 | }); | |
| 236 | ||
| 237 | test("POST /tick: the day turns for whoever may update leads; a stranger may not", async () => { | |
| 238 | const ticked = await api("/tick", { method: "POST", ...jsonBody({}) }, alice); | |
| 239 | expect(ticked.status).toBe(200); | |
| 240 | expect(Array.isArray(((await ticked.json()) as { leads: number[] }).leads)).toBe(true); | |
| 241 | expect((await api("/tick", { method: "POST" })).status).toBe(401); | |
| 242 | // The sample desk shows follow-ups already due. | |
| 243 | const desk = (await (await api("/leads", {}, alice)).json()) as { | |
| 244 | ready: { day: number } | null; | |
| 245 | }[]; | |
| 246 | expect(desk.some((l) => l.ready !== null && l.ready.day > 0)).toBe(true); | |
| 247 | }); | |
| 248 | ||
| 249 | test("DELETE /leads/:id and the sample restart are an admin's", async () => { | |
| 250 | const one = await created({ ...NEW, name: "Spam" }); | |
| 251 | expect((await api(`/leads/${one.id}`, { method: "DELETE" }, alice)).status).toBe(403); | |
| 252 | expect((await api(`/leads/${one.id}`, { method: "DELETE" }, root)).status).toBe(200); | |
| 253 | expect((await api(`/leads/${one.id}`, { headers: asJson }, alice)).status).toBe(404); | |
| 254 | expect( | |
| 255 | (await api("/sample/reset", { method: "POST", ...jsonBody({}) }, alice)).status, | |
| 256 | ).toBe(403); | |
| 124 | 257 | }); |
| 125 | 258 | |
| 126 | 259 | test("the MCP server lists the tools and calls them as the caller", async () => { |
| @@ -133,9 +266,11 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 133 | 266 | expect(hello.result.capabilities).toEqual({ tools: {} }); |
| 134 | 267 | const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" }); |
| 135 | 268 | expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([ |
| 136 | "list_notes", | |
| 137 | "add_note", | |
| 138 | "delete_note", | |
| 269 | "list_leads", | |
| 270 | "get_lead", | |
| 271 | "add_lead", | |
| 272 | "send_reply", | |
| 273 | "mark_lead", | |
| 139 | 274 | ]); |
| 140 | 275 | const call = (name: string, args: unknown, who = {}) => |
| 141 | 276 | rpc( |
| @@ -147,19 +282,14 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 147 | 282 | }, |
| 148 | 283 | who, |
| 149 | 284 | ); |
| 150 | const refused = await call("add_note", { body: "as nobody" }); | |
| 285 | const refused = await call("add_lead", NEW); | |
| 151 | 286 | expect(refused.result.isError).toBe(true); |
| 152 | const added = await call("add_note", { body: "over mcp" }, root); | |
| 287 | const added = await call("add_lead", { ...NEW, name: "Over MCP" }, root); | |
| 153 | 288 | expect(added.result.isError).toBeUndefined(); |
| 154 | const note = JSON.parse(added.result.content[0].text); | |
| 155 | expect(note.author_name).toBe("root"); | |
| 156 | const notes = JSON.parse( | |
| 157 | (await call("list_notes", {})).result.content[0].text, | |
| 158 | ); | |
| 159 | expect(notes.map((n: { id: number }) => n.id)).toContain(note.id); | |
| 160 | expect( | |
| 161 | (await call("delete_note", { id: note.id }, root)).result.isError, | |
| 162 | ).toBeUndefined(); | |
| 289 | const made = JSON.parse(added.result.content[0].text); | |
| 290 | expect(made.name).toBe("Over MCP"); | |
| 291 | const sent = await call("send_reply", { id: made.id }, root); | |
| 292 | expect(JSON.parse(sent.result.content[0].text).state).toBe("contacted"); | |
| 163 | 293 | expect( |
| 164 | 294 | (await rpc({ jsonrpc: "2.0", id: 4, method: "nothing" })).error.code, |
| 165 | 295 | ).toBe(-32601); |
| @@ -183,13 +313,9 @@ test("a change is on the event stream, and a late client hears what it missed", | ||
| 183 | 313 | if (frame) return { id: frame[1]!, type: JSON.parse(frame[2]!).type }; |
| 184 | 314 | } |
| 185 | 315 | }; |
| 186 | await api( | |
| 187 | "/api/notes", | |
| 188 | { method: "POST", ...jsonBody({ body: "live" }) }, | |
| 189 | alice, | |
| 190 | ); | |
| 316 | await created({ ...NEW, name: "Live One" }); | |
| 191 | 317 | const heard = await next(); |
| 192 | expect(heard.type).toBe("note.added"); | |
| 318 | expect(heard.type).toBe("lead.added"); | |
| 193 | 319 | await reader.cancel(); |
| 194 | 320 | const late = await fetch(base + "/events", { |
| 195 | 321 | headers: { "last-event-id": String(Number(heard.id) - 1) }, |
| @@ -198,18 +324,14 @@ test("a change is on the event stream, and a late client hears what it missed", | ||
| 198 | 324 | (await late.body!.getReader().read()).value, |
| 199 | 325 | ); |
| 200 | 326 | expect(replay).toContain(`id: ${heard.id}\n`); |
| 201 | expect(replay).toContain("note.added"); | |
| 327 | expect(replay).toContain("lead.added"); | |
| 202 | 328 | }); |
| 203 | 329 | |
| 204 | 330 | test("writes are rationed per person", async () => { |
| 205 | 331 | const flood = as("u9", "flood"); |
| 206 | 332 | const answers = await Promise.all( |
| 207 | 333 | Array.from({ length: 40 }, () => |
| 208 | api( | |
| 209 | "/api/notes", | |
| 210 | { method: "POST", ...jsonBody({ body: "again" }) }, | |
| 211 | flood, | |
| 212 | ), | |
| 334 | api("/leads", { method: "POST", ...jsonBody(NEW) }, flood), | |
| 213 | 335 | ), |
| 214 | 336 | ); |
| 215 | 337 | const codes = answers.map((r) => r.status); |
| @@ -224,17 +346,17 @@ test("stands on the security floor", async () => { | ||
| 224 | 346 | ); |
| 225 | 347 | expect(response.headers.get("x-content-type-options")).toBe("nosniff"); |
| 226 | 348 | expect( |
| 227 | (await fetch(base + "/api/notes")).headers.get("content-security-policy"), | |
| 349 | (await api("/leads", {}, alice)).headers.get("content-security-policy"), | |
| 228 | 350 | ).toContain("default-src"); |
| 229 | 351 | }); |
| 230 | 352 | |
| 231 | 353 | test("a body is capped by the bytes read, whatever it claims", async () => { |
| 232 | 354 | const response = await api( |
| 233 | "/notes", | |
| 355 | "/leads", | |
| 234 | 356 | { |
| 235 | 357 | method: "POST", |
| 236 | 358 | headers: { "content-type": "application/x-www-form-urlencoded" }, |
| 237 | body: "body=" + "x".repeat(1024 * 1024), | |
| 359 | body: "message=" + "x".repeat(1024 * 1024), | |
| 238 | 360 | }, |
| 239 | 361 | alice, |
| 240 | 362 | ); |
| @@ -248,13 +370,11 @@ test("HEAD sees the app up", async () => { | ||
| 248 | 370 | }); |
| 249 | 371 | |
| 250 | 372 | test("refuses a cross-site post", async () => { |
| 251 | const form = new FormData(); | |
| 252 | form.set("body", "from another site"); | |
| 253 | 373 | const posted = await api( |
| 254 | "/notes", | |
| 374 | "/leads", | |
| 255 | 375 | { |
| 256 | 376 | method: "POST", |
| 257 | body: form, | |
| 377 | body: form(NEW as unknown as Record<string, string>), | |
| 258 | 378 | redirect: "manual", |
| 259 | 379 | headers: { |
| 260 | 380 | origin: "https://evil.example", |
src/server.ts +14
| @@ -7,10 +7,13 @@ | ||
| 7 | 7 | * serves what the forge said; a test calls `serve` with its own. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { turn } from "./actions.ts"; | |
| 10 | 11 | import { openDb } from "./db.ts"; |
| 11 | 12 | import { dataDir, identityKey, title, where } from "./env.ts"; |
| 12 | 13 | import { html, text } from "./http.ts"; |
| 14 | import { watch } from "./live.ts"; | |
| 13 | 15 | import { match } from "./routes.ts"; |
| 16 | import { seedOnce } from "./sample.ts"; | |
| 14 | 17 | import { door } from "./security.ts"; |
| 15 | 18 | import { who } from "./who.ts"; |
| 16 | 19 | |
| @@ -19,10 +22,21 @@ export interface ServeOptions { | ||
| 19 | 22 | readonly hostname?: string | undefined; |
| 20 | 23 | readonly dataDir: string; |
| 21 | 24 | readonly identityKey: string; |
| 25 | /** Lay out the sample leads the first time the database opens (yes, unless a test says no). */ | |
| 26 | readonly sample?: boolean; | |
| 22 | 27 | } |
| 23 | 28 | |
| 29 | /** How often the server turns the cadence on its own, whether or not anyone calls `POST /tick`. */ | |
| 30 | const TURN_MS = 60 * 60_000; | |
| 31 | ||
| 24 | 32 | export function serve(options: ServeOptions) { |
| 25 | 33 | const db = openDb(options.dataDir); |
| 34 | if (options.sample ?? true) seedOnce(db); | |
| 35 | turn(db); | |
| 36 | const turning = setInterval(() => turn(db), TURN_MS); | |
| 37 | turning.unref(); | |
| 38 | // The terminal writes from its own process; open pages hear it all the same. | |
| 39 | watch(db); | |
| 26 | 40 | return Bun.serve({ |
| 27 | 41 | port: options.port, |
| 28 | 42 | hostname: options.hostname ?? "127.0.0.1", |
src/terminal.test.ts added +204
| @@ -0,0 +1,204 @@ | ||
| 1 | /** | |
| 2 | * The terminal is a door like the page: nothing goes out from a screen | |
| 3 | * that has not shown it, and what the page can do, the keys can. | |
| 4 | */ | |
| 5 | import { expect, test } from "bun:test"; | |
| 6 | import { mkdtempSync } from "node:fs"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { getLead, listLeads } from "./actions.ts"; | |
| 10 | import { openDb } from "./db.ts"; | |
| 11 | import { agent } from "./env.ts"; | |
| 12 | import { seed } from "./sample.ts"; | |
| 13 | import { insertLead } from "./leads.ts"; | |
| 14 | import { clean, plain, terminal, wrap } from "./terminal.ts"; | |
| 15 | import type { Who } from "./who.ts"; | |
| 16 | ||
| 17 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 18 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 19 | const fresh = () => { | |
| 20 | const db = openDb(mkdtempSync(join(tmpdir(), "app-tty-"))); | |
| 21 | seed(db, new Date()); | |
| 22 | return db; | |
| 23 | }; | |
| 24 | const read = (t: ReturnType<typeof terminal>): string => | |
| 25 | t.screen(100).map(plain).join("\n"); | |
| 26 | const type = (t: ReturnType<typeof terminal>, text: string): void => { | |
| 27 | for (const ch of text) t.key(ch); | |
| 28 | }; | |
| 29 | ||
| 30 | test("enter opens the lead; it never sends", () => { | |
| 31 | const db = fresh(); | |
| 32 | const t = terminal(db, alice); | |
| 33 | const first = (listLeads(db, alice) as { ok: true; value: { id: number; name: string; message: string }[] }).value[0]!; | |
| 34 | expect(read(t)).toContain("Maria Gonzalez"); | |
| 35 | t.key("\r"); | |
| 36 | const screen = read(t); | |
| 37 | // What they asked, the words going out, the signature, and the channel. | |
| 38 | expect(screen).toContain("They asked"); | |
| 39 | expect(screen).toContain("418 Juniper Ln still available"); | |
| 40 | expect(screen).toContain("First reply — by text, as it will go"); | |
| 41 | expect(screen).toContain("Hi Maria"); | |
| 42 | expect(screen).toContain(agent.license); | |
| 43 | expect(screen).toContain("s approve and send"); | |
| 44 | const lead = getLead(db, alice, { id: first.id }); | |
| 45 | expect(lead.ok && lead.value.messages[0]!.status).toBe("draft"); | |
| 46 | }); | |
| 47 | ||
| 48 | test("s sends what was shown, from the lead screen", () => { | |
| 49 | const db = fresh(); | |
| 50 | const t = terminal(db, alice); | |
| 51 | t.key("s"); // On the desk, s is nothing. | |
| 52 | t.key("\r"); | |
| 53 | const id = (listLeads(db, alice) as { ok: true; value: { id: number }[] }).value[0]!.id; | |
| 54 | const shown = (getLead(db, alice, { id }) as { ok: true; value: { messages: { body: string }[] } }).value.messages[0]!.body; | |
| 55 | t.key("s"); | |
| 56 | expect(read(t)).toContain("Sent to Maria Gonzalez."); | |
| 57 | const after = getLead(db, alice, { id }); | |
| 58 | if (!after.ok) throw new Error(after.message); | |
| 59 | expect(after.value.messages[0]!.status).toBe("sent"); | |
| 60 | expect(after.value.messages[0]!.body).toBe(shown); | |
| 61 | expect(after.value.messages[0]!.sent_by).toBe("alice"); | |
| 62 | }); | |
| 63 | ||
| 64 | test("e edits the draft in place; ctrl-d sends the edit, esc sends nothing", () => { | |
| 65 | const db = fresh(); | |
| 66 | const t = terminal(db, alice); | |
| 67 | t.key("j"); // David Chen: email only. | |
| 68 | t.key("\r"); | |
| 69 | expect(read(t)).toContain("by email"); | |
| 70 | expect(read(t)).toContain("no written consent to text"); | |
| 71 | t.key("e"); | |
| 72 | expect(read(t)).toContain("ctrl-d approve and send"); | |
| 73 | t.key("\x1b"); | |
| 74 | expect(read(t)).toContain("nothing sent"); | |
| 75 | t.key("e"); | |
| 76 | for (let i = 0; i < 400; i++) t.key("\x7f"); | |
| 77 | type(t, "Hi David, happy to run the numbers."); | |
| 78 | t.key("\r"); | |
| 79 | type(t, "Thursday?"); | |
| 80 | t.key("\x04"); | |
| 81 | const id = (listLeads(db, alice) as { ok: true; value: { id: number }[] }).value[1]!.id; | |
| 82 | const after = getLead(db, alice, { id }); | |
| 83 | if (!after.ok) throw new Error(after.message); | |
| 84 | expect(after.value.messages[0]!.status).toBe("sent"); | |
| 85 | expect(after.value.messages[0]!.body).toBe("Hi David, happy to run the numbers.\nThursday?"); | |
| 86 | expect(after.value.messages[0]!.channel).toBe("email"); | |
| 87 | }); | |
| 88 | ||
| 89 | test("q and x close a lead from its screen", () => { | |
| 90 | const db = fresh(); | |
| 91 | const t = terminal(db, alice); | |
| 92 | t.key("\r"); | |
| 93 | t.key("x"); | |
| 94 | expect(read(t)).toContain("Maria Gonzalez: lost."); | |
| 95 | expect(read(t)).not.toContain("s approve and send"); | |
| 96 | }); | |
| 97 | ||
| 98 | test("n logs a lead by hand, field by field, and opens it with its reply drafted", () => { | |
| 99 | const db = fresh(); | |
| 100 | const t = terminal(db, alice); | |
| 101 | t.key("n"); | |
| 102 | for (const field of ["Zoe Park", "[email protected]", "", "3", "Saw the yard sign on Elm. Can we tour?", "n"]) { | |
| 103 | type(t, field); | |
| 104 | t.key("\r"); | |
| 105 | } | |
| 106 | const screen = read(t); | |
| 107 | expect(screen).toContain("Zoe Park is on the desk"); | |
| 108 | expect(screen).toContain("Open house"); | |
| 109 | expect(screen).toContain("by email"); | |
| 110 | const listed = listLeads(db, alice); | |
| 111 | expect(listed.ok && listed.value.some((l) => l.name === "Zoe Park" && l.source === "open_house" && !l.consent)).toBe(true); | |
| 112 | // A bad field is said, and nothing is logged. | |
| 113 | t.key("\x1b"); | |
| 114 | t.key("n"); | |
| 115 | for (const field of ["No Email", "nope", "", "1", "Hi", "y"]) { | |
| 116 | type(t, field); | |
| 117 | t.key("\r"); | |
| 118 | } | |
| 119 | expect(read(t)).toContain("An email address looks like"); | |
| 120 | }); | |
| 121 | ||
| 122 | test("remove and restart are an admin's, and ask first", () => { | |
| 123 | const db = fresh(); | |
| 124 | const user = terminal(db, alice); | |
| 125 | expect(read(user)).not.toContain("R restart"); | |
| 126 | user.key("R"); | |
| 127 | user.key("y"); | |
| 128 | expect(read(user)).toContain("Only an admin can reset"); | |
| 129 | user.key("\r"); | |
| 130 | expect(read(user)).not.toContain("D remove"); | |
| 131 | user.key("D"); | |
| 132 | user.key("y"); | |
| 133 | expect(read(user)).toContain("Only an admin can remove"); | |
| 134 | ||
| 135 | const t = terminal(db, root); | |
| 136 | expect(read(t)).toContain("R restart the samples"); | |
| 137 | t.key("\r"); | |
| 138 | t.key("D"); | |
| 139 | expect(read(t)).toContain("Remove Maria Gonzalez"); | |
| 140 | t.key("n"); | |
| 141 | expect(read(t)).toContain("They asked"); | |
| 142 | t.key("D"); | |
| 143 | t.key("y"); | |
| 144 | expect(read(t)).toContain("Removed."); | |
| 145 | expect(read(t)).not.toContain("Maria Gonzalez"); | |
| 146 | t.key("R"); | |
| 147 | t.key("y"); | |
| 148 | expect(read(t)).toContain("start again from now"); | |
| 149 | expect(read(t)).toContain("Maria Gonzalez"); | |
| 150 | }); | |
| 151 | ||
| 152 | test("a stranger sees no leads; esc leaves", () => { | |
| 153 | const t = terminal(fresh(), { role: "anon" }); | |
| 154 | expect(read(t)).toContain("Sign in to open the desk."); | |
| 155 | expect(read(t)).not.toContain("Maria"); | |
| 156 | t.key("\x1b"); | |
| 157 | expect(t.done).toBe(true); | |
| 158 | }); | |
| 159 | ||
| 160 | test("words fold to the width", () => { | |
| 161 | expect(wrap("one two three four", 9)).toEqual(["one two", "three", "four"]); | |
| 162 | expect(wrap("a\nb", 9)).toEqual(["a", "b"]); | |
| 163 | }); | |
| 164 | ||
| 165 | test("a lead's own text draws no escape: only the app's colours reach the pty", () => { | |
| 166 | const db = fresh(); | |
| 167 | // Straight into the file, past the action's check: the terminal holds on its own. | |
| 168 | const id = insertLead( | |
| 169 | db, | |
| 170 | { | |
| 171 | name: "Eve\x1b[2J\x1b]52;c;aGk=\x07\x1b[8m", | |
| 172 | email: "[email protected]\x1b[2J", | |
| 173 | phone: "\x9b2J", | |
| 174 | source: "website", | |
| 175 | message: "hi\x1b[2Jfake\r\nsecond line\x00", | |
| 176 | consent: false, | |
| 177 | }, | |
| 178 | new Date().toISOString(), | |
| 179 | agent, | |
| 180 | ); | |
| 181 | db.query("UPDATE message SET body = 'Hi\x1b[8m hidden\x07' WHERE lead_id = ?1").run(id); | |
| 182 | const ours = /\x1b\[[0-9;]*m/g; | |
| 183 | const t = terminal(db, root); | |
| 184 | const screens = [t.screen(100).join("\n")]; | |
| 185 | t.key("\r"); // The newest lead: Eve. | |
| 186 | screens.push(t.screen(100).join("\n")); | |
| 187 | t.key("D"); | |
| 188 | screens.push(t.screen(100).join("\n")); | |
| 189 | for (const screen of screens) { | |
| 190 | const left = screen.replace(ours, ""); | |
| 191 | expect(left).not.toContain("\x1b"); | |
| 192 | expect(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/.test(left)).toBe(false); | |
| 193 | } | |
| 194 | expect(plain(screens[1]!)).toContain("Eve[2J]52;c;aGk=[8m"); | |
| 195 | expect(plain(screens[1]!)).toContain("hi[2Jfake"); | |
| 196 | expect(plain(screens[1]!)).toContain("second line"); | |
| 197 | expect(plain(screens[1]!)).toContain("Hi[8m hidden"); | |
| 198 | }); | |
| 199 | ||
| 200 | test("clean keeps words and lines, drops every control", () => { | |
| 201 | expect(clean("a\x1b[2Jb\x07c\x9bd\te")).toBe("a[2Jbcd e"); | |
| 202 | expect(clean("one\r\ntwo")).toBe("one two"); | |
| 203 | expect(clean("one\r\ntwo", false)).toBe("one\ntwo"); | |
| 204 | }); |
src/terminal.ts added +400
| @@ -0,0 +1,400 @@ | ||
| 1 | /** | |
| 2 | * The desk as a terminal: what `src/tty.ts` draws and what each key does, | |
| 3 | * kept apart from the pty so a test can press keys and read the screen. | |
| 4 | * Every write is an action, as the page's are; nothing here decides who | |
| 5 | * may — the hints only leave out keys the table would refuse. | |
| 6 | * | |
| 7 | * Screens: | |
| 8 | * desk j/k move · enter open · n log a lead · R restart samples (admin) · esc quit | |
| 9 | * lead s approve and send · e edit, then send · q qualified · x lost · | |
| 10 | * D remove (admin) · esc back | |
| 11 | * edit type; enter is a new line · ctrl-d approve and send · esc cancel | |
| 12 | * add one field at a time; enter next · esc cancel | |
| 13 | * | |
| 14 | * Nothing is sent from a screen that has not shown it: the lead screen | |
| 15 | * shows what they asked, the words going out, the signature under them, | |
| 16 | * and whether it goes by text or email. | |
| 17 | */ | |
| 18 | ||
| 19 | import type { Database } from "bun:sqlite"; | |
| 20 | import { | |
| 21 | addLead, | |
| 22 | deleteLead, | |
| 23 | getLead, | |
| 24 | listLeads, | |
| 25 | resetSample, | |
| 26 | sendReply, | |
| 27 | setState, | |
| 28 | } from "./actions.ts"; | |
| 29 | import { between, elapsed, tone } from "./clock.ts"; | |
| 30 | import { permit } from "./contract.ts"; | |
| 31 | import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts"; | |
| 32 | import { agent, ssh, title, where } from "./env.ts"; | |
| 33 | import type { DeskLead, LeadDetail, Message } from "./leads.ts"; | |
| 34 | import type { Who } from "./who.ts"; | |
| 35 | ||
| 36 | const ESC = "\x1b["; | |
| 37 | export const dim = (s: string): string => `${ESC}2m${s}${ESC}0m`; | |
| 38 | export const bold = (s: string): string => `${ESC}1m${s}${ESC}0m`; | |
| 39 | const COLOUR = { ok: "32", warn: "33", late: "31" } as const; | |
| 40 | const paint = (code: string, s: string): string => `${ESC}${code}m${s}${ESC}0m`; | |
| 41 | ||
| 42 | /** Text without its colours: what a person reads, for a test to compare. */ | |
| 43 | export const plain = (s: string): string => | |
| 44 | s.replace(/\x1b\[[0-9;]*m/g, ""); | |
| 45 | ||
| 46 | /** | |
| 47 | * Data made safe to draw: every control character dropped (C0 but the line | |
| 48 | * break, DEL, C1), so a lead's own text can never clear, hide or rewrite | |
| 49 | * the screen the agent approves from, or reach their clipboard. The only | |
| 50 | * escapes on the screen are this module's own colours. `oneLine` drops | |
| 51 | * line breaks too, for a field drawn on one line. | |
| 52 | */ | |
| 53 | export const clean = (s: string, oneLine = true): string => | |
| 54 | s | |
| 55 | .replace(/\r\n?/g, "\n") | |
| 56 | .replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, (c) => (c === "\t" ? " " : "")) | |
| 57 | .replace(/\n/g, oneLine ? " " : "\n"); | |
| 58 | ||
| 59 | /** Words folded to `width` columns, line breaks kept, cleaned first. */ | |
| 60 | export function wrap(text: string, width: number): string[] { | |
| 61 | return clean(text, false).split("\n").flatMap((line) => { | |
| 62 | const out: string[] = []; | |
| 63 | let current = ""; | |
| 64 | for (const word of line.split(" ")) { | |
| 65 | if (current !== "" && current.length + 1 + word.length > width) { | |
| 66 | out.push(current); | |
| 67 | current = word; | |
| 68 | } else current = current === "" ? word : `${current} ${word}`; | |
| 69 | } | |
| 70 | out.push(current); | |
| 71 | return out; | |
| 72 | }); | |
| 73 | } | |
| 74 | ||
| 75 | const ADD_FIELDS = [ | |
| 76 | { key: "name", label: "Name" }, | |
| 77 | { key: "email", label: "Email" }, | |
| 78 | { key: "phone", label: "Phone (blank for none)" }, | |
| 79 | { | |
| 80 | key: "source", | |
| 81 | label: `Source — ${SOURCES.map((s, i) => `${i + 1} ${SOURCE_LABEL[s]}`).join(", ")}`, | |
| 82 | }, | |
| 83 | { key: "message", label: "What they asked" }, | |
| 84 | { key: "consent", label: "Written consent to be texted? y/n" }, | |
| 85 | ] as const; | |
| 86 | ||
| 87 | type View = | |
| 88 | | { name: "desk" } | |
| 89 | | { name: "lead"; id: number } | |
| 90 | | { name: "edit"; id: number; text: string } | |
| 91 | | { name: "add"; step: number; typed: string; fields: Record<string, string> } | |
| 92 | | { name: "confirm"; what: "remove" | "reset"; id?: number; back: View }; | |
| 93 | ||
| 94 | const titleOf = (m: Message): string => | |
| 95 | m.day === 0 ? "First reply" : `Day ${m.day} follow-up`; | |
| 96 | ||
| 97 | export interface Terminal { | |
| 98 | /** The screen as lines, for the width given. */ | |
| 99 | screen(width?: number): string[]; | |
| 100 | /** One key (or a pasted run of text) as the pty delivered it. */ | |
| 101 | key(input: string): void; | |
| 102 | /** True once the person has left. */ | |
| 103 | readonly done: boolean; | |
| 104 | } | |
| 105 | ||
| 106 | export function terminal( | |
| 107 | db: Database, | |
| 108 | me: Who, | |
| 109 | now: () => number = Date.now, | |
| 110 | ): Terminal { | |
| 111 | let view: View = { name: "desk" }; | |
| 112 | let cursor = 0; | |
| 113 | let said = ""; | |
| 114 | let done = false; | |
| 115 | const admin = (): boolean => permit(me, "lead", "delete") === "yes"; | |
| 116 | ||
| 117 | const leads = (): DeskLead[] => { | |
| 118 | const listed = listLeads(db, me); | |
| 119 | return listed.ok ? listed.value : []; | |
| 120 | }; | |
| 121 | const lead = (id: number): LeadDetail | undefined => { | |
| 122 | const found = getLead(db, me, { id }); | |
| 123 | return found.ok ? found.value : undefined; | |
| 124 | }; | |
| 125 | const ready = (l: LeadDetail): Message | undefined => | |
| 126 | l.messages.find((m) => m.status === "draft" || m.status === "due"); | |
| 127 | ||
| 128 | function clockOf(l: DeskLead | LeadDetail): string { | |
| 129 | const waiting = l.replied_at === null; | |
| 130 | const ms = waiting | |
| 131 | ? between(l.created_at, now()) | |
| 132 | : between(l.created_at, l.replied_at!); | |
| 133 | return `${paint(COLOUR[tone(ms)], elapsed(ms).padStart(7))} ${waiting ? "waiting " : "answered"}`; | |
| 134 | } | |
| 135 | ||
| 136 | function header(): string[] { | |
| 137 | return [ | |
| 138 | `${bold(title)} ${clean(agent.name)} · ${clean(agent.brokerage)} ${dim(clean(where))} ${dim(me.role === "anon" ? "guest" : clean(me.name))}`, | |
| 139 | ssh === undefined ? "" : dim(`connect: ${ssh}`), | |
| 140 | "", | |
| 141 | ]; | |
| 142 | } | |
| 143 | ||
| 144 | function deskScreen(): string[] { | |
| 145 | const listed = listLeads(db, me); | |
| 146 | if (!listed.ok) | |
| 147 | return [listed.message, "", dim("esc quit")]; | |
| 148 | const rows = listed.value; | |
| 149 | cursor = Math.min(cursor, Math.max(0, rows.length - 1)); | |
| 150 | const lines: string[] = []; | |
| 151 | if (rows.length === 0) lines.push(dim("No leads yet. Press n to log one.")); | |
| 152 | rows.forEach((l, i) => { | |
| 153 | const next = | |
| 154 | l.ready === null | |
| 155 | ? dim(l.state === "qualified" || l.state === "lost" ? l.state : "") | |
| 156 | : l.ready.day === 0 | |
| 157 | ? "reply drafted" | |
| 158 | : `day ${l.ready.day} follow-up ready`; | |
| 159 | const name = clean(l.name).padEnd(18).slice(0, 18); | |
| 160 | lines.push( | |
| 161 | `${i === cursor ? "▸" : " "} ${clockOf(l)} ${i === cursor ? bold(name) : name} ${dim(SOURCE_LABEL[l.source].padEnd(12))} ${next}`, | |
| 162 | ); | |
| 163 | }); | |
| 164 | lines.push( | |
| 165 | "", | |
| 166 | dim( | |
| 167 | `j/k move · enter open · n log a lead${admin() ? " · R restart the samples" : ""} · esc quit`, | |
| 168 | ), | |
| 169 | ); | |
| 170 | return lines; | |
| 171 | } | |
| 172 | ||
| 173 | function leadScreen(id: number, width: number, editing?: string): string[] { | |
outdated
High: |
||
| 174 | const l = lead(id); | |
| 175 | if (l === undefined) { | |
| 176 | view = { name: "desk" }; | |
| 177 | return deskScreen(); | |
| 178 | } | |
| 179 | const r = ready(l); | |
| 180 | const channel = channelFor(l); | |
| 181 | const lines = [ | |
| 182 | `${bold(clean(l.name))} ${SOURCE_LABEL[l.source]} · ${channel === "text" ? "Text OK" : "Email only"} · ${l.state} ${clockOf(l)}`, | |
| 183 | dim([l.email, l.phone].filter((s) => s !== "").map((s) => clean(s)).join(" · ")), | |
| 184 | "", | |
| 185 | bold("They asked"), | |
| 186 | ...wrap(l.message, width).map((s) => ` ${s}`), | |
| 187 | "", | |
| 188 | ]; | |
| 189 | if (r === undefined) { | |
| 190 | const next = l.messages.find((m) => m.status === "scheduled"); | |
| 191 | lines.push( | |
| 192 | dim( | |
| 193 | l.state === "qualified" || l.state === "lost" | |
| 194 | ? `Marked ${l.state}: out of the follow-up plan.` | |
| 195 | : next !== undefined | |
| 196 | ? `Nothing to send now. ${titleOf(next)} comes due ${next.due_at.slice(0, 10)}.` | |
| 197 | : "Every follow-up has gone out.", | |
| 198 | ), | |
| 199 | ); | |
| 200 | } else { | |
| 201 | lines.push( | |
| 202 | bold( | |
| 203 | `${titleOf(r)} — by ${r.channel}${editing === undefined ? ", as it will go" : ", editing"}`, | |
| 204 | ), | |
| 205 | ); | |
| 206 | if (r.channel === "email") | |
| 207 | lines.push( | |
| 208 | dim( | |
| 209 | l.consent | |
| 210 | ? " Email only: no phone number to text." | |
| 211 | : " Email only: no written consent to text.", | |
| 212 | ), | |
| 213 | ); | |
| 214 | const body = editing === undefined ? r.body : `${editing}█`; | |
| 215 | lines.push( | |
| 216 | ...wrap(body, width).map((s) => ` ${s}`), | |
| 217 | ...wrap(r.signature, width).map((s) => dim(` ${s}`)), | |
| 218 | ); | |
| 219 | } | |
| 220 | const sent = l.messages.filter((m) => m.status === "sent").length; | |
| 221 | lines.push( | |
| 222 | "", | |
| 223 | dim( | |
| 224 | `${sent} sent · plan: ${l.messages | |
| 225 | .filter((m) => m.day > 0) | |
| 226 | .map((m) => `day ${m.day} ${m.status}`) | |
| 227 | .join(", ") || "starts with the first reply"}`, | |
| 228 | ), | |
| 229 | "", | |
| 230 | editing !== undefined | |
| 231 | ? dim("type to edit · enter new line · ctrl-d approve and send · esc cancel") | |
| 232 | : dim( | |
| 233 | [ | |
| 234 | ...(r === undefined ? [] : ["s approve and send", "e edit"]), | |
| 235 | ...(l.state === "qualified" || l.state === "lost" | |
| 236 | ? [] | |
| 237 | : ["q qualified", "x lost"]), | |
| 238 | ...(admin() ? ["D remove"] : []), | |
| 239 | "esc back", | |
| 240 | ].join(" · "), | |
| 241 | ), | |
| 242 | ); | |
| 243 | return lines; | |
| 244 | } | |
| 245 | ||
| 246 | function addScreen(v: Extract<View, { name: "add" }>): string[] { | |
| 247 | const lines = [bold("Log a lead by hand"), ""]; | |
| 248 | ADD_FIELDS.forEach((field, i) => { | |
| 249 | if (i < v.step) lines.push(`${field.label}: ${clean(v.fields[field.key] ?? "")}`); | |
| 250 | if (i === v.step) lines.push(`${field.label}: ${clean(v.typed)}█`); | |
| 251 | }); | |
| 252 | lines.push("", dim("enter next · esc cancel")); | |
| 253 | return lines; | |
| 254 | } | |
| 255 | ||
| 256 | function send(id: number, body?: string): void { | |
| 257 | const sent = sendReply(db, me, { id, body }); | |
| 258 | said = sent.ok ? `Sent to ${sent.value.name}.` : sent.message; | |
| 259 | view = { name: "lead", id }; | |
| 260 | } | |
| 261 | ||
| 262 | function finishAdd(fields: Record<string, string>): void { | |
| 263 | const pick = Number(fields.source); | |
| 264 | const added = addLead(db, me, { | |
| 265 | ...fields, | |
| 266 | source: SOURCES[pick - 1] ?? fields.source, | |
| 267 | consent: /^y/i.test(fields.consent ?? ""), | |
| 268 | }); | |
| 269 | if (added.ok) { | |
| 270 | said = `${added.value.name} is on the desk; the first reply is drafted.`; | |
| 271 | view = { name: "lead", id: added.value.id }; | |
| 272 | } else { | |
| 273 | said = added.message; | |
| 274 | view = { name: "desk" }; | |
| 275 | } | |
| 276 | } | |
| 277 | ||
| 278 | function typing(text: string, input: string): string | undefined { | |
| 279 | if (input === "\x7f" || input === "\b") return text.slice(0, -1); | |
| 280 | // Printable text, typed or pasted; control keys are not words. | |
| 281 | if (!/[\x00-\x1f\x7f]/.test(input)) return text + input; | |
| 282 | return undefined; | |
| 283 | } | |
| 284 | ||
| 285 | return { | |
| 286 | get done() { | |
| 287 | return done; | |
| 288 | }, | |
| 289 | screen(width = 80) { | |
| 290 | const w = Math.max(30, width - 4); | |
| 291 | const body = | |
| 292 | view.name === "desk" | |
| 293 | ? deskScreen() | |
| 294 | : view.name === "lead" | |
| 295 | ? leadScreen(view.id, w) | |
| 296 | : view.name === "edit" | |
| 297 | ? leadScreen(view.id, w, view.text) | |
| 298 | : view.name === "add" | |
| 299 | ? addScreen(view) | |
| 300 | : [ | |
| 301 | view.what === "reset" | |
| 302 | ? "Restart the sample leads from now? Every lead on the desk is replaced." | |
| 303 | : `Remove ${clean(lead(view.id ?? 0)?.name ?? "this lead")} and everything said to them?`, | |
| 304 | "", | |
| 305 | dim("y yes · any other key no"), | |
| 306 | ]; | |
| 307 | return [...header(), ...body, ...(said === "" ? [] : ["", clean(said)])]; | |
| 308 | }, | |
| 309 | key(input) { | |
| 310 | said = ""; | |
| 311 | if (input === "\x03") { | |
| 312 | done = true; | |
| 313 | return; | |
| 314 | } | |
| 315 | switch (view.name) { | |
| 316 | case "desk": { | |
| 317 | const rows = leads(); | |
| 318 | if (input === "\x1b") done = true; | |
| 319 | else if (input === "j" || input === "\x1b[B") | |
| 320 | cursor = Math.min(cursor + 1, Math.max(0, rows.length - 1)); | |
| 321 | else if (input === "k" || input === "\x1b[A") | |
| 322 | cursor = Math.max(cursor - 1, 0); | |
| 323 | else if (input === "\r" && rows[cursor] !== undefined) | |
| 324 | view = { name: "lead", id: rows[cursor]!.id }; | |
| 325 | else if (input === "n") | |
| 326 | view = { name: "add", step: 0, typed: "", fields: {} }; | |
| 327 | else if (input === "R") | |
| 328 | view = { name: "confirm", what: "reset", back: view }; | |
| 329 | return; | |
| 330 | } | |
| 331 | case "lead": { | |
| 332 | const id = view.id; | |
| 333 | const l = lead(id); | |
| 334 | if (input === "\x1b" || input === "\x7f") view = { name: "desk" }; | |
| 335 | else if (l === undefined) view = { name: "desk" }; | |
| 336 | else if (input === "s") send(id); | |
Same point as on the page: |
||
| 337 | else if (input === "e") { | |
| 338 | const r = ready(l); | |
| 339 | if (r === undefined) said = "Nothing is waiting to go to this lead right now."; | |
| 340 | else view = { name: "edit", id, text: r.body }; | |
| 341 | } else if (input === "q" || input === "x") { | |
| 342 | const marked = setState(db, me, { | |
| 343 | id, | |
| 344 | state: input === "q" ? "qualified" : "lost", | |
| 345 | }); | |
| 346 | said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message; | |
| 347 | } else if (input === "D") | |
| 348 | view = { name: "confirm", what: "remove", id, back: view }; | |
| 349 | return; | |
| 350 | } | |
| 351 | case "edit": { | |
| 352 | if (input === "\x1b") { | |
| 353 | said = "Edit cancelled; nothing sent."; | |
| 354 | view = { name: "lead", id: view.id }; | |
| 355 | } else if (input === "\x04") send(view.id, view.text); | |
| 356 | else if (input === "\r") view = { ...view, text: `${view.text}\n` }; | |
| 357 | else { | |
| 358 | const next = typing(view.text, input.replace(/\r\n?/g, "\n")); | |
| 359 | if (next !== undefined) view = { ...view, text: next }; | |
| 360 | } | |
| 361 | return; | |
| 362 | } | |
| 363 | case "add": { | |
| 364 | if (input === "\x1b") { | |
| 365 | said = "Nothing logged."; | |
| 366 | view = { name: "desk" }; | |
| 367 | } else if (input === "\r") { | |
| 368 | const field = ADD_FIELDS[view.step]!; | |
| 369 | const fields = { ...view.fields, [field.key]: view.typed.trim() }; | |
| 370 | if (view.step + 1 < ADD_FIELDS.length) | |
| 371 | view = { name: "add", step: view.step + 1, typed: "", fields }; | |
| 372 | else finishAdd(fields); | |
| 373 | } else { | |
| 374 | const next = typing(view.typed, input); | |
| 375 | if (next !== undefined) view = { ...view, typed: next }; | |
| 376 | } | |
| 377 | return; | |
| 378 | } | |
| 379 | case "confirm": { | |
| 380 | const { what, id, back } = view; | |
| 381 | if (input !== "y") { | |
| 382 | view = back; | |
| 383 | return; | |
| 384 | } | |
| 385 | if (what === "reset") { | |
| 386 | const reset = resetSample(db, me); | |
| 387 | said = reset.ok ? "The sample leads start again from now." : reset.message; | |
| 388 | cursor = 0; | |
| 389 | view = { name: "desk" }; | |
| 390 | } else { | |
| 391 | const removed = deleteLead(db, me, { id: id ?? 0 }); | |
| 392 | said = removed.ok ? "Removed." : removed.message; | |
| 393 | view = removed.ok ? { name: "desk" } : back; | |
| 394 | } | |
| 395 | return; | |
| 396 | } | |
| 397 | } | |
| 398 | }, | |
| 399 | }; | |
| 400 | } |
src/tty.ts +15 −94
| @@ -1,115 +1,36 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The app in a terminal. The forge runs this on a pty when someone |
| 3 | 3 | * `ssh`es to the app, over the same data as the page and through the same |
| 4 | * actions, as the account at the keyboard. j/k move, a adds, d removes the | |
| 5 | * note under the cursor, q leaves. Plain ANSI, no dependencies. | |
| 4 | * actions, as the account at the keyboard. What each screen shows and | |
| 5 | * each key does is `src/terminal.ts`; this file is only the pty: raw keys | |
| 6 | * in, the screen out, redrawn every second so the clocks tick and what | |
| 7 | * others do on the page shows here. | |
| 6 | 8 | */ |
| 7 | 9 | |
| 8 | import { | |
| 9 | addNote, | |
| 10 | canDelete, | |
| 11 | deleteNote, | |
| 12 | listNotes, | |
| 13 | type Note, | |
| 14 | } from "./actions.ts"; | |
| 15 | 10 | import { openDb } from "./db.ts"; |
| 16 | import { ssh, title, where } from "./env.ts"; | |
| 11 | import { terminal } from "./terminal.ts"; | |
| 17 | 12 | import { whoAtTty } from "./who.ts"; |
| 18 | 13 | |
| 19 | const db = openDb(); | |
| 20 | const me = whoAtTty(); | |
| 21 | const esc = "\x1b["; | |
| 22 | const dim = (s: string): string => `${esc}2m${s}${esc}0m`; | |
| 23 | const bold = (s: string): string => `${esc}1m${s}${esc}0m`; | |
| 14 | const term = terminal(openDb(), whoAtTty()); | |
| 24 | 15 | const out = (s: string): void => { |
| 25 | 16 | process.stdout.write(s); |
| 26 | 17 | }; |
| 27 | ||
| 28 | let cursor = 0; | |
| 29 | let typing: string | undefined; | |
| 30 | let said = ""; | |
| 31 | ||
| 32 | const notes = (): Note[] => { | |
| 33 | const listed = listNotes(db, me); | |
| 34 | return listed.ok ? listed.value : []; | |
| 35 | }; | |
| 36 | ||
| 37 | function draw(): void { | |
| 38 | const rows = notes(); | |
| 39 | const lines = [ | |
| 40 | `${bold(title)} ${dim(where)} ${dim(me.role === "anon" ? "guest" : `${me.name}${me.role === "admin" ? " (admin)" : ""}`)}`, | |
| 41 | ssh === undefined ? "" : dim(`connect: ${ssh}`), | |
| 42 | "", | |
| 43 | ]; | |
| 44 | if (rows.length === 0) | |
| 45 | lines.push( | |
| 46 | dim( | |
| 47 | me.role === "anon" | |
| 48 | ? "No notes yet." | |
| 49 | : "No notes yet. Press a to add one.", | |
| 50 | ), | |
| 51 | ); | |
| 52 | rows.forEach((note, i) => { | |
| 53 | const body = i === cursor ? bold(note.body) : note.body; | |
| 54 | lines.push( | |
| 55 | `${i === cursor ? "▸" : " "} ${body} ${dim(`${note.author_name} · ${note.created_at.slice(0, 16).replace("T", " ")}`)}`, | |
| 56 | ); | |
| 57 | }); | |
| 58 | lines.push(""); | |
| 59 | if (typing !== undefined) lines.push(`New note: ${typing}${esc}7m ${esc}0m`); | |
| 60 | else if (said !== "") lines.push(said); | |
| 61 | else | |
| 62 | lines.push( | |
| 63 | dim( | |
| 64 | me.role === "anon" | |
| 65 | ? "j/k move · q quit · sign in with a key the forge knows to add" | |
| 66 | : "j/k move · a add · d delete · q quit", | |
| 67 | ), | |
| 68 | ); | |
| 69 | out(`${esc}2J${esc}H${lines.join("\r\n")}`); | |
| 70 | } | |
| 18 | const draw = (): void => | |
| 19 | out( | |
| 20 | `\x1b[2J\x1b[H${term.screen(process.stdout.columns ?? 80).join("\r\n")}`, | |
| 21 | ); | |
| 71 | 22 | |
| 72 | 23 | process.stdin.setRawMode?.(true); |
| 73 | 24 | process.stdin.resume(); |
| 74 | 25 | process.stdin.setEncoding("utf8"); |
| 75 | 26 | draw(); |
| 76 | process.stdin.on("data", (key: string) => { | |
| 77 | said = ""; | |
| 78 | if (typing !== undefined) { | |
| 79 | if (key === "\r") { | |
| 80 | const added = addNote(db, me, { body: typing }); | |
| 81 | if (!added.ok) said = added.message; | |
| 82 | typing = undefined; | |
| 83 | cursor = 0; | |
| 84 | } else if (key === "\x1b") typing = undefined; | |
| 85 | else if (key === "\x7f") typing = typing.slice(0, -1); | |
| 86 | else if (key >= " ") typing += key; | |
| 87 | draw(); | |
| 88 | return; | |
| 89 | } | |
| 90 | if (key === "q" || key === "\x03") { | |
| 91 | out(`${esc}2J${esc}H`); | |
| 27 | setInterval(draw, 1000).unref(); | |
| 28 | process.stdin.on("data", (input: string) => { | |
| 29 | term.key(input); | |
| 30 | if (term.done) { | |
| 31 | out("\x1b[2J\x1b[H"); | |
| 92 | 32 | process.exit(0); |
| 93 | 33 | } |
| 94 | const rows = notes(); | |
| 95 | if (key === "j" || key === "\x1b[B") | |
| 96 | cursor = Math.min(cursor + 1, Math.max(0, rows.length - 1)); | |
| 97 | if (key === "k" || key === "\x1b[A") cursor = Math.max(cursor - 1, 0); | |
| 98 | if (key === "a") { | |
| 99 | if (me.role === "anon") said = "Sign in to add a note."; | |
| 100 | else typing = ""; | |
| 101 | } | |
| 102 | if (key === "d") { | |
| 103 | const note = rows[cursor]; | |
| 104 | if (note === undefined) said = "Nothing to remove."; | |
| 105 | else if (!canDelete(me, note)) | |
| 106 | said = "Only the author or an admin can remove a note."; | |
| 107 | else { | |
| 108 | const removed = deleteNote(db, me, { id: note.id }); | |
| 109 | if (!removed.ok) said = removed.message; | |
| 110 | cursor = Math.min(cursor, Math.max(0, rows.length - 2)); | |
| 111 | } | |
| 112 | } | |
| 113 | 34 | draw(); |
| 114 | 35 | }); |
| 115 | 36 | process.stdout.on("resize", draw); |
static/app.css +403 −56
| @@ -15,24 +15,50 @@ body { | ||
| 15 | 15 | font: var() / var() var(); |
| 16 | 16 | } |
| 17 | 17 | .page { |
| 18 | max-width: 40rem; | |
| 18 | max-width: 60rem; | |
| 19 | 19 | margin: 0 auto; |
| 20 | padding: var() var() var(); | |
| 20 | padding: var() var() var(); | |
| 21 | 21 | } |
| 22 | 22 | .head { |
| 23 | 23 | display: flex; |
| 24 | 24 | flex-wrap: wrap; |
| 25 | 25 | justify-content: space-between; |
| 26 | align-items: flex-start; | |
| 26 | align-items: center; | |
| 27 | 27 | gap: var() var(); |
| 28 | padding-bottom: var(); | |
| 28 | 29 | margin-bottom: var(); |
| 30 | border-bottom: 1px solid var(); | |
| 31 | } | |
| 32 | .brand { | |
| 33 | display: grid; | |
| 34 | color: inherit; | |
| 35 | text-decoration: none; | |
| 36 | line-height: var(); | |
| 37 | } | |
| 38 | .agent { | |
| 39 | font-family: var(); | |
| 40 | font-size: var(); | |
| 41 | font-weight: 600; | |
| 42 | } | |
| 43 | .brokerage { | |
| 44 | color: var(); | |
| 45 | font-size: var(); | |
| 46 | letter-spacing: 0.06em; | |
| 47 | text-transform: uppercase; | |
| 48 | } | |
| 49 | h1, | |
| 50 | h2 { | |
| 51 | margin: 0; | |
| 52 | font-family: var(); | |
| 53 | font-weight: 600; | |
| 54 | line-height: var(); | |
| 29 | 55 | } |
| 30 | 56 | h1 { |
| 31 | margin: 0; | |
| 32 | font-size: var(); | |
| 33 | font-weight: 650; | |
| 34 | letter-spacing: -0.01em; | |
| 35 | line-height: var(); | |
| 57 | font-size: var(); | |
| 58 | } | |
| 59 | h2 { | |
| 60 | font-size: var(); | |
| 61 | margin-bottom: var(); | |
| 36 | 62 | } |
| 37 | 63 | p { |
| 38 | 64 | margin: 0; |
| @@ -42,57 +68,41 @@ a { | ||
| 42 | 68 | text-decoration-thickness: 1px; |
| 43 | 69 | text-underline-offset: 0.15em; |
| 44 | 70 | } |
| 45 | code, | |
| 46 | .mono { | |
| 47 | font-family: var(); | |
| 48 | font-size: var(); | |
| 49 | } | |
| 50 | 71 | :focus-visible { |
| 51 | 72 | outline: 2px solid var(); |
| 52 | 73 | outline-offset: 2px; |
| 53 | 74 | } |
| 54 | 75 | .muted { |
| 55 | 76 | color: var(); |
| 77 | font-weight: 400; | |
| 56 | 78 | } |
| 57 | 79 | .you { |
| 58 | 80 | color: var(); |
| 59 | 81 | white-space: nowrap; |
| 60 | 82 | } |
| 61 | ||
| 62 | /* Blocks. */ | |
| 63 | .card { | |
| 64 | background: var(); | |
| 65 | border: 1px solid var(); | |
| 66 | border-radius: var(); | |
| 67 | padding: var(); | |
| 68 | margin-bottom: var(); | |
| 83 | .sr { | |
| 84 | position: absolute; | |
| 85 | width: 1px; | |
| 86 | height: 1px; | |
| 87 | overflow: hidden; | |
| 88 | clip-path: inset(50%); | |
| 89 | white-space: nowrap; | |
| 69 | 90 | } |
| 70 | 91 | .row { |
| 71 | 92 | display: flex; |
| 72 | 93 | align-items: center; |
| 73 | 94 | gap: var(); |
| 74 | 95 | } |
| 75 | .list { | |
| 76 | list-style: none; | |
| 77 | margin: 0; | |
| 78 | padding: 0; | |
| 79 | } | |
| 80 | .note { | |
| 81 | display: flex; | |
| 82 | justify-content: space-between; | |
| 83 | align-items: flex-start; | |
| 96 | .stack { | |
| 97 | display: grid; | |
| 84 | 98 | gap: var(); |
| 85 | padding: var() 0; | |
| 86 | border-top: 1px solid var(); | |
| 87 | 99 | } |
| 88 | .note:first-child { | |
| 89 | border-top: 0; | |
| 90 | } | |
| 91 | .note p { | |
| 92 | overflow-wrap: anywhere; | |
| 93 | } | |
| 94 | .note small { | |
| 95 | font-size: var(); | |
| 100 | .card { | |
| 101 | background: var(); | |
| 102 | border: 1px solid var(); | |
| 103 | border-radius: var(); | |
| 104 | padding: var(); | |
| 105 | margin-top: var(); | |
| 96 | 106 | } |
| 97 | 107 | .empty { |
| 98 | 108 | padding: var() var(); |
| @@ -103,22 +113,366 @@ code, | ||
| 103 | 113 | } |
| 104 | 114 | footer { |
| 105 | 115 | margin-top: var(); |
| 116 | padding-top: var(); | |
| 117 | border-top: 1px solid var(); | |
| 106 | 118 | font-size: var(); |
| 107 | 119 | display: grid; |
| 108 | 120 | gap: var(); |
| 109 | 121 | } |
| 110 | footer code { | |
| 122 | ||
| 123 | /* The welcome, for whoever has not signed in. */ | |
| 124 | .welcome { | |
| 125 | display: grid; | |
| 126 | gap: var(); | |
| 127 | max-width: 34rem; | |
| 128 | padding: var() 0; | |
| 129 | } | |
| 130 | ||
| 131 | /* The desk. */ | |
| 132 | .desk-head { | |
| 133 | display: flex; | |
| 134 | flex-wrap: wrap; | |
| 135 | align-items: baseline; | |
| 136 | justify-content: space-between; | |
| 137 | gap: var() var(); | |
| 138 | margin-bottom: var(); | |
| 139 | } | |
| 140 | .summary { | |
| 141 | color: var(); | |
| 142 | } | |
| 143 | .summary b { | |
| 144 | color: var(); | |
| 145 | } | |
| 146 | .desk { | |
| 147 | list-style: none; | |
| 148 | margin: 0; | |
| 149 | padding: 0; | |
| 150 | background: var(); | |
| 151 | border: 1px solid var(); | |
| 152 | border-radius: var(); | |
| 153 | } | |
| 154 | .desk li + li { | |
| 155 | border-top: 1px solid var(); | |
| 156 | } | |
| 157 | .lead-row { | |
| 158 | display: grid; | |
| 159 | grid-template-columns: minmax(0, 1fr) auto; | |
| 160 | align-items: center; | |
| 161 | gap: var(); | |
| 162 | min-height: var(); | |
| 163 | padding: var() var(); | |
| 164 | color: inherit; | |
| 165 | text-decoration: none; | |
| 166 | } | |
| 167 | .lead-row:hover { | |
| 168 | background: var(); | |
| 169 | } | |
| 170 | .lead-row[data-closed] { | |
| 171 | opacity: 0.72; | |
| 172 | } | |
| 173 | .lead-main { | |
| 174 | display: grid; | |
| 175 | gap: var(); | |
| 176 | min-width: 0; | |
| 177 | } | |
| 178 | .lead-name { | |
| 179 | font-family: var(); | |
| 180 | font-size: var(); | |
| 181 | font-weight: 600; | |
| 182 | line-height: var(); | |
| 183 | } | |
| 184 | .ask { | |
| 185 | color: var(); | |
| 186 | display: -webkit-box; | |
| 187 | -webkit-line-clamp: 2; | |
| 188 | -webkit-box-orient: vertical; | |
| 189 | overflow: hidden; | |
| 111 | 190 | overflow-wrap: anywhere; |
| 112 | 191 | } |
| 192 | .status { | |
| 193 | font-size: var(); | |
| 194 | color: var(); | |
| 195 | } | |
| 196 | .status[data-ready] { | |
| 197 | color: var(); | |
| 198 | font-weight: 600; | |
| 199 | } | |
| 200 | .tags { | |
| 201 | display: flex; | |
| 202 | flex-wrap: wrap; | |
| 203 | gap: var() var(); | |
| 204 | } | |
| 205 | .chip, | |
| 206 | .badge { | |
| 207 | display: inline-block; | |
| 208 | padding: 0.05rem 0.55rem; | |
| 209 | font-size: var(); | |
| 210 | font-weight: 600; | |
| 211 | border-radius: var(); | |
| 212 | border: 1px solid var(); | |
| 213 | color: var(); | |
| 214 | white-space: nowrap; | |
| 215 | } | |
| 216 | .badge[data-consent="text"] { | |
| 217 | color: var(); | |
| 218 | background: var(); | |
| 219 | border-color: transparent; | |
| 220 | } | |
| 221 | .badge[data-consent="email"] { | |
| 222 | color: var(); | |
| 223 | background: var(); | |
| 224 | border-color: transparent; | |
| 225 | } | |
| 226 | .chip[data-state="qualified"] { | |
| 227 | color: var(); | |
| 228 | border-color: currentColor; | |
| 229 | } | |
| 230 | .chip[data-state="lost"] { | |
| 231 | color: var(); | |
| 232 | border-color: currentColor; | |
| 233 | } | |
| 234 | ||
| 235 | /* The clock: the hero of every row. Fixed width and tabular figures, so a | |
| 236 | ticking second never moves anything. */ | |
| 237 | .clock { | |
| 238 | display: grid; | |
| 239 | justify-items: end; | |
| 240 | min-width: 6.5ch; | |
| 241 | padding: var() var(); | |
| 242 | border-radius: var(); | |
| 243 | font-variant-numeric: tabular-nums; | |
| 244 | line-height: var(); | |
| 245 | text-align: right; | |
| 246 | } | |
| 247 | .clock small { | |
| 248 | font-size: var(); | |
| 249 | font-weight: 600; | |
| 250 | letter-spacing: 0.04em; | |
| 251 | text-transform: uppercase; | |
| 252 | } | |
| 253 | .clock-time { | |
| 254 | font-size: var(); | |
| 255 | font-weight: 700; | |
| 256 | white-space: nowrap; | |
| 257 | } | |
| 258 | .clock-done .clock-time { | |
| 259 | font-size: var(); | |
| 260 | } | |
| 261 | .clock[data-tone="ok"] { | |
| 262 | color: var(); | |
| 263 | background: var(); | |
| 264 | } | |
| 265 | .clock[data-tone="warn"] { | |
| 266 | color: var(); | |
| 267 | background: var(); | |
| 268 | } | |
| 269 | .clock[data-tone="late"] { | |
| 270 | color: var(); | |
| 271 | background: var(); | |
| 272 | } | |
| 273 | .clock-done { | |
| 274 | background: transparent ; | |
| 275 | } | |
| 276 | ||
| 277 | /* A lead. */ | |
| 278 | .backlink { | |
| 279 | display: inline-flex; | |
| 280 | align-items: center; | |
| 281 | min-height: var(); | |
| 282 | } | |
| 283 | .lead-head { | |
| 284 | display: flex; | |
| 285 | flex-wrap: wrap; | |
| 286 | justify-content: space-between; | |
| 287 | align-items: flex-start; | |
| 288 | gap: var(); | |
| 289 | margin-bottom: var(); | |
| 290 | } | |
| 291 | .lead-head > div { | |
| 292 | display: grid; | |
| 293 | gap: var(); | |
| 294 | } | |
| 295 | .contact { | |
| 296 | overflow-wrap: anywhere; | |
| 297 | } | |
| 298 | .split { | |
| 299 | display: grid; | |
| 300 | gap: var(); | |
| 301 | } | |
| 302 | @media (min-width: 48rem) { | |
| 303 | .split { | |
| 304 | grid-template-columns: 1fr 1.25fr; | |
| 305 | align-items: start; | |
| 306 | } | |
| 307 | } | |
| 308 | .pane { | |
| 309 | background: var(); | |
| 310 | border: 1px solid var(); | |
| 311 | border-radius: var(); | |
| 312 | padding: var(); | |
| 313 | } | |
| 314 | .ours.ready { | |
| 315 | border-color: var(); | |
| 316 | } | |
| 317 | blockquote { | |
| 318 | margin: 0; | |
| 319 | padding-left: var(); | |
| 320 | border-left: 3px solid var(); | |
| 321 | font-family: var(); | |
| 322 | font-size: var(); | |
| 323 | overflow-wrap: anywhere; | |
| 324 | } | |
| 325 | .body { | |
| 326 | white-space: pre-line; | |
| 327 | overflow-wrap: anywhere; | |
| 328 | } | |
| 329 | .sig { | |
| 330 | margin-top: var(); | |
| 331 | padding-top: var(); | |
| 332 | border-top: 1px dashed var(); | |
| 333 | color: var(); | |
| 334 | font-size: var(); | |
| 335 | white-space: pre-line; | |
| 336 | } | |
| 337 | .hint { | |
| 338 | margin-top: var(); | |
| 339 | color: var(); | |
| 340 | font-size: var(); | |
| 341 | } | |
| 342 | .actions { | |
| 343 | display: flex; | |
| 344 | flex-wrap: wrap; | |
| 345 | gap: var(); | |
| 346 | margin-top: var(); | |
| 347 | } | |
| 348 | .edit summary { | |
| 349 | list-style: none; | |
| 350 | } | |
| 351 | .edit summary::-webkit-details-marker { | |
| 352 | display: none; | |
| 353 | } | |
| 354 | .edit[open] summary { | |
| 355 | display: none; | |
| 356 | } | |
| 357 | .edit[open] { | |
| 358 | flex-basis: 100%; | |
| 359 | } | |
| 360 | /* Edit opens the text in place: the draft gives way to the box that holds it. */ | |
| 361 | .ready:has(.edit[open]) .draft-view, | |
| 362 | .ready:has(.edit[open]) .actions > form:first-child { | |
| 363 | display: none; | |
| 364 | } | |
| 365 | textarea.input { | |
| 366 | padding: var(); | |
| 367 | resize: vertical; | |
| 368 | line-height: var(); | |
| 369 | } | |
| 370 | .thread, | |
| 371 | .plan { | |
| 372 | list-style: none; | |
| 373 | margin: 0; | |
| 374 | padding: 0; | |
| 375 | display: grid; | |
| 376 | gap: var(); | |
| 377 | } | |
| 378 | .thread li + li { | |
| 379 | padding-top: var(); | |
| 380 | border-top: 1px solid var(); | |
| 381 | } | |
| 382 | .meta { | |
| 383 | color: var(); | |
| 384 | font-size: var(); | |
| 385 | margin-bottom: var(); | |
| 386 | } | |
| 387 | .plan li { | |
| 388 | display: grid; | |
| 389 | grid-template-columns: 4.5rem 1fr auto; | |
| 390 | align-items: baseline; | |
| 391 | gap: var() var(); | |
| 392 | } | |
| 393 | .plan-day { | |
| 394 | font-weight: 700; | |
| 395 | } | |
| 396 | .plan-when { | |
| 397 | color: var(); | |
| 398 | } | |
| 399 | .plan-status { | |
| 400 | font-size: var(); | |
| 401 | font-weight: 600; | |
| 402 | color: var(); | |
| 403 | } | |
| 404 | .plan [data-status="sent"] .plan-status { | |
| 405 | color: var(); | |
| 406 | } | |
| 407 | .plan [data-status="due"] .plan-status { | |
| 408 | color: var(); | |
| 409 | } | |
| 410 | .plan [data-status="skipped"] { | |
| 411 | color: var(); | |
| 412 | text-decoration: line-through; | |
| 413 | } | |
| 414 | .peek { | |
| 415 | grid-column: 1 / -1; | |
| 416 | font-size: var(); | |
| 417 | } | |
| 418 | .peek summary { | |
| 419 | cursor: pointer; | |
| 420 | color: var(); | |
| 421 | min-height: var(); | |
| 422 | display: flex; | |
| 423 | align-items: center; | |
| 424 | } | |
| 425 | .states { | |
| 426 | display: flex; | |
| 427 | flex-wrap: wrap; | |
| 428 | gap: var(); | |
| 429 | margin-top: var(); | |
| 430 | } | |
| 431 | ||
| 432 | /* Logging a lead by hand. */ | |
| 433 | .add summary { | |
| 434 | cursor: pointer; | |
| 435 | font-weight: 600; | |
| 436 | min-height: var(); | |
| 437 | display: flex; | |
| 438 | align-items: center; | |
| 439 | } | |
| 440 | .add form { | |
| 441 | margin-top: var(); | |
| 442 | } | |
| 443 | label { | |
| 444 | display: grid; | |
| 445 | gap: var(); | |
| 446 | font-size: var(); | |
| 447 | font-weight: 600; | |
| 448 | } | |
| 449 | label.check { | |
| 450 | display: flex; | |
| 451 | align-items: center; | |
| 452 | gap: var(); | |
| 453 | min-height: var(); | |
| 454 | font-weight: 400; | |
| 455 | font-size: var(); | |
| 456 | } | |
| 457 | label.check input { | |
| 458 | width: 1.25rem; | |
| 459 | height: 1.25rem; | |
| 460 | accent-color: var(); | |
| 461 | } | |
| 462 | .reset { | |
| 463 | margin-top: var(); | |
| 464 | } | |
| 113 | 465 | |
| 114 | 466 | /* Controls: at least 44px on a side, keyboard and mouse alike. */ |
| 115 | 467 | .input { |
| 116 | flex: 1; | |
| 468 | width: 100%; | |
| 469 | box-sizing: border-box; | |
| 117 | 470 | min-width: 0; |
| 118 | 471 | min-height: var(); |
| 119 | 472 | padding: 0 var(); |
| 120 | 473 | font: inherit; |
| 121 | 474 | font-size: max(16px, var()); |
| 475 | font-weight: 400; | |
| 122 | 476 | color: inherit; |
| 123 | 477 | background: var(); |
| 124 | 478 | border: 1px solid var(); |
| @@ -141,32 +495,24 @@ footer code { | ||
| 141 | 495 | text-decoration: none; |
| 142 | 496 | display: inline-flex; |
| 143 | 497 | align-items: center; |
| 498 | justify-content: center; | |
| 144 | 499 | } |
| 145 | 500 | .button:hover { |
| 146 | 501 | filter: brightness(1.08); |
| 147 | 502 | } |
| 148 | 503 | .button-quiet { |
| 149 | color: var(); | |
| 504 | color: var(); | |
| 150 | 505 | background: transparent; |
| 506 | border-color: var(); | |
| 151 | 507 | padding: 0 var(); |
| 152 | 508 | } |
| 153 | 509 | .button-quiet:hover { |
| 154 | color: var(); | |
| 155 | border-color: var(); | |
| 510 | border-color: var(); | |
| 156 | 511 | filter: none; |
| 157 | 512 | } |
| 158 | .pill { | |
| 159 | display: inline-block; | |
| 160 | padding: 0.1rem 0.6rem; | |
| 161 | font-size: var(); | |
| 162 | font-weight: 600; | |
| 513 | .head .button-quiet { | |
| 514 | border-color: transparent; | |
| 163 | 515 | color: var(); |
| 164 | border: 1px solid var(); | |
| 165 | border-radius: var(); | |
| 166 | } | |
| 167 | .pill[data-env="production"] { | |
| 168 | color: var(); | |
| 169 | border-color: currentColor; | |
| 170 | 516 | } |
| 171 | 517 | |
| 172 | 518 | /* A word from the last request, shown once, gone in a moment. */ |
| @@ -176,6 +522,7 @@ footer code { | ||
| 176 | 522 | bottom: var(); |
| 177 | 523 | transform: translateX(-50%); |
| 178 | 524 | max-width: calc(100% - 2 * var()); |
| 525 | margin: 0; | |
| 179 | 526 | padding: var() var(); |
| 180 | 527 | color: var(); |
| 181 | 528 | background: var(); |
static/clock.js added +27
| @@ -0,0 +1,27 @@ | ||
| 1 | // The response clock keeps ticking: every element with data-since counts up | |
| 2 | // from it, and turns amber at five minutes and red at an hour. The same two | |
| 3 | // rules as src/clock.ts, which painted it first. | |
| 4 | ||
| 5 | const GREEN = 5 * 60_000; | |
| 6 | const AMBER = 60 * 60_000; | |
| 7 | ||
| 8 | const pad = (n) => String(n).padStart(2, "0"); | |
| 9 | function elapsed(ms) { | |
| 10 | const s = Math.max(0, Math.floor(ms / 1000)); | |
| 11 | if (s < 3600) return `${Math.floor(s / 60)}:${pad(s % 60)}`; | |
| 12 | if (s < 86400) return `${Math.floor(s / 3600)}h ${pad(Math.floor((s % 3600) / 60))}m`; | |
| 13 | return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h`; | |
| 14 | } | |
| 15 | ||
| 16 | function tick() { | |
| 17 | const now = Date.now(); | |
| 18 | for (const el of document.querySelectorAll("[data-since]")) { | |
| 19 | const ms = now - Date.parse(el.dataset.since); | |
| 20 | const time = el.querySelector(".clock-time"); | |
| 21 | if (time) time.textContent = elapsed(ms); | |
| 22 | el.dataset.tone = ms < GREEN ? "ok" : ms < AMBER ? "warn" : "late"; | |
| 23 | } | |
| 24 | } | |
| 25 | ||
| 26 | tick(); | |
| 27 | setInterval(tick, 1000); |
High:
text()keeps control characters, so ESC, BEL and the other C0/C1 bytes in a posted lead are stored and later written raw to the terminal. Reject them here (/[\x00-\x08\x0b-\x1f\x7f-\x9f]/, allowing\ninmessageonly) and returninvalid, so every door gets clean data.