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

A one-page "this week" report the agent can print or show their broker: leads in, answered within 5 minutes, showings, closed and lost #96

Merged opened this

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

Merged

mason/speed-to-lead:mason/94-a-one-page-this-week-report-the-agent-ca → main 4 commits fork

  • Merged. mason/94-a-one-page-this-week-report-the-agent-ca was merged into main as 4e8ad15.

Review

Sign in to review this change.
20 files changed +965 −23
README.md +19
@@ -142,6 +142,11 @@ what you see right after a restart. Do step 1 first.
142142 (to someone who has not agreed to be texted, so the card says so and the
143143 choice is yours), held until 8:00 a.m. if you approve it after hours. The referrer shows on the lead's page, in
144144 the spreadsheet and in Activity, and is never put in a message to the lead.
145 13. For the sales meeting, press "This week's report" under the list: one
146 printable page (no nav, no JavaScript) with the last 7 days in your time
147 zone beside the 7 before: leads in by source, median time to first reply
148 and how many were answered inside 5 minutes, follow-ups sent, showings
149 booked, leads marked qualified and lost with their reasons.
145150
146151 Nothing is really sent in this prototype: "send" records the message in the
147152 lead's history and goes no further. To run the tour again, restart the
@@ -543,6 +548,8 @@ On the desk:
543548 phone, source as a number, what they asked, consent `y` or `n`).
544549 - `f` cycles the views (needs you, in follow-up, closed, all); the desk
545550 shows the current one with its count.
551 - `w` shows this week's report (the last 7 days beside the 7 before, in the
552 same words as the page; `esc` goes back).
546553 - `x` shows the leads as CSV for the current view and search.
547554 - `R` restarts the sample leads from now (admins only; asks first).
548555 - `esc` leaves.
@@ -562,6 +569,18 @@ until you press a key on this screen:
562569 - `D` removes the lead (admins only; asks first).
563570 - `esc` goes back to the desk.
564571
572 ## The week on one page
573
574 `GET /report` (the desk's "This week's report" link) shows the last 7
575 calendar days in the agent's time zone, today included, beside the 7 before.
576 Leads, answer times and losses come from the same code as the desk's response
577 record (`responseRecord`, `lostCounts`), so the two never disagree; follow-ups
578 sent (everything sent after the first reply except answers to a lead's own
579 message), showings booked and leads qualified are counted in `src/report.ts`.
580 A lead is "qualified" in the week it was marked qualified (`lead.qualified_at`, set when it is marked and cleared when reopened), so a later edit or note never moves it; one qualified and then lost counts in both. Follow-ups sent are days after the first reply (day 0) and before the answers to a lead's own messages. The terminal's `w` shows the same report. A script
581 asks the same path for `application/json` (in `/openapi.json`); the MCP tool is
582 `weekly_report`. It needs the right to list leads, like the desk; anon gets 401.
583
565584 ## Taking your leads with you
566585
567586 Every lead and its status, as a spreadsheet, for whoever may list leads, with no cap on the count:
contract/openapi.json +289
@@ -168,6 +168,295 @@
168168 }
169169 }
170170 },
171 "/report": {
172 "get": {
173 "summary": "This week for the agent's broker: the last 7 days in the agent's time zone beside the 7 before — leads in by source, median time to first reply and leads answered inside 5 minutes (the response record's rules), follow-ups sent, showings booked, leads qualified and lost with reasons. Ask for application/json.",
174 "operationId": "getReport",
175 "responses": {
176 "200": {
177 "description": "This week for the agent's broker: the last 7 days in the agent's time zone beside the 7 before — leads in by source, median time to first reply and leads answered inside 5 minutes (the response record's rules), follow-ups sent, showings booked, leads qualified and lost with reasons. Ask for application/json.",
178 "content": {
179 "application/json": {
180 "schema": {
181 "type": "object",
182 "properties": {
183 "days": {
184 "type": "integer",
185 "minimum": 0
186 },
187 "time_zone": {
188 "type": "string"
189 },
190 "this_week": {
191 "type": "object",
192 "properties": {
193 "from": {
194 "type": "string",
195 "format": "date-time",
196 "description": "Midnight opening the week, in the agent's zone."
197 },
198 "to": {
199 "type": "string",
200 "format": "date-time",
201 "description": "Where the week ends (exclusive); now for the current week."
202 },
203 "leads": {
204 "type": "integer",
205 "minimum": 0
206 },
207 "replied": {
208 "type": "integer",
209 "minimum": 0
210 },
211 "answered_within_5_min": {
212 "type": "integer",
213 "minimum": 0,
214 "description": "Leads answered, or still waiting, under five minutes."
215 },
216 "median_ms": {
217 "type": [
218 "integer",
219 "null"
220 ],
221 "description": "Median time to first reply in milliseconds; null with no leads."
222 },
223 "within_5_min_pct": {
224 "type": [
225 "integer",
226 "null"
227 ],
228 "description": "Whole percent of the week's leads answered inside 5 minutes."
229 },
230 "by_source": {
231 "type": "array",
232 "items": {
233 "type": "object",
234 "properties": {
235 "source": {
236 "type": "string"
237 },
238 "count": {
239 "type": "integer",
240 "minimum": 0
241 },
242 "median_ms": {
243 "type": "integer"
244 },
245 "under_five": {
246 "type": "integer",
247 "minimum": 0
248 }
249 },
250 "required": [
251 "source",
252 "count",
253 "median_ms",
254 "under_five"
255 ]
256 }
257 },
258 "follow_ups_sent": {
259 "type": "integer",
260 "minimum": 0
261 },
262 "showings_booked": {
263 "type": "integer",
264 "minimum": 0
265 },
266 "qualified": {
267 "type": "integer",
268 "minimum": 0
269 },
270 "lost": {
271 "type": "array",
272 "items": {
273 "type": "object",
274 "properties": {
275 "reason": {
276 "type": [
277 "string",
278 "null"
279 ]
280 },
281 "count": {
282 "type": "integer",
283 "minimum": 0
284 }
285 },
286 "required": [
287 "reason",
288 "count"
289 ]
290 }
291 },
292 "lost_total": {
293 "type": "integer",
294 "minimum": 0
295 }
296 },
297 "required": [
298 "from",
299 "to",
300 "leads",
301 "replied",
302 "answered_within_5_min",
303 "median_ms",
304 "within_5_min_pct",
305 "by_source",
306 "follow_ups_sent",
307 "showings_booked",
308 "qualified",
309 "lost",
310 "lost_total"
311 ]
312 },
313 "week_before": {
314 "type": "object",
315 "properties": {
316 "from": {
317 "type": "string",
318 "format": "date-time",
319 "description": "Midnight opening the week, in the agent's zone."
320 },
321 "to": {
322 "type": "string",
323 "format": "date-time",
324 "description": "Where the week ends (exclusive); now for the current week."
325 },
326 "leads": {
327 "type": "integer",
328 "minimum": 0
329 },
330 "replied": {
331 "type": "integer",
332 "minimum": 0
333 },
334 "answered_within_5_min": {
335 "type": "integer",
336 "minimum": 0,
337 "description": "Leads answered, or still waiting, under five minutes."
338 },
339 "median_ms": {
340 "type": [
341 "integer",
342 "null"
343 ],
344 "description": "Median time to first reply in milliseconds; null with no leads."
345 },
346 "within_5_min_pct": {
347 "type": [
348 "integer",
349 "null"
350 ],
351 "description": "Whole percent of the week's leads answered inside 5 minutes."
352 },
353 "by_source": {
354 "type": "array",
355 "items": {
356 "type": "object",
357 "properties": {
358 "source": {
359 "type": "string"
360 },
361 "count": {
362 "type": "integer",
363 "minimum": 0
364 },
365 "median_ms": {
366 "type": "integer"
367 },
368 "under_five": {
369 "type": "integer",
370 "minimum": 0
371 }
372 },
373 "required": [
374 "source",
375 "count",
376 "median_ms",
377 "under_five"
378 ]
379 }
380 },
381 "follow_ups_sent": {
382 "type": "integer",
383 "minimum": 0
384 },
385 "showings_booked": {
386 "type": "integer",
387 "minimum": 0
388 },
389 "qualified": {
390 "type": "integer",
391 "minimum": 0
392 },
393 "lost": {
394 "type": "array",
395 "items": {
396 "type": "object",
397 "properties": {
398 "reason": {
399 "type": [
400 "string",
401 "null"
402 ]
403 },
404 "count": {
405 "type": "integer",
406 "minimum": 0
407 }
408 },
409 "required": [
410 "reason",
411 "count"
412 ]
413 }
414 },
415 "lost_total": {
416 "type": "integer",
417 "minimum": 0
418 }
419 },
420 "required": [
421 "from",
422 "to",
423 "leads",
424 "replied",
425 "answered_within_5_min",
426 "median_ms",
427 "within_5_min_pct",
428 "by_source",
429 "follow_ups_sent",
430 "showings_booked",
431 "qualified",
432 "lost",
433 "lost_total"
434 ]
435 }
436 },
437 "required": [
438 "days",
439 "time_zone",
440 "this_week",
441 "week_before"
442 ]
443 }
444 }
445 }
446 },
447 "default": {
448 "description": "{ error, message }: why not",
449 "content": {
450 "application/json": {
451 "schema": {
452 "$ref": "#/components/schemas/Error"
453 }
454 }
455 }
456 }
457 }
458 }
459 },
171460 "/leads.csv": {
172461 "get": {
173462 "summary": "Every lead and its status as a spreadsheet (CSV), narrowed like the desk by show and q, with no cap on the count.",
docs/design/areas/report.md added +13
@@ -0,0 +1,13 @@
1 # Report: this week
2
3 `/report` is one page for the agent's broker. Server-rendered, no JavaScript
4 (the layout is given `bare`, which leaves the scripts out).
5
6 New classes: `.report` (the article), `.report-table` (a table of metric,
7 last 7 days, the 7 before; under 40rem each row stacks and the column names
8 move into the cells), `.report-note` (the caption, in `.muted`), and
9 `.report-actions` (the way back; hidden in print).
10
11 Print (`@media print`): the header, footer and `.report-actions` are hidden,
12 the page is black on white, and the article avoids a page break so it prints
13 on one sheet.
src/actions.ts +8
@@ -86,6 +86,7 @@ import { nextInquiry, seed } from "./sample.ts";
8686 import { goesAt, isZone } from "./quiet.ts";
8787 import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
8888 import { MAX_ADDRESS, timeOf } from "./showings.ts";
89 import { weekReport, type WeekReport } from "./report.ts";
8990 import { draftPriceChange, readChange, type Outcome as PriceChanged } from "./price-change.ts";
9091 import { dateOf } from "./putaway.ts";
9192 import { MAX_SIGNIN_LINES, MAX_SIGNIN_TEXT, readSignIns, type SignIn } from "./signins.ts";
@@ -165,6 +166,13 @@ export function listLeads(
165166 });
166167 }
167168
169 /** This week against the week before, read as a lead list is: whoever may not list leads is refused as they are at the desk. */
170 export function reportWeek(db: Database, who: Who, input: { now?: number } = {}): Result<WeekReport> {
171 if (permit(who, "lead", "list") !== "yes")
172 return refuse(who, "Sign in to open the report.", "You may not see the report.");
173 return ok(weekReport(db, input.now ?? Date.now(), currentAgent(db).timeZone));
174 }
175
168176 /**
169177 * Every lead the desk would show for `show` and `q`, as a spreadsheet: all of
170178 * them, however many, under the same gate as the desk.
src/contract.test.ts +3
@@ -13,6 +13,7 @@ import {
1313 addSampleInquiry,
1414 deleteLead,
1515 exportLeads,
16 reportWeek,
1617 editLead,
1718 getAudit,
1819 getLead,
@@ -139,6 +140,8 @@ const doors: Record<
139140 list: (who) => {
140141 const listed = listLeads(db, who).ok;
141142 expect(exportLeads(db, who).ok).toBe(listed);
143 // And so is the week's report (GET /report, the MCP tool weekly_report).
144 expect(reportWeek(db, who).ok).toBe(listed);
142145 return listed;
143146 },
144147 read: (who, authorId) => getLead(db, who, { id: aLead(authorId) }).ok,
src/db.ts +4
@@ -306,6 +306,10 @@ export const migrations: string[] = [
306306 PRIMARY KEY (lead_id, day),
307307 UNIQUE (lead_id, street, price)
308308 )`,
309 // When a lead became qualified, so the week report counts it in that week and an edit or a note made later cannot move it.
310 // Kept when the lead is later lost; cleared when it is reopened. Leads qualified before this existed use their last change.
311 `ALTER TABLE lead ADD COLUMN qualified_at TEXT`,
312 `UPDATE lead SET qualified_at = updated_at WHERE state = 'qualified'`,
309313 ];
310314
311315 /**
src/leads.ts +27 −11
@@ -238,8 +238,10 @@ type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostA
238238 note_updated_at: string | null;
239239 lost_reason: LostReason | null;
240240 lost_at: string | null;
241 /** When it became qualified (see report.ts); not part of a Lead. */
242 qualified_at: string | null;
241243 };
242 const lead = ({ note_updated_at, lost_reason, lost_at, ...row }: LeadRecord): Lead => ({
244 const lead = ({ note_updated_at, lost_reason, lost_at, qualified_at: _qualifiedAt, ...row }: LeadRecord): Lead => ({
243245 ...row,
244246 consent: row.consent === 1,
245247 starred: row.starred === 1,
@@ -510,20 +512,34 @@ const medianOf = (sorted: readonly number[]): number => {
510512
511513 export const RECORD_DAYS = 30;
512514
515 /** Where a record starts: the instant its window opens, and where the window before it opens. */
516 export interface RecordWindow {
517 readonly days: number;
518 readonly from: number;
519 readonly earlierFrom: number;
520 /** Where the window closes; open-ended (up to now) when absent. */
521 readonly to?: number;
522 }
523
513524 /**
514525 * The record over the last 30 days. A lead still waiting is measured by
515526 * its time so far, so the numbers cannot improve by ignoring red clocks.
516527 */
517 export function responseRecord(db: Database, now: number): ResponseRecord {
518 const cut = now - RECORD_DAYS * DAY_MS;
519 const since = new Date(cut - RECORD_DAYS * DAY_MS).toISOString();
520 const cutIso = new Date(cut).toISOString();
528 export function responseRecord(
529 db: Database,
530 now: number,
531 /** The window to read: by default the last 30 days and the 30 before; the weekly report passes its own. */
532 window: RecordWindow = { days: RECORD_DAYS, from: now - RECORD_DAYS * DAY_MS, earlierFrom: now - 2 * RECORD_DAYS * DAY_MS },
533 ): ResponseRecord {
534 const since = new Date(window.earlierFrom).toISOString();
535 const cutIso = new Date(window.from).toISOString();
536 const endIso = window.to === undefined ? "9999" : new Date(window.to).toISOString();
521537 // One pass: the earlier window is read with the same rules as the current one.
522538 const rows = db
523 .query<{ source: Source; created_at: string; replied_at: string | null }, [string]>(
524 "SELECT source, created_at, replied_at FROM lead WHERE created_at >= ?1",
539 .query<{ source: Source; created_at: string; replied_at: string | null }, [string, string]>(
540 "SELECT source, created_at, replied_at FROM lead WHERE created_at >= ?1 AND created_at < ?2",
525541 )
526 .all(since)
542 .all(since, endIso)
527543 .map((row) => ({
528544 source: row.source,
529545 current: row.created_at >= cutIso,
@@ -553,7 +569,7 @@ export function responseRecord(db: Database, now: number): ResponseRecord {
553569 }))
554570 .sort((a, b) => b.count - a.count || a.source.localeCompare(b.source));
555571 return {
556 days: RECORD_DAYS,
572 days: window.days,
557573 leads: n,
558574 replied: all.filter((w) => w.replied).length,
559575 median_ms: n === 0 ? null : medianOf(all.map((w) => w.ms)),
@@ -1034,7 +1050,7 @@ export type Closing = { readonly state: "qualified" } | { readonly state: "lost"
10341050 export function close(db: Database, id: number, closing: Closing, at: string): void {
10351051 db.transaction(() => {
10361052 db.query(
1037 "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5, back_on = NULL WHERE id = ?3",
1053 "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5, qualified_at = CASE WHEN ?1 = 'qualified' THEN ?2 ELSE qualified_at END, back_on = NULL WHERE id = ?3",
10381054 ).run(
10391055 closing.state,
10401056 at,
@@ -1058,7 +1074,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
10581074 db.transaction(() => {
10591075 const replied = found.replied_at !== null;
10601076 db.query(
1061 "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = NULL, lost_at = NULL WHERE id = ?3",
1077 "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = NULL, lost_at = NULL, qualified_at = NULL WHERE id = ?3",
10621078 ).run(
10631079 replied ? "contacted" : "new",
10641080 at,
src/lost.ts +6 −5
@@ -33,14 +33,15 @@ export interface LostCount {
3333 const DAY_MS = 86_400_000;
3434
3535 /** Leads lost in the 30 days up to `now`, counted by reason, the listed reasons first (zeros left out). */
36 export function lostCounts(db: Database, now: number): LostCount[] {
37 const since = new Date(now - 30 * DAY_MS).toISOString();
36 export function lostCounts(db: Database, now: number, from: number = now - 30 * DAY_MS, to?: number): LostCount[] {
37 const since = new Date(from).toISOString();
38 const until = to === undefined ? "9999" : new Date(to).toISOString();
3839 const found = new Map<string | null, number>(
3940 db
40 .query<{ reason: string | null; count: number }, [string]>(
41 "SELECT lost_reason AS reason, count(*) AS count FROM lead WHERE state = 'lost' AND coalesce(lost_at, updated_at) >= ?1 GROUP BY lost_reason",
41 .query<{ reason: string | null; count: number }, [string, string]>(
42 "SELECT lost_reason AS reason, count(*) AS count FROM lead WHERE state = 'lost' AND coalesce(lost_at, updated_at) >= ?1 AND coalesce(lost_at, updated_at) < ?2 GROUP BY lost_reason",
4243 )
43 .all(since)
44 .all(since, until)
4445 .map((r) => [r.reason, r.count]),
4546 );
4647 return [...LOST_REASONS, null]
src/mcp.ts +8
@@ -13,6 +13,7 @@ import {
1313 skipThanksFor,
1414 addSampleInquiry,
1515 exportLeads,
16 reportWeek,
1617 getLead,
1718 getProfile,
1819 listLeads,
@@ -101,6 +102,13 @@ export const tools: readonly Tool[] = [
101102 q: args.q,
102103 }),
103104 },
105 {
106 name: "weekly_report",
107 description:
108 "This week for the agent's broker: the last 7 days in the agent's time zone beside the 7 before — leads in by source, median first reply and leads answered inside 5 minutes (the response record's rules), follow-ups sent, showings booked, leads qualified, leads lost with reasons. Returns { this_week, week_before }.",
109 inputSchema: { type: "object", properties: {} },
110 run: (db, who) => reportWeek(db, who),
111 },
104112 {
105113 name: "export_leads",
106114 description:
src/pages/desk.ts +1 −1
@@ -107,7 +107,7 @@ export function deskPage(input: {
107107 ${search}
108108 ${views}
109109 ${list}
110 <p class="export"><a href="${escape(exportHref(show, q))}" download>Download leads (CSV)</a></p>
110 <p class="export"><a href="${escape(exportHref(show, q))}" download>Download leads (CSV)</a> · <a href="/report">This week's report</a></p>
111111 </div>
112112 ${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)}` : ""}
113113 ${input.mayPrice === true ? priceForm : ""}
src/pages/layout.ts +4 −2
@@ -28,6 +28,8 @@ export function layout(input: {
2828 /** A title that replaces the heading: the desk's, with the count of leads waiting. */
2929 tab?: string;
3030 notice?: string | undefined;
31 /** A page that ships no JavaScript at all (the report). */
32 bare?: boolean;
3133 }): string {
3234 const { body, who, agent, path, notice } = input;
3335 const name = input.tab ?? (input.heading === undefined ? title : `${input.heading} · ${title}`);
@@ -59,9 +61,9 @@ export function layout(input: {
5961 <meta name="twitter:description" content="${escape(description)}">
6062 <link rel="stylesheet" href="${tokensHref}">
6163 <link rel="stylesheet" href="${asset("app.css")}">
62 <script type="module" src="${asset("live.js")}"></script>
64 ${input.bare === true ? "" : `<script type="module" src="${asset("live.js")}"></script>
6365 <script type="module" src="${asset("clock.js")}"></script>
64 <script type="module" src="${asset("replies.js")}"></script>
66 <script type="module" src="${asset("replies.js")}"></script>`}
6567 <body>
6668 <div class="page">
6769 <header class="head">
src/pages/report.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * The week, on one page: server-rendered, no JavaScript, and printable on
3 * one sheet without the nav. Every number is said in words, this week
4 * beside the week before. All text is escaped.
5 */
6
7 import type { Agent } from "../env.ts";
8 import { escape } from "../http.ts";
9 import { REPORT_ROWS } from "../report-words.ts";
10 import type { Week, WeekReport } from "../report.ts";
11 import type { Who } from "../who.ts";
12 import { layout } from "./layout.ts";
13 import { day } from "./parts.ts";
14
15 const range = (w: Week, zone: string, last: string): string =>
16 `${day(w.from, zone)} – ${day(last, zone)}`;
17
18 export function reportPage(input: { who: Who; agent: Agent; report: WeekReport }): string {
19 const { who, agent, report } = input;
20 const zone = agent.timeZone;
21 const { this_week: now, week_before: before } = report;
22 const body = REPORT_ROWS.map(
23 ([label, say]) =>
24 `<tr><th scope="row">${escape(label)}</th><td>${escape(say(now))}</td><td class="muted">${escape(say(before))}</td></tr>`,
25 ).join("");
26 return layout({
27 who,
28 agent,
29 path: "/report",
30 heading: "This week",
31 bare: true,
32 body: `<article class="report">
33 <h1>This week at ${escape(agent.name)}'s desk</h1>
34 <p class="muted">${escape(range(now, zone, now.to))} beside ${escape(range(before, zone, new Date(Date.parse(before.to) - 1).toISOString()))} · times in ${escape(zone)}</p>
35 <table class="report-table">
36 <caption class="report-note muted">Answer times follow the response record: a lead still waiting counts its time so far.</caption>
37 <thead><tr><th scope="col">&nbsp;</th><th scope="col">Last 7 days</th><th scope="col">The 7 before</th></tr></thead>
38 <tbody>${body}</tbody>
39 </table>
40 <p class="report-actions"><a href="/">Back to the desk</a> <span class="muted">· Print this page: it fits one sheet.</span></p>
41 </article>`,
42 });
43 }
src/report-words.ts added +38
@@ -0,0 +1,38 @@
1 /**
2 * The week report said in words: one row per number, this week and the week
3 * before. The page and the terminal both read these, so they never differ.
4 * Plain data in, plain strings out (the page escapes them).
5 */
6
7 import { span } from "./clock.ts";
8 import { SOURCE_LABEL } from "./drafts.ts";
9 import { REASON_LABEL } from "./lost.ts";
10 import type { Week } from "./report.ts";
11
12 const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
13
14 const bySource = (w: Week): string =>
15 w.by_source.length === 0
16 ? "—"
17 : w.by_source.map((s) => `${plural(s.count, "lead")} from ${SOURCE_LABEL[s.source] ?? s.source}`).join(", ");
18
19 const answers = (w: Week): string =>
20 w.leads === 0
21 ? "—"
22 : `${w.leads} ${w.leads === 1 ? "lead" : "leads"}, ${w.answered_within_5_min} answered inside 5 minutes (${w.within_5_min_pct}%)`;
23
24 const losses = (w: Week): string =>
25 w.lost_total === 0
26 ? "No lead lost"
27 : `${w.lost_total} lost: ${w.lost.map((l) => `${l.count} ${l.reason === null ? "no reason given" : REASON_LABEL[l.reason]}`).join(", ")}`;
28
29 export const REPORT_ROWS: readonly (readonly [string, (w: Week) => string])[] = [
30 ["Leads in", (w) => (w.leads === 0 ? "No leads" : plural(w.leads, "lead"))],
31 ["By source", bySource],
32 ["Answered fast", answers],
33 ["Median time to first reply", (w) => (w.median_ms === null ? "—" : span(w.median_ms))],
34 ["Follow-ups sent", (w) => plural(w.follow_ups_sent, "follow-up") + " sent"],
35 ["Showings booked", (w) => plural(w.showings_booked, "showing") + " booked"],
36 ["Marked qualified", (w) => plural(w.qualified, "lead") + " qualified"],
37 ["Lost", losses],
38 ];
src/report.test.ts added +218
@@ -0,0 +1,218 @@
1 /**
2 * The week report: the counts across the week's edge in a zone that is not
3 * UTC, the same answer as the response record, the refusal, the JSON shape,
4 * the page in words, and the sample desk showing non-zero numbers.
5 */
6 import { afterAll, 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 { reportWeek, setNote, setState } from "./actions.ts";
11 import { openDb } from "./db.ts";
12 import { insertLead, responseRecord } from "./leads.ts";
13 import { reportPage } from "./pages/report.ts";
14 import { currentAgent } from "./profile.ts";
15 import { weekReport } from "./report.ts";
16 import { seed } from "./sample.ts";
17 import { serve } from "./server.ts";
18 import { tools } from "./mcp.ts";
19 import { sign } from "./who.ts";
20 import type { Who } from "./who.ts";
21
22 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-report-")));
23 const LA = "America/Los_Angeles";
24 // Monday 9 March 2026, 03:00 in Los Angeles (daylight time began the day before).
25 const NOW = Date.parse("2026-03-09T10:00:00Z");
26 let n = 0;
27 const arrive = (db: ReturnType<typeof fresh>, at: string, source = "website", answeredMs?: number): number => {
28 n++;
29 const id = insertLead(
30 db,
31 { name: `Pat ${n}`, email: `p${n}@example.com`, phone: "", source: source as "website", message: "Hello", consent: false },
32 at,
33 currentAgent(db),
34 );
35 if (answeredMs !== undefined)
36 db.query("UPDATE lead SET replied_at = ?1 WHERE id = ?2").run(new Date(Date.parse(at) + answeredMs).toISOString(), id);
37 return id;
38 };
39
40 test("a week is seven calendar days in the agent's zone: a lead at 23:30 the evening before belongs to the week before", () => {
41 const db = fresh();
42 // The week opens at midnight Tuesday 3 March in Los Angeles: 08:00 UTC.
43 arrive(db, "2026-03-03T07:30:00.000Z", "zillow", 60_000); // Mar 2, 23:30 PST: the week before
44 arrive(db, "2026-03-03T08:30:00.000Z", "zillow", 60_000); // 00:30 PST: this week
45 arrive(db, "2026-03-09T09:00:00.000Z", "website", 10 * 60_000); // today, slow
46 arrive(db, "2026-02-24T07:59:00.000Z", "website", 60_000); // before even the week before
47 const report = weekReport(db, NOW, LA);
48 expect(report.this_week.leads).toBe(2);
49 expect(report.this_week.answered_within_5_min).toBe(1);
50 expect(report.this_week.by_source.map((s) => [s.source, s.count])).toEqual([["website", 1], ["zillow", 1]]);
51 expect(report.week_before.leads).toBe(1);
52 expect(report.this_week.from).toBe("2026-03-03T08:00:00.000Z");
53 expect(report.week_before.from).toBe("2026-02-24T08:00:00.000Z");
54 // In UTC the same instants fall differently: the week opens at 00:00Z on 3 March, so the 07:30Z lead is in it.
55 expect(weekReport(db, NOW, "UTC").this_week.leads).toBe(3);
56 expect(weekReport(db, NOW, "UTC").week_before.leads).toBe(1);
57 expect(weekReport(db, Date.parse("2026-03-03T07:45:00Z"), "UTC").this_week.leads).toBe(1);
58 });
59
60 test("the numbers are the response record's, not a recount", () => {
61 const db = fresh();
62 arrive(db, "2026-03-05T18:00:00.000Z", "zillow", 30_000);
63 arrive(db, "2026-03-06T18:00:00.000Z", "website", 20 * 60_000);
64 arrive(db, "2026-03-07T18:00:00.000Z", "website"); // still waiting: counts its time so far
65 const week = weekReport(db, NOW, LA).this_week;
66 const record = responseRecord(db, NOW);
67 expect(week.leads).toBe(record.leads);
68 expect(week.median_ms).toBe(record.median_ms);
69 expect(week.within_5_min_pct).toBe(record.within_5_min_pct);
70 expect(week.by_source).toEqual(record.by_source);
71 expect(week.replied).toBe(2);
72 });
73
74 test("follow-ups, showings, qualified and lost are counted inside the week only", () => {
75 const db = fresh();
76 const a = arrive(db, "2026-03-01T18:00:00.000Z", "zillow", 60_000);
77 const sent = (day: number, at: string) =>
78 db
79 .query("INSERT INTO message (lead_id, day, channel, body, signature, status, due_at, sent_at) VALUES (?1, ?2, 'email', 'hi', 'sig', 'sent', ?3, ?3)")
80 .run(a, day, at);
81 sent(1, "2026-03-04T18:00:00.000Z"); // this week
82 sent(3, "2026-03-07T18:00:00.000Z"); // this week
83 sent(7, "2026-03-02T18:00:00.000Z"); // the week before
84 sent(1001, "2026-03-08T18:00:00.000Z"); // an answer to what they wrote: not a follow-up
85 db.query("INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (?1, ?2, '1 Elm', ?2, ?3)").run(a, "2026-03-12T18:00:00.000Z", "2026-03-06T18:00:00.000Z");
86 const b = arrive(db, "2026-03-01T18:00:00.000Z");
87 db.query("UPDATE lead SET state = 'qualified', qualified_at = ?2, updated_at = ?2 WHERE id = ?1").run(b, "2026-03-05T18:00:00.000Z");
88 const c = arrive(db, "2026-03-01T18:00:00.000Z");
89 db.query("UPDATE lead SET state = 'lost', lost_reason = 'not_ready', lost_at = ?2, updated_at = ?2 WHERE id = ?1").run(c, "2026-03-04T18:00:00.000Z");
90 const d = arrive(db, "2026-02-20T18:00:00.000Z");
91 db.query("UPDATE lead SET state = 'lost', lost_reason = 'other', lost_at = ?2, updated_at = ?2 WHERE id = ?1").run(d, "2026-02-27T18:00:00.000Z");
92 const { this_week: now, week_before: before } = weekReport(db, NOW, LA);
93 expect([now.follow_ups_sent, now.showings_booked, now.qualified, now.lost_total]).toEqual([2, 1, 1, 1]);
94 expect(now.lost).toEqual([{ reason: "not_ready", count: 1 }]);
95 expect([before.follow_ups_sent, before.showings_booked, before.qualified, before.lost_total]).toEqual([1, 0, 0, 1]);
96 expect(before.lost).toEqual([{ reason: "other", count: 1 }]);
97 });
98
99 test("whoever cannot list leads is refused as at the desk; a user gets the report", () => {
100 const db = fresh();
101 const anon: Who = { role: "anon", id: "", name: "" };
102 const user: Who = { role: "user", id: "u1", name: "alice" };
103 const refused = reportWeek(db, anon);
104 expect(refused.ok).toBe(false);
105 if (!refused.ok) expect(refused.error).toBe("signin_required");
106 expect(reportWeek(db, user, { now: NOW }).ok).toBe(true);
107 expect(tools.find((t) => t.name === "weekly_report")!.run(db, anon, {}).ok).toBe(false);
108 expect(tools.find((t) => t.name === "weekly_report")!.run(db, user, {}).ok).toBe(true);
109 });
110
111 test("the sample desk gives a report with non-zero numbers, said in words", () => {
112 const db = fresh();
113 seed(db, new Date());
114 const user: Who = { role: "user", id: "u1", name: "alice" };
115 const report = reportWeek(db, user);
116 if (!report.ok) throw new Error(report.message);
117 const week = report.value.this_week;
118 expect(week.leads).toBeGreaterThan(0);
119 expect(week.answered_within_5_min).toBeGreaterThan(0);
120 expect(week.median_ms).not.toBeNull();
121 const page = reportPage({ who: user, agent: currentAgent(db), report: report.value });
122 expect(page).toContain(`${week.leads} leads, ${week.answered_within_5_min} answered inside 5 minutes`);
123 expect(page).not.toContain("<script");
124 });
125
126 const KEY = "a-key-only-the-forge-holds";
127 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-report-srv-")), identityKey: KEY });
128 const base = `http://${server.hostname}:${server.port}`;
129 afterAll(() => server.stop(true));
130 const alice = (() => {
131 const identity = `u1|alice|user|${Date.now() + 600_000}`;
132 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
133 })();
134
135 test("/report is a page with a print stylesheet and no script, and JSON for a script", async () => {
136 const page = await fetch(`${base}/report`, { headers: { ...alice, accept: "text/html" } });
137 expect(page.status).toBe(200);
138 const html = await page.text();
139 expect(html).toContain("This week at");
140 expect(html).not.toContain("<script");
141 expect(await (await fetch(`${base}/`, { headers: alice })).text()).toContain('href="/report"');
142 const res = await fetch(`${base}/report`, { headers: { ...alice, accept: "application/json" } });
143 expect(res.headers.get("content-type")).toContain("application/json");
144 const body = (await res.json()) as Record<string, any>;
145 expect(Object.keys(body).sort()).toEqual(["days", "this_week", "time_zone", "week_before"]);
146 expect(body.days).toBe(7);
147 expect(Object.keys(body.this_week).sort()).toEqual(
148 ["answered_within_5_min", "by_source", "follow_ups_sent", "from", "leads", "lost", "lost_total", "median_ms", "qualified", "replied", "showings_booked", "to", "within_5_min_pct"],
149 );
150 expect(body.this_week.leads).toBeGreaterThan(0);
151 });
152
153 test("anyone who cannot list leads gets the usual refusal at /report", async () => {
154 const json = await fetch(`${base}/report`, { headers: { accept: "application/json" } });
155 expect(json.status).toBe(401);
156 const page = await fetch(`${base}/report`, { headers: { accept: "text/html" } });
157 expect(page.status).toBe(401);
158 expect(await page.text()).toContain("Sign in to open the report.");
159 });
160
161 test("a later note or touch on a qualified lead does not move it between weeks; the week it was marked is the week it counts in", () => {
162 const db = fresh();
163 const alice: Who = { role: "user", id: "u1", name: "alice" };
164 const id = arrive(db, "2026-03-01T18:00:00.000Z");
165 db.query("UPDATE lead SET state = 'qualified', qualified_at = ?2, updated_at = ?2 WHERE id = ?1").run(id, "2026-02-28T18:00:00.000Z");
166 expect(weekReport(db, NOW, LA).week_before.qualified).toBe(1);
167 expect(weekReport(db, NOW, LA).this_week.qualified).toBe(0);
168 const noted = setNote(db, alice, { id, note: "Called the lender" }, new Date(NOW));
169 if (!noted.ok) throw new Error(noted.message);
170 // Any later touch moves updated_at into the newer week; the count follows qualified_at, not that.
171 db.query("UPDATE lead SET updated_at = ?2 WHERE id = ?1").run(id, "2026-03-08T18:00:00.000Z");
172 expect(weekReport(db, NOW, LA).week_before.qualified).toBe(1);
173 expect(weekReport(db, NOW, LA).this_week.qualified).toBe(0);
174 // Lost afterwards: still counted as qualified in its week. Reopened: no longer.
175 db.query("UPDATE lead SET state = 'lost', lost_reason = 'other', lost_at = ?2 WHERE id = ?1").run(id, "2026-03-06T18:00:00.000Z");
176 expect(weekReport(db, NOW, LA).week_before.qualified).toBe(1);
177 });
178
179 test("marking a lead qualified records the moment, and reopening clears it", () => {
180 const db = fresh();
181 const alice: Who = { role: "user", id: "u1", name: "alice" };
182 const id = arrive(db, "2026-03-05T18:00:00.000Z");
183 expect(setState(db, alice, { id, state: "qualified" }).ok).toBe(true);
184 const at = () => db.query<{ q: string | null }, [number]>("SELECT qualified_at AS q FROM lead WHERE id = ?1").get(id)!.q;
185 expect(at()).not.toBeNull();
186 expect(setState(db, alice, { id, state: "open" }).ok).toBe(true);
187 expect(at()).toBeNull();
188 });
189
190 test("the numbers are the response record's: leads outside the week but inside 30 days are left out of the week", () => {
191 const db = fresh();
192 arrive(db, "2026-03-05T18:00:00.000Z", "zillow", 30_000);
193 arrive(db, "2026-02-14T18:00:00.000Z", "website", 20 * 60_000); // 23 days ago: in the 30 days, not in either week
194 arrive(db, "2026-02-18T18:00:00.000Z", "website", 20 * 60_000);
195 const week = weekReport(db, NOW, LA).this_week;
196 expect(responseRecord(db, NOW).leads).toBe(3);
197 expect(week.leads).toBe(1);
198 expect(week.within_5_min_pct).toBe(100);
199 expect(week.by_source.map((s) => s.source)).toEqual(["zillow"]);
200 });
201
202 test("follow-ups sent leave out day 0 (the first reply) by design, as the README says: only the touches after it", () => {
203 const db = fresh();
204 const a = arrive(db, "2026-03-04T18:00:00.000Z", "zillow", 60_000);
205 for (const day of [0, 1]) {
206 db.query("DELETE FROM message WHERE lead_id = ?1 AND day = ?2").run(a, day);
207 db.query("INSERT INTO message (lead_id, day, channel, body, signature, status, due_at, sent_at) VALUES (?1, ?2, 'email', 'hi', 'sig', 'sent', ?3, ?3)").run(a, day, "2026-03-05T18:00:00.000Z");
208 }
209 expect(weekReport(db, NOW, LA).this_week.follow_ups_sent).toBe(1);
210 });
211
212 test("the print stylesheet hides the nav, the footer and the report's own links", async () => {
213 const css = await Bun.file(join(import.meta.dir, "..", "static", "app.css")).text();
214 const print = css.slice(css.indexOf("@media print"));
215 const rule = print.slice(0, print.indexOf("}") + 1);
216 for (const hidden of [".head", "footer", ".report-actions"]) expect(rule).toContain(hidden);
217 expect(rule).toContain("display: none");
218 });
src/report.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The week in numbers: the last 7 days on the agent's calendar and the 7
3 * before, for the one page the agent shows their broker. Leads, answer times
4 * and losses come from the response record's own code (`responseRecord`,
5 * `lostCounts`) over a window; only the counts that record does not hold
6 * (follow-ups sent, showings booked, leads qualified) are counted here.
7 * Plain data in, plain data out.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { ANSWER_DAY } from "./drafts.ts";
12 import { responseRecord, type ResponseRecord } from "./leads.ts";
13 import { lostCounts, type LostCount } from "./lost.ts";
14 import { wallAt } from "./showings.ts";
15
16 export const REPORT_DAYS = 7;
17
18 /** One week of the report. */
19 export interface Week {
20 /** The first instant of the week: midnight, in the agent's zone. */
21 readonly from: string;
22 /** The instant the week ends (exclusive): the next midnight for the week before, now for this one. */
23 readonly to: string;
24 readonly leads: number;
25 readonly replied: number;
26 /** Leads answered (or still waiting) in under five minutes: the record's own count. */
27 readonly answered_within_5_min: number;
28 readonly median_ms: number | null;
29 readonly within_5_min_pct: number | null;
30 readonly by_source: ResponseRecord["by_source"];
31 /** Follow-ups sent: every message sent after the first reply, except answers to what a lead wrote. */
32 readonly follow_ups_sent: number;
33 readonly showings_booked: number;
34 readonly qualified: number;
35 readonly lost: readonly LostCount[];
36 readonly lost_total: number;
37 }
38
39 export interface WeekReport {
40 readonly days: number;
41 readonly time_zone: string;
42 readonly this_week: Week;
43 readonly week_before: Week;
44 }
45
46 /** Midnight `back` days before today's, on the wall clock of `zone`; falls back a day's length across a gap. */
47 const midnight = (now: number, back: number, zone: string): number =>
48 wallAt(now, -back, 0, zone) ?? wallAt(now, -back, 1, zone) ?? now - back * 86_400_000;
49
50 function counts(db: Database, from: number, to: number): { followUps: number; showings: number; qualified: number } {
51 const [a, b] = [new Date(from).toISOString(), new Date(to).toISOString()];
52 const one = (sql: string): number => db.query<{ n: number }, [string, string]>(sql).get(a, b)!.n;
53 return {
54 followUps: one(
55 `SELECT count(*) AS n FROM message WHERE status = 'sent' AND day > 0 AND day < ${ANSWER_DAY} AND sent_at >= ?1 AND sent_at < ?2`,
56 ),
57 showings: one("SELECT count(*) AS n FROM showing WHERE booked_at >= ?1 AND booked_at < ?2"),
58 qualified: one("SELECT count(*) AS n FROM lead WHERE qualified_at >= ?1 AND qualified_at < ?2"),
59 };
60 }
61
62 function week(db: Database, now: number, from: number, to: number, earlierFrom: number): Week {
63 const record = responseRecord(db, now, { days: REPORT_DAYS, from, earlierFrom, to });
64 const lost = lostCounts(db, now, from, to);
65 const found = counts(db, from, to);
66 return {
67 from: new Date(from).toISOString(),
68 to: new Date(Math.min(to, now)).toISOString(),
69 leads: record.leads,
70 replied: record.replied,
71 answered_within_5_min: record.by_source.reduce((n, s) => n + s.under_five, 0),
72 median_ms: record.median_ms,
73 within_5_min_pct: record.within_5_min_pct,
74 by_source: record.by_source,
75 follow_ups_sent: found.followUps,
76 showings_booked: found.showings,
77 qualified: found.qualified,
78 lost,
79 lost_total: lost.reduce((n, l) => n + l.count, 0),
80 };
81 }
82
83 /** The last 7 calendar days in `zone` (today included) beside the 7 before. */
84 export function weekReport(db: Database, now: number, zone: string): WeekReport {
85 const start = midnight(now, REPORT_DAYS - 1, zone);
86 const before = midnight(now, 2 * REPORT_DAYS - 1, zone);
87 return {
88 days: REPORT_DAYS,
89 time_zone: zone,
90 this_week: week(db, now, start, now + 1, before),
91 week_before: week(db, now, before, start, before - REPORT_DAYS * 86_400_000),
92 };
93 }
src/routes.ts +81
@@ -27,6 +27,7 @@ import {
2727 listAudit,
2828 exportLeads,
2929 listLeads,
30 reportWeek,
3031 parseLeadEmail,
3132 previewSignIns,
3233 addSignIns,
@@ -89,6 +90,7 @@ import { deskPage } from "./pages/desk.ts";
8990 import { layout } from "./pages/layout.ts";
9091 import { leadPage } from "./pages/lead.ts";
9192 import { activityPage } from "./pages/activity.ts";
93 import { reportPage } from "./pages/report.ts";
9294 import { profilePage } from "./pages/profile.ts";
9395 import { currentAgent } from "./profile.ts";
9496 import { tokensCss } from "./tokens.ts";
@@ -323,6 +325,58 @@ const SHOW: Schema = {
323325 description: VIEW_HELP,
324326 };
325327 const Q: Schema = { type: "string", maxLength: MAX_QUERY, description: Q_HELP };
328 const COUNT: Schema = { type: "integer", minimum: 0 };
329 const WEEK: Schema = {
330 type: "object",
331 properties: {
332 from: { type: "string", format: "date-time", description: "Midnight opening the week, in the agent's zone." },
333 to: { type: "string", format: "date-time", description: "Where the week ends (exclusive); now for the current week." },
334 leads: COUNT,
335 replied: COUNT,
336 answered_within_5_min: { ...COUNT, description: "Leads answered, or still waiting, under five minutes." },
337 median_ms: { type: ["integer", "null"], description: "Median time to first reply in milliseconds; null with no leads." },
338 within_5_min_pct: { type: ["integer", "null"], description: "Whole percent of the week's leads answered inside 5 minutes." },
339 by_source: {
340 type: "array",
341 items: {
342 type: "object",
343 properties: {
344 source: { type: "string" },
345 count: COUNT,
346 median_ms: { type: "integer" },
347 under_five: COUNT,
348 },
349 required: ["source", "count", "median_ms", "under_five"],
350 },
351 },
352 follow_ups_sent: COUNT,
353 showings_booked: COUNT,
354 qualified: COUNT,
355 lost: {
356 type: "array",
357 items: {
358 type: "object",
359 properties: { reason: { type: ["string", "null"] }, count: COUNT },
360 required: ["reason", "count"],
361 },
362 },
363 lost_total: COUNT,
364 },
365 required: [
366 "from", "to", "leads", "replied", "answered_within_5_min", "median_ms", "within_5_min_pct",
367 "by_source", "follow_ups_sent", "showings_booked", "qualified", "lost", "lost_total",
368 ],
369 };
370 export const REPORT: Schema = {
371 type: "object",
372 properties: {
373 days: COUNT,
374 time_zone: { type: "string" },
375 this_week: WEEK,
376 week_before: WEEK,
377 },
378 required: ["days", "time_zone", "this_week", "week_before"],
379 };
326380 export const DESK: Schema = {
327381 type: "object",
328382 properties: {
@@ -749,6 +803,33 @@ export const routes: readonly Route[] = [
749803 answer: DESK,
750804 },
751805 },
806 // The week on one page: HTML for a browser, JSON for a script.
807 {
808 method: "GET",
809 path: "/report",
810 handle: (c) => {
811 const found = reportWeek(c.db, c.who);
812 if (!browsing(c.request)) return answer(found);
813 const agent = currentAgent(c.db);
814 if (!found.ok)
815 return html(
816 layout({
817 who: c.who,
818 agent,
819 path: c.url.pathname,
820 heading: "This week",
821 body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`,
822 }),
823 STATUS[found.error],
824 );
825 return html(reportPage({ who: c.who, agent, report: found.value }));
826 },
827 api: {
828 summary:
829 "This week for the agent's broker: the last 7 days in the agent's time zone beside the 7 before — leads in by source, median time to first reply and leads answered inside 5 minutes (the response record's rules), follow-ups sent, showings booked, leads qualified and lost with reasons. Ask for application/json.",
830 answer: REPORT,
831 },
832 },
752833 {
753834 method: "GET",
754835 path: "/leads.csv",
src/server.test.ts +1
@@ -316,6 +316,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
316316 const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" });
317317 expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([
318318 "list_leads",
319 "weekly_report",
319320 "export_leads",
320321 "get_lead",
321322 "add_lead",
src/terminal.test.ts +20
@@ -571,3 +571,23 @@ test("a lead whose follow-ups finished says so, and m marks it lost, never answe
571571 const guest = terminal(db, { role: "anon" });
572572 expect(read(guest)).not.toContain("Follow-ups finished");
573573 });
574
575 test("w on the desk shows the week report in the page's words; esc goes back; a guest sees nothing", () => {
576 const db = fresh();
577 const t = terminal(db, alice);
578 expect(read(t)).toContain("w week report");
579 t.key("w");
580 const screen = read(t);
581 expect(screen).toContain("This week");
582 expect(screen).toContain("Leads in");
583 expect(screen).toContain("answered inside 5 minutes");
584 expect(screen).toContain("Marked qualified");
585 t.key("\x1b");
586 expect(read(t)).toContain("Maria Gonzalez");
587 const guest = terminal(db, { role: "anon", id: "", name: "" });
588 expect(read(guest)).not.toContain("w week report");
589 guest.key("w");
590 const refused = read(guest);
591 expect(refused).toContain("Sign in to open the report.");
592 expect(refused).not.toContain("Leads in");
593 });
src/terminal.ts +30 −4
@@ -5,7 +5,7 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · $ price change · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · $ price change · w this week's report · 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 · m lost, never answered (follow-ups finished) · 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
@@ -17,6 +17,7 @@
1717 * profile the name, brokerage and license every message carries ·
1818 * e edit (admin): one field at a time, enter next, the last saves · esc back
1919 *
20 * report the last 7 days beside the 7 before, in words (anyone who may list leads) · esc back
2021 * activity every change in words, newest first (admin) · o older · n newer · m messages sent only · esc back
2122 *
2223 * Nothing is sent from a screen that has not shown it: the lead screen
@@ -30,6 +31,7 @@ import {
3031 activity,
3132 addLead,
3233 addSignIns,
34 reportWeek,
3335 previewSignIns,
3436 addSampleInquiry,
3537 deleteLead,
@@ -73,6 +75,7 @@ import { showingLine, showingWhen } from "./showings.ts";
7375 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
7476 import { between, elapsed, recordLine, sourceLine, tone, trendLine } from "./clock.ts";
7577 import { permit } from "./contract.ts";
78 import { REPORT_ROWS } from "./report-words.ts";
7679 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
7780 import { said as saidOf } from "./sentences.ts";
7881 import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, isCheckIn, isPriceChange, planLabel, type Channel, type Source } from "./drafts.ts";
@@ -80,7 +83,7 @@ import { ssh, title, where } from "./env.ts";
8083 import { FINISHED_ACTION, FINISHED_LABEL } from "./finished.ts";
8184 import { LOST_REASONS, REASON_LABEL, lostSaid } from "./lost.ts";
8285 import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
83 import { when } from "./pages/parts.ts";
86 import { day as dayOn, when } from "./pages/parts.ts";
8487 import { currentAgent } from "./profile.ts";
8588 import type { Who } from "./who.ts";
8689
@@ -183,6 +186,7 @@ type View =
183186 | { name: "desk" }
184187 | { name: "profile" }
185188 | { name: "export" }
189 | { name: "report" }
186190 | { name: "search"; typed: string }
187191 | { name: "activity"; sentOnly: boolean; before: number[] }
188192 | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> }
@@ -329,7 +333,7 @@ export function terminal(
329333 lines.push(
330334 "",
331335 dim(
332 `j/k move · enter open · f view · / find · n log a lead${permit(me, "lead", "update") === "yes" ? " · $ price change" : ""} · o open house · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
336 `j/k move · enter open · f view · / find · n log a lead${permit(me, "lead", "update") === "yes" ? " · $ price change" : ""} ${permit(me, "lead", "list") === "yes" ? " · w week report" : ""} · o open house · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
333337 ),
334338 );
335339 return lines;
@@ -532,6 +536,21 @@ export function terminal(
532536 ];
533537 }
534538
539 function reportScreen(): string[] {
540 const found = reportWeek(db, me);
541 if (!found.ok) return [found.message, "", dim("esc back")];
542 const { this_week: now, week_before: before, time_zone: zone } = found.value;
543 const span = (w: typeof now, last: string): string => `${dayOn(w.from, zone)} – ${dayOn(last, zone)}`;
544 return [
545 bold("This week"),
546 dim(`${span(now, now.to)} beside ${span(before, new Date(Date.parse(before.to) - 1).toISOString())} · times in ${zone}`),
547 "",
548 ...REPORT_ROWS.flatMap(([label, say]) => [bold(label), ` ${clean(say(now))}`, dim(` before: ${clean(say(before))}`)]),
549 "",
550 dim("Answer times follow the response record: a lead still waiting counts its time so far. esc back"),
551 ];
552 }
553
535554 function activityScreen(v: Extract<View, { name: "activity" }>): string[] {
536555 const before = v.before[v.before.length - 1];
537556 const found = activity(db, me, {
@@ -692,6 +711,8 @@ export function terminal(
692711 const body =
693712 view.name === "desk"
694713 ? deskScreen()
714 : view.name === "report"
715 ? reportScreen()
695716 : view.name === "activity"
696717 ? activityScreen(view)
697718 : view.name === "export"
@@ -818,7 +839,8 @@ export function terminal(
818839 const taken = exportLeads(db, me, { show, q });
819840 if (taken.ok) view = { name: "export" };
820841 else said = taken.message;
821 } else if (input === "p") view = { name: "profile" };
842 } else if (input === "w") view = { name: "report" };
843 else if (input === "p") view = { name: "profile" };
822844 else if (input === "a")
823845 view = { name: "activity", sentOnly: false, before: [] };
824846 else if (input === "R")
@@ -842,6 +864,10 @@ export function terminal(
842864 }
843865 return;
844866 }
867 case "report": {
868 if (input === "\x1b" || input === "\x7f" || input === "q") view = { name: "desk" };
869 return;
870 }
845871 case "export": {
846872 if (input === "\x1b" || input === "\x7f" || input === "q") view = { name: "desk" };
847873 return;
static/app.css +59
@@ -767,3 +767,62 @@ label.check input {
767767 .showing-when {
768768 font-weight: 600;
769769 }
770
771 /* The report: this week beside the week before, in words. */
772 .report-table {
773 width: 100%;
774 border-collapse: collapse;
775 margin: var(--space-3) 0;
776 }
777 .report-table th,
778 .report-table td {
779 padding: var(--space-2) var(--space-3);
780 text-align: left;
781 vertical-align: top;
782 border-bottom: 1px solid var(--color-line);
783 }
784 .report-table caption {
785 caption-side: bottom;
786 text-align: left;
787 padding-top: var(--space-2);
788 }
789 @media (max-width: 40rem) {
790 .report-table thead {
791 position: absolute;
792 left: -999rem;
793 }
794 .report-table tr,
795 .report-table th,
796 .report-table td {
797 display: block;
798 }
799 .report-table td:nth-of-type(1)::before {
800 content: "Last 7 days: ";
801 }
802 .report-table td:nth-of-type(2)::before {
803 content: "The 7 before: ";
804 }
805 }
806
807 /* On paper: the report alone, on one sheet, in black on white. */
808 @media print {
809 .head,
810 footer,
811 .toast,
812 .report-actions {
813 display: none;
814 }
815 body {
816 background: none;
817 color: black;
818 }
819 .report-table th,
820 .report-table td {
821 padding: var(--space-1) var(--space-2);
822 border-bottom-color: currentcolor;
823 }
824 .report {
825 break-inside: avoid;
826 page-break-after: avoid;
827 }
828 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs