diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 95f8a908d7..dbb9d93924 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -414,6 +414,9 @@ The **last band's one press** (v2.9258, punch list #464 step 3, `permitBandPass. A permit of the last band is **held back for a look** when its builder line or its size line reads *We want it*, and it stays on the deck with its reason, while **Undo** in the box puts every passed permit back as one more row each. 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 c4c42662fe..14979ad90b 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. Since v2.9196 (punch list #464, `permitBand.ts`) every card on the skim sits in one of three bands, **We want it**, **Acceptable** or **Likely not a fit**, with three presses over the deck. Since v2.9231 the press **What we want** over a deck opens the sheet the bands are read against ([`PermitSheetPanel`](../src/components/prospects/PermitSheetPanel.tsx), `?sheet=1`, also opened from the Overview's Identify box): a line a subject and a column a band, each of its seven numbers changed in place with a line that counts what the change would move on the skim in every city before it is kept, a refusal in words, an **Undo**, and **Changes**, the record of who changed what, all kept append-only in `permit_sheet_changes` and folded by `permitSheet.ts` over today's rules (`TODAYS_SHEET`). Since v2.9258 the skim's **Likely not a fit** band carries a box with one press, *Pass 11 of 13* (`permitBandPass.ts`): it passes the band's permits one row each with the code `likely_not_a_fit` and the line that put each there, holds back a permit whose builder or size line reads *We want it* with its reason, names a row that failed, and its **Undo** puts every passed permit back. Since v2.9259 the sheet's picks are changed in place too: a kind of work is a `choice` value moved to another band (`sheetKindInserts`, the lists that change kept as one insert by `keepSheetChanges`, refused when it would leave *We want it* with no kind), and the **Never** line is switched on or off. + - **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. Since v2.9196 (punch list #464, `permitBand.ts`) every card on the skim sits in one of three bands, **We want it**, **Acceptable** or **Likely not a fit**, with three presses over the deck. Since v2.9231 the press **What we want** over a deck opens the sheet the bands are read against ([`PermitSheetPanel`](../src/components/prospects/PermitSheetPanel.tsx), `?sheet=1`, also opened from the Overview's Identify box): a line a subject and a column a band, each of its seven numbers changed in place with a line that counts what the change would move on the skim in every city before it is kept, a refusal in words, an **Undo**, and **Changes**, the record of who changed what, all kept append-only in `permit_sheet_changes` and folded by `permitSheet.ts` over today's rules (`TODAYS_SHEET`). Since v2.9258 the skim's **Likely not a fit** band carries a box with one press, *Pass 11 of 13* (`permitBandPass.ts`): it passes the band's permits one row each with the code `likely_not_a_fit` and the line that put each there, holds back a permit whose builder or size line reads *We want it* with its reason, names a row that failed, and its **Undo** puts every passed permit back. Since v2.9259 the sheet's picks are changed in place too: a kind of work is a `choice` value moved to another band (`sheetKindInserts`, the lists that change kept as one insert by `keepSheetChanges`, refused when it would leave *We want it* with no kind), and the **Never** line is switched on or off. - **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/migrations/20261203033600_research_builders_v2.md b/docs/migrations/20261203033600_research_builders_v2.md index 93950579db..2108ef2859 100644 --- a/docs/migrations/20261203033600_research_builders_v2.md +++ b/docs/migrations/20261203033600_research_builders_v2.md @@ -44,4 +44,4 @@ A function's return type cannot change with `CREATE OR REPLACE`, and the client ## Applied -Not yet. This section is written when the push is read back. +Pushed to prod on 2026-12-03 at 04:21 UTC with `supabase db push`, from a clean checkout of `origin/main`. The dry run named this migration alone. `npm run check:migration-drift` then read 1,548 local files and 1,548 remote versions, fully applied. 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 4927c0025c..d5ddafd2c5 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' import { resetPermitSheet } from '../../lib/research/permitSheetStore' @@ -28,6 +28,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(), @@ -156,6 +157,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([]) @@ -826,13 +829,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() @@ -861,7 +896,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() @@ -1009,14 +1044,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() }) @@ -1024,7 +1063,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 8fdca7e592..d5ebe3806a 100644 --- a/src/components/prospects/ProspectsResearchTab.tsx +++ b/src/components/prospects/ProspectsResearchTab.tsx @@ -60,6 +60,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, permitsLinkSheetOpen, permitsLinkViewOf, permitsLinkWithSheet, readPermitsLink } from '../../lib/research/permitsLink' @@ -166,6 +167,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') @@ -409,7 +415,22 @@ export function ProspectsResearchTab({ authUserId, step }: { authUserId: string; Permits