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

After an open house, paste the sign-in sheet and every visitor lands on the desk with a thank-you draft naming the house #84

Merged opened this

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

Merged

mason/speed-to-lead:mason/81-after-an-open-house-paste-the-sign-in-sh → main 2 commits fork

  • Merged. mason/81-after-an-open-house-paste-the-sign-in-sh was merged into main as 3816539.

Review

Sign in to review this change.
14 files changed +909 −9
README.md +16
@@ -113,6 +113,13 @@ what you see right after a restart. Do step 1 first.
113113 anything the email did not hold. "Text OK" stays unticked: consent is never
114114 read from an email. Check it and press "Add to the desk": her reply is
115115 drafted.
116 11. After an open house, press "Open house sign-ins", type the property
117 address and paste the sheet, one visitor per line (a name, then an email
118 and/or phone, separated by commas or tabs, as a spreadsheet copy gives
119 them). "Read the sheet" lists each line as read and marks the ones it
120 cannot; "Add" makes each visitor a lead with a thank-you for that address
121 drafted. Someone already on the desk lands on their lead. Nothing is sent
122 until you approve it.
116123
117124 Nothing is really sent in this prototype: "send" records the message in the
118125 lead's history and goes no further. To run the tour again, restart the
@@ -125,6 +132,15 @@ samples (step 1).
125132 terminal desk. They go through the same path as `POST /leads`, for anyone who
126133 may add a lead. The turn is read off the desk, so it needs no extra state.
127134
135 **Open house sign-ins.** `readSignIns` (`src/signins.ts`) reads one visitor
136 per line (tab- or comma-separated, any order) and marks a line it cannot
137 read instead of guessing; `openHouseDraft` (`src/drafts.ts`) words the
138 thank-you. `POST /leads/signins/preview` (`previewSignIns`, MCP
139 `preview_sign_ins`) writes nothing; `POST /leads/signins` (`addSignIns`, MCP
140 `add_sign_ins`, `o` in the terminal) adds, re-reading the sheet itself. At
141 most 100 lines and 20,000 characters (422 otherwise); the cell is `lead
142 create`, and a match by email or phone joins the existing lead.
143
128144 **Pasting a lead email.** `readLeadEmail` (`src/intake.ts`) reads the
129145 labelled lines of a Zillow, Realtor.com or website-form notification (Name,
130146 Email, Phone, Message and the usual variants) into a new lead's fields and
contract/openapi.json +201
@@ -282,6 +282,207 @@
282282 }
283283 }
284284 },
285 "/leads/signins/preview": {
286 "post": {
287 "summary": "Read a pasted open house sign-in sheet (one visitor per line: a name, then an email and/or phone, split by commas or tabs) into visitors, marking each line it cannot read. At most 100 lines. Nothing is written; add them with POST /leads/signins once checked. Needs the same role as adding a lead.",
288 "operationId": "postLeadsSigninsPreview",
289 "requestBody": {
290 "required": true,
291 "content": {
292 "application/json": {
293 "schema": {
294 "type": "object",
295 "properties": {
296 "address": {
297 "type": "string",
298 "minLength": 1,
299 "maxLength": 200
300 },
301 "text": {
302 "type": "string",
303 "maxLength": 20000
304 }
305 },
306 "required": [
307 "address",
308 "text"
309 ]
310 }
311 }
312 }
313 },
314 "responses": {
315 "200": {
316 "description": "Read a pasted open house sign-in sheet (one visitor per line: a name, then an email and/or phone, split by commas or tabs) into visitors, marking each line it cannot read. At most 100 lines. Nothing is written; add them with POST /leads/signins once checked. Needs the same role as adding a lead.",
317 "content": {
318 "application/json": {
319 "schema": {
320 "type": "object",
321 "properties": {
322 "address": {
323 "type": "string"
324 },
325 "readable": {
326 "type": "integer"
327 },
328 "visitors": {
329 "type": "array",
330 "items": {
331 "type": "object",
332 "properties": {
333 "line": {
334 "type": "integer"
335 },
336 "raw": {
337 "type": "string"
338 },
339 "name": {
340 "type": "string"
341 },
342 "email": {
343 "type": "string"
344 },
345 "phone": {
346 "type": "string"
347 },
348 "problem": {
349 "type": "string",
350 "description": "Why the line could not be read; absent when it could."
351 }
352 }
353 }
354 }
355 }
356 }
357 }
358 }
359 },
360 "default": {
361 "description": "{ error, message }: why not",
362 "content": {
363 "application/json": {
364 "schema": {
365 "$ref": "#/components/schemas/Error"
366 }
367 }
368 }
369 }
370 }
371 }
372 },
373 "/leads/signins": {
374 "post": {
375 "summary": "After an open house: every visitor on the pasted sheet becomes a lead (source open_house) with a thank-you for coming to the address drafted. Someone already on the desk (same email or phone) is not made twice. Lines that cannot be read are skipped and returned. Nothing is sent; the agent approves each draft.",
376 "operationId": "postLeadsSignins",
377 "requestBody": {
378 "required": true,
379 "content": {
380 "application/json": {
381 "schema": {
382 "type": "object",
383 "properties": {
384 "address": {
385 "type": "string",
386 "minLength": 1,
387 "maxLength": 200
388 },
389 "text": {
390 "type": "string",
391 "maxLength": 20000
392 }
393 },
394 "required": [
395 "address",
396 "text"
397 ]
398 }
399 }
400 }
401 },
402 "responses": {
403 "201": {
404 "description": "After an open house: every visitor on the pasted sheet becomes a lead (source open_house) with a thank-you for coming to the address drafted. Someone already on the desk (same email or phone) is not made twice. Lines that cannot be read are skipped and returned. Nothing is sent; the agent approves each draft.",
405 "content": {
406 "application/json": {
407 "schema": {
408 "type": "object",
409 "properties": {
410 "address": {
411 "type": "string"
412 },
413 "added": {
414 "type": "array",
415 "items": {
416 "type": "object",
417 "properties": {
418 "id": {
419 "type": "integer"
420 },
421 "name": {
422 "type": "string"
423 }
424 }
425 }
426 },
427 "again": {
428 "type": "array",
429 "items": {
430 "type": "object",
431 "properties": {
432 "id": {
433 "type": "integer"
434 },
435 "name": {
436 "type": "string"
437 }
438 }
439 }
440 },
441 "skipped": {
442 "type": "array",
443 "items": {
444 "type": "object",
445 "properties": {
446 "line": {
447 "type": "integer"
448 },
449 "raw": {
450 "type": "string"
451 },
452 "name": {
453 "type": "string"
454 },
455 "email": {
456 "type": "string"
457 },
458 "phone": {
459 "type": "string"
460 },
461 "problem": {
462 "type": "string",
463 "description": "Why the line could not be read; absent when it could."
464 }
465 }
466 }
467 }
468 }
469 }
470 }
471 }
472 },
473 "default": {
474 "description": "{ error, message }: why not",
475 "content": {
476 "application/json": {
477 "schema": {
478 "$ref": "#/components/schemas/Error"
479 }
480 }
481 }
482 }
483 }
484 }
485 },
285486 "/leads/{id}": {
286487 "get": {
287488 "summary": "One lead, with every message: sent, drafted, and the follow-ups to come. Ask for application/json.",
src/actions.ts +115
@@ -81,6 +81,7 @@ import { goesAt, isZone } from "./quiet.ts";
8181 import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
8282 import { MAX_ADDRESS, timeOf } from "./showings.ts";
8383 import { dateOf } from "./putaway.ts";
84 import { MAX_SIGNIN_LINES, MAX_SIGNIN_TEXT, readSignIns, type SignIn } from "./signins.ts";
8485 import type { Who } from "./who.ts";
8586
8687 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid" | "conflict";
@@ -356,6 +357,120 @@ export function parseLeadEmail(
356357 return ok(readLeadEmail(input.text));
357358 }
358359
360 /** A pasted sign-in sheet as read: the house, and each line as read or marked. */
361 export type SignInPreview = {
362 readonly address: string;
363 readonly visitors: readonly SignIn[];
364 readonly readable: number;
365 };
366
367 /** The address and sheet that arrived, checked: what is wrong with them, or what was read. */
368 function readSheet(input: Record<string, unknown>): Result<SignInPreview> {
369 const address = typeof input.address === "string" ? input.address.trim() : "";
370 if (address.length === 0 || address.length > MAX_ADDRESS)
371 return fail("invalid", `The open house's address is 1 to ${MAX_ADDRESS} characters.`);
372 if (hasControl(address, false))
373 return fail("invalid", "An address is plain text, with no control characters.");
374 if (typeof input.text !== "string" || input.text.trim() === "")
375 return fail("invalid", "Paste the sign-in sheet, one visitor per line.");
376 if (input.text.length > MAX_SIGNIN_TEXT)
377 return fail("invalid", `The sheet is at most ${MAX_SIGNIN_TEXT} characters.`);
378 // The stricter check adding applies, so the preview and the 422 agree with what will be added.
379 const visitors = readSignIns(input.text).map((v): SignIn => {
380 if (v.problem !== undefined) return v;
381 const wrong = contactProblem({ name: v.name, email: v.email, phone: v.phone }, true);
382 return wrong === undefined ? v : { ...v, problem: wrong };
383 });
384 if (visitors.length > MAX_SIGNIN_LINES)
385 return fail("invalid", `A sheet is at most ${MAX_SIGNIN_LINES} lines; this one has ${visitors.length}. Paste it in parts.`);
386 const readable = visitors.filter((v) => v.problem === undefined).length;
387 if (readable === 0)
388 return fail("invalid", "No line could be read as a name with an email or phone number. Each line is a name, then an email and/or a phone, separated by commas or tabs.");
389 return ok({ address, visitors, readable });
390 }
391
392 /**
393 * A pasted sign-in sheet read line by line, to check before adding. Same
394 * cell as adding a lead (lead create); writes nothing, so nothing is audited.
395 */
396 export function previewSignIns(
397 who: Who,
398 input: Record<string, unknown>,
399 ): Result<SignInPreview> {
400 if (permit(who, "lead", "create") !== "yes")
401 return refuse(who, "Sign in to add leads.", "You may not add a lead.");
402 return readSheet(input);
403 }
404
405 /** What adding a sheet did: who is new, who was already on the desk, which lines were left out. */
406 export type SignInsAdded = {
407 readonly id: number;
408 readonly address: string;
409 readonly added: readonly { id: number; name: string }[];
410 readonly again: readonly { id: number; name: string }[];
411 readonly skipped: readonly SignIn[];
412 };
413
414 /**
415 * The visitors of an open house become leads (source `open_house`), each with
416 * a thank-you for coming to `address` drafted and nothing sent. Someone already
417 * on the desk (same email, or same phone) is not made twice: the sign-in joins
418 * their history, as `addLead` does. Lines that could not be read are skipped
419 * and returned. The sheet is read again here, never trusted from the preview;
420 * the trail holds one row per lead.
421 */
422 export function addSignIns(
423 db: Database,
424 who: Who,
425 input: Record<string, unknown>,
426 at?: Date,
427 ): Result<SignInsAdded> {
428 const sheet =
429 permit(who, "lead", "create") !== "yes"
430 ? refuse<SignInPreview>(who, "Sign in to add leads.", "You may not add a lead.")
431 : readSheet(input);
432 if (!sheet.ok) {
433 audited(db, who, "lead", "create", undefined, sheet as Result<{ id: number }>);
434 return sheet as Result<SignInsAdded>;
435 }
436 const { address, visitors } = sheet.value;
437 const message = `Signed in at the open house at ${address}.`;
438 const added: { id: number; name: string }[] = [];
439 const again: { id: number; name: string }[] = [];
440 const skipped: SignIn[] = [];
441 const agent = currentAgent(db);
442 const now = stamp(at);
443 db.transaction(() => {
444 for (const v of visitors) {
445 if (v.problem !== undefined) {
446 skipped.push(v);
447 continue;
448 }
449 const lead: NewLead = {
450 name: v.name,
451 email: v.email,
452 phone: v.phone,
453 source: "open_house",
454 message,
455 consent: false,
456 };
457 const known = findMatch(db, lead);
458 if (known !== null) {
459 writeInAgain(db, known, message, now, agent);
460 again.push({ id: known.id, name: known.name });
461 audited(db, who, "lead", "create", undefined, ok({ id: known.id }), "merged", mergeDetail({ source: "open_house", lead: known.id }));
462 } else {
463 const id = insertLead(db, lead, now, agent, address);
464 added.push({ id, name: v.name });
465 audited(db, who, "lead", "create", undefined, ok({ id }));
466 }
467 }
468 })();
469 for (const l of added) emit("lead.added", { id: l.id });
470 for (const l of again) emit("lead.changed", { id: l.id });
471 return ok({ id: (added[0] ?? again[0])!.id, address, added, again, skipped });
472 }
473
359474 /** The fields of a lead's details, in the order they are told. */
360475 const CONTACT_FIELDS = ["name", "email", "phone"] as const;
361476 export type ContactField = (typeof CONTACT_FIELDS)[number];
src/contract.test.ts +6
@@ -28,6 +28,8 @@ import {
2828 cancelShowing,
2929 logLeadReply,
3030 parseLeadEmail,
31 previewSignIns,
32 addSignIns,
3133 saveProfile,
3234 setNote,
3335 setState,
@@ -115,6 +117,10 @@ const doors: Record<
115117 expect(addSampleInquiry(db, who).ok).toBe(added);
116118 // So is reading a pasted lead email (POST /leads/parse, the MCP tool parse_lead_email).
117119 expect(parseLeadEmail(who, { text: "Name: Pat" }).ok).toBe(added);
120 // And the open house sign-in sheet (POST /leads/signins and /preview, the MCP tools).
121 const sheet = { address: "1 Elm St", text: "Pat Lee, [email protected]" };
122 expect(previewSignIns(who, sheet).ok).toBe(added);
123 expect(addSignIns(db, who, sheet).ok).toBe(added);
118124 return added;
119125 },
120126 // The spreadsheet is the same cell through its own door (GET /leads.csv, the MCP tool export_leads, `x` in the terminal).
src/drafts.ts +15
@@ -357,6 +357,21 @@ export function confirmationDraft(
357357 return `Hi ${first},\n\nA quick note before your showing: ${line(address)}\n\nBest,`;
358358 }
359359
360 /**
361 * After an open house: thanks for coming to `address`, and a next step. The
362 * agent approves it like any first reply. An address is at most 200
363 * characters, so even the text always fits.
364 */
365 export function openHouseDraft(lead: Asker, address: string): string {
366 const first = firstName(lead.name);
367 const thanks = (place: string): string =>
368 `thanks for coming to the open house at ${place}! If you'd like to see it again, or see other homes like it, just say the word.`;
369 if (channelFor(lead) === "text") {
370 return `Hi ${first}, it's the agent who hosted — ${thanks(address)}`;
371 }
372 return `Hi ${first},\n\nIt was great to meet you — ${thanks(address)}\n\nTalk soon,`;
373 }
374
360375 /**
361376 * The morning a lead put away comes back: they said to get in touch around
362377 * now. Short enough to text; it says nothing of the agent's private note.
src/intake.ts +3 −3
@@ -55,9 +55,9 @@ const labelled = (line: string): { field: Field | undefined; value: string } | u
5555 return { field: LABELS[label], value: line.slice(colon + 1).trim() };
5656 };
5757
58 const CONTROL = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
58 export const CONTROL = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
5959
60 const emailIn = (value: string): string | undefined => {
60 export const emailIn = (value: string): string | undefined => {
6161 for (const token of value.split(/[\s<>(),;:"'[\]]+/)) {
6262 const at = token.indexOf("@");
6363 if (at < 1 || at !== token.lastIndexOf("@")) continue;
@@ -68,7 +68,7 @@ const emailIn = (value: string): string | undefined => {
6868 return undefined;
6969 };
7070
71 const phoneIn = (value: string): string | undefined => {
71 export const phoneIn = (value: string): string | undefined => {
7272 const phone = value.trim();
7373 if (phone.length > 20 || phone.length === 0) return undefined;
7474 let digits = 0;
src/leads.ts +4 −1
@@ -26,6 +26,7 @@ import {
2626 CADENCE,
2727 channelFor,
2828 draft,
29 openHouseDraft,
2930 isAfterShowing,
3031 isAnswer,
3132 signature,
@@ -475,6 +476,8 @@ export function insertLead(
475476 input: NewLead,
476477 at: string,
477478 agent: Agent,
479 /** The open house this lead signed in at: its first reply thanks them for coming there. */
480 openHouse?: string,
478481 ): number {
479482 return db.transaction(() => {
480483 const { id } = db
@@ -496,7 +499,7 @@ export function insertLead(
496499 const channel = channelFor(input);
497500 db.query(
498501 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, 0, ?2, ?3, ?4, 'draft', ?5)",
499 ).run(id, channel, draft(input, 0, agent), signature(channel, agent), at);
502 ).run(id, channel, openHouse === undefined ? draft(input, 0, agent) : openHouseDraft(input, openHouse), signature(channel, agent), at);
500503 return id;
501504 })();
502505 }
src/mcp.ts +26
@@ -29,12 +29,15 @@ import {
2929 skipFollowUp,
3030 logLeadReply,
3131 parseLeadEmail,
32 previewSignIns,
33 addSignIns,
3234 type Result,
3335 CADENCE_MAX_DAY,
3436 CADENCE_MAX_TOUCHES,
3537 } from "./actions.ts";
3638 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
3739 import { MAX_EMAIL_TEXT } from "./intake.ts";
40 import { MAX_SIGNIN_TEXT } from "./signins.ts";
3841 import { MAX_ADDRESS } from "./showings.ts";
3942 import { OPENER_MAX, SOURCES } from "./drafts.ts";
4043 import { title } from "./env.ts";
@@ -60,6 +63,15 @@ const ONE = {
6063 required: ["id"],
6164 };
6265
66 const SIGNINS = {
67 type: "object",
68 properties: {
69 address: { type: "string", maxLength: MAX_ADDRESS },
70 text: { type: "string", maxLength: MAX_SIGNIN_TEXT },
71 },
72 required: ["address", "text"],
73 } as const;
74
6375 export const tools: readonly Tool[] = [
6476 {
6577 name: "list_leads",
@@ -131,6 +143,20 @@ export const tools: readonly Tool[] = [
131143 },
132144 run: (db, who, args) => parseLeadEmail(who, args),
133145 },
146 {
147 name: "preview_sign_ins",
148 description:
149 "Read a pasted open house sign-in sheet (one visitor per line: name, then email and/or phone, separated by commas or tabs; at most 100 lines) and show each line as read or marked unreadable. Nothing is added; check it, then call add_sign_ins.",
150 inputSchema: SIGNINS,
151 run: (db, who, args) => previewSignIns(who, args),
152 },
153 {
154 name: "add_sign_ins",
155 description:
156 "After an open house: every readable visitor on the pasted sheet becomes a lead (source open_house) with a thank-you for coming to the address drafted. Someone already on the desk (same email or phone) is not made twice. Nothing is sent; the agent approves each draft.",
157 inputSchema: SIGNINS,
158 run: (db, who, args) => addSignIns(db, who, args),
159 },
134160 {
135161 name: "new_sample_inquiry",
136162 description:
src/pages/desk.ts +39 −2
@@ -10,10 +10,12 @@ import { recordLine, sourceLine } from "../clock.ts";
1010 import { isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts";
1111 import { dateName } from "../putaway.ts";
1212 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
13 import { MAX_LISTED, showingWhen } from "../showings.ts";
13 import { MAX_ADDRESS, MAX_LISTED, showingWhen } from "../showings.ts";
1414 import { MAX_EMAIL_TEXT, missingLine } from "../intake.ts";
1515 import { inView, type Ahead, noteLine, type DeskLead, type NewLead, type ResponseRecord, type View } from "../leads.ts";
1616 import type { Agent } from "../env.ts";
17 import type { SignInPreview } from "../actions.ts";
18 import { MAX_SIGNIN_TEXT } from "../signins.ts";
1719 import type { Who } from "../who.ts";
1820
1921 export function deskPage(input: {
@@ -31,6 +33,8 @@ export function deskPage(input: {
3133 notice?: string | undefined;
3234 /** What a pasted email was read into: the add form opens with it filled in. */
3335 prefill?: Partial<NewLead> | undefined;
36 /** A pasted sign-in sheet: what was typed, and how it was read when it could be. */
37 signIns?: { preview?: SignInPreview | undefined; address: string; text: string } | undefined;
3438 }): string {
3539 const { who, agent, leads, notice } = input;
3640 if (leads === undefined)
@@ -94,7 +98,7 @@ export function deskPage(input: {
9498 ${list}
9599 <p class="export"><a href="${escape(exportHref(show, q))}" download>Download leads (CSV)</a></p>
96100 </div>
97 ${input.mayAdd ? `<form class="reset" method="post" action="/sample/inquiry"><button class="button button-quiet">Bring in a new inquiry</button></form>${pasteForm}${addForm(input.prefill)}` : ""}
101 ${input.mayAdd ? `<form class="reset" method="post" action="/sample/inquiry"><button class="button button-quiet">Bring in a new inquiry</button></form>${pasteForm}${signInForm(input.signIns)}${addForm(input.prefill)}` : ""}
98102 ${
99103 input.mayReset
100104 ? `<form class="reset" method="post" action="/sample/reset"><button class="button button-quiet">Restart the sample leads from now</button></form>`
@@ -223,6 +227,39 @@ const pasteForm = `<details class="card add">
223227 </form>
224228 </details>`;
225229
230 const signInForm = (sheet?: { preview?: SignInPreview | undefined; address: string; text: string }): string => {
231 const typed = `<label>Property address <input class="input" name="address" required maxlength="${MAX_ADDRESS}" autocomplete="off" value="${escape(sheet?.address ?? "")}"></label>
232 <label>The sign-in sheet, one visitor per line: name, then email and/or phone, separated by commas or tabs <textarea class="input" name="text" required maxlength="${MAX_SIGNIN_TEXT}" rows="8">${escape(sheet?.text ?? "")}</textarea></label>`;
233 const preview = sheet?.preview;
234 const lines =
235 preview === undefined
236 ? ""
237 : `<div class="stack" role="status">
238 <p class="muted"><b>${preview.readable}</b> of ${preview.visitors.length} lines read. Each becomes a lead with a thank-you for ${escape(preview.address)} drafted; nothing is sent until you approve it.</p>
239 <ol>${preview.visitors
240 .map((v) =>
241 v.problem === undefined
242 ? `<li>${escape(v.name)} · ${v.email === "" ? "no email" : escape(v.email)} · ${v.phone === "" ? "no phone" : escape(v.phone)}</li>`
243 : `<li><b>Cannot read</b> line ${v.line}: ${escape(v.raw)} <span class="muted">(${escape(v.problem)}; it will be left out)</span></li>`,
244 )
245 .join("")}</ol>
246 <form class="stack" method="post" action="/leads/signins">
247 <input type="hidden" name="address" value="${escape(preview.address)}">
248 <input type="hidden" name="text" value="${escape(sheet?.text ?? "")}">
249 <button class="button">Add ${preview.readable} to the desk</button>
250 </form>
251 <p class="muted">Or fix the sheet and read it again:</p>
252 </div>`;
253 return `<details class="card add"${sheet === undefined ? "" : " open"}>
254 <summary>Open house sign-ins</summary>
255 ${lines}
256 <form class="stack" method="post" action="/leads/signins/preview">
257 ${typed}
258 <button class="button">Read the sheet</button>
259 </form>
260 </details>`;
261 };
262
226263 const addForm = (prefill?: Partial<NewLead>): string => `<details class="card add"${prefill === undefined ? "" : " open"}>
227264 <summary>Log a lead by hand</summary>
228265 ${prefill === undefined ? "" : `<p class="muted" role="status">${escape(missingLine(prefill))} Text OK is never taken from an email: tick it only with written consent.</p>`}
src/routes.ts +95 −1
@@ -28,6 +28,9 @@ import {
2828 exportLeads,
2929 listLeads,
3030 parseLeadEmail,
31 previewSignIns,
32 addSignIns,
33 type SignInPreview,
3134 resetSample,
3235 saveProfile,
3336 optOutTexts,
@@ -68,6 +71,7 @@ import {
6871 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
6972 import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts";
7073 import { MAX_EMAIL_TEXT } from "./intake.ts";
74 import { MAX_SIGNIN_TEXT } from "./signins.ts";
7175 import { LOST_REASONS, lostSaid } from "./lost.ts";
7276 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type NewLead } from "./leads.ts";
7377 import { events } from "./live.ts";
@@ -427,6 +431,25 @@ const LIMIT: Schema = {
427431 maximum: 500,
428432 default: 100,
429433 };
434 const SIGNINS_BODY: Schema = {
435 type: "object",
436 properties: {
437 address: { type: "string", minLength: 1, maxLength: MAX_ADDRESS },
438 text: { type: "string", maxLength: MAX_SIGNIN_TEXT },
439 },
440 required: ["address", "text"],
441 };
442 const SIGNIN_LINE: Schema = {
443 type: "object",
444 properties: {
445 line: { type: "integer" },
446 raw: { type: "string" },
447 name: { type: "string" },
448 email: { type: "string" },
449 phone: { type: "string" },
450 problem: { type: "string", description: "Why the line could not be read; absent when it could." },
451 },
452 };
430453 const ID = (c: Context): number => Number(c.params.id);
431454 const list = (items: Schema): Schema => ({ type: "array", items });
432455
@@ -547,7 +570,12 @@ const openapi = existsSync(OPENAPI) ? readFileSync(OPENAPI, "utf8") : undefined;
547570 /** The desk page, with what a pasted email was read into when there is one. */
548571 function desk(
549572 c: Context,
550 pasted?: { found: Partial<NewLead>; status?: number; notice?: string },
573 pasted?: {
574 found?: Partial<NewLead>;
575 signIns?: { preview?: SignInPreview; address: string; text: string };
576 status?: number;
577 notice?: string;
578 },
551579 ): Response {
552580 const { notice, clear } = readNotice(c.request);
553581 const show = c.url.searchParams.get("show");
@@ -575,6 +603,7 @@ function desk(
575603 mayReset: permit(c.who, "lead", "delete") === "yes",
576604 notice: pasted?.notice ?? refused ?? notice,
577605 prefill: pasted?.found,
606 signIns: pasted?.signIns,
578607 }),
579608 pasted?.status ?? 200,
580609 clear,
@@ -690,6 +719,71 @@ export const routes: readonly Route[] = [
690719 },
691720 },
692721 },
722 {
723 // Reads a pasted open house sign-in sheet line by line and writes
724 // nothing; a form gets the desk back with the preview and a confirm.
725 method: "POST",
726 path: "/leads/signins/preview",
727 handle: async (c) => {
728 const input = await readFields(c.request);
729 if (input === undefined)
730 return scripted(c.request) ? json({ error: "too_large" }, 413) : text("too large", 413);
731 const read = previewSignIns(c.who, input);
732 if (scripted(c.request)) return answer(read);
733 const sheet = { address: String(input.address ?? ""), text: String(input.text ?? "") };
734 if (!read.ok) return desk(c, { signIns: sheet, status: STATUS[read.error], notice: read.message });
735 return desk(c, { signIns: { ...sheet, preview: read.value } });
736 },
737 api: {
738 summary:
739 "Read a pasted open house sign-in sheet (one visitor per line: a name, then an email and/or phone, split by commas or tabs) into visitors, marking each line it cannot read. At most 100 lines. Nothing is written; add them with POST /leads/signins once checked. Needs the same role as adding a lead.",
740 body: SIGNINS_BODY,
741 answer: {
742 type: "object",
743 properties: {
744 address: { type: "string" },
745 readable: { type: "integer" },
746 visitors: list(SIGNIN_LINE),
747 },
748 },
749 },
750 },
751 {
752 // Every readable visitor becomes a lead (source open_house) with a
753 // thank-you for that address drafted; nothing is sent. Not under
754 // /leads/:id, so the action asks the lead-create cell.
755 method: "POST",
756 path: "/leads/signins",
757 handle: (c) =>
758 posted(
759 c,
760 (input) => addSignIns(c.db, c.who, input),
761 (r) => ({
762 to: "/",
763 ...(r === undefined
764 ? {}
765 : {
766 said: `Open house: ${r.added.length} added with a thank-you drafted${r.again.length === 0 ? "" : `, ${r.again.length} already on the desk`}${r.skipped.length === 0 ? "" : `, ${r.skipped.length} line${r.skipped.length === 1 ? "" : "s"} left out`}`,
767 }),
768 }),
769 201,
770 ),
771 api: {
772 summary:
773 "After an open house: every visitor on the pasted sheet becomes a lead (source open_house) with a thank-you for coming to the address drafted. Someone already on the desk (same email or phone) is not made twice. Lines that cannot be read are skipped and returned. Nothing is sent; the agent approves each draft.",
774 body: SIGNINS_BODY,
775 answer: {
776 type: "object",
777 properties: {
778 address: { type: "string" },
779 added: list({ type: "object", properties: { id: { type: "integer" }, name: { type: "string" } } }),
780 again: list({ type: "object", properties: { id: { type: "integer" }, name: { type: "string" } } }),
781 skipped: list(SIGNIN_LINE),
782 },
783 },
784 status: 201,
785 },
786 },
693787 {
694788 method: "GET",
695789 path: "/leads/:id",
src/server.test.ts +2
@@ -320,6 +320,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
320320 "get_lead",
321321 "add_lead",
322322 "parse_lead_email",
323 "preview_sign_ins",
324 "add_sign_ins",
323325 "new_sample_inquiry",
324326 "send_reply",
325327 "log_lead_reply",
src/signins.test.ts added +255
@@ -0,0 +1,255 @@
1 /**
2 * The open house sign-in sheet: how a line is read, what the preview shows,
3 * and that adding makes leads with a thank-you for that address, once each,
4 * through every door.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addLead, addSignIns, getLead, listLeads, previewSignIns } from "./actions.ts";
11 import { openDb } from "./db.ts";
12 import { MAX_BODY, openHouseDraft } from "./drafts.ts";
13 import { tools } from "./mcp.ts";
14 import { MAX_SIGNIN_LINES, MAX_SIGNIN_TEXT, readSignIns } from "./signins.ts";
15 import { serve } from "./server.ts";
16 import { terminal } from "./terminal.ts";
17 import { sign } from "./who.ts";
18 import type { Who } from "./who.ts";
19
20 const anon: Who = { role: "anon" };
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-signins-")));
23 const HOUSE = "12 Example St";
24 const names = (db: ReturnType<typeof fresh>): string[] => {
25 const l = listLeads(db, alice);
26 return l.ok ? l.value.leads.map((x) => x.name) : [];
27 };
28
29 test("a line is read from commas or tabs, in any order, with an email or a phone or both", () => {
30 const read = readSignIns(
31 [
32 "Priya Raman, [email protected], (206) 555-0101",
33 "Tom Becker\t206-555-0102\[email protected]",
34 "206 555 0103, Lena Novak",
35 '"Ada Cole", [email protected]',
36 "",
37 ].join("\r\n"),
38 );
39 expect(read.map((r) => [r.name, r.email, r.phone, r.problem])).toEqual([
40 ["Priya Raman", "[email protected]", "(206) 555-0101", undefined],
41 ["Tom Becker", "[email protected]", "206-555-0102", undefined],
42 ["Lena Novak", "", "206 555 0103", undefined],
43 ["Ada Cole", "[email protected]", "", undefined],
44 ]);
45 });
46
47 test("a line that cannot be read is marked, with its place and why, never guessed", () => {
48 const read = readSignIns("Name, Email, Phone\nJust A Name\n\nPat Lee, [email protected], [email protected]\nok Person, [email protected]");
49 expect(read.map((r) => [r.line, r.problem === undefined])).toEqual([
50 [1, false],
51 [2, false],
52 [4, false],
53 [5, true],
54 ]);
55 expect(read[0]!.problem).toContain("More than one name");
56 expect(read[1]!.problem).toContain("No email or phone");
57 expect(read[2]!.problem).toContain("More than one email");
58 });
59
60 test("the preview shows each line as read and writes nothing", () => {
61 const db = fresh();
62 const before = names(db).length;
63 const p = previewSignIns(alice, { address: HOUSE, text: "Priya Raman, [email protected]\njunk" });
64 expect(p.ok && p.value.readable).toBe(1);
65 expect(p.ok && p.value.visitors[1]!.problem).toBeDefined();
66 expect(names(db).length).toBe(before);
67 });
68
69 test("each visitor becomes an open_house lead whose first draft thanks them for coming to that address; nothing is sent", () => {
70 const db = fresh();
71 const r = addSignIns(db, alice, { address: HOUSE, text: "Priya Raman, [email protected]\nTom Becker, 206-555-0102\nnot a visitor" });
72 expect(r.ok).toBe(true);
73 if (!r.ok) return;
74 expect(r.value.added.map((a) => a.name)).toEqual(["Priya Raman", "Tom Becker"]);
75 expect(r.value.skipped.length).toBe(1);
76 const lead = getLead(db, alice, { id: r.value.added[0]!.id });
77 expect(lead.ok && lead.value.source).toBe("open_house");
78 const msg = lead.ok && lead.value.messages[0]!;
79 expect(msg && msg.status).toBe("draft");
80 expect(msg && msg.body).toContain("thanks for coming to the open house at 12 Example St");
81 expect(msg && msg.body).toContain("Hi Priya");
82 expect(lead.ok && lead.value.consent).toBe(false);
83 });
84
85 test("a visitor already on the desk (same email or phone) lands on that lead, not a second one", () => {
86 const db = fresh();
87 const had = addLead(db, alice, { name: "Priya R.", email: "[email protected]", phone: "", source: "zillow", message: "Is it available?" });
88 expect(had.ok).toBe(true);
89 const known = listLeads(db, alice);
90 const phone = known.ok ? known.value.leads[0]!.phone : "";
91 const r = addSignIns(db, alice, {
92 address: HOUSE,
93 text: `Priya Raman, [email protected]\nSomeone Else, ${phone || "206-555-0101"}\nPriya Raman, [email protected]`,
94 });
95 expect(r.ok).toBe(true);
96 if (!r.ok || !had.ok) return;
97 expect(r.value.again[0]!.id).toBe(had.value.id);
98 expect(names(db).filter((n) => n.startsWith("Priya"))).toEqual(["Priya R."]);
99 // The same visitor twice in one sheet is one lead.
100 const twice = addSignIns(db, alice, { address: HOUSE, text: "Ned Fox, [email protected]\nNed Fox, [email protected]" });
101 expect(twice.ok && [twice.value.added.length, twice.value.again.length]).toEqual([1, 1]);
102 });
103
104 test("a long address is kept out of a text rather than cutting it, and one too long is refused", () => {
105 const db = fresh();
106 expect(addSignIns(db, alice, { address: "x".repeat(201), text: "A B, [email protected]" }).ok).toBe(false);
107 expect(addSignIns(db, alice, { address: "", text: "A B, [email protected]" }).ok).toBe(false);
108 expect(addSignIns(db, alice, { address: "1 St\u0007", text: "A B, [email protected]" }).ok).toBe(false);
109 });
110
111 test("too many lines, or none readable, is refused with the problem named", () => {
112 const db = fresh();
113 const many = Array.from({ length: MAX_SIGNIN_LINES + 1 }, (_, i) => `Visitor ${i}, v${i}@example.com`).join("\n");
114 const big = addSignIns(db, alice, { address: HOUSE, text: many });
115 expect(!big.ok && big.error === "invalid" && big.message).toContain("at most 100 lines");
116 const ok100 = addSignIns(db, alice, { address: HOUSE, text: many.split("\n").slice(0, 100).join("\n") });
117 expect(ok100.ok && ok100.value.added.length).toBe(100);
118 const none = addSignIns(db, alice, { address: HOUSE, text: "junk\nmore junk" });
119 expect(!none.ok && none.error === "invalid" && none.message).toContain("No line could be read");
120 expect(previewSignIns(alice, { address: HOUSE, text: "junk" }).ok).toBe(false);
121 });
122
123 test("an anon post is refused and adds nothing", () => {
124 const db = fresh();
125 const r = addSignIns(db, anon, { address: HOUSE, text: "A B, [email protected]" });
126 expect(!r.ok && r.error).toBe("signin_required");
127 expect(previewSignIns(anon, { address: HOUSE, text: "A B, [email protected]" }).ok).toBe(false);
128 expect(names(db).length).toBe(0);
129 });
130
131 test("the MCP tools run the same actions", () => {
132 const db = fresh();
133 const add = tools.find((t) => t.name === "add_sign_ins")!;
134 const r = add.run(db, alice, { address: HOUSE, text: "A Bee, [email protected]" }) as { ok: boolean };
135 expect(r.ok).toBe(true);
136 expect(tools.some((t) => t.name === "preview_sign_ins")).toBe(true);
137 });
138
139 test("o in the terminal asks the address, reads the sheet, and adds on y", () => {
140 const db = fresh();
141 const t = terminal(db, alice);
142 t.key("o");
143 for (const ch of HOUSE) t.key(ch);
144 t.key("\r");
145 t.key("Priya Raman, [email protected]\rjunk line");
146 t.key("\x04");
147 const screen = t.screen().join("\n");
148 expect(screen).toContain("Priya Raman");
149 expect(screen).toContain("cannot read");
150 t.key("y");
151 expect(t.screen().join("\n")).toContain("1 added with a thank-you drafted");
152 expect(names(db)).toContain("Priya Raman");
153 });
154
155 const KEY = "a-key-only-the-forge-holds";
156 test("over HTTP: the desk form previews, the confirm adds, the API answers 201/422/401, and the page escapes", async () => {
157 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-signins-http-")), identityKey: KEY });
158 try {
159 const base = `http://${server.hostname}:${server.port}`;
160 const identity = `u9|zed|user|${Date.now() + 60_000}`;
161 const who = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
162 const form = (path: string, fields: Record<string, string>) =>
163 fetch(base + path, { method: "POST", headers: { ...who }, body: new URLSearchParams(fields) });
164 const jsonPost = (path: string, body: unknown, h: Record<string, string> = who) =>
165 fetch(base + path, { method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify(body) });
166
167 const prev = await form("/leads/signins/preview", { address: "<b>9 Elm St</b>", text: "Zoe <script>, [email protected]\nbad" });
168 const page = await prev.text();
169 expect(prev.status).toBe(200);
170 expect(page).toContain("Add 1 to the desk");
171 expect(page).toContain("Cannot read");
172 expect(page).not.toContain("<script>");
173 expect(page).not.toContain("<b>9 Elm");
174
175 const bad = await form("/leads/signins/preview", { address: HOUSE, text: "nothing readable" });
176 expect(bad.status).toBe(422);
177
178 const api = await jsonPost("/leads/signins", { address: HOUSE, text: "Zoe Q, [email protected]" });
179 expect(api.status).toBe(201);
180 expect(((await api.json()) as { added: unknown[] }).added.length).toBe(1);
181 expect((await jsonPost("/leads/signins", { address: HOUSE, text: "junk" })).status).toBe(422);
182 expect((await jsonPost("/leads/signins", { address: HOUSE, text: "A B, [email protected]" }, {})).status).toBe(401);
183 const cross = await fetch(base + "/leads/signins", { method: "POST", headers: { ...who, "sec-fetch-site": "cross-site" }, body: new URLSearchParams({ address: HOUSE, text: "A B, [email protected]" }) });
184 expect(cross.status).toBe(403);
185
186 const spec = await (await fetch(base + "/openapi.json", { headers: who })).text();
187 expect(spec).toContain('"/leads/signins"');
188 expect(spec).toContain('"/leads/signins/preview"');
189 } finally {
190 server.stop(true);
191 }
192 });
193
194 test("lines that read but fail the stricter contact check are marked in the preview and refused alike, never a crash", () => {
195 const db = fresh();
196 // Reads as a phone (7 to 15 digits) but a "+" in the middle is not a phone number to add.
197 const text = "Pat Lee, 555+123+4567";
198 const p = previewSignIns(alice, { address: HOUSE, text });
199 expect(!p.ok && p.error).toBe("invalid");
200 const r = addSignIns(db, alice, { address: HOUSE, text });
201 expect(!r.ok && r.error === "invalid" && r.message).toContain("No line could be read");
202 expect(names(db).length).toBe(0);
203 // Mixed with a good line, the preview counts only what will be added, and add skips the same one.
204 const mixed = `${text}\nZed Ray, [email protected]`;
205 const pm = previewSignIns(alice, { address: HOUSE, text: mixed });
206 expect(pm.ok && pm.value.readable).toBe(1);
207 expect(pm.ok && pm.value.visitors[0]!.problem).toContain("phone");
208 const am = addSignIns(db, alice, { address: HOUSE, text: mixed });
209 expect(am.ok && [am.value.added.length, am.value.skipped.length]).toEqual([1, 1]);
210 });
211
212 test("a text thanks them at the address, and the longest address still fits a text", () => {
213 const asker = (consent: boolean) => ({ name: "Priya Raman", phone: "206-555-0101", source: "open_house" as const, message: "m", consent });
214 const short = openHouseDraft(asker(true), HOUSE);
215 expect(short).toContain(HOUSE);
216 expect(short.length).toBeLessThanOrEqual(MAX_BODY.text);
217 const long = openHouseDraft(asker(true), "x".repeat(200));
218 expect(long).toContain("x".repeat(200));
219 expect(long.length).toBeLessThanOrEqual(MAX_BODY.text);
220 // A sign-in never carries consent, so a phone-only visitor's draft is an email naming the address.
221 expect(openHouseDraft(asker(false), HOUSE)).toContain(`open house at ${HOUSE}`);
222 const db = fresh();
223 const r = addSignIns(db, alice, { address: HOUSE, text: "Phil Only, 206-555-0188" });
224 const lead = r.ok && getLead(db, alice, { id: r.value.added[0]!.id });
225 expect(lead && lead.ok && lead.value.messages[0]!.channel).toBe("email");
226 expect(lead && lead.ok && lead.value.messages[0]!.body).toContain(HOUSE);
227 });
228
229 test("a different name with the same phone lands on the lead that has it", () => {
230 const db = fresh();
231 const had = addLead(db, alice, { name: "Old Lead", email: "[email protected]", phone: "(206) 555-0177", source: "zillow", message: "Is it available?" });
232 const r = addSignIns(db, alice, { address: HOUSE, text: "New Name, 206.555.0177" });
233 expect(r.ok && had.ok && r.value.again.map((a) => a.id)).toEqual(had.ok ? [had.value.id] : []);
234 expect(names(db)).toEqual(["Old Lead"]);
235 });
236
237 test("a sheet over 20,000 characters is a 422 naming the limit", () => {
238 const db = fresh();
239 const r = addSignIns(db, alice, { address: HOUSE, text: `A B, [email protected]\n${" ".repeat(MAX_SIGNIN_TEXT)}` });
240 expect(!r.ok && r.error === "invalid" && r.message).toContain("20000");
241 });
242
243 test("over HTTP an anon post to the preview is refused", async () => {
244 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-signins-anon-")), identityKey: KEY });
245 try {
246 const res = await fetch(`http://${server.hostname}:${server.port}/leads/signins/preview`, {
247 method: "POST",
248 headers: { "content-type": "application/json" },
249 body: JSON.stringify({ address: HOUSE, text: "A B, [email protected]" }),
250 });
251 expect(res.status).toBe(401);
252 } finally {
253 server.stop(true);
254 }
255 });
src/signins.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * Reading an open house sign-in sheet: one visitor per line, a name and an
3 * email and/or a phone number in any order, split by tabs (a spreadsheet
4 * copy) or commas. Plain text in, plain data out; nothing is written and
5 * nothing is guessed beyond that shape. A line that does not fit it is
6 * marked with why, so the agent sees it in the preview and nothing is
7 * silently dropped. Consent to be texted is never among what is read.
8 */
9
10 import { CONTROL, emailIn, phoneIn } from "./intake.ts";
11
12 /** The most visitors one paste may hold. */
13 export const MAX_SIGNIN_LINES = 100;
14 /** The most characters a pasted sheet may hold. */
15 export const MAX_SIGNIN_TEXT = 20_000;
16
17 export type SignIn = {
18 /** Its place among the pasted lines, counting from 1 (blank lines included). */
19 readonly line: number;
20 readonly raw: string;
21 readonly name: string;
22 readonly email: string;
23 readonly phone: string;
24 /** Why the line could not be read; absent when it could. */
25 readonly problem?: string;
26 };
27
28 const unquote = (field: string): string => {
29 const f = field.trim();
30 return f.length >= 2 && f.startsWith('"') && f.endsWith('"') ? f.slice(1, -1).trim() : f;
31 };
32
33 const readLine = (raw: string, line: number): SignIn => {
34 const fields = raw
35 .split(raw.includes("\t") ? "\t" : /[,;]/)
36 .map(unquote)
37 .filter((f) => f !== "");
38 let name = "";
39 let email = "";
40 let phone = "";
41 const bad = (problem: string): SignIn => ({ line, raw, name, email, phone, problem });
42 for (const field of fields) {
43 const asEmail = emailIn(field);
44 if (asEmail !== undefined && asEmail === field.toLowerCase()) {
45 if (email !== "") return bad("More than one email address.");
46 email = asEmail;
47 } else if (phoneIn(field) !== undefined) {
48 if (phone !== "") return bad("More than one phone number.");
49 phone = field;
50 } else if (name === "") name = field;
51 else return bad("More than one name, or text that is not an email or phone.");
52 }
53 if (name === "") return bad("No name.");
54 if (name.length > 120) return bad("A name is at most 120 characters.");
55 if (email === "" && phone === "") return bad("No email or phone number to reach them by.");
56 return { line, raw, name, email, phone };
57 };
58
59 /** Every non-blank line of the pasted sheet, as read or as marked. */
60 export function readSignIns(text: string): SignIn[] {
61 return text
62 .replace(/\r\n?/g, "\n")
63 .replace(CONTROL, " ")
64 .split("\n")
65 .map((raw, i) => ({ raw: raw.trim(), line: i + 1 }))
66 .filter((l) => l.raw !== "")
67 .map((l) => readLine(l.raw, l.line));
68 }
src/terminal.ts +64 −2
@@ -5,12 +5,13 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · w they wrote back · ] next lead that needs you ·
1010 * q qualified · x lost · t asked to stop texts · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
1212 * wrote type what they wrote · ctrl-t text/email (text only with consent) · ctrl-d record it and draft the answer · esc cancel
1313 * paste paste the notification email · ctrl-d read it, then check each field in the add screen (consent starts as n) · esc cancel
14 * signins the property address, then paste the sheet (one visitor per line) · ctrl-d read it · y add them · esc cancel
1415 * add one field at a time; enter next · esc cancel
1516 * profile the name, brokerage and license every message carries ·
1617 * e edit (admin): one field at a time, enter next, the last saves · esc back
@@ -26,6 +27,8 @@ import type { Database } from "bun:sqlite";
2627 import {
2728 activity,
2829 addLead,
30 addSignIns,
31 previewSignIns,
2932 addSampleInquiry,
3033 deleteLead,
3134 editLead,
@@ -52,8 +55,10 @@ import {
5255 setState,
5356 CADENCE_MAX_DAY,
5457 CADENCE_MAX_TOUCHES,
58 type SignInPreview,
5559 } from "./actions.ts";
5660 import { missingLine } from "./intake.ts";
61 import { MAX_SIGNIN_LINES } from "./signins.ts";
5762 import { dateName, MAX_AWAY_DAYS } from "./putaway.ts";
5863 import { showingLine, showingWhen } from "./showings.ts";
5964 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
@@ -169,6 +174,7 @@ type View =
169174 | { name: "lost"; id: number }
170175 | { name: "details"; id: number; step: number; typed: string; fields: Record<string, string> }
171176 | { name: "paste"; text: string }
177 | { name: "signins"; step: "address" | "text" | "check"; address: string; text: string; preview?: SignInPreview }
172178 | { name: "add"; step: number; typed: string; fields: Record<string, string>; found?: Record<string, string>; note?: string }
173179 | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View };
174180
@@ -297,7 +303,7 @@ export function terminal(
297303 lines.push(
298304 "",
299305 dim(
300 `j/k move · enter open · f view · / find · n log a lead · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
306 `j/k move · enter open · f view · / find · n log a lead · o open house · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
301307 ),
302308 );
303309 return lines;
@@ -536,6 +542,27 @@ export function terminal(
536542 return lines;
537543 }
538544
545 function signinsScreen(v: Extract<View, { name: "signins" }>): string[] {
546 const lines = [bold("Open house sign-ins"), ""];
547 if (v.step === "address")
548 return [...lines, `Property address: ${clean(v.address)}█`, "", dim("enter next · esc cancel")];
549 lines.push(`Property address: ${clean(v.address)}`, "");
550 if (v.step === "text") {
551 const shown = clean(v.text).split("\n").slice(-12);
552 lines.push(...shown.map((l, i) => (i === shown.length - 1 ? `${l}█` : l)));
553 lines.push("", dim(`one visitor per line: name, then email and/or phone · at most ${MAX_SIGNIN_LINES} lines · ctrl-d read it · esc cancel`));
554 return lines;
555 }
556 for (const r of v.preview?.visitors ?? [])
557 lines.push(
558 r.problem === undefined
559 ? ` ${clean(r.name)} · ${r.email === "" ? "no email" : clean(r.email)} · ${r.phone === "" ? "no phone" : clean(r.phone)}`
560 : ` ${bold("cannot read")} line ${r.line}: ${clean(r.raw)} (${r.problem})`,
561 );
562 lines.push("", dim(`y add ${v.preview?.readable ?? 0} with a thank-you drafted (nothing is sent) · esc cancel`));
563 return lines;
564 }
565
539566 function pasteScreen(v: Extract<View, { name: "paste" }>): string[] {
540567 const lines = [bold("Paste a lead email"), ""];
541568 const shown = clean(v.text).split("\n").slice(-12);
@@ -671,6 +698,8 @@ export function terminal(
671698 ? detailsScreen(view)
672699 : view.name === "paste"
673700 ? pasteScreen(view)
701 : view.name === "signins"
702 ? signinsScreen(view)
674703 : view.name === "add"
675704 ? addScreen(view)
676705 : [
@@ -705,6 +734,7 @@ export function terminal(
705734 cursor = 0;
706735 } else if (input === "/") view = { name: "search", typed: q };
707736 else if (input === "v") view = { name: "paste", text: "" };
737 else if (input === "o") view = { name: "signins", step: "address", address: "", text: "" };
708738 else if (input === "n")
709739 view = { name: "add", step: 0, typed: "", fields: {} };
710740 else if (input === "i") {
@@ -1022,6 +1052,38 @@ export function terminal(
10221052 }
10231053 return;
10241054 }
1055 case "signins": {
1056 if (input === "\x1b") {
1057 said = "Nothing added.";
1058 view = { name: "desk" };
1059 } else if (view.step === "address") {
1060 if (input === "\r") view = { ...view, step: "text" };
1061 else {
1062 const next = typing(view.address, input);
1063 if (next !== undefined) view = { ...view, address: next };
1064 }
1065 } else if (view.step === "text") {
1066 if (input === "\x04") {
1067 const read = previewSignIns(me, { address: view.address, text: view.text });
1068 if (read.ok) view = { ...view, step: "check", preview: read.value };
1069 else {
1070 said = read.message;
1071 view = { name: "desk" };
1072 }
1073 } else if (input === "\r") view = { ...view, text: `${view.text}\n` };
1074 else {
1075 const text = input.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
1076 view = input === "\x7f" || input === "\b" ? { ...view, text: view.text.slice(0, -1) } : { ...view, text: view.text + text };
1077 }
1078 } else if (input === "y") {
1079 const added = addSignIns(db, me, { address: view.address, text: view.text }, new Date(now()));
1080 said = added.ok
1081 ? `${added.value.added.length} added with a thank-you drafted${added.value.again.length === 0 ? "" : `, ${added.value.again.length} already on the desk`}${added.value.skipped.length === 0 ? "" : `, ${added.value.skipped.length} left out`}. Nothing is sent.`
1082 : added.message;
1083 view = { name: "desk" };
1084 }
1085 return;
1086 }
10251087 case "add": {
10261088 if (input === "\x1b") {
10271089 said = "Nothing logged.";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs