From e99ceed8a4ad767dcd3f609c98f226577554d89a Mon Sep 17 00:00:00 2001 From: Tony Date: Wed, 2 Dec 2026 21:36:48 -0600 Subject: [PATCH 1/5] =?UTF-8?q?v2.9261=20=E2=80=94=20Builders:=20the=20rea?= =?UTF-8?q?d=20of=20the=20dollars=20declared,=20every=20city=20at=20once?= =?UTF-8?q?=20(punch=20list=20#465,=20step=201,=20the=20migration)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit research_builders_v2(p_cities text[]) is research_builders as it stands with three changes: the cities come as a list and a name is one row over all of them, `declared` and `declared_permits` say the dollars declared on its commercial building permits and how many declare some, and `cities` says where they are. The old function is not touched: main's client calls it until the next PR. A migration alone, as the card asks. No client reads it yet. Owes a supabase db push. The permit skim bed holds the new read to the old one, one city at a time, and runs the file twice. Co-Authored-By: Claude Fable 5.2 --- .../20261203033600_research_builders_v2.md | 47 +++++ docs/recent-features/v2.9261.md | 32 ++++ scripts/pgtest-permit-skim.sh | 7 +- src/content/releaseNotes/v2.9261.ts | 15 ++ .../20261203033600_research_builders_v2.sql | 169 ++++++++++++++++++ supabase/tests/permit_skim/20_scenario.sql | 33 +++- to-dos/prospects-profiles/README.md | 6 +- 7 files changed, 305 insertions(+), 4 deletions(-) create mode 100644 docs/migrations/20261203033600_research_builders_v2.md create mode 100644 docs/recent-features/v2.9261.md create mode 100644 src/content/releaseNotes/v2.9261.ts create mode 100644 supabase/migrations/20261203033600_research_builders_v2.sql diff --git a/docs/migrations/20261203033600_research_builders_v2.md b/docs/migrations/20261203033600_research_builders_v2.md new file mode 100644 index 0000000000..93950579db --- /dev/null +++ b/docs/migrations/20261203033600_research_builders_v2.md @@ -0,0 +1,47 @@ +# 20261203033600_research_builders_v2.sql (2026-12-02, v2.9261) + +Permits, Builders: the dollars a name declared, and every city in one read ([v2.9261](../recent-features/v2.9261.md), punch list #465, step 1). One function added. No table, column, index or policy changes, and no function replaced. + +## What it adds + +`research_builders_v2(p_cities text[])`. Its body is `research_builders(p_city)` as [`20261122230500`](./20261122230500_permit_building_plumbing_only.md) left it, with three changes. + +| Change | What it does | +|---|---| +| `p_cities text[]` in place of `p_city text` | One call reads one city or several. `mine` takes the permits whose city is `= ANY (p_cities)`, so each city is still read on `permits_city_kind_filed_idx`. Every later step already joined a plumbing permit to a building permit of its own city, so nothing else in the body knows how many cities were asked for. A name is one row over all of them. An empty list and a null read no rows. | +| `declared numeric`, `declared_permits integer` | The sum of `permits.declared_value` over the name's commercial building permits in the window, and how many of them declare a value. Only a value over zero counts: a blank and a zero are no number. A name whose permits declare nothing reads `declared` null and `declared_permits` 0. | +| `cities text[]` | The cities the name's permits are in, each once, in order. | + +The sixteen columns `research_builders` returns come first, in its order, and the three new ones after. The order of the rows is the old one: most permits first, then the newest permit, then the key. + +`LANGUAGE sql STABLE SECURITY INVOKER SET search_path = public`, as the old function. The caller's own row policies decide which permits, bids, marks and names are read. Closed to `PUBLIC` and `anon` by name, granted to `authenticated` and `service_role`. + +## Why a new name + +A function's return type cannot change with `CREATE OR REPLACE`, and the client on `main` calls `research_builders(text)` until step 1's client PR merges. So the old function stays exactly as it is, and the two live side by side. A later migration drops the old one once no client, bed or script reads it. + +## What a reader should know + +- **One city of the new read is the old read.** `research_builders_v2(ARRAY['X'])`, cut to the old columns, is `research_builders('X')` row for row. The bed holds the two together. +- **A name's row over several cities is not the sum of its rows a city at a time in every column.** Its permits, its open permits, its dollars and its bids are. Its plumber is the one it used on the most jobs over all the cities asked for. +- **An application and the permit issued from it are two rows of `permits`.** Both are counted, as they always were, and both add their dollars when both declare some. +- **No value floor.** The floor is the skim's and is kept in the browser. This read counts every commercial building permit, as Builders always has. + +## Safety + +- `SET lock_timeout = '3s'` first. One `CREATE OR REPLACE FUNCTION`, one comment, one revoke, one grant. No lock on a table. +- Idempotent: a second run changes nothing. +- Nothing on `main` calls the function, so the push changes no screen. + +## Tested + +`supabase/tests/permit_skim` (`npm run test:pg:permit-skim`, the SQL beds workflow), which runs the file a second time: + +- One city of the new read against the old read, both ways with `EXCEPT`, in the bed's four cities and in a city with no permit: no row differs. +- Three cities in one read. A name with jobs in two cities is one row, with both cities, its permits and its dollars added. A name with a zero on one permit counts the permit and not the zero. A name that declares nothing reads no dollars and 0. +- A city not asked for adds nothing. An empty list and a null read no rows. +- `anon` cannot run it. + +## Applied + +Not yet. This section is written when the push is read back. diff --git a/docs/recent-features/v2.9261.md b/docs/recent-features/v2.9261.md new file mode 100644 index 0000000000..99d8aabdcf --- /dev/null +++ b/docs/recent-features/v2.9261.md @@ -0,0 +1,32 @@ +# v2.9261 — Builders: the groundwork for the dollars each company holds, in every city at once (2026-12-02) + +Punch list #465, step 1, the migration. A migration alone, as the card asks: *A migration, alone, before its client*. No client calls the new function yet, so no screen changes. It owes a `supabase db push`. + +## Why + +The owner's second purpose for the card is to see who holds the work, and which of those companies are not ours yet. Builders reads one city at a time (`research_builders(p_city)`) and counts permits. A share of the dollars needs the dollars. A company's whole book needs every city in one read, the card's call 4, answered 2026-12-02. + +## What ships + +[`20261203033600_research_builders_v2.sql`](../../supabase/migrations/20261203033600_research_builders_v2.sql), documented in [`docs/migrations/20261203033600_research_builders_v2.md`](../migrations/20261203033600_research_builders_v2.md): + +- `research_builders_v2(p_cities text[])`. It is `research_builders` as it stands, with three changes and no other. +- It takes the cities as a list. A name is one row over every city asked for. +- `declared` is the dollars declared on the name's commercial building permits of twelve months. `declared_permits` is how many of them declare some. A blank and a zero are no number, so a name whose permits declare nothing reads null and 0, and the list can say so in place of a share of zero. +- `cities` is where the name's permits are. + +The old function is not touched. The client on `main` calls it until the next PR, and a function's return cannot change in place. A later migration drops it once nothing reads it. + +## What it does not settle + +- **An application and the permit issued from it are two rows.** Both count as permits today, and both add their dollars here when both declare some. The permits' bar has always counted them so. The list's words must not promise more than *the dollars declared on its permits*. +- **The value floor is the skim's, not this read's.** Builders has always counted every commercial building permit, whatever its value, and the dollars are added over the same permits, so a row's dollars are the sum of the permits the row counts. + +## Tested + +- `supabase/tests/permit_skim` (`npm run test:pg:permit-skim`, the SQL beds workflow). One city of the new read is the old read column for column, in every city of the bed and in a city with no permit. Three cities in one read give one row a name, with its dollars, how many permits declare some and its cities. A zero adds nothing. A city not asked for adds nothing, and an empty list and a null read nothing. `anon` cannot run it. The file runs twice. +- Before the PR, on a throwaway Postgres 15 on this Mac with stand-in tables: the file ran twice, and the same checks read as written. Docker does not run in a session here, so the bed itself first ran on GitHub. + +## Owed + +`supabase db push`, after the merge, from a checkout at `origin/main`. Then step 1's client: `builderShare.ts`, the two bars, sorting on any column, the three chips and *All five cities* on the picker. diff --git a/scripts/pgtest-permit-skim.sh b/scripts/pgtest-permit-skim.sh index 23cf39b8c0..74cd79426b 100755 --- a/scripts/pgtest-permit-skim.sh +++ b/scripts/pgtest-permit-skim.sh @@ -16,7 +16,9 @@ # plumber and its mark, and counts our bids with it by the one rule (no practice bid, two years, once a bid; migration # *_research_builders_our_bids), and neither it nor the table carries a customer (migration # *_builders_customer_id_dropped); only the building's own plumbing permit closes a job, on every read (migration -# *_permit_building_plumbing_only, which runs last and twice: the two files before it pair any plumbing permit); the count adds up; a helper reads and marks nothing; the fences reached both tables and anon +# *_permit_building_plumbing_only, which runs last and twice: the two files before it pair any plumbing permit); Builders reads +# every city at once with the dollars declared, and one city of that read is the old read (migration *_research_builders_v2, which +# also runs twice); the count adds up; a helper reads and marks nothing; the fences reached both tables and anon # runs none of the new functions. It raises on its first failed assertion and ends with "permit_skim PASSED". # PGTEST_KEEP=1 leaves the container up. Needs docker; the SQL beds workflow runs it from scripts/sql-beds.txt. Never # touches prod. @@ -29,6 +31,7 @@ IMAGE="${PGTEST_SUPABASE_IMAGE:-public.ecr.aws/supabase/postgres:17.6.1.071}" WRITES="$(ls supabase/migrations/*_builders_customer_id_dropped.sql)" LATER="$(ls supabase/migrations/*_permit_first_plumbing_day.sql)" RULE="$(ls supabase/migrations/*_permit_building_plumbing_only.sql)" +EVERY_CITY="$(ls supabase/migrations/*_research_builders_v2.sql)" command -v docker >/dev/null || { echo "docker not on PATH"; exit 2; } docker info >/dev/null 2>&1 || { echo "docker is not running"; exit 2; } @@ -58,6 +61,8 @@ done for _ in 1 2; do psql_as postgres -f - < "$RULE" >/dev/null 2>"$ERR" || { echo "FAILED re-applying $RULE"; grep -E -A6 "ERROR|FATAL" "$ERR" | head -20; exit 1; } done +# Builders' read of every city is a function of its own, made after the rule: a second run must change nothing. +psql_as postgres -f - < "$EVERY_CITY" >/dev/null 2>"$ERR" || { echo "FAILED re-applying $EVERY_CITY"; grep -E -A6 "ERROR|FATAL" "$ERR" | head -20; exit 1; } out="$(psql_as postgres -f - < supabase/tests/permit_skim/20_scenario.sql 2>&1 || true)" if ! grep -q "permit_skim PASSED" <<<"$out"; then echo "$out" | tail -40; exit 1; fi grep -o "ok: .*" <<<"$out" diff --git a/src/content/releaseNotes/v2.9261.ts b/src/content/releaseNotes/v2.9261.ts new file mode 100644 index 0000000000..63ce9d6eab --- /dev/null +++ b/src/content/releaseNotes/v2.9261.ts @@ -0,0 +1,15 @@ +import type { ReleaseNote } from '../../lib/releaseNotes' + +const note: ReleaseNote = { + version: 'v2.9261', + date: '2026-12-02', + title: 'Builders: the groundwork for the dollars each company holds, in every city at once', + kind: 'feature', + highlights: [ + 'Builders, on Prospects → Permits, counts the permits each company pulled in one city. It could not say the dollars on them, or a company\'s work across cities.', + 'This lays the read that adds up the dollars each company declared on its permits, over all five cities in one go. Nothing on a screen changes yet.', + 'The next change draws each company\'s share of the dollars and of the permits as two bars, and lets any column sort.', + ], +} + +export default note diff --git a/supabase/migrations/20261203033600_research_builders_v2.sql b/supabase/migrations/20261203033600_research_builders_v2.sql new file mode 100644 index 0000000000..e643f4273d --- /dev/null +++ b/supabase/migrations/20261203033600_research_builders_v2.sql @@ -0,0 +1,169 @@ +SET lock_timeout = '3s'; + +-- v2.9261 — Builders: the dollars declared, and every city in one read (punch list #465, step 1, the +-- migration alone, before its client). +-- +-- The owner's second purpose for the card: see who holds the work, ours or not. Builders reads one city at +-- a time and counts permits. A share of the dollars needs the dollars, and a company's whole book needs +-- every city at once. +-- +-- research_builders_v2(p_cities text[]) is research_builders(p_city) as *_permit_building_plumbing_only +-- left it, with three changes and no other: +-- 1. It takes the cities as a list, so one call reads one city or all of them. A name is one row over +-- every city asked for. The list is met with = ANY, so each city still reads on +-- permits_city_kind_filed_idx as the one city did. +-- 2. `declared`, the sum of declared_value over the name's commercial building permits in the window, +-- and `declared_permits`, how many of them declare one. A blank and a zero are no number: null and 0 +-- for a name whose permits declare nothing, so the client can say so in place of a share of zero. +-- 3. `cities`, the cities the name's permits are in, in order. +-- +-- A new name, not a replacement: a function's return cannot change in place, and the client on main calls +-- research_builders(text) until the next PR. The old function is left exactly as it is; a later migration +-- drops it once no client reads it. One city of the new read is the old read column for column, and the +-- bed holds the two together (supabase/tests/permit_skim). +-- +-- SECURITY INVOKER as the old one, so the caller's own row policies decide what is counted. No table, no +-- column, no index, no policy. Idempotent. + +CREATE OR REPLACE FUNCTION public.research_builders_v2(p_cities text[]) +RETURNS TABLE ( + key text, + name text, + sample_contact text, + kind text, + mark text, + mark_reason text, + mark_by_name text, + mark_at timestamptz, + permits integer, + open integer, + last_permit_on date, + plumber text, + plumber_jobs integer, + bids integer, + won integer, + last_bid_on date, + declared numeric, + declared_permits integer, + cities text[] +) +LANGUAGE sql +STABLE +SECURITY INVOKER +SET search_path = public +AS $$ + WITH mine AS ( + SELECT q.id, q.builder_key, q.contact, q.permit_number, q.address_key, q.city, COALESCE(q.issued_on, q.submitted_on) AS filed_on, + COALESCE(q.submitted_on, q.issued_on) - 30 AS plumbing_from, + q.declared_value + FROM public.permits q + WHERE q.city = ANY (p_cities) AND q.kind = 'building' AND NOT q.residential AND q.builder_key IS NOT NULL + AND COALESCE(q.issued_on, q.submitted_on) >= public.app_today() - 365 + ), + -- The plumbing permits of each of those building permits' own jobs, as research_permits pairs them: + -- on the number, or at the address when the two are one job, and no older than 30 days before it. + -- Two joins, each on an index; UNION keeps a permit found both ways once. + plumb_pairs AS ( + SELECT m.id AS building_id, pl.id AS plumbing_id + FROM mine m + JOIN public.permits pl + ON pl.city = m.city AND pl.permit_number = m.permit_number AND pl.kind = 'plumbing' AND public.permit_is_building_plumbing(pl.permit_type) + AND COALESCE(pl.issued_on, pl.submitted_on) >= m.plumbing_from + UNION + SELECT m.id, pl.id + FROM mine m + JOIN public.permits pl + ON pl.city = m.city AND pl.address_key = m.address_key AND pl.kind = 'plumbing' AND public.permit_is_building_plumbing(pl.permit_type) + AND COALESCE(pl.issued_on, pl.submitted_on) >= m.plumbing_from + AND public.permit_address_plumbing_counts(m.city, m.builder_key, pl.builder_key) + ), + plumb AS ( + SELECT m.id, m.builder_key, pl.contact AS plumber, + (pl.contact IS NOT NULL + AND public.research_name_key(pl.contact) IS DISTINCT FROM public.research_name_key(m.contact) + AND (pl.builder_key IS NULL OR pl.builder_key IS DISTINCT FROM m.builder_key)) AS named + FROM plumb_pairs pp + JOIN mine m ON m.id = pp.building_id + JOIN public.permits pl ON pl.id = pp.plumbing_id + ), + taken AS ( + SELECT DISTINCT id FROM plumb + ), + per AS ( + SELECT m.builder_key, + count(*)::integer AS permits, + count(*) FILTER (WHERE t.id IS NULL)::integer AS open, + max(m.filed_on) AS last_permit_on, + (array_agg(m.contact ORDER BY m.filed_on DESC NULLS LAST))[1] AS sample_contact, + -- The dollars the filers declared. A blank and a zero are no number: such a permit counts and adds nothing. + sum(m.declared_value) FILTER (WHERE m.declared_value > 0) AS declared, + count(*) FILTER (WHERE m.declared_value > 0)::integer AS declared_permits, + array_agg(DISTINCT m.city ORDER BY m.city) AS cities + FROM mine m + LEFT JOIN taken t ON t.id = m.id + GROUP BY m.builder_key + ), + used AS ( + SELECT builder_key, plumber, count(DISTINCT id)::integer AS jobs, + row_number() OVER (PARTITION BY builder_key ORDER BY count(DISTINCT id) DESC, plumber) AS rn + FROM plumb + WHERE named + GROUP BY builder_key, plumber + ), + -- Our bids that count (public.research_bid_counts), each under the names it counts under + -- (public.research_bid_party_key). The day is the company calendar's, as the window's is. + named_bids AS ( + SELECT b.id, b.outcome, (b.created_at AT TIME ZONE 'America/Chicago')::date AS bid_on, + public.research_bid_party_key(c.name) AS customer_key, + public.research_bid_party_key(g.name) AS gc_key + FROM public.bids b + LEFT JOIN public.customers c ON c.id = b.customer_id + LEFT JOIN public.bids_gc_builders g ON g.id = b.gc_builder_id + WHERE public.research_bid_counts(b.project_name, b.created_at) + ), + -- Our bids with each name, by the customer's name or the legacy builder's: two equal joins the + -- planner can hash, in place of one on an OR that compared every builder with every bid. + our_bids AS ( + SELECT p.builder_key, nb.id, nb.outcome, nb.bid_on + FROM per p + JOIN named_bids nb ON nb.customer_key = p.builder_key + UNION + SELECT p.builder_key, nb.id, nb.outcome, nb.bid_on + FROM per p + JOIN named_bids nb ON nb.gc_key = p.builder_key + ), + ours AS ( + SELECT ob.builder_key, + count(DISTINCT ob.id)::integer AS bids, + count(DISTINCT ob.id) FILTER (WHERE ob.outcome IN ('won', 'started_or_complete'))::integer AS won, + max(ob.bid_on) AS last_bid_on + FROM our_bids ob + GROUP BY ob.builder_key + ), + marks AS ( + SELECT DISTINCT ON (m.builder_key) m.builder_key, m.mark, m.reason, m.marked_by, m.marked_at + FROM public.builder_marks m + ORDER BY m.builder_key, m.marked_at DESC + ) + SELECT p.builder_key, bd.name, p.sample_contact, bd.kind, + NULLIF(mk.mark, 'none'), + CASE WHEN mk.mark IS NULL OR mk.mark = 'none' THEN NULL ELSE mk.reason END, + CASE WHEN mk.mark IS NULL OR mk.mark = 'none' THEN NULL ELSE mu.name END, + CASE WHEN mk.mark IS NULL OR mk.mark = 'none' THEN NULL ELSE mk.marked_at END, + p.permits, p.open, p.last_permit_on, + u.plumber, COALESCE(u.jobs, 0), + COALESCE(o.bids, 0), COALESCE(o.won, 0), o.last_bid_on, + p.declared, p.declared_permits, p.cities + FROM per p + LEFT JOIN public.builders bd ON bd.key = p.builder_key + LEFT JOIN marks mk ON mk.builder_key = p.builder_key + LEFT JOIN public.users mu ON mu.id = mk.marked_by + LEFT JOIN used u ON u.builder_key = p.builder_key AND u.rn = 1 + LEFT JOIN ours o ON o.builder_key = p.builder_key + ORDER BY p.permits DESC, p.last_permit_on DESC NULLS LAST, p.builder_key; +$$; +COMMENT ON FUNCTION public.research_builders_v2(text[]) IS + 'Permits, Builders (punch list #465): every name on the commercial building permits of twelve months in the cities asked for, one row a name over all of them, with what research_builders gives a name in one city (its permits, the ones with no plumbing permit yet, the plumber it uses most, the office''s mark, our bids with it) and three more: declared, the dollars declared on those permits (null when none declares any), declared_permits, how many declare some, and cities, where they are. One city asked for is research_builders of that city, column for column.'; +-- A function made new takes the default grants, anon's among them. +REVOKE ALL ON FUNCTION public.research_builders_v2(text[]) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.research_builders_v2(text[]) TO authenticated, service_role; diff --git a/supabase/tests/permit_skim/20_scenario.sql b/supabase/tests/permit_skim/20_scenario.sql index dc896a2a81..28742b234b 100644 --- a/supabase/tests/permit_skim/20_scenario.sql +++ b/supabase/tests/permit_skim/20_scenario.sql @@ -324,11 +324,42 @@ SELECT ps.same('in San Antonio a sprinkler permit on the job''s own number close FROM public.research_permits_v4('San Antonio', CURRENT_DATE - 60, false) WHERE permit_number = 'SA-APP-1'), 'none:open:open:1:2'); +-- Builders, the dollars declared and every city in one read (migration *_research_builders_v2, punch list #465, +-- step 1). One city of the new read is the old read, column for column, in every city of this bed. +SELECT ps.same('one city of research_builders_v2 is research_builders, column for column', + (SELECT count(*)::text FROM (VALUES ('Skim City'), ('San Antonio'), ('Elm City'), ('Fern City'), ('No Such City')) c(city), + LATERAL ((SELECT key, name, sample_contact, kind, mark, mark_reason, mark_by_name, mark_at, permits, open, last_permit_on, plumber, plumber_jobs, bids, won, last_bid_on + FROM public.research_builders_v2(ARRAY[c.city]) + EXCEPT SELECT * FROM public.research_builders(c.city)) + UNION ALL + (SELECT * FROM public.research_builders(c.city) + EXCEPT SELECT key, name, sample_contact, kind, mark, mark_reason, mark_by_name, mark_at, permits, open, last_permit_on, plumber, plumber_jobs, bids, won, last_bid_on + FROM public.research_builders_v2(ARRAY[c.city]))) d), + '0'); +-- Ridgeline declares a value on two of its three San Antonio permits and a zero on the third. Brookline's first Fern +-- City job declares one, and it files a job in Elm City too. Harbor Fitouts declares nothing. +UPDATE public.permits SET declared_value = 250000 WHERE id = '00000000-0000-0000-0000-0000003020d1'; +UPDATE public.permits SET declared_value = 0 WHERE id = '00000000-0000-0000-0000-0000003020d6'; +UPDATE public.permits SET declared_value = 750000.50 WHERE id = '00000000-0000-0000-0000-0000003020d7'; +UPDATE public.permits SET declared_value = 90000 WHERE id = '00000000-0000-0000-0000-0000003021a1'; +INSERT INTO public.permits (id, city, source, permit_number, permit_type, kind, stage, residential, work_type, address, address_key, submitted_on, issued_on, contact, builder_key, declared_value) VALUES + ('00000000-0000-0000-0000-0000003021b1', 'Elm City', 'bed', 'EC-9', 'Comm Remodel Permit', 'building', 'applied', false, 'Commercial remodel', '31 BIRCH RD', '31 birch rd', CURRENT_DATE - 1, NULL, 'Ada Brook, Brookline Build', 'brooklinebuild', 10000); +SELECT ps.same('every city in one read: a name is one row, with its dollars, how many permits declare some, and its cities', + (SELECT string_agg(key || ':' || permits || '/' || open || ':' || COALESCE(declared::text, 'none') || '/' || declared_permits || ':' || array_to_string(cities, '+'), ' ' ORDER BY key) + FROM public.research_builders_v2(ARRAY['San Antonio', 'Elm City', 'Fern City']) + WHERE key IN ('ridgelineinteriors', 'brooklinebuild', 'harborfitouts')), + 'brooklinebuild:3/2:100000/2:Elm City+Fern City harborfitouts:1/0:none/0:San Antonio ridgelineinteriors:3/1:1000000.50/2:San Antonio'); +SELECT ps.same('a city not asked for adds nothing, and no city reads nothing', + (SELECT permits || ':' || declared::text || ':' || array_to_string(cities, '+') FROM public.research_builders_v2(ARRAY['Fern City']) WHERE key = 'brooklinebuild') + || ' ' || (SELECT count(*)::text FROM public.research_builders_v2(ARRAY[]::text[])) + || ' ' || (SELECT count(*)::text FROM public.research_builders_v2(NULL)), + '2:90000:Fern City 0 0'); + -- The fences reached the two new tables, and the new reads are closed to the anon key. SELECT ps.same('both tables carry the read-only fence', (SELECT count(DISTINCT tablename)::text FROM pg_policies WHERE schemaname = 'public' AND tablename IN ('builders', 'builder_marks') AND permissive = 'RESTRICTIVE'), '2'); SELECT ps.same('anon runs none of the new functions', - (SELECT count(*)::text FROM pg_proc p WHERE p.pronamespace = 'public'::regnamespace AND p.proname IN ('research_permits_v2', 'research_builders', 'permit_funnel', 'permit_set_builder_keys', 'permit_skim_wait', 'permit_address_plumbing_counts', 'permit_is_building_plumbing', 'research_permits_v3', 'research_permits_v4', 'research_bid_counts', 'research_bid_party_key') AND has_function_privilege('anon', p.oid, 'EXECUTE')), '0'); + (SELECT count(*)::text FROM pg_proc p WHERE p.pronamespace = 'public'::regnamespace AND p.proname IN ('research_permits_v2', 'research_builders', 'research_builders_v2', 'permit_funnel', 'permit_set_builder_keys', 'permit_skim_wait', 'permit_address_plumbing_counts', 'permit_is_building_plumbing', 'research_permits_v3', 'research_permits_v4', 'research_bid_counts', 'research_bid_party_key') AND has_function_privilege('anon', p.oid, 'EXECUTE')), '0'); DO $$ BEGIN RAISE NOTICE 'permit_skim PASSED'; END $$; ROLLBACK; diff --git a/to-dos/prospects-profiles/README.md b/to-dos/prospects-profiles/README.md index 1c25fd214a..18323cca48 100644 --- a/to-dos/prospects-profiles/README.md +++ b/to-dos/prospects-profiles/README.md @@ -2,7 +2,7 @@ name: "Prospects: a profile for every company and every person on a permit" number: 465 group: ready -status: asked 2026-12-01 by the owner · what the app holds about a builder read in the code the same day · the card and the mock-up written · the owner's answer the same day: a share is drawn as two bars, dollars and permits · his word the same day, *let's roll with it*, and his question of how a person reaches the view, answered here as six ways in · his word the same day that the build should look like the drawing, so each step is tied to its drawing · calls 2 to 7 answered 2026-12-02, every pick stands · nothing built +status: asked 2026-12-01 by the owner · what the app holds about a builder read in the code the same day · the card and the mock-up written · the owner's answer the same day: a share is drawn as two bars, dollars and permits · his word the same day, *let's roll with it*, and his question of how a person reaches the view, answered here as six ways in · his word the same day that the build should look like the drawing, so each step is tied to its drawing · calls 2 to 7 answered 2026-12-02, every pick stands · step 1's migration written 2026-12-02 (v2.9261, `research_builders_v2`), its push owed, its client next summary: > The owner wants to sort permits by GC or by the person who files them, and build a profile for each. It serves two ends. When the office calls someone, it should see everything they are @@ -12,7 +12,7 @@ summary: > own sheet and the calling deck. No one screen shows a company whole, none counts dollars or share, none is sorted by the person, and a call is logged against one job. This card gathers them into one page a name, one call for every job, and a share for every company. -next: Step 1. On the Builders list, the two shares beside each name, of the dollars declared and of the permits, sorting on any column, and the three chips Everyone, Ours and Not ours yet. +next: Step 1's client. The migration of step 1 is written (v2.9261, `research_builders_v2`, the dollars and every city in one read) and owes its push. After the push: `builderShare.ts`, the two shares beside each name as bars, sorting on any column, the three chips Everyone, Ours and Not ours yet, and *All five cities* on the picker. size: L as a train of six (M · M · M · M · S · M) blocker: Nothing. All seven calls are answered. opinion: build — the facts are already read and kept, a place at a time, and the two things the owner wants are the two things no place does @@ -146,6 +146,8 @@ Card #464 has a robot research the builder behind a wanted permit, and writes a Smallest first. Each step is one pull request with its release note and its fragment. 1. **Dollars, the two shares and sorting on Builders (M).** The value and the every-city read, `builderShare.ts`, the two bars, any column sorts, and the three chips. Useful alone: it is the second purpose in its plainest form. + - **The migration is written** (v2.9261, 2026-12-02): `research_builders_v2(p_cities text[])`, which gives a name one row over every city asked for, with `declared`, `declared_permits` and `cities` beside what `research_builders` gives. The old function stands until the client leaves it. Two things the list's words must respect: an application and the permit issued from it are two rows and both add their dollars, and the read uses no value floor, as Builders never has. + - **Left to do:** the push, then the client. 2. **A company's profile (M).** `builderProfile.ts`, the page and its address, opened from a row on Builders, from a name wherever it is drawn, from the search, from the Overview and from a tied customer's record. 3. **One call, every job (M).** The call's screen, the four answers, and the one save. The calling deck's press on a lead that came from a permit. 4. **People (M).** The *People* side of the list, and a person's page. From a84c6ad0db402636cbffe4f29c09e930ce7c3f9e Mon Sep 17 00:00:00 2001 From: Tony Date: Wed, 2 Dec 2026 21:50:56 -0600 Subject: [PATCH 2/5] =?UTF-8?q?v2.9263=20=E2=80=94=20Builders:=20who=20hol?= =?UTF-8?q?ds=20the=20work,=20in=20all=20five=20cities=20at=20once=20(punc?= =?UTF-8?q?h=20list=20#465,=20step=201,=20the=20client)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builders opens on All five cities, the picker's first choice on that view, and reads them in one call through research_builders_v2 (v2.9261), one row a name. Each name has two bars, its share of the dollars declared and its share of the permits, green for a name that is ours and grey for one not ours yet. A press on a heading sorts, and the chips Everyone, Ours and Not ours yet narrow the list. The shares, the ranks, the order and the words are the new kernel builderShare.ts. Kept, though the card's drawing has neither: the mark chips and the search. Over every city the look-alike chip and the read-back press wait for a city to be picked. Stands on v2.9261's migration: it must not merge before that is merged and pushed. Co-Authored-By: Claude Fable 5.2 --- docs/GLOSSARY.md | 3 + docs/PROJECT_DOCUMENTATION.md | 2 +- docs/recent-features/v2.9263.md | 37 +++ .../prospects/PermitBuilders.render.test.tsx | 108 ++++++- src/components/prospects/PermitBuilders.tsx | 263 ++++++++++++++---- .../ProspectsResearchTab.render.test.tsx | 49 +++- .../prospects/ProspectsResearchTab.tsx | 25 +- .../help/research-permits-for-work-to-bid.md | 16 ++ src/content/releaseNotes/v2.9263.ts | 16 ++ src/hooks/usePermitRecordsStart.ts | 21 ++ src/lib/research/builderShare.test.ts | 140 ++++++++++ src/lib/research/builderShare.ts | 191 +++++++++++++ src/lib/research/permitBuilders.ts | 8 +- src/lib/research/permitResearchIo.ts | 14 +- to-dos/prospects-profiles/README.md | 7 +- 15 files changed, 828 insertions(+), 72 deletions(-) create mode 100644 docs/recent-features/v2.9263.md create mode 100644 src/content/releaseNotes/v2.9263.ts create mode 100644 src/lib/research/builderShare.test.ts create mode 100644 src/lib/research/builderShare.ts diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index ae91bbd105..4d63e873d8 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -410,6 +410,9 @@ Since v2.9249 (finding 853) the skim says *Reading the permits…* until the off Since v2.9223 the sheet has its table, `permit_sheet_changes`, which is append-only, and since v2.9226 its fold and its refusals (`sheetFromChanges`, `sheetRefusal` in `permitSheet.ts`), and no screen reads either yet. Our place among the plumbers the permits name has its working in a kernel no screen reads yet (v2.9235, punch list #466, `src/lib/scoreboard/scoreboard.ts` over `plumbersCounted` in `permitMarketShape.ts`). A city on Permits is **quiet** (v2.7880, `permitQuiet.ts`) when its newest permit day is more than 7 days back, 10 for San Antonio, while our own pull ran clean inside two days: the city picker then reads *quiet since* that day, and never when the pull itself stopped. +A builder's **share of dollars** and **share of permits** (v2.9263, punch list #465, `builderShare.ts`) are its parts of the dollars declared and of the permits on the Builders list as it was read, drawn as a dark bar and a light bar, so every name's shares add up to the whole list. +A name on Builders is **ours** when we priced a job for it in two years or a person tied it to a customer, and **not ours yet** otherwise: its bars are green or grey, and the chips **Everyone**, **Ours** and **Not ours yet** narrow the list. +Builders reads **All five cities** at once unless a city is picked, one row a name, through `research_builders_v2` (`20261203033600`, `loadBuildersOf`), which adds the dollars a name's permits declare, how many declare some and the cities they are in. **Market** (v2.7978, punch list #405, `permitMarket.ts`) is the Permits view beside Builders that says what the permits mean for us: every **company we bid** in two years beside the commercial permits its names pulled in twelve months, each row reading *Builds, and we win*, *Builds, we never win*, too early to say or *No permit on record*, and **the clock**, the middle wait between two dates on a city's permits. A **company we bid** there is a bid's customer or the old builders list's name on it, keyed as permits are, with practice bids (a project name that starts with the word ZZ) and a bid platform's catch-all customer left out, in the last two years. That is **the one rule for our bids**: in the client `src/lib/research/ourBids.ts` (`bidCounts`, `bidPartyKey`), on the database `research_bid_counts` and `research_bid_party_key`, and since v2.8138, v2.8147 and v2.8181 Builders' **Our bids**, the call list's *We bid N, won N* and *Never bid*, a tied customer's bids and the skim's *warm · cold · seen · new name* word all count by it. diff --git a/docs/PROJECT_DOCUMENTATION.md b/docs/PROJECT_DOCUMENTATION.md index 3f79395437..017e830a39 100644 --- a/docs/PROJECT_DOCUMENTATION.md +++ b/docs/PROJECT_DOCUMENTATION.md @@ -1954,7 +1954,7 @@ Clickable addresses (Google Maps), `mailto:`/`tel:` links, and `#step-{id}` deep - **Page**: [`Prospects.tsx`](../src/pages/Prospects.tsx), which opens on **Overview** (v2.8767, punch list #450, `?tab=overview`, [`ProspectsOverview`](../src/components/prospects/ProspectsOverview.tsx) over `lib/prospects/funnelOverview.ts`: the page as three funnels of four steps with their counts, the ratio between two steps and a press for each); since v2.8776 its top row is **Overview**, **Jobs**, **Hires** and **Subs**, each funnel with its four steps in a row under it (`FunnelStepRow`, `prospectsPillRow`), and the surfaces below, top-level tabs of their own until v2.8770, are those steps: - **Customers** — the sales-lead pipeline, with sub-tabs **Follow Up**, **Prospect List**, **Convert**, and **Activity** (renamed from **Team** in v2.708; per-user/per-day marked+updated activity tables). Since v2.5559 (punch list #110) the deck finds three kinds of company through the top row — **Customers**, **Jobs to GC** (an owner, developer, architect or owner's rep with a job we could build as the GC) and **Subs** (a trade company for the bench) — one `prospects.kind` with each kind's facts (`source`; a sub's trades, range and language; a lead's role), its own last press (**Add to the bench ✓** opens the bench's Add a company filled from the card, `gc_add_company`; **Asked us ✓** opens Add customer) and its own Prospect List and Activity; Convert stays on Customers. Kernels `src/lib/prospects/prospectKinds.ts`, `subsLane.ts` (the bench's needs, v2.5560) and `gcLeadLane.ts` (a lead's jobs in `prospect_jobs`, Asked us ✓ → New project, v2.5561); every other reader keeps to its kind (v2.5563). Since punch lists #113 and #117 (v2.5578–v2.5585, v2.5600–v2.5606): a lane's deck is its own on a refresh (`laneLoad.ts`), one double line over every home a company can already have (`companyDouble.ts`), a lead's job edited in place, the two windows fit the screen and ask before a touched one closes, a ZZ company stays out of every non-dev lane, and the person we call comes first (`personBlock.ts`: `is_person`, title, cell and language on every kind; **May we text?**, which `quo-send` waits on; a sub pasted from Google Maps with its license and Maps link; the person carried into Add customer and the bench). Since punch list #148 the Subs lane opens on **What GC mode needs right now** (v2.5782, `gcNeeds.ts`: each trade short of quotes or of bench companies, with a door from the need to the bench, the subs here or Add a sub) and Jobs to GC's strip names the projects bidding now (v2.5785); since punch list #153 the Subs lane carries the path onto the bench as a strip (To call → Called → Talked → On the bench → Quoted, read and never stored, `subsStages.ts`), the Prospect List by trade with **For** the project a set of plans is for (v2.5807), the **Board** sub-tab, one column a trade with **Call the top 3 →** running Follow Up as a run (v2.5808, `SubsBoard.tsx`, `callRun.ts`), a drag that pins a card and Call first · Normal · Later on every sub (v2.5809, `prospect_trade_ranks`, `prospects.priority`), and the sub that says yes asked on the project's job as it lands on the bench (v2.5810, `benchAsk.ts`). Lead warmth, fit status (`prospect_fit_status`), callbacks, and copy templates feed the Calendar and the Quickfill **Prospects** section. - **Hiring** (`?tab=team`; labelled Team until v2.1253, and since v2.8776 the Decide, Contact and Ours steps under **Hires**) — the **prospective-hires board** ([`TeamProspectsTab`](../src/components/prospects/TeamProspectsTab.tsx)): candidate cards in `team_prospects` with roles in `team_prospect_roles` (`20260717190000`, `20260717230000`), including per-source success tracking (v2.715). Access is per-user via `users.team_prospects_access` (`20260717250000_team_prospects_access_flag.sql`, helper `user_has_team_prospects_access()`, v2.714) — prospects-staff role alone is not enough. Since v2.5812 a candidate has a flow (Screening call, Qualifications, Try-out, Hired or passed, read from the board's row by `flows/candidateLoad.ts`), and its **Qualifications** step notes a level from 0 to 3 in plumbing, electrical and HVAC, the license and where they drive in from (`trade_levels`, `lib/hiring/tradeScale.ts`, `QualificationsWindow.tsx`), the same scale a sub's coming-on lane carries. The **Try-out** stage (v2.3627) holds trial helpers; each card carries the tally and the nudge (v2.3715 — `team_prospect_trial_tally()` read into `src/lib/hiring/trialTally.ts`; *Keep trying* stamps `trial_deferred_at / _by`). A column can be **shared** with an account that has prospects staff access but not the switch (v2.3798 `team_prospect_role_shares` + `user_hiring_shared_role_ids()` in the policies; v2.3802 the header's ⋯ → *Share with…*, `ShareColumnDialog`, and the *Hiring columns shared with them* line on the person desk's Extra access row (v2.4348; it was in Settings → Active accounts); v2.3805 the share holder's tab — the Hiring pill, the **Hires** pill since v2.8776, opens for a share (`useMyHiringShares`) and the board renders `shared`, trimmed by `src/lib/hiring/sharedHiringTab.ts`). - - **Permits** (v2.6782, punch list #292, `?tab=permits`; labelled Research and keyed `?tab=research` until v2.6787, which the page still accepts) — the permit ledger ([`ProspectsResearchTab`](../src/components/prospects/ProspectsResearchTab.tsx) over [`permitResearch.ts`](../src/lib/research/permitResearch.ts)): a city's building permits and project applications from `permits` (each city's open-data feed, five cities since v2.6861, pulled nightly by `permit-pull`), newest first, each with who pulled it and the **Plumber** cell, which since v2.6785 names a plumber only when a plumbing permit on the same number or address was pulled under a name other than the applicant's and else reads *on file, no plumber named* or *none yet* (`plumberWords`; `research_permits` replaced in place, `20261109100000`; since v2.7922 a San Antonio plumbing permit at the address counts only from the same applicant, because that city issues a project's plumbing permit on the project's own number and another tenant's permit was closing jobs, `permit_address_plumbing_counts`, `20261119063000`; since v2.7935 a permit left uncounted is said under *none yet* and on the skim card, `nearbyPlumbingWords` over `research_permits_v3`, `20261119073000`; since v2.8295 every read that pairs a plumbing permit with a building permit (the skim's and the ledger's plumber and his day, a builder's open count, the permits said as *at this address, not counted*, Market's first plumbing day and Builders' plumber) counts only the building's own plumbing permit, a general plumbing permit or a plumbing type with no qualifier, through `permit_is_building_plumbing` beside each `kind = 'plumbing'` in `research_permits`, `_v2`, `_v3`, `_v4` and `research_builders` (`20261122230500`), the rule `plumbingTypeOf` already read a bid's window by, so a lawn sprinkler, gas or sewer permit no longer closes a building as **Has a plumber**; since v2.7966 Builders draws its plumber column only where some builder's permits name one, `cityNamesPlumbers`, and a caught-up skim in a quiet city says what stopped, `caughtUpWords`); one **Decide…** press per row opens [`PermitDecideSheet`](../src/components/prospects/PermitDecideSheet.tsx) — Pursue (Approach them until v2.6830; makes a lead with *A permit* as its source, on the deck `leadDeck` picks from **They are**: a general contractor is a `customer` prospect with the permit in its notes, an owner or an architect a `gc_lead` prospect with the permit as a `prospect_jobs` row; every one was a `gc_lead` until v2.6907, and `loadLeadDecks` tells a row's lead door which deck to open), Investigate (with a look-again day), Pass, Has a plumber — each with a reason, kept in `permit_verdicts`. Open to the office and every estimator (`user_can_research_permits()`); an estimator without `estimator_prospects_access` lands here and sees no calling-deck tabs. Since v2.6784 a **Map** view ([`ResearchMapCard`](../src/components/prospects/ResearchMapCard.tsx) over the Bid Board's pins canvas, in the shared `PinsMapFrame` with Satellite, Streets and **Time** since v2.7802) draws the lens as pins, a group of pins names what it holds since v2.8745 (*N permits here*, with *jobs* on the Jobs map, *bids* on the Bid Board's and *pins* for a map that names nothing; `clusterTitle` in [`clusterPins.ts`](../src/lib/map/clusterPins.ts)), a word under each name reads our bid history with it (`research_contact_history`, `20261109080000`; an open lead of that name on either calling deck reads **on the deck** since `20261111043500`; its bids are the ones the one rule counts since `20261121152000`, v2.8181), and the taken lens opens with **Who wins what**. Since v2.6830 (punch list #302) the tab opens on **Skim** ([`PermitSkimDeck`](../src/components/prospects/PermitSkimDeck.tsx) over [`permitSkim.ts`](../src/lib/research/permitSkim.ts)): one permit at a time with no date window, best first, two answers (Investigate writes `look`, Pass writes `not_for_us`), held a few seconds so Undo can take one back, with a street view and a map across the top of the card and a swipe on a phone since v2.6833 ([`PermitSkimLook`](../src/components/prospects/PermitSkimLook.tsx), [`permitLook.ts`](../src/lib/research/permitLook.ts)); and the four verdicts read **Investigate, Pass, Pursue, Has a plumber** on every screen, the place a permit waits in reading **Investigating** (Keep and Kept until v2.6879; the stored value is `look` throughout) (Look into it, Not for us, Approach them and Already taken before it). Since v2.6835 a strip counts where every permit is — **Skim, Investigating, Pursuing, Closed** ([`permitBuilders.ts`](../src/lib/research/permitBuilders.ts), [`PermitPlaceList`](../src/components/prospects/PermitPlaceList.tsx)): an Investigate can be handed to a person (the bar asks *Investigating. Who?*), a permit under Investigating closes on **Pursue…** (what for, who follows up) or **Not pursuing…** ([`PermitCloseOutSheet`](../src/components/prospects/PermitCloseOutSheet.tsx)), the city box lists the cities the pull reads, San Antonio, Austin (v2.6859) and New Braunfels, San Marcos and Seguin (v2.6861) ([`permitCities.ts`](../supabase/functions/_shared/permitCities.ts), the browser remembering the last one, and on a phone's Skim riding on the strip as a chip after the magnifier since v2.6905, each city's row reading its newest permit day or, since v2.7880, *quiet since* the day the city's own source stopped while our pull still runs clean ([`permitQuiet.ts`](../src/lib/research/permitQuiet.ts) over `usePermitCityQuiet`, more than 7 days back, 10 for San Antonio's weekly rhythm); a card's county, appraisal district, city permit search and deed search come from [`permitCityDoors.ts`](../src/lib/research/permitCityDoors.ts), and every city's county parcel record is read for the owner of record since v2.6912 (each county by house number and street name, then by the permit's point, in [`permitParcels.ts`](../supabase/functions/_shared/permitParcels.ts) and [`permitLookup.ts`](../supabase/functions/_shared/permitLookup.ts), Bexar at the point since v2.6978 and by number and street name since v2.6991; since v2.6974 an Austin permit's lot is asked first by the county id the permit carries, at Travis or, since v2.6984, at Williamson for Austin over the county line; since v2.6980 a neighbouring county's layer is asked at the point when the city's own county holds nothing there; the order of the questions and how long each answer is kept: [EDGE_FUNCTIONS.md](./EDGE_FUNCTIONS.md) → *permit-lookup*); a building's sheet offers **Open this permit at the city** when the feed's row carries the city's own page, `permitOwnPage`); the magnifier at the start of the strip is **Find a permit** ([`PermitFindPanel`](../src/components/prospects/PermitFindPanel.tsx), [`permitFind.ts`](../src/lib/research/permitFind.ts), v2.6892): one search over every list and every city, the other cities read one at a time; Closed also reads **On a map**, every permit on the chip as a pin; Closed has a search, **Put back** and, on a pass or a drop, **Investigate** for anyone; every card and sheet reads the permit's history from `permit_verdicts` ([`permitHistory.ts`](../src/lib/research/permitHistory.ts), v2.6850); **Second look** ([`permitSecondLook.ts`](../src/lib/research/permitSecondLook.ts), v2.6843) deals what someone else passed through the same deck in `second` mode, opened from the grey *N passed* segment joined to the Skim chip, once per permit, a second pass written with an `sl_` reason code; **Builders** ([`PermitBuilders`](../src/components/prospects/PermitBuilders.tsx) over `research_builders`) lists every name on permits, read a page at a time past the API's 1,000 rows like the skim's own read (`fetchAllRows`, v2.6924), as far back as the records go, a year at most, every count saying the day the records start ([`permitReach.ts`](../src/lib/research/permitReach.ts) over `permit_pulls.since`, v2.6857) and a **Read back to …** press reading a step further as history, flagged `permits.backfilled` and kept off the skim (v2.6873, `20261110224035`), with a Good or Avoid mark that shows on the skim card, and since v2.6963 an **Our bids** count that adds the bids of the customers someone tied the name to, since v2.8138 and v2.8147 only the bids of two years with no practice bid, the rule Market's table counts by ([`ourBids.ts`](../src/lib/research/ourBids.ts), on the database `research_bid_counts` and `research_bid_party_key`) ([`builderAnswers.ts`](../src/lib/research/builderAnswers.ts), `useBuilderAnswers`, read once for the list) and a sheet section **Our customer under this name** ([`BuilderNameTies`](../src/components/prospects/BuilderNameTies.tsx)) with each tie, whose word it is, **Take back**, *Same company?* and **Tie to a customer**; and [`PermitCountStrip`](../src/components/prospects/PermitCountStrip.tsx) reads the month's count (`permit_funnel`). **Market** (v2.7978, punch list #405, [`PermitMarket`](../src/components/prospects/PermitMarket.tsx) over [`permitMarket.ts`](../src/lib/research/permitMarket.ts) and `usePermitMarket`, on the address as `view=market`) is the view beside Builders that says what the permits mean for us: every company we priced a job for in two years with our bids, our wins and the commercial permits its names pulled in twelve months in every city (`bidCompanies`: a bid under its customer's name and the old builders list's, practice bids and a bid platform's bucket left out, the permits each city's `research_builders` count under the company's key or a name a person tied to it), what that reads as, **Tie a name** on a customer with no permit on record opening Find their names on permits, a name on a row opening the builder's sheet, and **the clock** (`marketClocks`), the quarter marks of the days from an application to its permit, read off `permits` with the history rows (since v2.8260 a line under it says how many applications of the twelve months still wait and how many of those were filed over six months ago, `applicationsWaiting` and `clockWaitingNote`), or from a building permit to the plumber's permit where the city names plumbers (since v2.8254 to the job's first plumbing permit, `plumber_first_permit_on` off `research_permits_v4`, `20261122032000`, where it ran to the newest); since v2.7993 it leads with **Call this week** ([`PermitCallList`](../src/components/prospects/PermitCallList.tsx) over [`permitCallList.ts`](../src/lib/research/permitCallList.ts)): five builders with three or more commercial jobs in twelve months, a job being one name's rows of one day at one address since v2.8112 (`marketJobs`), never an Avoid or a name said to file for others, each with its reasons as tags and no score (`callRows`: since v2.8112 a name with a building word first, `saysItBuilds`, then a name that reads as a company, then a job open now, then picking up or new and busy, then never bid), chips over it, **Pursue** making the lead the skim makes through the kept permit's own sheet, **Not for us**, and either answer kept append-only in `builder_call_answers` (`20261120031349`) so the name leaves the list for everyone until its day to look again, and since v2.8112 until it has applied for a new job after the answer (`backWithNewJob`), and **Put back** undoes it, and since v2.8121 each row's **Ask for** block ([`PermitAskFor`](../src/components/prospects/PermitAskFor.tsx) over [`builderLookups.ts`](../src/lib/research/builderLookups.ts)) shows what a one-time lookup found about the name, the kind of company, an office phone and a person to ask for, each with its page and day out of `builder_lookups` (`20261120120000`), grey as looked up and not checked until a person presses **Checked**, off the row on **Wrong**, the presses append-only in `builder_lookup_checks`, a looked-up kind tagging the name and ordering it only once checked (`lookupOrder`) and never removing it; and beside the clock **Who holds the work**, drawn only where the permits name plumbers, and **How much is being built** by month, kind and size ([`PermitMarketShape`](../src/components/prospects/PermitMarketShape.tsx) over [`permitMarketShape.ts`](../src/lib/research/permitMarketShape.ts)), all counted over a city's year of commercial permits read off `permits` with the history rows (`loadMarketPermits`, the pages after the first asked together). Since v2.6828 an address opens **The building** ([`PermitBuildingSheet`](../src/components/prospects/PermitBuildingSheet.tsx) over [`permitPublic.ts`](../src/lib/research/permitPublic.ts)): the permit with every field the feed sent (`permits.raw`), the county's parcel, every permit on the address and the doors to the city's record and the county clerk's deeds; the Who pulled it card lists the name's other permits and opens the state's franchise tax search; and a round **G** ([`GoogleSearchPress`](../src/components/prospects/GoogleSearchPress.tsx)) beside a name or an address opens a Google search in a new tab. Guide `research-permits-for-work-to-bid`. Since v2.6866 (punch list #307) a bid's Edit window reads the same permits by the bid's own address: **This site** under Location ([`BidSitePermits`](../src/components/bids/BidSitePermits.tsx)) and **What we can see about** the GC under its card ([`BidGcPermits`](../src/components/bids/BidGcPermits.tsx)), over [`bidSite.ts`](../src/lib/research/bidSite.ts), [`bidSitePanel.ts`](../src/lib/research/bidSitePanel.ts) and the read `bid_site_permits` (`20261110220345`); guide `see-what-the-city-has-on-a-bids-address`. Since v2.6870 the Bid Board carries the same read as a chip on each undecided bid's row (`useBidPermitNews`, [`bidPermitNews.ts`](../src/lib/research/bidPermitNews.ts)). Since v2.7941 the news lines are a lens on Followup, **Permit news** ([`BidsPermitNewsLens`](../src/components/bids/BidsPermitNewsLens.tsx)). There each line is answered in `bid_permit_answers` (`20261119130000`), and a sent bid's plumbing line opens the board's own outcome through **We lost it…** ([`BidBoardNewsMarkLost`](../src/components/bids/BidBoardNewsMarkLost.tsx)). Until v2.7941 the lines were the strip **Permit news on your bids** above the board's sections. Since v2.6872 the site's lead permit asks once who the city lists on it ([`BidNameQuestion`](../src/components/bids/BidNameQuestion.tsx); *Same company?* since v2.6963 when one name begins the other), the answers kept append-only in `builder_customer_answers` (`20261110223054`) and folded by [`nameAnswers.ts`](../src/lib/research/nameAnswers.ts), and the GC's panel lists the names tied to it ([`BidGcTiedNames`](../src/components/bids/BidGcTiedNames.tsx)). Since v2.6886 a person links a customer to its names on permits: **Find their names on permits** ([`FindNamesSheet`](../src/components/bids/FindNamesSheet.tsx), from the GC's panel and the customer page's **Names on permits** card) suggests names with their reasons over [`nameLikeness.ts`](../src/lib/research/nameLikeness.ts), a phone or a web domain the name shares with the customer among them since v2.8308 (`permit_name_contact_matches`, migration `20261122233000`, read through `loadNameContactMatches`; **Compare** lists the phones and web domains each side holds), and Builders carries **Looks like a customer** ([`PermitLookAlikes`](../src/components/prospects/PermitLookAlikes.tsx)), whose count the Dashboard's Needs you card carries since v2.6962 (*N names on permits look like a customer*, **Answer them** opening `/prospects?tab=permits&view=builders&looks=1`, [`permitsLink.ts`](../src/lib/research/permitsLink.ts)); the app ties nothing on a likeness. + - **Permits** (v2.6782, punch list #292, `?tab=permits`; labelled Research and keyed `?tab=research` until v2.6787, which the page still accepts) — the permit ledger ([`ProspectsResearchTab`](../src/components/prospects/ProspectsResearchTab.tsx) over [`permitResearch.ts`](../src/lib/research/permitResearch.ts)): a city's building permits and project applications from `permits` (each city's open-data feed, five cities since v2.6861, pulled nightly by `permit-pull`), newest first, each with who pulled it and the **Plumber** cell, which since v2.6785 names a plumber only when a plumbing permit on the same number or address was pulled under a name other than the applicant's and else reads *on file, no plumber named* or *none yet* (`plumberWords`; `research_permits` replaced in place, `20261109100000`; since v2.7922 a San Antonio plumbing permit at the address counts only from the same applicant, because that city issues a project's plumbing permit on the project's own number and another tenant's permit was closing jobs, `permit_address_plumbing_counts`, `20261119063000`; since v2.7935 a permit left uncounted is said under *none yet* and on the skim card, `nearbyPlumbingWords` over `research_permits_v3`, `20261119073000`; since v2.8295 every read that pairs a plumbing permit with a building permit (the skim's and the ledger's plumber and his day, a builder's open count, the permits said as *at this address, not counted*, Market's first plumbing day and Builders' plumber) counts only the building's own plumbing permit, a general plumbing permit or a plumbing type with no qualifier, through `permit_is_building_plumbing` beside each `kind = 'plumbing'` in `research_permits`, `_v2`, `_v3`, `_v4` and `research_builders` (`20261122230500`), the rule `plumbingTypeOf` already read a bid's window by, so a lawn sprinkler, gas or sewer permit no longer closes a building as **Has a plumber**; since v2.7966 Builders draws its plumber column only where some builder's permits name one, `cityNamesPlumbers`, and a caught-up skim in a quiet city says what stopped, `caughtUpWords`; since v2.9263, punch list #465 step 1, Builders reads every city at once, *All five cities* on the tab's picker and the one the list opens on, through `research_builders_v2` (`loadBuildersOf`), and draws each name's share of the dollars declared and of the permits as a dark and a light bar, green for a name that is ours and grey for one not ours yet, with headings that sort and the chips Everyone, Ours and Not ours yet, `builderShare.ts`); one **Decide…** press per row opens [`PermitDecideSheet`](../src/components/prospects/PermitDecideSheet.tsx) — Pursue (Approach them until v2.6830; makes a lead with *A permit* as its source, on the deck `leadDeck` picks from **They are**: a general contractor is a `customer` prospect with the permit in its notes, an owner or an architect a `gc_lead` prospect with the permit as a `prospect_jobs` row; every one was a `gc_lead` until v2.6907, and `loadLeadDecks` tells a row's lead door which deck to open), Investigate (with a look-again day), Pass, Has a plumber — each with a reason, kept in `permit_verdicts`. Open to the office and every estimator (`user_can_research_permits()`); an estimator without `estimator_prospects_access` lands here and sees no calling-deck tabs. Since v2.6784 a **Map** view ([`ResearchMapCard`](../src/components/prospects/ResearchMapCard.tsx) over the Bid Board's pins canvas, in the shared `PinsMapFrame` with Satellite, Streets and **Time** since v2.7802) draws the lens as pins, a group of pins names what it holds since v2.8745 (*N permits here*, with *jobs* on the Jobs map, *bids* on the Bid Board's and *pins* for a map that names nothing; `clusterTitle` in [`clusterPins.ts`](../src/lib/map/clusterPins.ts)), a word under each name reads our bid history with it (`research_contact_history`, `20261109080000`; an open lead of that name on either calling deck reads **on the deck** since `20261111043500`; its bids are the ones the one rule counts since `20261121152000`, v2.8181), and the taken lens opens with **Who wins what**. Since v2.6830 (punch list #302) the tab opens on **Skim** ([`PermitSkimDeck`](../src/components/prospects/PermitSkimDeck.tsx) over [`permitSkim.ts`](../src/lib/research/permitSkim.ts)): one permit at a time with no date window, best first, two answers (Investigate writes `look`, Pass writes `not_for_us`), held a few seconds so Undo can take one back, with a street view and a map across the top of the card and a swipe on a phone since v2.6833 ([`PermitSkimLook`](../src/components/prospects/PermitSkimLook.tsx), [`permitLook.ts`](../src/lib/research/permitLook.ts)); and the four verdicts read **Investigate, Pass, Pursue, Has a plumber** on every screen, the place a permit waits in reading **Investigating** (Keep and Kept until v2.6879; the stored value is `look` throughout) (Look into it, Not for us, Approach them and Already taken before it). Since v2.6835 a strip counts where every permit is — **Skim, Investigating, Pursuing, Closed** ([`permitBuilders.ts`](../src/lib/research/permitBuilders.ts), [`PermitPlaceList`](../src/components/prospects/PermitPlaceList.tsx)): an Investigate can be handed to a person (the bar asks *Investigating. Who?*), a permit under Investigating closes on **Pursue…** (what for, who follows up) or **Not pursuing…** ([`PermitCloseOutSheet`](../src/components/prospects/PermitCloseOutSheet.tsx)), the city box lists the cities the pull reads, San Antonio, Austin (v2.6859) and New Braunfels, San Marcos and Seguin (v2.6861) ([`permitCities.ts`](../supabase/functions/_shared/permitCities.ts), the browser remembering the last one, and on a phone's Skim riding on the strip as a chip after the magnifier since v2.6905, each city's row reading its newest permit day or, since v2.7880, *quiet since* the day the city's own source stopped while our pull still runs clean ([`permitQuiet.ts`](../src/lib/research/permitQuiet.ts) over `usePermitCityQuiet`, more than 7 days back, 10 for San Antonio's weekly rhythm); a card's county, appraisal district, city permit search and deed search come from [`permitCityDoors.ts`](../src/lib/research/permitCityDoors.ts), and every city's county parcel record is read for the owner of record since v2.6912 (each county by house number and street name, then by the permit's point, in [`permitParcels.ts`](../supabase/functions/_shared/permitParcels.ts) and [`permitLookup.ts`](../supabase/functions/_shared/permitLookup.ts), Bexar at the point since v2.6978 and by number and street name since v2.6991; since v2.6974 an Austin permit's lot is asked first by the county id the permit carries, at Travis or, since v2.6984, at Williamson for Austin over the county line; since v2.6980 a neighbouring county's layer is asked at the point when the city's own county holds nothing there; the order of the questions and how long each answer is kept: [EDGE_FUNCTIONS.md](./EDGE_FUNCTIONS.md) → *permit-lookup*); a building's sheet offers **Open this permit at the city** when the feed's row carries the city's own page, `permitOwnPage`); the magnifier at the start of the strip is **Find a permit** ([`PermitFindPanel`](../src/components/prospects/PermitFindPanel.tsx), [`permitFind.ts`](../src/lib/research/permitFind.ts), v2.6892): one search over every list and every city, the other cities read one at a time; Closed also reads **On a map**, every permit on the chip as a pin; Closed has a search, **Put back** and, on a pass or a drop, **Investigate** for anyone; every card and sheet reads the permit's history from `permit_verdicts` ([`permitHistory.ts`](../src/lib/research/permitHistory.ts), v2.6850); **Second look** ([`permitSecondLook.ts`](../src/lib/research/permitSecondLook.ts), v2.6843) deals what someone else passed through the same deck in `second` mode, opened from the grey *N passed* segment joined to the Skim chip, once per permit, a second pass written with an `sl_` reason code; **Builders** ([`PermitBuilders`](../src/components/prospects/PermitBuilders.tsx) over `research_builders`) lists every name on permits, read a page at a time past the API's 1,000 rows like the skim's own read (`fetchAllRows`, v2.6924), as far back as the records go, a year at most, every count saying the day the records start ([`permitReach.ts`](../src/lib/research/permitReach.ts) over `permit_pulls.since`, v2.6857) and a **Read back to …** press reading a step further as history, flagged `permits.backfilled` and kept off the skim (v2.6873, `20261110224035`), with a Good or Avoid mark that shows on the skim card, and since v2.6963 an **Our bids** count that adds the bids of the customers someone tied the name to, since v2.8138 and v2.8147 only the bids of two years with no practice bid, the rule Market's table counts by ([`ourBids.ts`](../src/lib/research/ourBids.ts), on the database `research_bid_counts` and `research_bid_party_key`) ([`builderAnswers.ts`](../src/lib/research/builderAnswers.ts), `useBuilderAnswers`, read once for the list) and a sheet section **Our customer under this name** ([`BuilderNameTies`](../src/components/prospects/BuilderNameTies.tsx)) with each tie, whose word it is, **Take back**, *Same company?* and **Tie to a customer**; and [`PermitCountStrip`](../src/components/prospects/PermitCountStrip.tsx) reads the month's count (`permit_funnel`). **Market** (v2.7978, punch list #405, [`PermitMarket`](../src/components/prospects/PermitMarket.tsx) over [`permitMarket.ts`](../src/lib/research/permitMarket.ts) and `usePermitMarket`, on the address as `view=market`) is the view beside Builders that says what the permits mean for us: every company we priced a job for in two years with our bids, our wins and the commercial permits its names pulled in twelve months in every city (`bidCompanies`: a bid under its customer's name and the old builders list's, practice bids and a bid platform's bucket left out, the permits each city's `research_builders` count under the company's key or a name a person tied to it), what that reads as, **Tie a name** on a customer with no permit on record opening Find their names on permits, a name on a row opening the builder's sheet, and **the clock** (`marketClocks`), the quarter marks of the days from an application to its permit, read off `permits` with the history rows (since v2.8260 a line under it says how many applications of the twelve months still wait and how many of those were filed over six months ago, `applicationsWaiting` and `clockWaitingNote`), or from a building permit to the plumber's permit where the city names plumbers (since v2.8254 to the job's first plumbing permit, `plumber_first_permit_on` off `research_permits_v4`, `20261122032000`, where it ran to the newest); since v2.7993 it leads with **Call this week** ([`PermitCallList`](../src/components/prospects/PermitCallList.tsx) over [`permitCallList.ts`](../src/lib/research/permitCallList.ts)): five builders with three or more commercial jobs in twelve months, a job being one name's rows of one day at one address since v2.8112 (`marketJobs`), never an Avoid or a name said to file for others, each with its reasons as tags and no score (`callRows`: since v2.8112 a name with a building word first, `saysItBuilds`, then a name that reads as a company, then a job open now, then picking up or new and busy, then never bid), chips over it, **Pursue** making the lead the skim makes through the kept permit's own sheet, **Not for us**, and either answer kept append-only in `builder_call_answers` (`20261120031349`) so the name leaves the list for everyone until its day to look again, and since v2.8112 until it has applied for a new job after the answer (`backWithNewJob`), and **Put back** undoes it, and since v2.8121 each row's **Ask for** block ([`PermitAskFor`](../src/components/prospects/PermitAskFor.tsx) over [`builderLookups.ts`](../src/lib/research/builderLookups.ts)) shows what a one-time lookup found about the name, the kind of company, an office phone and a person to ask for, each with its page and day out of `builder_lookups` (`20261120120000`), grey as looked up and not checked until a person presses **Checked**, off the row on **Wrong**, the presses append-only in `builder_lookup_checks`, a looked-up kind tagging the name and ordering it only once checked (`lookupOrder`) and never removing it; and beside the clock **Who holds the work**, drawn only where the permits name plumbers, and **How much is being built** by month, kind and size ([`PermitMarketShape`](../src/components/prospects/PermitMarketShape.tsx) over [`permitMarketShape.ts`](../src/lib/research/permitMarketShape.ts)), all counted over a city's year of commercial permits read off `permits` with the history rows (`loadMarketPermits`, the pages after the first asked together). Since v2.6828 an address opens **The building** ([`PermitBuildingSheet`](../src/components/prospects/PermitBuildingSheet.tsx) over [`permitPublic.ts`](../src/lib/research/permitPublic.ts)): the permit with every field the feed sent (`permits.raw`), the county's parcel, every permit on the address and the doors to the city's record and the county clerk's deeds; the Who pulled it card lists the name's other permits and opens the state's franchise tax search; and a round **G** ([`GoogleSearchPress`](../src/components/prospects/GoogleSearchPress.tsx)) beside a name or an address opens a Google search in a new tab. Guide `research-permits-for-work-to-bid`. Since v2.6866 (punch list #307) a bid's Edit window reads the same permits by the bid's own address: **This site** under Location ([`BidSitePermits`](../src/components/bids/BidSitePermits.tsx)) and **What we can see about** the GC under its card ([`BidGcPermits`](../src/components/bids/BidGcPermits.tsx)), over [`bidSite.ts`](../src/lib/research/bidSite.ts), [`bidSitePanel.ts`](../src/lib/research/bidSitePanel.ts) and the read `bid_site_permits` (`20261110220345`); guide `see-what-the-city-has-on-a-bids-address`. Since v2.6870 the Bid Board carries the same read as a chip on each undecided bid's row (`useBidPermitNews`, [`bidPermitNews.ts`](../src/lib/research/bidPermitNews.ts)). Since v2.7941 the news lines are a lens on Followup, **Permit news** ([`BidsPermitNewsLens`](../src/components/bids/BidsPermitNewsLens.tsx)). There each line is answered in `bid_permit_answers` (`20261119130000`), and a sent bid's plumbing line opens the board's own outcome through **We lost it…** ([`BidBoardNewsMarkLost`](../src/components/bids/BidBoardNewsMarkLost.tsx)). Until v2.7941 the lines were the strip **Permit news on your bids** above the board's sections. Since v2.6872 the site's lead permit asks once who the city lists on it ([`BidNameQuestion`](../src/components/bids/BidNameQuestion.tsx); *Same company?* since v2.6963 when one name begins the other), the answers kept append-only in `builder_customer_answers` (`20261110223054`) and folded by [`nameAnswers.ts`](../src/lib/research/nameAnswers.ts), and the GC's panel lists the names tied to it ([`BidGcTiedNames`](../src/components/bids/BidGcTiedNames.tsx)). Since v2.6886 a person links a customer to its names on permits: **Find their names on permits** ([`FindNamesSheet`](../src/components/bids/FindNamesSheet.tsx), from the GC's panel and the customer page's **Names on permits** card) suggests names with their reasons over [`nameLikeness.ts`](../src/lib/research/nameLikeness.ts), a phone or a web domain the name shares with the customer among them since v2.8308 (`permit_name_contact_matches`, migration `20261122233000`, read through `loadNameContactMatches`; **Compare** lists the phones and web domains each side holds), and Builders carries **Looks like a customer** ([`PermitLookAlikes`](../src/components/prospects/PermitLookAlikes.tsx)), whose count the Dashboard's Needs you card carries since v2.6962 (*N names on permits look like a customer*, **Answer them** opening `/prospects?tab=permits&view=builders&looks=1`, [`permitsLink.ts`](../src/lib/research/permitsLink.ts)); the app ties nothing on a likeness. - **State roll** (v2.8198, punch list #411, `?tab=roll`) — the state's public roll of licensed plumbers kept for our counties, and since v2.8202 for our own people's license numbers wherever they live ([`StateRollTab`](../src/components/prospects/StateRollTab.tsx)), shown to the Hiring switch (`users.team_prospects_access`) alone. **Our own** (v2.8233, [`StateRollOwn`](../src/components/prospects/StateRollOwn.tsx), `?tab=roll&roll=own`) lays each plumbing license we hold beside the state's row of the same number and rank, with **Use the state's date**, for a person who may also open People → Licenses; its rule is [`ownLicenses.ts`](../src/lib/licenseRoll/ownLicenses.ts), and since v2.8783 its two chips, *Needs a look* and *Matches*, are Everyone's `RollChip` ([`StateRollChip.tsx`](../src/components/prospects/StateRollChip.tsx), with `LIT_LINE` and `filterHeight` in `stateRollFilterLook.ts`), 30 px on a desk and 44 px under 640 px, the lit one in the blue tint. **Everyone** (v2.8390, `roll=everyone`, `StateRollEveryone`) is the kept roll searched by name or number, its head two lines and a desk row one since v2.8765 (→ `GLOSSARY.md`, *State roll*). The third view is **Pulls** (`roll=pulls`): what is kept, a card a state file with when it was last read and what that read changed, and **Pull 4 files**, which pulls the four weekly files in turn through `license-roll-pull` (the apprentice file, read for our own numbers since v2.8202, has no card and runs on its Monday job alone). The roll's rule is [`_shared/licenseRoll.ts`](../supabase/functions/_shared/licenseRoll.ts); the view's lines are [`rollPulls.ts`](../src/lib/licenseRoll/rollPulls.ts). No home address, home phone or email is kept, and since v2.8771 a responsible master's row keeps the company phone and address the state's file lists (the four `license_roll` columns v2.8769 added, `20261128180500_license_roll_business_contact`). - See [ACCESS_CONTROL.md](./ACCESS_CONTROL.md), [PROSPECTS_TABS_ARCHITECTURE.md](./PROSPECTS_TABS_ARCHITECTURE.md), and [RECENT_FEATURES.md](./RECENT_FEATURES.md) (v2.708–v2.715) for details. diff --git a/docs/recent-features/v2.9263.md b/docs/recent-features/v2.9263.md new file mode 100644 index 0000000000..407259d2cd --- /dev/null +++ b/docs/recent-features/v2.9263.md @@ -0,0 +1,37 @@ +# v2.9263 — Builders: who holds the work, in all five cities at once (2026-12-02) + +Punch list #465, step 1, the client. It stands on v2.9261, the migration, which must be merged and pushed first: the list reads `research_builders_v2`, and until the push it says the database change is not in yet. Client only. Nothing owed on prod of its own. + +## What it does + +- **Every city at once.** The Permits tab's city picker has a first choice on Builders, *All five cities*, and the list opens on it unless the address asked for a city. `PermitBuilders` takes the cities it reads (`cities`), and `loadBuildersOf` in `permitResearchIo.ts` reads `research_builders_v2` for them, one row a name. A city picked reads that city alone, through the same function. +- **Two shares a name.** `builderShares` in the new kernel `src/lib/research/builderShare.ts` gives each name its part of the dollars declared and its part of the permits, with a rank on each for step 2. Both are parts of the whole list as it was read, whatever is drawn, so every row's shares add up to the whole. +- **Two bars.** The dollars' bar is the dark one and the permits' the light one, cut to the longest share drawn (`longestShare`, `barWidth`). Green is a name that is ours, grey one that is not yet. A name whose permits declare nothing reads *none declared* and has the permits' bar alone. Under the dollars' share the row says the dollars themselves, through `Money`. +- **Ours.** `isOurs`: a bid from us in two years, which `bids` already counts by the one rule, or a name a person tied to a customer (the keys of `book.tied`). The chips **Everyone**, **Ours** and **Not ours yet** narrow the list, each with its count, and each row ends in its chip. +- **Sorting.** A press on a heading sorts (`pressSort`, `sortBuilders`). The lit heading carries a mark and turns round on a second press. A name and a plumber start A to Z, a number starts with the most. A name with nothing to sort by goes last either way. The list opens on the most dollars. A phone has a picker in place of headings. +- **The lines.** *10 drawn here of 212 companies* beside the chips (`drawnWords`). Under the list, over every city, the cities whose records start less than a year ago, each with its day (`recordsStartWords`, over the new `usePermitRecordsStarts`). + +## Where it differs from the drawing + +The card ties the step to section 2 of its mock-up and says to name each difference. + +- The theme's colours and the app's own chips stand where the drawing has its own. The greys of a bar are `var(--text-faint)` and `var(--border-strong)`. The greens are literals, as every status colour is. +- **The Companies or People switch is not here.** It is step 4's. +- **Kept, though the drawing has neither:** the chips *All*, *3 or more permits and never bid*, *Good*, *Avoid* and *No mark*, and the search. They narrow by our mark, and the new three narrow by whether the name is ours, so both rows stand. Nothing the list could do is taken away. +- **Moved:** the drawing has no *Mark* column and no *Last permit* column. A mark is a pill beside the name, drawn only where there is one, and the last permit's day is in the line under the name. +- **Without a plumber** is now headed **Open now**, the drawing's words, with the old words on its tip. +- **Over every city, two things of one city are not drawn:** the *Looks like a customer* chip and the *Read back to* press. A city picked brings both back. The Dashboard's *Answer them* line names a city, so it still opens on the chip. + +## What it does not settle + +- **How long the read of every city takes.** `research_builders_v2` runs once for each 1,000 names, as the one-city read did. Only prod can say how long five cities take. A failed read shows its reason with Retry, and a city picked reads less. +- **An application and the permit issued from it are two rows.** Both add their dollars. The guide says the dollars are what each filer wrote, and that a share is a part of the permits we hold. + +## Tested + +- `builderShare.test.ts`: the shares add up, a name with no dollars, ranks, ours by a bid or by a tie, the words of a share, the bars' measure, every column's order both ways, the heading's mark, the count drawn and the records' line. +- `PermitBuilders.render.test.tsx` and `ProspectsResearchTab.render.test.tsx`: the list over the new read, the bars, the chips, a heading's press, and *All five cities* on the picker. + +## Owes a look + +After its deploy, and after v2.9261's push: Prospects → Permits → Builders. It reads only. Time the first draw on *All five cities*. Add three names' permits' declared values by hand from the Ledger and hold each to its row. Press each heading. Press the three chips. diff --git a/src/components/prospects/PermitBuilders.render.test.tsx b/src/components/prospects/PermitBuilders.render.test.tsx index 4f6a46a693..36adb98cf5 100644 --- a/src/components/prospects/PermitBuilders.render.test.tsx +++ b/src/components/prospects/PermitBuilders.render.test.tsx @@ -13,7 +13,7 @@ import type { LookupCheckRow, LookupRow } from '../../lib/research/builderLookup * is, takes it back, asks *Same company?* of a customer whose name begins this one, and ties * any other through a search. Every name here is made up. */ -const research = vi.hoisted(() => ({ loadBuilders: vi.fn(), loadPermitsOfBuilder: vi.fn(), markBuilder: vi.fn(), saveBuilder: vi.fn(), pullPermitsBack: vi.fn(), loadRecordsStart: vi.fn() })) +const research = vi.hoisted(() => ({ loadBuilders: vi.fn(), loadBuildersOf: vi.fn(), loadPermitsOfBuilder: vi.fn(), markBuilder: vi.fn(), saveBuilder: vi.fn(), pullPermitsBack: vi.fn(), loadRecordsStart: vi.fn() })) const siteIo = vi.hoisted(() => ({ loadAllNameAnswers: vi.fn(), loadAllNameContactMatches: vi.fn(), loadCustomerNames: vi.fn(), loadRecentBidsWithCustomer: vi.fn(), loadPermitsByHouseNumber: vi.fn(), recordNameAnswer: vi.fn() })) const answersIo = vi.hoisted(() => ({ loadBuilderAnswersGround: vi.fn() })) const marketIo = vi.hoisted(() => ({ loadBuilderLookupOf: vi.fn(), recordLookupCheck: vi.fn() })) @@ -56,6 +56,8 @@ async function openSheet(name: string) { beforeEach(() => { research.loadBuilders.mockReset().mockResolvedValue([builder(), copperline]) + // The list reads `research_builders_v2` for the cities it is given. Each case sets what a city's read gives, as before. + research.loadBuildersOf.mockReset().mockImplementation((cities: string[]) => research.loadBuilders(cities[0])) research.loadPermitsOfBuilder.mockReset().mockResolvedValue([]) research.markBuilder.mockReset().mockResolvedValue(undefined) research.saveBuilder.mockReset().mockResolvedValue(undefined) @@ -109,13 +111,13 @@ describe('Builders, Our bids', () => { // Nobody named: no column on the desk, and the phone card and the sheet say nothing of a plumber. draw() await screen.findByText('Ridgeway Builders of Texas LLC') - expect(screen.queryByRole('columnheader', { name: 'Plumber they use' })).toBeNull() + expect(screen.queryByRole('columnheader', { name: 'Their plumber' })).toBeNull() expect(screen.queryByText(/not named on the permits/)).toBeNull() cleanup() // One builder's permits name a plumber: the column is back, and the other builder reads not named. research.loadBuilders.mockResolvedValue([builder(), builder({ key: 'tallpine', sample_contact: 'Tall Pine Development', plumber: 'Blue Heron Plumbing', plumber_jobs: 2 })]) draw() - expect(await screen.findByRole('columnheader', { name: 'Plumber they use' })).toBeTruthy() + expect(await screen.findByRole('columnheader', { name: 'Their plumber' })).toBeTruthy() expect(screen.getByText('Blue Heron Plumbing on 2')).toBeTruthy() expect(screen.getByText('not named on the permits')).toBeTruthy() }) @@ -138,6 +140,106 @@ describe('Builders, Our bids', () => { }) }) +describe('Builders, who holds the work (punch list #465, step 1)', () => { + const halden = builder({ key: 'haldencommercial', sample_contact: 'Halden Commercial', permits: 6, open: 3, declared: 600_000, declared_permits: 5, bids: 4, won: 1, cities: ['Austin', 'San Antonio'] }) + const sable = builder({ key: 'sablecreek', sample_contact: 'Sable Creek Construction', permits: 3, open: 2, declared: 300_000, declared_permits: 3, cities: ['Austin'] }) + const bexley = builder({ key: 'bexleygroup', sample_contact: 'Bexley Group', permits: 1, open: 1, declared: null, declared_permits: 0, cities: ['Seguin'] }) + const names = () => screen.getAllByRole('row').slice(1).map((r) => within(r).getAllByRole('button')[0]?.textContent) + const everyCity = (isMobile = false) => renderWithProviders( {}} />) + + it('gives each name its share of the dollars and of the permits, each a bar, and says the dollars', async () => { + research.loadBuilders.mockResolvedValue([halden, sable, bexley]) + draw() + const row = (await screen.findByRole('button', { name: 'Halden Commercial' })).closest('tr') as HTMLElement + expect(within(row).getByLabelText('Share of dollars: 66.7%')).toBeTruthy() + expect(within(row).getByLabelText('Share of permits: 60.0%')).toBeTruthy() + expect(row.querySelectorAll('[data-share-bar]')).toHaveLength(2) + expect(row.textContent).toContain('$600,000 declared') + expect(within(row).getByText('Ours')).toBeTruthy() + // A name whose permits declare nothing has the permits' bar alone, and is not ours yet. + const none = screen.getByRole('button', { name: 'Bexley Group' }).closest('tr') as HTMLElement + expect(within(none).getByLabelText('Share of dollars: none declared')).toBeTruthy() + expect(none.querySelectorAll('[data-share-bar]')).toHaveLength(1) + expect(within(none).getByText('Not ours yet')).toBeTruthy() + }) + + it('opens on the most dollars, and a press on a heading sorts and says which way', async () => { + research.loadBuilders.mockResolvedValue([sable, bexley, halden]) + draw() + await screen.findByRole('button', { name: 'Halden Commercial' }) + expect(names()).toEqual(['Halden Commercial', 'Sable Creek Construction', 'Bexley Group']) + expect(screen.getByRole('columnheader', { name: 'Share of dollars ▾' }).getAttribute('aria-sort')).toBe('descending') + fireEvent.click(screen.getByRole('button', { name: 'Builder' })) + expect(names()).toEqual(['Bexley Group', 'Halden Commercial', 'Sable Creek Construction']) + expect(screen.getByRole('columnheader', { name: 'Builder ▴' }).getAttribute('aria-sort')).toBe('ascending') + fireEvent.click(screen.getByRole('button', { name: 'Builder ▴' })) + expect(names()).toEqual(['Sable Creek Construction', 'Halden Commercial', 'Bexley Group']) + fireEvent.click(screen.getByRole('button', { name: 'Open now' })) + expect(names()).toEqual(['Halden Commercial', 'Sable Creek Construction', 'Bexley Group']) + }) + + it('narrows to ours or not ours yet, counts each, and says how many are drawn', async () => { + research.loadBuilders.mockResolvedValue([halden, sable, bexley]) + draw() + await screen.findByRole('button', { name: 'Halden Commercial' }) + const whose = screen.getByRole('group', { name: 'Whose work' }) + expect(within(whose).getByRole('button', { name: 'Everyone 3' }).getAttribute('aria-pressed')).toBe('true') + expect(whose.parentElement?.textContent).toContain('3 drawn here of 3 companies') + fireEvent.click(within(whose).getByRole('button', { name: 'Not ours yet 2' })) + expect(names()).toEqual(['Sable Creek Construction', 'Bexley Group']) + expect(whose.parentElement?.textContent).toContain('2 drawn here of 3 companies') + fireEvent.click(within(whose).getByRole('button', { name: 'Ours 1' })) + expect(names()).toEqual(['Halden Commercial']) + }) + + it('counts a name a person tied to a customer as ours, with no bid of its own', async () => { + research.loadBuilders.mockResolvedValue([builder({ declared: 100, declared_permits: 1 }), sable]) + answersIo.loadBuilderAnswersGround.mockResolvedValue(ground([tie()])) + draw() + const row = (await screen.findByRole('button', { name: 'Ridgeway Builders of Texas LLC' })).closest('tr') as HTMLElement + expect(within(row).getByText('Ours')).toBeTruthy() + expect(screen.getByRole('button', { name: 'Ours 1' })).toBeTruthy() + }) + + it('reads every city in one call, says a name’s cities, and leaves out what is one city’s', async () => { + research.loadBuildersOf.mockResolvedValue([halden, sable, bexley]) + research.loadRecordsStart.mockImplementation(async (c: string) => (c === 'Austin' ? '2025-01-01' : c === 'Seguin' ? '2026-08-26' : null)) + siteIo.loadAllNameAnswers.mockResolvedValue([]) + everyCity() + const row = (await screen.findByRole('button', { name: 'Halden Commercial' })).closest('tr') as HTMLElement + expect(research.loadBuildersOf).toHaveBeenCalledWith(['San Antonio', 'Austin', 'Seguin']) + expect(research.loadBuildersOf).toHaveBeenCalledTimes(1) + expect(row.textContent).toContain('Austin, San Antonio') + // No one day is where every city's records start: the column says Permits, and the line under the list names the short city. + expect(screen.getByRole('columnheader', { name: 'Permits' })).toBeTruthy() + await waitFor(() => expect(document.body.textContent).toContain('The records here start in Seguin on Aug 26. A count covers a year at most, and less where the records start later.')) + expect(screen.queryByRole('button', { name: /Looks like a customer/ })).toBeNull() + expect(screen.queryByRole('button', { name: /Read back to/ })).toBeNull() + // The sheet reads the name's permits in every city it is in. + await openSheet('Halden Commercial') + expect(research.loadPermitsOfBuilder).toHaveBeenCalledWith(['Austin', 'San Antonio'], 'haldencommercial', '2026-11-11') + }) + + it('draws the two shares and the chip on a phone card, with a picker to sort', async () => { + research.loadBuilders.mockResolvedValue([sable, halden]) + draw(true) + const first = await screen.findByRole('button', { name: /Halden Commercial/ }) + expect(within(first).getByLabelText('Share of dollars: 66.7%')).toBeTruthy() + expect(within(first).getByText('Ours')).toBeTruthy() + fireEvent.change(screen.getByLabelText('Sort by'), { target: { value: 'name' } }) + const cards = screen.getAllByRole('button', { name: /Halden Commercial|Sable Creek Construction/ }) + expect(cards[0]?.textContent).toContain('Halden Commercial') + fireEvent.change(screen.getByLabelText('Sort by'), { target: { value: 'open' } }) + expect(screen.getAllByRole('button', { name: /Halden Commercial|Sable Creek Construction/ })[0]?.textContent).toContain('Halden Commercial') + }) + + it('says the database change is not in yet when the read of every city is not on the database', async () => { + research.loadBuildersOf.mockResolvedValue(null) + draw() + expect(await screen.findByText(/Builders opens once tonight’s database change is in/)).toBeTruthy() + }) +}) + describe('Builders, the chips', () => { it('draws the lit chip bold at the chip size from the first draw, and moves the weight with a press (v2.7907)', async () => { draw() diff --git a/src/components/prospects/PermitBuilders.tsx b/src/components/prospects/PermitBuilders.tsx index c13d7140d8..999a7d57f3 100644 --- a/src/components/prospects/PermitBuilders.tsx +++ b/src/components/prospects/PermitBuilders.tsx @@ -25,7 +25,7 @@ import { } from '../../lib/research/permitBuilders' import { googleAskForCompany, sitePermitLines, type SitePermit } from '../../lib/research/permitPublic' import { historyAsk, historyDoneWords, permitsColumnWords, reachWords, recordsReach, recordsStartLine, theirPermitsTitle, type RecordsReach } from '../../lib/research/permitReach' -import { usePermitRecordsStart } from '../../hooks/usePermitRecordsStart' +import { usePermitRecordsStarts } from '../../hooks/usePermitRecordsStart' import { usePermitLookAlikes } from '../../hooks/usePermitLookAlikes' import { useBuilderAnswers } from '../../hooks/useBuilderAnswers' import { byWordWords, openLookAlikes, throughWords, withAnsweredBids } from '../../lib/research/builderAnswers' @@ -33,7 +33,10 @@ import type { BuilderAnswersGround } from '../../lib/research/builderAnswersIo' import { BuilderNameTies } from './BuilderNameTies' import { PermitLookAlikes } from './PermitLookAlikes' import { permitsLinkWithLooks, readPermitsLink } from '../../lib/research/permitsLink' -import { loadBuilders, loadPermitsOfBuilder, markBuilder, pullPermitsBack, saveBuilder } from '../../lib/research/permitResearchIo' +import { loadBuildersOf, loadPermitsOfBuilder, markBuilder, pullPermitsBack, saveBuilder } from '../../lib/research/permitResearchIo' +import { BUILDER_OURS, BUILDER_OURS_WORDS, DEFAULT_BUILDER_SORT, ariaSortOf, barWidth, builderShares, buildersOfOurs, drawnWords, longestShare, oursCounts, pressSort, recordsStartWords, shareWords, sortBuilders, sortMark, type BuilderOurs, type BuilderShare, type BuilderSort, type BuilderSortBy } from '../../lib/research/builderShare' +import { Money } from '../Money' +import { ValueSentence } from '../valuesInPlace/ValuesInPlace' import { GoogleSearchPress } from './GoogleSearchPress' import { PermitAskFor } from './PermitAskFor' import { foldLookups, lookupPressedWords, type BuilderLookup, type LookupStanding, type LookupVerdict } from '../../lib/research/builderLookups' @@ -47,6 +50,11 @@ import { loadBuilderLookupOf, recordLookupCheck } from '../../lib/research/permi * company it is, and its permits. Our bids are the customer of the same name plus the customers * someone tied the name to (punch list #307): the answers are read once for the list, and the * builder's sheet shows each tie with whose word it is and takes it back. + * + * Who holds the work (punch list #465, step 1): the list reads every city at once when the tab's picker says so, + * one row a name. Each name has two bars, its share of the dollars declared and its share of the permits, green + * for a name that is ours and grey for one that is not yet. A press on a heading sorts, and three chips narrow + * the list to everyone, ours or not ours yet (`builderShare.ts`). */ const muted: CSSProperties = { color: 'var(--text-muted)', fontSize: '0.78rem' } const chip = (on: boolean): CSSProperties => ({ padding: '5px 11px', borderRadius: 999, fontSize: '0.78rem', border: `1px solid ${on ? '#2563eb' : 'var(--border)'}`, background: on ? 'var(--bg-blue-tint)' : 'var(--surface)', color: on ? 'var(--text-blue-800)' : 'var(--text)', fontWeight: on ? 600 : 400, minHeight: 32, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }) @@ -64,7 +72,46 @@ function MarkPill({ mark }: { mark: BuilderMarkValue | null }) { const SHOWING: BuilderShowing[] = ['all', 'never_bid', 'good', 'avoid', 'unmarked'] -export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged }: { city: string; authUserId: string; todayYmd: string; isMobile: boolean; /** A mark or a kind changed: the deck's rows carry them, so they read again. */ onChanged: () => void }) { +/** Ours, or not ours yet: the chip at the end of a row. */ +function OursPill({ ours }: { ours: boolean }) { + const base: CSSProperties = { display: 'inline-block', borderRadius: 999, padding: '1px 8px', fontSize: '0.72rem', fontWeight: 600, whiteSpace: 'nowrap' } + return ours ? {BUILDER_OURS_WORDS.ours} : {BUILDER_OURS_WORDS.not_ours} +} + +/** + * One share as a bar and its number. The dollars' bar is the dark one and the permits' the light one, green for a + * name that is ours and grey for one that is not. The greens are literals, as every status colour is, and the + * greys are the theme's. + */ +function ShareBar({ share, longest, ours, light, label }: { share: number | null; longest: number; ours: boolean; light: boolean; label: string }) { + const width = barWidth(share, longest) + const background = ours ? (light ? '#86efac' : '#15803d') : light ? 'var(--border-strong)' : 'var(--text-faint)' + return ( + + {width > 0 && + ) +} + +/** A heading that sorts. The lit one says which way with its mark. */ +function SortHead({ by, sort, onSort, right, children }: { by: BuilderSortBy; sort: BuilderSort; onSort: (by: BuilderSortBy) => void; right?: boolean; children: string }) { + const on = sort.by === by + return ( + + + + ) +} + +/** What a phone's sort picker offers, since a phone has no headings to press. */ +const SORT_WORDS: Record = { dollars: 'Share of dollars', permit_share: 'Share of permits', permits: 'Permits', open: 'Open now', name: 'Name', plumber: 'Their plumber', bids: 'Our bids' } +const NO_ROWS: BuilderRow[] = [] + +export function PermitBuilders({ city, cities, authUserId, todayYmd, isMobile, onChanged }: { city: string; /** The cities the list reads at once: every city the pull reads, or the picker's one. The picker's one when left out. */ cities?: readonly string[]; authUserId: string; todayYmd: string; isMobile: boolean; /** A mark or a kind changed: the deck's rows carry them, so they read again. */ onChanged: () => void }) { const [rows, setRows] = useState(null) const [notYet, setNotYet] = useState(false) const [loading, setLoading] = useState(true) @@ -72,22 +119,31 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged const [showing, setShowing] = useState('all') const [search, setSearch] = useState('') const [openKey, setOpenKey] = useState(null) + const [ours, setOurs] = useState('everyone') + const [sort, setSort] = useState(DEFAULT_BUILDER_SORT) + // One city, or every city at once (punch list #465). The list is keyed by the cities' names, so a new array of the same cities reads nothing again. + const citiesKey = (cities && cities.length > 0 ? cities : [city]).join('|') + const reads = useMemo(() => citiesKey.split('|'), [citiesKey]) + const everyCity = reads.length > 1 // How far back every count here can see (punch list #307): the day the records start, or a year. const { showToast } = useToastContext() const [readBacks, setReadBacks] = useState(0) const [reading, setReading] = useState(false) - const recordsStart = usePermitRecordsStart(city, readBacks) + const starts = usePermitRecordsStarts(reads, readBacks) + // Over every city no one day is where the records start: the column says Permits and the line under the list names each city's day. + const recordsStart = everyCity ? null : (starts[city] ?? null) const reach = useMemo(() => recordsReach(recordsStart, todayYmd), [recordsStart, todayYmd]) // One step further back as history, while the records are short of the goal (punch list #307). - const ask = historyAsk(city, recordsStart, todayYmd) + const ask = everyCity ? null : historyAsk(city, recordsStart, todayYmd) const reachSays = reachWords(reach, todayYmd) const startLine = recordsStartLine(city, reach, todayYmd) + const everyCityLine = useMemo(() => (everyCity ? recordsStartWords(reads.map((c) => ({ city: c, startYmd: starts[c] ?? null })), todayYmd) : null), [everyCity, reads, starts, todayYmd]) const load = useCallback(async () => { setLoading(true) setError(null) try { - const list = await loadBuilders(city) + const list = await loadBuildersOf(reads) setNotYet(list == null) setRows(list ?? []) } catch (e) { @@ -95,7 +151,7 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged } finally { setLoading(false) } - }, [city]) + }, [reads]) useEffect(() => { void load() }, [load]) @@ -121,9 +177,10 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged const ground = answers.ground const all = useMemo(() => (ground ? withAnsweredBids(rows ?? [], ground.book, ground.bids, todayYmd) : (rows ?? [])), [rows, ground, todayYmd]) // Names that may be one of our customers (punch list #307): a chip with its count, and the list behind it. - const lookAlikes = usePermitLookAlikes(city, all) + // The worklist is one city's: over every city the chip is not drawn, and a city picked brings it back. + const lookAlikes = usePermitLookAlikes(city, everyCity ? NO_ROWS : all) // A pair answered from a builder's sheet leaves the worklist at once. - const pairs = useMemo(() => (lookAlikes.pairs == null ? null : ground ? openLookAlikes(lookAlikes.pairs, ground.book) : lookAlikes.pairs), [lookAlikes.pairs, ground]) + const pairs = useMemo(() => (everyCity || lookAlikes.pairs == null ? null : ground ? openLookAlikes(lookAlikes.pairs, ground.book) : lookAlikes.pairs), [everyCity, lookAlikes.pairs, ground]) // The chip rides the address (`looks=1`), so the Needs you line opens on it and a reload comes back to it. const [searchParams, setSearchParams] = useSearchParams() const [looking, setLooking] = useState(() => readPermitsLink(searchParams).looks) @@ -132,7 +189,15 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged setSearchParams(permitsLinkWithLooks(searchParams, on), { replace: true }) } const counts = useMemo(() => builderChipCounts(all), [all]) - const list = useMemo(() => buildersShowing(all, showing, search), [all, showing, search]) + // The two shares are parts of the whole list, whatever is drawn, so every name's shares add up to the whole (punch list #465). + const tiedKeys = useMemo(() => new Set(ground ? ground.book.tied.keys() : []), [ground]) + const shares = useMemo(() => builderShares(all, tiedKeys), [all, tiedKeys]) + const found = useMemo(() => buildersShowing(all, showing, search), [all, showing, search]) + const oursOf = useMemo(() => oursCounts(found, shares), [found, shares]) + const list = useMemo(() => sortBuilders(buildersOfOurs(found, shares, ours), shares, sort), [found, shares, ours, sort]) + const longest = useMemo(() => longestShare(list.map((r) => shares.get(r.key)).filter((x): x is BuilderShare => x != null)), [list, shares]) + const shareOf = (r: BuilderRow): BuilderShare => shares.get(r.key) ?? { dollars: null, dollarsShare: null, permitsShare: 0, dollarsRank: null, permitsRank: 1, ours: false } + const onSort = (by: BuilderSortBy) => setSort((now) => pressSort(now, by)) // Where no builder's permits name a plumber the column would say one thing on every row: left out. const namesPlumbers = useMemo(() => cityNamesPlumbers(all), [all]) const open = useMemo(() => all.find((r) => r.key === openKey) ?? null, [all, openKey]) @@ -166,6 +231,30 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged setSearch(e.target.value)} placeholder="Search a builder or a plumber" style={{ flex: '1 1 200px', minWidth: 0, border: '1px solid var(--border)', borderRadius: 8, padding: '7px 11px', font: 'inherit', fontSize: '0.875rem', minHeight: 36, background: 'var(--surface)', color: 'var(--text)' }} /> + {all.length > 0 && !(looking && pairs != null) && ( +
+
+ {BUILDER_OURS.map((o) => ( + + ))} +
+ {isMobile && ( + + )} + + + +
+ )} + {(startLine || ask) && all.length > 0 && (
{startLine ?? ask?.words} @@ -205,6 +294,7 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged onPress: () => { setSearch('') setShowing('all') + setOurs('everyone') }, })} compact @@ -216,9 +306,22 @@ export function PermitBuilders({ city, authUserId, todayYmd, isMobile, onChanged
) : (
- +
- - - - - - - {namesPlumbers && } + + Builder + + + {permitsColumnWords(reach, todayYmd)} + + + Open now + + + Share of dollars + + + Share of permits + + {namesPlumbers && ( + + Their plumber + + )} + + Our bids + + - {list.map((r) => ( - - - - - - - - {namesPlumbers && } - - ))} + {list.map((r) => { + const sh = shareOf(r) + return ( + + + + + + + {namesPlumbers && } + + + + ) + })}
BuilderMark{permitsColumnWords(reach, todayYmd)}Without a plumberLast permitOur bidsPlumber they use + Ours or not +
- - {isBuilderKind(r.kind) && ( - <> -
- {BUILDER_KIND_WORDS[r.kind]} - - )} -
- - {r.permits}{r.open}{shortDay(r.last_permit_on)} - {ourBidsWords(r)} - {throughWords(r) && ( - <> -
- {throughWords(r)} - - )} -
{plumberUsedWords(r)}
+ + {r.mark && ( + <> + {' '} + + + )} +
+ + {isBuilderKind(r.kind) ? `${BUILDER_KIND_WORDS[r.kind]} · ` : ''} + last permit {shortDay(r.last_permit_on)} + {everyCity && r.cities && r.cities.length > 0 ? ` · ${r.cities.join(', ')}` : ''} + +
{r.permits} + {r.open} + + + {sh.dollars != null && ( + <> +
+ + declared + + + )} +
+ + {plumberUsedWords(r)} + {ourBidsWords(r)} + {throughWords(r) && ( + <> +
+ {throughWords(r)} + + )} +
+ +
)} + {everyCityLine && list.length > 0 && !(looking && pairs != null) && ( +
+ +
+ )} + {open && ( void; /** A press on a looked-up fact was kept: a list behind the sheet reads its lookups again. */ onLookupChecked?: () => void; onClose: () => void; onSaved: () => void }) { +export function BuilderSheet({ row, city, permitCities, authUserId, todayYmd, reach, namesPlumbers, ground, onAnswered, onLookupChecked, onClose, onSaved }: { row: BuilderRow; city: string; /** The cities the name's permits are read in, when the list read more than one. The one city when left out. */ permitCities?: readonly string[]; authUserId: string; todayYmd: string; reach: RecordsReach; /** False where no builder's permits in the city name a plumber: the sheet says nothing of one. */ namesPlumbers: boolean; /** The answers on names. Null before they are read, and before the table is on the database: the section is not drawn. */ ground: BuilderAnswersGround | null; onAnswered: () => void; /** A press on a looked-up fact was kept: a list behind the sheet reads its lookups again. */ onLookupChecked?: () => void; onClose: () => void; onSaved: () => void }) { const { showToast } = useToastContext() const name = builderName(row) const [mark, setMark] = useState(row.mark ?? 'none') @@ -317,16 +470,18 @@ export function BuilderSheet({ row, city, authUserId, todayYmd, reach, namesPlum const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const [permits, setPermits] = useState(null) + const permitsInKey = (permitCities ?? []).join('|') + const permitsIn = useMemo(() => (permitsInKey === '' ? [] : permitsInKey.split('|')), [permitsInKey]) useEffect(() => { let live = true - loadPermitsOfBuilder(city, row.key, todayYmd) + loadPermitsOfBuilder(permitsIn.length > 1 ? permitsIn : city, row.key, todayYmd) .then((list) => live && setPermits(list)) .catch(() => live && setPermits([])) return () => { live = false } - }, [city, row.key, todayYmd]) + }, [city, permitsIn, row.key, todayYmd]) // What was looked up about this one name. Null until the read lands; `unread` when it could not be read. const [askFor, setAskFor] = useState<{ lookup: BuilderLookup | null; unread: boolean } | null>(null) diff --git a/src/components/prospects/ProspectsResearchTab.render.test.tsx b/src/components/prospects/ProspectsResearchTab.render.test.tsx index e6e6930a24..5f9b8ce409 100644 --- a/src/components/prospects/ProspectsResearchTab.render.test.tsx +++ b/src/components/prospects/ProspectsResearchTab.render.test.tsx @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react' import { useLocation } from 'react-router-dom' import { installDomShims, renderWithProviders } from '../../test/renderSmokeMocks' -import { shortDay, ymdPlusDays, type ResearchPermitRow } from '../../lib/research/permitResearch' +import { RESEARCH_CITIES, shortDay, ymdPlusDays, type ResearchPermitRow } from '../../lib/research/permitResearch' import { reachDay } from '../../lib/research/permitReach' import { todayYmdInAppTz } from '../../utils/dateUtils' @@ -26,6 +26,7 @@ const io = vi.hoisted(() => ({ putBackPermit: vi.fn(), loadPermitHistory: vi.fn(), loadBuilders: vi.fn(), + loadBuildersOf: vi.fn(), markBuilder: vi.fn(), saveBuilder: vi.fn(), loadPermitsOfBuilder: vi.fn(), @@ -151,6 +152,8 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { io.putBackPermit.mockReset().mockResolvedValue(undefined) io.loadPermitHistory.mockReset().mockResolvedValue([]) io.loadBuilders.mockReset().mockResolvedValue([]) + // Builders reads `research_builders_v2` for the cities it is given. Each case sets what a city's read gives, as before. + io.loadBuildersOf.mockReset().mockImplementation((cities: string[]) => io.loadBuilders(cities[0])) io.markBuilder.mockReset().mockResolvedValue(undefined) io.saveBuilder.mockReset().mockResolvedValue(undefined) io.loadPermitsOfBuilder.mockReset().mockResolvedValue([]) @@ -749,13 +752,45 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { }) }) + /** Builders opens on every city (punch list #465). These cases read one city's own lines, so they pick it. */ + async function openBuildersIn(city: string) { + fireEvent.click(await screen.findByRole('button', { name: 'Builders' })) + fireEvent.change(screen.getByLabelText('City'), { target: { value: city } }) + } + + it('Builders opens on All five cities and reads them in one call, and a city picked reads it alone', async () => { + io.loadBuildersOf.mockResolvedValue([ + { key: 'tallpinedevelopment', name: null, sample_contact: 'Tall Pine Development', kind: null, mark: null, mark_reason: null, mark_by_name: null, mark_at: null, permits: 5, open: 1, last_permit_on: '2026-11-08', plumber: null, plumber_jobs: 0, bids: 0, won: 0, last_bid_on: null, declared: 400000, declared_permits: 3, cities: ['Austin', 'San Antonio'] }, + ]) + renderWithProviders() + // Off Builders the picker holds one city, and every city is not a choice. + const picker = (await screen.findByLabelText('City')) as HTMLSelectElement + expect(within(picker).queryByRole('option', { name: 'All five cities' })).toBeNull() + fireEvent.click(await screen.findByRole('button', { name: 'Builders' })) + await waitFor(() => expect(screen.getByRole('button', { name: 'Tall Pine Development' })).toBeTruthy()) + expect((screen.getByLabelText('City') as HTMLSelectElement).value).toBe('*') + expect(within(screen.getByLabelText('City')).getByRole('option', { name: 'All five cities' })).toBeTruthy() + expect(io.loadBuildersOf).toHaveBeenCalledWith([...RESEARCH_CITIES]) + expect(screen.getByLabelText('Share of dollars: 100.0%')).toBeTruthy() + expect(document.body.textContent).toContain('1 drawn here of 1 company') + // A city picked reads that city alone, and the browser remembers it as it does any picked city. + io.loadBuildersOf.mockClear() + fireEvent.change(screen.getByLabelText('City'), { target: { value: 'Austin' } }) + await waitFor(() => expect(io.loadBuildersOf).toHaveBeenCalledWith(['Austin'])) + expect((screen.getByLabelText('City') as HTMLSelectElement).value).toBe('Austin') + // And every city is one pick away again. + fireEvent.change(screen.getByLabelText('City'), { target: { value: '*' } }) + await waitFor(() => expect(io.loadBuildersOf).toHaveBeenCalledWith([...RESEARCH_CITIES])) + window.localStorage.removeItem('permits.lastCity') + }) + it('Builders lists who is building, and a mark needs its reason', async () => { io.loadBuilders.mockResolvedValue([ { key: 'tallpinedevelopment', name: null, sample_contact: 'Tall Pine Development', kind: null, mark: null, mark_reason: null, mark_by_name: null, mark_at: null, permits: 5, open: 1, last_permit_on: '2026-11-08', plumber: 'Copperline Mechanical', plumber_jobs: 4, bids: 0, won: 0, last_bid_on: null }, { key: 'ridgewaybuilders', name: null, sample_contact: 'Dana Whitlock, Ridgeway Builders', kind: 'gc', mark: 'good', mark_reason: 'Pays on time.', mark_by_name: 'Eve', mark_at: '2026-03-03T15:00:00Z', permits: 4, open: 2, last_permit_on: '2026-11-06', plumber: 'Blue Heron Plumbing', plumber_jobs: 2, bids: 5, won: 3, last_bid_on: '2026-06-01' }, ]) renderWithProviders() - fireEvent.click(await screen.findByRole('button', { name: 'Builders' })) + await openBuildersIn('San Antonio') await waitFor(() => expect(screen.getByRole('button', { name: 'Tall Pine Development' })).toBeTruthy()) expect(screen.getByRole('button', { name: '3 or more permits and never bid 1' })).toBeTruthy() expect(screen.getByText('5 priced, 3 won')).toBeTruthy() @@ -784,7 +819,7 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { siteIo.loadAllNameAnswers.mockResolvedValue({ rows: [], me: 'u1' }) siteIo.loadCustomerNames.mockResolvedValue([{ id: 'c7', name: 'Tall Pine Development' }, { id: 'c8', name: 'Larkspur Dental' }]) renderWithProviders() - fireEvent.click(await screen.findByRole('button', { name: 'Builders' })) + await openBuildersIn('San Antonio') fireEvent.click(await screen.findByRole('button', { name: 'Looks like a customer 1' })) expect(await screen.findByText('One name begins the other')).toBeTruthy() expect(screen.getByText('Tall Pine Development', { selector: 'strong' })).toBeTruthy() @@ -932,14 +967,18 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { expect(screen.getByTestId('address').textContent).toBe('?tab=permits') fireEvent.click(screen.getByRole('button', { name: 'Builders' })) await waitFor(() => expect(screen.getByTestId('address').textContent).toBe('?tab=permits&view=builders')) + // Opened by its press the list reads every city, and the chip is one city's: a city picked draws it, off. + expect(screen.queryByRole('button', { name: /^Looks like a customer/ })).toBeNull() + fireEvent.change(screen.getByLabelText('City'), { target: { value: 'San Antonio' } }) expect((await screen.findByRole('button', { name: 'Looks like a customer 1' })).getAttribute('aria-pressed')).toBe('false') + expect(screen.getByTestId('address').textContent).toBe('?tab=permits&view=builders') }) }) it('draws no look-alike chip before the answers table is on the database', async () => { io.loadBuilders.mockResolvedValue([{ key: 'tallpinedevelopment', name: null, sample_contact: 'Tall Pine Development', kind: null, mark: null, mark_reason: null, mark_by_name: null, mark_at: null, permits: 5, open: 1, last_permit_on: '2026-11-08', plumber: null, plumber_jobs: 0, bids: 0, won: 0, last_bid_on: null }]) renderWithProviders() - fireEvent.click(await screen.findByRole('button', { name: 'Builders' })) + await openBuildersIn('San Antonio') await waitFor(() => expect(screen.getByRole('button', { name: 'Tall Pine Development' })).toBeTruthy()) expect(screen.queryByRole('button', { name: /^Looks like a customer/ })).toBeNull() }) @@ -947,7 +986,7 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { it('reads one step further back on the press, and reads where the records start again', async () => { io.loadBuilders.mockResolvedValue([{ key: 'tallpinedevelopment', name: null, sample_contact: 'Tall Pine Development', kind: null, mark: null, mark_reason: null, mark_by_name: null, mark_at: null, permits: 5, open: 1, last_permit_on: '2026-11-08', plumber: null, plumber_jobs: 0, bids: 0, won: 0, last_bid_on: null }]) renderWithProviders() - fireEvent.click(await screen.findByRole('button', { name: 'Builders' })) + await openBuildersIn('San Antonio') const since = ymdPlusDays(RECORDS_START, -92) const press = await screen.findByRole('button', { name: `Read back to ${reachDay(since, todayYmdInAppTz())}` }) const reads = io.loadRecordsStart.mock.calls.length diff --git a/src/components/prospects/ProspectsResearchTab.tsx b/src/components/prospects/ProspectsResearchTab.tsx index 1d9fabf834..1a3724881e 100644 --- a/src/components/prospects/ProspectsResearchTab.tsx +++ b/src/components/prospects/ProspectsResearchTab.tsx @@ -59,6 +59,7 @@ import { PermitMarket } from './PermitMarket' import { PermitCountStrip } from './PermitCountStrip' import { usePermitCityQuiet } from '../../hooks/usePermitCityQuiet' import { cityPickerTitle, cityPickerWords, isQuiet } from '../../lib/research/permitQuiet' +import { EVERY_CITY, everyCityWords } from '../../lib/research/builderShare' import { keepFromPassedReason } from '../../lib/research/permitHistory' import { readLastCity, writeLastCity } from '../../lib/research/permitCityDoors' import { permitsLinkForView, permitsLinkViewOf, readPermitsLink } from '../../lib/research/permitsLink' @@ -163,6 +164,11 @@ export function ProspectsResearchTab({ authUserId, step }: { authUserId: string; writeLastCity(next) setCityState(next) } + // Builders reads every city at once (punch list #465, call 4): a company's whole book is the point. It is the + // picker's first choice on that view, and the one the list opens on unless the address asked for a city, or for + // the **Looks like a customer** chip, which is one city's. + const [buildersEveryCity, setBuildersEveryCity] = useState(() => !door.city && !door.looks) + const buildersOfEveryCity = buildersEveryCity && view === 'builders' const [windowDays, setWindowDays] = useState(30) const [residential, setResidential] = useState(false) const [showing, setShowing] = useState('waiting') @@ -406,7 +412,22 @@ export function ProspectsResearchTab({ authUserId, step }: { authUserId: string; Permits