diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index dbb9d93924..b0f011b8f0 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -417,6 +417,8 @@ A city on Permits is **quiet** (v2.7880, `permitQuiet.ts`) when its newest permi 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. +A **company's profile** (v2.9266, punch list #465 step 2, `builderProfile.ts`, `PermitBuilderProfile`) is the page a name on Builders opens in place of the list, on an address of its own (`view=builders&builder=`): the name with its chips and the other spellings it files under, four numbers, **Working on now**, **Who to ask for**, **Who they use** and **Us and them**, over every city the name files in. +On a profile a job is **open now** while no plumbing permit sits on it, whatever we answered, which is the rule behind the list's **Open now**, and its chip says where it stands with us in the tab's own words. **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 14979ad90b..af442762ed 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`; 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. + - **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`; since v2.9266, step 2, a name on Builders opens the company's profile in place of the list, [`PermitBuilderProfile`](../src/components/prospects/PermitBuilderProfile.tsx) over `builderProfile.ts`, on the address `view=builders&builder=`, with its open jobs and where each stands read by `loadBuilderStanding`, and the builder's sheet opens from the page's **Mark, kind and ties**); 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/recent-features/v2.9266.md b/docs/recent-features/v2.9266.md new file mode 100644 index 0000000000..206f23d7e6 --- /dev/null +++ b/docs/recent-features/v2.9266.md @@ -0,0 +1,43 @@ +# v2.9266 — Builders: a page for every company (2026-12-02) + +Punch list #465, step 2, the page and its first way in. It stands on v2.9263, the Builders list's client, which stands on v2.9261's migration. Client only. Nothing owed on prod of its own. + +## What it does + +- **A company's page.** A press on a name on Builders opens `PermitBuilderProfile` in place of the list. The page is on the address: `view=builders&builder=` (`builderProfileHref`, `permitsLinkWithBuilder` and `PermitsLink.builder` in `permitsLink.ts`). So it has a link of its own, the browser's Back leaves it, and another view of the tab drops the key. +- **Every city.** A profile covers every city (call 4). While one is open the list behind it reads every city, and the tab's picker says *All five cities*. A city picked over a profile goes back to that city's list. +- **The top line.** The name, **Ours** or **Not ours yet**, the kind of company where the office set one, our mark where there is one, and *also files as* with the other spellings of the company on its own permits (`filesAs`, three named and the rest counted). +- **Four numbers** (`profileTiles`): the jobs open now, its share of the dollars declared with its rank and its share of the permits with its rank under it, the plumbers its permits name, and our bids in two years. A name whose permits declare nothing leads with its share of the permits and says so. +- **Working on now** (`openJobs`): every permit of the name with no plumbing permit on file, the newest first, with its title, its declared value, its street, its city and the day it was filed. Each has a chip that says where it stands with us (`jobStanding`). +- **Who to ask for.** The call list's own block (`PermitAskFor`), with **Checked**, **Wrong** and **Put back** kept the same way, and under it the people the permits name beside the company (`filers`). +- **Who they use** (`plumbersUsed`, `plumbersUsedWords`): each plumber by the jobs that name it, and one of *One plumber nearly every time*, *Leans to one plumber* or *Shops around* once three jobs name a plumber, by Market's own rule (`tieOf`, `TIE_MIN_JOBS`). +- **Us and them**: our bids in two years with the last one's day, how many came through a tied customer, and our mark with who set it and why. +- **The builder's sheet opens from the page**, on **Mark, kind and ties**. The mark, the kind of company and the ties to a customer are set there as before. Once the sheet keeps something, the page reads again. + +## How it reads + +- The name's row and its two shares are the Builders list's own (`research_builders_v2`, `builderShares`), so the page and the row cannot disagree. +- The jobs come from a new read in `permitResearchIo.ts`, `loadBuilderStanding`: the tab's own `research_permits_v4`, a city at a time, held to the name's key, and asked only of the cities the name files in. So a job's place is said by the rule every list of the tab uses (`placeOf`). The database works a city's permits out before it keeps the name's, so the walker should time a profile's first draw for a company in a large city. +- The looked-up facts are read by a new hook, `useBuilderAskFor`, which the sheet now uses too. The two pills moved to `BuilderPills.tsx`. + +## Where it differs from the drawing + +- **What open means.** The drawing's five jobs held one with a plumber. Here a job is open while no plumbing permit sits on it, the rule behind the list's **Open now**, so the tile, the list and the column are one count. A job the office said has a plumber, with no plumbing permit on the feed yet, is still open and its chip reads *Has a plumber*. +- **The chips' words** are the tab's own, as the card asks: *Skim*, *Investigating*, *Pursuing*, *Passed* with the count's reason, *Not pursuing* with its reason, *Has a plumber*. +- **Plumbers are counted on the jobs that name one**, and the tile says how many those are. The drawing said *on their last 7 jobs*. +- **The press *Call about all 5 jobs* is not drawn.** It opens step 3's screen, which is not built, and a press that does nothing is worse than none. +- ***Never called* is not said.** No call is kept against a builder today. Step 3 keeps one. +- ***Also files for 2 other companies* is not said.** That is a count across companies, which is step 4's. +- **A press on a name opens the page, not the sheet.** The sheet is one press further, from the page. + +## Left of step 2 + +The other five ways in: a name wherever it is drawn (a skim card, the ledger, Market), the calling deck, the search, the Overview's second press, and a tied customer's record. Each is a link to `builderProfileHref`. + +## Tests + +`builderProfile.test.ts` (12), `permitsLink.test.ts` (four new cases), `PermitBuilders.render.test.tsx` (five new cases, and every case that opened the sheet now opens it through the page), `ProspectsResearchTab.render.test.tsx` (one new case). + +## To verify on the live site + +Read only. Prospects → Permits → Builders. Press a name with several permits. Count its *Working on now* rows against the row's **Open now**. Open the ledger and check two of the jobs' places. Copy the address into a new tab and see the same page. Pick a city in the picker and see that city's list. Time the page's first draw for the largest name. diff --git a/docs/twins/APP_DIRECTORY.md b/docs/twins/APP_DIRECTORY.md index 40f6e53315..2ec5fae3b1 100644 --- a/docs/twins/APP_DIRECTORY.md +++ b/docs/twins/APP_DIRECTORY.md @@ -75,7 +75,7 @@ Help guides open at `/help?g=`, and `/help/` typed or pasted opens t - New-builder pipeline / hiring pipeline, as three funnels with their counts and a press for each step → `/prospects` (Overview, guide `find-your-way-around-prospects`) - Note a candidate's or a new sub's qualifications, a level from 0 to 3 in plumbing, electrical and HVAC, the license and where they drive in from → their thread on `/messages`, the flow's **Qualifications** step (a candidate's flow and a sub's coming-on lane since v2.5812; guide `see-where-a-person-stands-and-what-comes-next`) - Owners, developers and architects with a job we could build as the GC → `/prospects?kind=gc-leads` (guide `find-jobs-to-build-as-the-gc`) -- The permits five cities issue (San Antonio, Austin, New Braunfels, San Marcos, Seguin), skimmed one at a time best first with Investigate or Pass, then worked under Investigating, Pursuing and Closed, with who pulled it, whether a plumber already has it, a search over every list and city, and Builders, every name on permits with our bids and the customers the name is tied to (Pursue makes a lead: a GC on the Customers deck, an owner or architect on Jobs to GC) → `/prospects?tab=permits` (guide `research-permits-for-work-to-bid`; `?tab=research` still opens it); five builders to call this week with who to ask for at each, whether the companies we bid build, and the clock from application to permit → `/prospects?tab=permits&view=market` (Market, v2.7978, v2.7993, v2.8121; the same guide); the names on permits that look like one of our customers, each answered **Same company** or **Not them** → `/prospects?tab=permits&view=builders&looks=1` (v2.6962; the Dashboard's Needs you line opens it); what the city has on a bid's own address and on the jobs priced for its GC, in the bid's Edit window → `/bids?tab=bid-board` (v2.6866; guide `see-what-the-city-has-on-a-bids-address`); **Permit news** on Followup, the permits on the addresses of your bids not yet won or lost, each a card answered in one press (**We lost it…**, **Still waiting**, **Got it** or **Not our job**), with a red count beside Followup → `/bids?tab=permit-news` (v2.7941; the same guide); the names a city lists that are us, so our own plumbing permit reads **Ours**, the owner's with a dev → `/settings?tab=settings-company#settings-company-our-permit-names` (v2.6959) +- The permits five cities issue (San Antonio, Austin, New Braunfels, San Marcos, Seguin), skimmed one at a time best first with Investigate or Pass, then worked under Investigating, Pursuing and Closed, with who pulled it, whether a plumber already has it, a search over every list and city, and Builders, every name on permits with our bids and the customers the name is tied to (Pursue makes a lead: a GC on the Customers deck, an owner or architect on Jobs to GC) → `/prospects?tab=permits` (guide `research-permits-for-work-to-bid`; `?tab=research` still opens it); five builders to call this week with who to ask for at each, whether the companies we bid build, and the clock from application to permit → `/prospects?tab=permits&view=market` (Market, v2.7978, v2.7993, v2.8121; the same guide); who holds the work, every name on the permits of all five cities with its share of the dollars and of the permits, and a company's own page from a press on its name → `/prospects?tab=permits&view=builders` (Builders; a company's page adds `&builder=` and its key; the same guide); the names on permits that look like one of our customers, each answered **Same company** or **Not them** → `/prospects?tab=permits&view=builders&looks=1` (v2.6962; the Dashboard's Needs you line opens it); what the city has on a bid's own address and on the jobs priced for its GC, in the bid's Edit window → `/bids?tab=bid-board` (v2.6866; guide `see-what-the-city-has-on-a-bids-address`); **Permit news** on Followup, the permits on the addresses of your bids not yet won or lost, each a card answered in one press (**We lost it…**, **Still waiting**, **Got it** or **Not our job**), with a red count beside Followup → `/bids?tab=permit-news` (v2.7941; the same guide); the names a city lists that are us, so our own plumbing permit reads **Ours**, the owner's with a dev → `/settings?tab=settings-company#settings-company-our-permit-names` (v2.6959) - The state's public roll of licensed plumbers kept for our counties, with when each state file was last read and what the read changed, for the people who hold the Hiring switch, and for one who also opens People → Licenses the **Our own** view, each plumbing license we hold beside the state's row of the same number and rank, with **Use the state's date** (v2.8233), and the **Everyone** view, the kept roll searched by name or number, where a row opens the person's sheet with what changed, our notes and **Leave off** (v2.8390) → `/prospects?tab=roll` (`&roll=everyone`, `&person=`; guides `see-the-state-roll-of-licensed-plumbers`, `look-up-a-licensed-plumber-on-the-state-roll`) - Trade companies to call for the bench, by what GC mode needs right now (every trade short of quotes, the bench, the scope book's trades), the path onto the bench as a strip (To call → Called → Talked → On the bench → Quoted), the list by trade with For, the project a set of plans is for, and the Board by trade whose Call the top 3 → runs the deck through a column's best three, a drag pinning a card and Call first · Normal · Later on every sub (v2.5809), and the sub that says yes asked on the project's job as it lands on the bench (v2.5810) → `/prospects?kind=subs` (the list `/prospects?kind=subs&tab=prospect-list`, the board `/prospects?kind=subs&tab=board`; guide `find-subs-for-the-bench`) - Small quotes to homeowners (not bids) → `/estimates` diff --git a/src/components/prospects/BuilderPills.tsx b/src/components/prospects/BuilderPills.tsx new file mode 100644 index 0000000000..a85df11854 --- /dev/null +++ b/src/components/prospects/BuilderPills.tsx @@ -0,0 +1,18 @@ +import type { CSSProperties } from 'react' +import { BUILDER_OURS_WORDS } from '../../lib/research/builderShare' +import { BUILDER_SHOWING_WORDS } from '../../lib/research/permitBuilders' +import type { BuilderMarkValue } from '../../lib/research/permitResearch' + +/** The small pills a builder wears on the Builders list and on its profile: our mark, and ours or not ours yet. */ +const pill: CSSProperties = { display: 'inline-block', borderRadius: 999, padding: '1px 8px', fontSize: '0.72rem', fontWeight: 600, whiteSpace: 'nowrap' } + +export function MarkPill({ mark }: { mark: BuilderMarkValue | null }) { + if (mark === 'good') return Good + if (mark === 'avoid') return Avoid + return {BUILDER_SHOWING_WORDS.unmarked} +} + +/** Ours, or not ours yet. */ +export function OursPill({ ours }: { ours: boolean }) { + return ours ? {BUILDER_OURS_WORDS.ours} : {BUILDER_OURS_WORDS.not_ours} +} diff --git a/src/components/prospects/PermitBuilderProfile.tsx b/src/components/prospects/PermitBuilderProfile.tsx new file mode 100644 index 0000000000..354de271ff --- /dev/null +++ b/src/components/prospects/PermitBuilderProfile.tsx @@ -0,0 +1,228 @@ +import { useCallback, useEffect, useMemo, useState, type CSSProperties } from 'react' +import { useBuilderAskFor } from '../../hooks/useBuilderAskFor' +import { byWordWords } from '../../lib/research/builderAnswers' +import type { BuilderAnswersGround } from '../../lib/research/builderAnswersIo' +import { + TIE_WORDS, + filerWords, + filers, + filesAs, + filesAsWords, + markLine, + openJobs, + openJobsWords, + ourBidsLine, + plumbersUsed, + plumbersUsedWords, + profileTiles, + type JobStanding, +} from '../../lib/research/builderProfile' +import type { BuilderShare } from '../../lib/research/builderShare' +import { BUILDER_KIND_WORDS, builderName, isBuilderKind, type BuilderRow } from '../../lib/research/permitBuilders' +import { googleAskForCompany } from '../../lib/research/permitPublic' +import type { ResearchPermitRow } from '../../lib/research/permitResearch' +import { loadBuilderStanding } from '../../lib/research/permitResearchIo' +import { formatErrorMessage } from '../../utils/errorHandling' +import { ValueSentence } from '../valuesInPlace/ValuesInPlace' +import { MarkPill, OursPill } from './BuilderPills' +import { GoogleSearchPress } from './GoogleSearchPress' +import { PermitAskFor } from './PermitAskFor' + +/** + * A company's profile (punch list #465, step 2): everything the Permits tab holds about one name, on one page + * with an address of its own. The name with its chips and the other spellings it files under, four numbers, + * the jobs it has open now with where each stands with us, who to ask for, who it uses and us and them. + * + * It opens from a name on Builders, over every city the name files in. Its mark, its kind and its ties to a + * customer are still set on the builder's sheet, which the page opens. The rules are `builderProfile.ts`. + */ +const muted: CSSProperties = { color: 'var(--text-muted)', fontSize: '0.78rem' } +const press: CSSProperties = { background: 'var(--surface)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 8, padding: '6px 10px', fontSize: '0.8125rem', minHeight: 34, cursor: 'pointer', fontFamily: 'inherit' } +const card: CSSProperties = { border: '1px solid var(--border)', borderRadius: 10, background: 'var(--surface)', padding: '12px 14px' } +const heading: CSSProperties = { margin: '0 0 6px', fontSize: '0.875rem', fontWeight: 600 } +const pill: CSSProperties = { display: 'inline-block', borderRadius: 999, padding: '1px 8px', fontSize: '0.72rem', fontWeight: 600, whiteSpace: 'nowrap' } + +/** A job's chip: green while it waits on a skim, amber while we look, blue once we pursue, grey when closed. */ +function StandingChip({ standing }: { standing: JobStanding }) { + const tone: CSSProperties = + standing.place === 'skim' + ? { background: 'var(--bg-green-tint)', color: 'var(--text-green-700)' } + : standing.place === 'kept' + ? { background: 'var(--bg-amber-tint)', color: 'var(--text-amber-800)' } + : standing.place === 'pursuing' + ? { background: 'var(--bg-blue-tint)', color: 'var(--text-blue-800)' } + : { background: 'var(--bg-200)', color: 'var(--text-700)' } + return {standing.words} +} + +export function PermitBuilderProfile({ + row, + share, + city, + authUserId, + todayYmd, + isMobile, + ground, + readAgain, + onBack, + onOpenSheet, +}: { + row: BuilderRow + share: BuilderShare + /** The city a search for the company is held to when its row names none. */ + city: string + authUserId: string + todayYmd: string + isMobile: boolean + /** The answers on names. Null before they are read. */ + ground: BuilderAnswersGround | null + /** Goes up when the builder's sheet kept something: the jobs and the looked-up facts read again. */ + readAgain: number + onBack: () => void + /** Opens the builder's sheet, where its mark, its kind and its ties are set. */ + onOpenSheet: () => void +}) { + const name = builderName(row) + const citiesKey = (row.cities && row.cities.length > 0 ? row.cities : [city]).join('|') + const cities = useMemo(() => citiesKey.split('|'), [citiesKey]) + const [permits, setPermits] = useState(null) + const [error, setError] = useState(null) + const [tries, setTries] = useState(0) + + const read = useCallback(() => loadBuilderStanding(cities, row.key, todayYmd), [cities, row.key, todayYmd]) + useEffect(() => { + let live = true + setError(null) + read() + .then((list) => live && setPermits(list)) + .catch((e) => live && setError(formatErrorMessage(e))) + return () => { + live = false + } + }, [read, tries, readAgain]) + + const { askFor, checkingId, checkFact } = useBuilderAskFor(row.key, name, undefined, readAgain) + + const jobs = useMemo(() => (permits ? openJobs(permits, todayYmd) : []), [permits, todayYmd]) + const used = useMemo(() => plumbersUsed(permits ?? []), [permits]) + const spellings = useMemo(() => filesAsWords(filesAs(row, permits ?? [])), [row, permits]) + const people = useMemo(() => filers(permits ?? []), [permits]) + const tiles = useMemo(() => profileTiles(row, share, jobs.length, used), [row, share, jobs.length, used]) + const tied = ground?.book.tied.get(row.key) ?? [] + const byWord = byWordWords(row) + + return ( +
+
+ +
+ +
+

{name}

+ + {isBuilderKind(row.kind) && {BUILDER_KIND_WORDS[row.kind]}} + {row.mark && } + {spellings && {spellings}} + + +
+ + {error ? ( +
+ {error} + +
+ ) : permits == null ? ( +
Reading their jobs…
+ ) : ( + <> +
+ {tiles.map((t) => ( +
+ {t.big} + {t.words} + {t.more && {t.more}} +
+ ))} +
+ +
+
+

Working on now

+
0 ? 6 : 0 }}> + +
+ {jobs.map((j) => ( +
+
+
+ {j.title} + {j.money ? ` · ${j.money}` : ''} +
+
+ {j.address} · {j.city} · {j.filed} +
+
+ +
+ ))} +
+ +
+
+

Who to ask for

+ {askFor ? ( + ground?.people.get(userId) ?? null} todayYmd={todayYmd} busyId={checkingId} onPress={(standing, verdict) => void checkFact(standing, verdict)} /> + ) : ( + + )} + {people.length > 0 && ( +
+
Files their permits
+ {people.slice(0, 3).map((f) => ( +
+ +
+ ))} +
+ )} +
+ +
+

Who they use

+
+ + {used.tie && {TIE_WORDS[used.tie]}} +
+
+ +
+

Us and them

+
+
+ +
+ {byWord &&
{byWord}
} + {tied.length > 0 && !byWord &&
Tied to {tied.map((c) => c.name).join(', ')} by a person’s word.
} +
+ +
+
+
+
+
+ +
+ Their commercial building permits of the last twelve months in {cities.join(', ')}. A share is a part of the permits we hold, not of the market. +
+ + )} +
+ ) +} diff --git a/src/components/prospects/PermitBuilders.render.test.tsx b/src/components/prospects/PermitBuilders.render.test.tsx index 36adb98cf5..3c60541053 100644 --- a/src/components/prospects/PermitBuilders.render.test.tsx +++ b/src/components/prospects/PermitBuilders.render.test.tsx @@ -5,6 +5,7 @@ import { renderWithProviders } from '../../test/renderSmokeMocks' import { answerBook, type CountedBid, type CustomerName } from '../../lib/research/builderAnswers' import type { NameAnswerRow } from '../../lib/research/nameAnswers' import type { BuilderRow } from '../../lib/research/permitBuilders' +import type { ResearchPermitRow } from '../../lib/research/permitResearch' import type { LookupCheckRow, LookupRow } from '../../lib/research/builderLookups' /** @@ -13,7 +14,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(), loadBuildersOf: 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(), loadBuilderStanding: 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() })) @@ -49,8 +50,16 @@ function draw(isMobile = false) { return renderWithProviders( {}} />) } -async function openSheet(name: string) { +/** A name on the list opens its profile (punch list #465, step 2). */ +async function openProfile(name: string) { fireEvent.click(await screen.findByRole('button', { name })) + return await screen.findByRole('heading', { level: 2, name }) +} + +/** The builder's sheet opens from its profile. */ +async function openSheet(name: string) { + await openProfile(name) + fireEvent.click(screen.getByRole('button', { name: 'Mark, kind and ties' })) return await screen.findByRole('dialog') } @@ -59,6 +68,7 @@ beforeEach(() => { // 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.loadBuilderStanding.mockReset().mockResolvedValue([]) research.markBuilder.mockReset().mockResolvedValue(undefined) research.saveBuilder.mockReset().mockResolvedValue(undefined) research.pullPermitsBack.mockReset().mockResolvedValue(0) @@ -405,13 +415,14 @@ describe('A builder’s sheet, Ask for (punch list #405, v2.8732)', () => { it('keeps a press of Checked, says so, and reads the name’s facts again', async () => { const pressed: LookupCheckRow = { id: 'c1', lookup_id: 'f-phone', verdict: 'checked', said_by: 'u1', said_at: '2026-11-11T15:00:00Z' } - marketIo.loadBuilderLookupOf.mockResolvedValueOnce({ rows: FACTS, checks: [] }).mockResolvedValue({ rows: FACTS, checks: [pressed] }) + // The profile behind the sheet reads the name's facts too, so two reads come before the press and two after. + marketIo.loadBuilderLookupOf.mockResolvedValueOnce({ rows: FACTS, checks: [] }).mockResolvedValueOnce({ rows: FACTS, checks: [] }).mockResolvedValue({ rows: FACTS, checks: [pressed] }) draw() const sheet = await openSheet('Ridgeway Builders of Texas LLC') fireEvent.click(await within(sheet).findByRole('button', { name: /^Checked.*office phone/i })) await waitFor(() => expect(marketIo.recordLookupCheck).toHaveBeenCalledWith({ lookupId: 'f-phone', verdict: 'checked' })) expect(await screen.findByText('Checked the office phone of Ridgeway Builders of Texas LLC.')).toBeTruthy() - await waitFor(() => expect(marketIo.loadBuilderLookupOf).toHaveBeenCalledTimes(2)) + await waitFor(() => expect(marketIo.loadBuilderLookupOf).toHaveBeenCalledTimes(4)) await waitFor(() => expect((sheet.querySelector('[data-lookup-fact="phone"]') as HTMLElement).getAttribute('data-lookup-state')).toBe('checked')) expect((sheet.querySelector('[data-lookup-fact="phone"]') as HTMLElement).textContent).toContain('Checked by you, ') }) @@ -431,7 +442,8 @@ describe('A builder’s sheet, Ask for (punch list #405, v2.8732)', () => { const sheet = await openSheet('Ridgeway Builders of Texas LLC') fireEvent.click(await within(sheet).findByRole('button', { name: /^Wrong.*office phone/i })) expect(await screen.findByText(/the network is down/)).toBeTruthy() - expect(marketIo.loadBuilderLookupOf).toHaveBeenCalledTimes(1) + // The two reads are the profile's and the sheet's own, as each opened. + expect(marketIo.loadBuilderLookupOf).toHaveBeenCalledTimes(2) expect((sheet.querySelector('[data-lookup-fact="phone"]') as HTMLElement).getAttribute('data-lookup-state')).toBe('unchecked') }) @@ -451,3 +463,102 @@ describe('A builder’s sheet, Ask for (punch list #405, v2.8732)', () => { expect(await within(sheet).findByText('Nobody looked this name up yet.')).toBeTruthy() }) }) + +describe('A company’s profile (punch list #465, step 2)', () => { + const SABLE = 'sablecreek' + const sable = builder({ key: SABLE, sample_contact: 'Dana Whitlock, Sable Creek Construction', kind: 'gc', permits: 5, open: 3, declared: 700_000, declared_permits: 4, cities: ['Austin', 'San Antonio'] }) + const halden = builder({ key: 'haldencommercial', sample_contact: 'Halden Commercial', permits: 6, open: 3, declared: 300_000, declared_permits: 5, bids: 4, won: 1, last_bid_on: '2026-08-26', cities: ['Austin'] }) + let n = 0 + const job = (over: Partial = {}): ResearchPermitRow => + ({ id: `p${++n}`, city: 'Austin', stage: 'applied', project_name: null, work_type: 'New commercial', area_sf: null, address: '900 Tanner Row', filed_on: '2026-11-05', declared_value: 2_400_000, contact: 'Dana Whitlock, Sable Creek Construction', plumber: null, plumber_permit_on: null, verdict: null, verdict_reason_code: null, builder_key: SABLE, ...over }) as ResearchPermitRow + const JOBS = [ + job({ id: 'skim' }), + job({ id: 'kept', city: 'San Antonio', address: '300 Pell Avenue', filed_on: '2026-10-21', stage: 'issued', declared_value: 1_100_000, verdict: 'look' }), + job({ id: 'far', address: null, filed_on: '2026-11-02', declared_value: null, contact: 'Sable Creek Const. LLC', verdict: 'not_for_us', verdict_reason_code: 'too_far' }), + job({ id: 'oak1', plumber: 'Lone Oak Plumbing', plumber_permit_on: '2026-10-01' }), + job({ id: 'oak2', plumber: 'Lone Oak Plumbing', plumber_permit_on: '2026-10-02' }), + ] + const everyCity = (route?: string, isMobile = false) => renderWithProviders( {}} />, { route }) + + beforeEach(() => { + research.loadBuildersOf.mockResolvedValue([sable, halden]) + research.loadBuilderStanding.mockResolvedValue(JOBS) + }) + + it('opens from a name on the list: the chips, the four numbers, the open jobs with where each stands, and the rest', async () => { + everyCity() + await openProfile('Sable Creek Construction') + const page = document.querySelector('[data-builder-profile]') as HTMLElement + expect(page.getAttribute('data-builder-profile')).toBe(SABLE) + // The list is gone while the page is open, and the read is of the cities the name files in. + expect(screen.queryByRole('group', { name: 'Which builders' })).toBeNull() + expect(research.loadBuilderStanding).toHaveBeenCalledWith(['Austin', 'San Antonio'], SABLE, '2026-11-11') + await waitFor(() => expect(page.querySelector('[data-profile-tile="open"]')).not.toBeNull()) + expect(within(page).getByText('Not ours yet')).toBeTruthy() + expect(within(page).getByText('General contractor')).toBeTruthy() + expect(within(page).getByText('also files as Sable Creek Const. LLC')).toBeTruthy() + const tile = (key: string) => (page.querySelector(`[data-profile-tile="${key}"]`) as HTMLElement).textContent + expect(tile('open')).toBe('3jobs open now') + expect(tile('share')).toBe('70.0%of the dollars declared · 1st45.5% of the permits · 2nd') + expect(tile('plumbers')).toBe('1plumber on 2 jobs that name one') + expect(tile('bids')).toBe('0bids from us in two years') + // The open jobs, the newest first, each with its chip. A job with a plumbing permit is not one. + const now = within(page).getByRole('region', { name: 'Working on now' }) + expect([...now.querySelectorAll('[data-profile-job]')].map((j) => j.getAttribute('data-profile-job'))).toEqual(['skim', 'far', 'kept']) + expect(now.textContent).toContain('3 open jobs in 2 cities. 2 more have a plumbing permit.') + expect((now.querySelector('[data-profile-job="skim"]') as HTMLElement).textContent).toBe('New commercial · $2.4M900 Tanner Row · Austin · applied 6 days agoSkim') + expect((now.querySelector('[data-profile-job="kept"]') as HTMLElement).textContent).toContain('Investigating') + expect((now.querySelector('[data-profile-job="far"]') as HTMLElement).textContent).toBe('New commercialNo address on the permit · Austin · applied 9 days agoPassed: too far') + expect(within(page).getByRole('region', { name: 'Who to ask for' }).textContent).toContain('Dana Whitlock, on 4 of the 5.') + expect(within(page).getByRole('region', { name: 'Who they use' }).textContent).toBe('Who they useLone Oak Plumbing on 2 of the 2 jobs that name a plumber.') + expect(within(page).getByRole('region', { name: 'Us and them' }).textContent).toBe('Us and themNo bid in two years.No mark.') + expect(page.textContent).toContain('Their commercial building permits of the last twelve months in Austin, San Antonio.') + // Back leaves the page for the list. + fireEvent.click(within(page).getByRole('button', { name: 'Back to Builders' })) + expect(await screen.findByRole('group', { name: 'Which builders' })).toBeTruthy() + expect(document.querySelector('[data-builder-profile]')).toBeNull() + }) + + it('opens straight from its address, with our bids, the mark and the tie in words', async () => { + research.loadBuildersOf.mockResolvedValue([sable, builder({ ...halden, mark: 'good', mark_reason: 'Pays on time.', mark_by_name: 'Sam' })]) + research.loadBuilderStanding.mockResolvedValue([]) + everyCity('/prospects?tab=permits&view=builders&builder=haldencommercial', true) + expect(await screen.findByRole('heading', { level: 2, name: 'Halden Commercial' })).toBeTruthy() + const page = document.querySelector('[data-builder-profile]') as HTMLElement + await waitFor(() => expect(page.querySelector('[data-profile-tile="open"]')).not.toBeNull()) + expect(within(page).getByText('Ours')).toBeTruthy() + expect(within(page).getByRole('region', { name: 'Us and them' }).textContent).toBe('Us and them4 priced, 1 won in two years, the last on Aug 26.Marked Good by Sam: Pays on time.') + expect(within(page).getByRole('region', { name: 'Working on now' }).textContent).toBe('Working on nowNo permit in the last twelve months.') + expect(within(page).getByRole('region', { name: 'Who they use' }).textContent).toBe('Who they useNo plumbing permit on any of their jobs yet.') + }) + + it('says so when no permit of the year names the key, and offers the list', async () => { + everyCity('/prospects?tab=permits&view=builders&builder=nobodyweknow') + expect(await screen.findByText('No permit under this name in the last twelve months.')).toBeTruthy() + expect(research.loadBuilderStanding).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: 'Back to Builders' })) + expect(await screen.findByRole('group', { name: 'Which builders' })).toBeTruthy() + }) + + it('names the reason when the jobs cannot be read, and reads again on Retry', async () => { + research.loadBuilderStanding.mockRejectedValueOnce(new Error('Could not read this builder’s jobs: the network is down')).mockResolvedValue(JOBS) + everyCity() + await openProfile('Sable Creek Construction') + expect(await screen.findByText(/the network is down/)).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Retry' })) + await waitFor(() => expect(document.querySelector('[data-profile-tile="open"]')).not.toBeNull()) + expect(research.loadBuilderStanding).toHaveBeenCalledTimes(2) + }) + + it('opens the builder’s sheet for the mark, and reads the jobs again once it is kept', async () => { + everyCity() + const sheet = await openSheet('Sable Creek Construction') + fireEvent.click(within(sheet).getByRole('button', { name: 'Good' })) + fireEvent.change(within(sheet).getByLabelText('Why, in a line'), { target: { value: 'Pays on time.' } }) + fireEvent.click(within(sheet).getByRole('button', { name: 'Mark as Good' })) + await waitFor(() => expect(research.markBuilder).toHaveBeenCalledWith(SABLE, 'good', 'Pays on time.', 'u1')) + await waitFor(() => expect(research.loadBuilderStanding).toHaveBeenCalledTimes(2)) + // The page is still the one open behind the sheet. + expect(document.querySelector('[data-builder-profile]')?.getAttribute('data-builder-profile')).toBe(SABLE) + }) +}) diff --git a/src/components/prospects/PermitBuilders.tsx b/src/components/prospects/PermitBuilders.tsx index 999a7d57f3..aa5f50855b 100644 --- a/src/components/prospects/PermitBuilders.tsx +++ b/src/components/prospects/PermitBuilders.tsx @@ -32,15 +32,16 @@ import { byWordWords, openLookAlikes, throughWords, withAnsweredBids } from '../ import type { BuilderAnswersGround } from '../../lib/research/builderAnswersIo' import { BuilderNameTies } from './BuilderNameTies' import { PermitLookAlikes } from './PermitLookAlikes' -import { permitsLinkWithLooks, readPermitsLink } from '../../lib/research/permitsLink' +import { permitsLinkWithBuilder, permitsLinkWithLooks, readPermitsLink } from '../../lib/research/permitsLink' 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' -import { loadBuilderLookupOf, recordLookupCheck } from '../../lib/research/permitMarketIo' +import { MarkPill, OursPill } from './BuilderPills' +import { PermitBuilderProfile } from './PermitBuilderProfile' +import { useBuilderAskFor } from '../../hooks/useBuilderAskFor' /** * Permits, Builders (punch list #302, PR 6): every name that pulled a commercial building permit @@ -55,6 +56,9 @@ import { loadBuilderLookupOf, recordLookupCheck } from '../../lib/research/permi * 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`). + * + * A company's profile (punch list #465, step 2): a press on a name opens its page in place of the list, on an + * address of its own (`builder=`), and the page opens the builder's sheet for the mark, the kind and the ties. */ 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' }) @@ -63,21 +67,8 @@ const td: CSSProperties = { padding: '9px 10px', borderBottom: '1px solid var(-- const num: CSSProperties = { ...td, textAlign: 'right', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } const smallPress: CSSProperties = { background: 'var(--surface)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 8, padding: '6px 10px', fontSize: '0.8125rem', minHeight: 34, cursor: 'pointer', fontFamily: 'inherit' } -function MarkPill({ mark }: { mark: BuilderMarkValue | null }) { - const base: CSSProperties = { display: 'inline-block', borderRadius: 999, padding: '1px 8px', fontSize: '0.72rem', fontWeight: 600, whiteSpace: 'nowrap' } - if (mark === 'good') return Good - if (mark === 'avoid') return Avoid - return {BUILDER_SHOWING_WORDS.unmarked} -} - const SHOWING: BuilderShowing[] = ['all', 'never_bid', 'good', 'avoid', 'unmarked'] -/** 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 @@ -201,6 +192,12 @@ export function PermitBuilders({ city, cities, authUserId, todayYmd, isMobile, o // 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]) + // A company's profile rides the address, so it has a link of its own and the browser's Back leaves it. + const profileKey = readPermitsLink(searchParams).builder + const profile = useMemo(() => (profileKey ? (all.find((r) => r.key === profileKey) ?? null) : null), [all, profileKey]) + const openProfile = (key: string) => setSearchParams(permitsLinkWithBuilder(searchParams, key)) + const closeProfile = () => setSearchParams(permitsLinkWithBuilder(searchParams, null)) + const [sheetKept, setSheetKept] = useState(0) if (loading && rows == null) return
Reading the builders…
if (error) { @@ -215,6 +212,40 @@ export function PermitBuilders({ city, cities, authUserId, todayYmd, isMobile, o } if (notYet) return
Builders opens once tonight’s database change is in. Nothing is lost: every permit already carries who pulled it.
+ const sheet = open && ( + setSheetKept((n) => n + 1)} + onClose={() => setOpenKey(null)} + onSaved={() => { + void load() + onChanged() + setSheetKept((n) => n + 1) + }} + /> + ) + + if (profileKey) { + return ( + <> + {profile ? ( + setOpenKey(profile.key)} /> + ) : ( + + )} + {sheet} + + ) + } + return (
@@ -303,7 +334,7 @@ export function PermitBuilders({ city, cities, authUserId, todayYmd, isMobile, o ) : isMobile ? (
{list.map((r, i) => ( - {r.mark && ( @@ -429,24 +460,7 @@ export function PermitBuilders({ city, cities, authUserId, todayYmd, isMobile, o
)} - {open && ( - setOpenKey(null)} - onSaved={() => { - void load() - onChanged() - }} - /> - )} + {sheet}
) } @@ -483,35 +497,8 @@ export function BuilderSheet({ row, city, permitCities, authUserId, todayYmd, re } }, [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) - const [askForAsked, setAskForAsked] = useState(0) - const [checkingId, setCheckingId] = useState(null) - useEffect(() => { - let live = true - loadBuilderLookupOf(row.key) - .then((read) => live && setAskFor({ lookup: read ? (foldLookups(read.rows, read.checks).get(row.key) ?? null) : null, unread: false })) - // A read after a press that fails keeps what the sheet already drew. - .catch(() => live && setAskFor((held) => held ?? { lookup: null, unread: true })) - return () => { - live = false - } - }, [row.key, askForAsked]) - - /** Checked, Wrong, Not right or Put back on one looked-up fact, kept as the call list keeps it. */ - const checkFact = async (standing: LookupStanding, verdict: LookupVerdict) => { - setCheckingId(standing.row.id) - try { - await recordLookupCheck({ lookupId: standing.row.id, verdict }) - showToast(lookupPressedWords(verdict, standing.row.fact, name), 'success') - setAskForAsked((n) => n + 1) - onLookupChecked?.() - } catch (e) { - showToast(formatErrorMessage(e), 'error') - } finally { - setCheckingId(null) - } - } + // What was looked up about this one name, and the presses on each fact. Null until the read lands. + const { askFor, checkingId, checkFact } = useBuilderAskFor(row.key, name, onLookupChecked) const hold = markHold(mark, reason) const markChanged = mark !== (row.mark ?? 'none') || (mark !== 'none' && reason.trim() !== (row.mark_reason ?? '').trim()) diff --git a/src/components/prospects/ProspectsResearchTab.render.test.tsx b/src/components/prospects/ProspectsResearchTab.render.test.tsx index d5ddafd2c5..d766bb6dbc 100644 --- a/src/components/prospects/ProspectsResearchTab.render.test.tsx +++ b/src/components/prospects/ProspectsResearchTab.render.test.tsx @@ -32,6 +32,7 @@ const io = vi.hoisted(() => ({ markBuilder: vi.fn(), saveBuilder: vi.fn(), loadPermitsOfBuilder: vi.fn(), + loadBuilderStanding: vi.fn(), loadPermitFunnel: vi.fn(), loadNewestPermitDay: vi.fn(), })) @@ -162,6 +163,7 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { io.markBuilder.mockReset().mockResolvedValue(undefined) io.saveBuilder.mockReset().mockResolvedValue(undefined) io.loadPermitsOfBuilder.mockReset().mockResolvedValue([]) + io.loadBuilderStanding.mockReset().mockResolvedValue([]) io.loadPermitFunnel.mockReset().mockResolvedValue(null) // No newest day is read unless a test says so: the picker's rows are the names alone. io.loadNewestPermitDay.mockReset().mockResolvedValue(null) @@ -875,10 +877,15 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { // Every count says how far back it can see: the line over the list, the column, the sheet. await waitFor(() => expect(screen.getByText(`San Antonio's records here start ${SINCE.replace('since ', '')}. Every count is what we can see since then.`)).toBeTruthy()) expect(screen.getByRole('columnheader', { name: `Permits ${SINCE}` })).toBeTruthy() + // A name opens its profile, which covers every city, so the picker says so. The sheet opens from the profile. fireEvent.click(screen.getByRole('button', { name: 'Tall Pine Development' })) + expect(await screen.findByRole('heading', { level: 2, name: 'Tall Pine Development' })).toBeTruthy() + expect((screen.getByLabelText('City') as HTMLSelectElement).value).toBe('*') + fireEvent.click(screen.getByRole('button', { name: 'Mark, kind and ties' })) const sheet = await screen.findByRole('dialog') - expect(within(sheet).getByText(new RegExp(`^5 permits ${SINCE}, 1 with no plumber yet`))).toBeTruthy() - expect(within(sheet).getByText(`Their permits ${SINCE}`)).toBeTruthy() + // Over every city no one day is where the records start, so the sheet's counts say what we can see. + expect(within(sheet).getByText(/^5 permits we can see, 1 with no plumber yet/)).toBeTruthy() + expect(within(sheet).getByText('Their permits')).toBeTruthy() fireEvent.click(within(sheet).getByRole('button', { name: 'Avoid' })) fireEvent.click(within(sheet).getByRole('button', { name: 'Mark as Avoid' })) expect(io.markBuilder).not.toHaveBeenCalled() @@ -888,6 +895,20 @@ describe('ProspectsResearchTab (v2.6782, punch list #292)', () => { await waitFor(() => expect(io.markBuilder).toHaveBeenCalledWith('tallpinedevelopment', 'avoid', 'Slow pay on the Millrace job.', 'u1')) }) + it('a company’s profile reads every city, and a city picked over it goes back to that city’s list (punch list #465, step 2)', 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() + await openBuildersIn('San Antonio') + fireEvent.click(await screen.findByRole('button', { name: 'Tall Pine Development' })) + expect(await screen.findByRole('heading', { level: 2, name: 'Tall Pine Development' })).toBeTruthy() + const picker = screen.getByLabelText('City') as HTMLSelectElement + expect(picker.value).toBe('*') + fireEvent.change(picker, { target: { value: 'Austin' } }) + await waitFor(() => expect(screen.queryByRole('heading', { level: 2, name: 'Tall Pine Development' })).toBeNull()) + expect(picker.value).toBe('Austin') + expect(await screen.findByRole('group', { name: 'Which builders' })).toBeTruthy() + }) + it('lists the names that look like a customer behind a chip, and ties one on the press', async () => { io.loadBuilders.mockResolvedValue([ { key: 'tallpinedevelopmentgroup', name: null, sample_contact: 'Tall Pine Development Group LLC', 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 }, diff --git a/src/components/prospects/ProspectsResearchTab.tsx b/src/components/prospects/ProspectsResearchTab.tsx index d5ebe3806a..170e787a43 100644 --- a/src/components/prospects/ProspectsResearchTab.tsx +++ b/src/components/prospects/ProspectsResearchTab.tsx @@ -63,7 +63,7 @@ import { cityPickerTitle, cityPickerWords, isQuiet } from '../../lib/research/pe 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' +import { permitsLinkForView, permitsLinkSheetOpen, permitsLinkViewOf, permitsLinkWithBuilder, permitsLinkWithSheet, readPermitsLink } from '../../lib/research/permitsLink' import { secondLookCount, secondLookSegmentWords, showsSecondLookSegment } from '../../lib/research/permitSecondLook' import { notPursuingVerdict, placeCounts, pursueReason, stripCounts, type SkimLive } from '../../lib/research/permitBuilders' import { GoogleSearchPress } from './GoogleSearchPress' @@ -171,7 +171,9 @@ export function ProspectsResearchTab({ authUserId, step }: { authUserId: string; // 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' + // A company's profile covers every city (call 4), so the list behind it reads them all while one is open. + const profileOpen = readPermitsLink(searchParams).builder != null + const buildersOfEveryCity = (buildersEveryCity || profileOpen) && view === 'builders' const [windowDays, setWindowDays] = useState(30) const [residential, setResidential] = useState(false) const [showing, setShowing] = useState('waiting') @@ -422,7 +424,11 @@ export function ProspectsResearchTab({ authUserId, step }: { authUserId: string; onChange={(e) => { const picked = e.target.value setBuildersEveryCity(picked === EVERY_CITY) - if (picked !== EVERY_CITY) setCity(picked) + if (picked !== EVERY_CITY) { + setCity(picked) + // A city picked over a profile goes back to that city's list. + if (profileOpen) setSearchParams(permitsLinkWithBuilder(searchParams, null), { replace: true }) + } }} style={buildersOfEveryCity ? selectStyle : { ...selectStyle, ...quietSelect }} > diff --git a/src/content/help/research-permits-for-work-to-bid.md b/src/content/help/research-permits-for-work-to-bid.md index 502bcf0aa0..aa57500faa 100644 --- a/src/content/help/research-permits-for-work-to-bid.md +++ b/src/content/help/research-permits-for-work-to-bid.md @@ -217,7 +217,23 @@ Press **Looks like a customer** to see names that may be one of our customers. E The Dashboard's **Needs you** card says how many names wait on that answer. The line adds up the number on the chip in every city. Press **Answer them** there to open this list. That line goes away once every name is answered. -Press a builder's name. Pick **Good** or **Avoid** and say why in a line. The mark shows on every skim card of that builder. A Good builder's permits come first. An Avoid builder's permits come last. +### Open a company's page + +Press a builder's name on the list. Its page opens in place of the list. The page covers every city the company files in. + +The top line has the name and its chips. It also names the other spellings the company files under. + +Four numbers come next. The first counts the jobs open now. The second is its share of the dollars, with its rank. The third counts the plumbers its permits name. The fourth counts our bids in two years. + +**Working on now** lists every job with no plumbing permit yet. Each job has a chip that says where it stands with us. A job we passed stays on the list. Its chip says why we passed. + +**Who to ask for** shows what a lookup found about the company. It also names who files their permits. **Who they use** names their plumbers. **Us and them** has our bids and our mark. + +The page has an address of its own. Copy the address to send the page to a teammate. Press **Back to Builders** to return to the list. Picking a city in the picker returns to that city's list too. + +### Mark a builder + +Open the company's page and press **Mark, kind and ties**. The builder's sheet opens. Pick **Good** or **Avoid** and say why in a line. The mark shows on every skim card of that builder. A Good builder's permits come first. An Avoid builder's permits come last. Pick **Files for others** under what kind of company for a name that pulls permits for other people. Its cards then lead with the county's owner. diff --git a/src/content/releaseNotes/v2.9266.ts b/src/content/releaseNotes/v2.9266.ts new file mode 100644 index 0000000000..7ad6ba5308 --- /dev/null +++ b/src/content/releaseNotes/v2.9266.ts @@ -0,0 +1,16 @@ +import type { ReleaseNote } from '../../lib/releaseNotes' + +const note: ReleaseNote = { + version: 'v2.9266', + date: '2026-12-02', + title: 'Builders: a page for every company', + kind: 'feature', + highlights: [ + 'Press a company\'s name on Builders, on Prospects → Permits. Its own page opens, over every city it files in, and the page has an address you can send to a teammate.', + 'The page shows four numbers: its jobs open now, its share of the dollars and of the permits with a rank on each, the plumbers its permits name, and our bids in two years.', + 'Working on now lists every job with no plumbing permit yet, each with where it stands with us: Skim, Investigating, Pursuing, or passed and why.', + 'Who to ask for, who they use, and our bids and our mark are on the same page. Press Mark, kind and ties to set the mark as before.', + ], +} + +export default note diff --git a/src/hooks/useBuilderAskFor.ts b/src/hooks/useBuilderAskFor.ts new file mode 100644 index 0000000000..c22fdeef47 --- /dev/null +++ b/src/hooks/useBuilderAskFor.ts @@ -0,0 +1,48 @@ +import { useEffect, useState } from 'react' +import { useToastContext } from '../contexts/ToastContext' +import { foldLookups, lookupPressedWords, type BuilderLookup, type LookupStanding, type LookupVerdict } from '../lib/research/builderLookups' +import { loadBuilderLookupOf, recordLookupCheck } from '../lib/research/permitMarketIo' +import { formatErrorMessage } from '../utils/errorHandling' + +/** What was looked up about one name. `unread` when it could not be read. */ +export type BuilderAskFor = { lookup: BuilderLookup | null; unread: boolean } + +/** + * Who to ask for at one builder (v2.8732), for the builder's sheet and its profile: what a one-time lookup found + * about the name, read once and folded as the call list folds it, and the press that keeps **Checked**, + * **Wrong**, **Not right** or **Put back** on one fact. `askFor` is null until the read lands, so a screen + * never says nobody looked before it knows. `readAgain` goes up when another screen kept a press on the same + * name, and the facts read again. + */ +export function useBuilderAskFor(builderKey: string, name: string, onChecked?: () => void, readAgain = 0): { askFor: BuilderAskFor | null; checkingId: string | null; checkFact: (standing: LookupStanding, verdict: LookupVerdict) => Promise } { + const { showToast } = useToastContext() + const [askFor, setAskFor] = useState(null) + const [asked, setAsked] = useState(0) + const [checkingId, setCheckingId] = useState(null) + useEffect(() => { + let live = true + loadBuilderLookupOf(builderKey) + .then((read) => live && setAskFor({ lookup: read ? (foldLookups(read.rows, read.checks).get(builderKey) ?? null) : null, unread: false })) + // A read after a press that fails keeps what the screen already drew. + .catch(() => live && setAskFor((held) => held ?? { lookup: null, unread: true })) + return () => { + live = false + } + }, [builderKey, asked, readAgain]) + + const checkFact = async (standing: LookupStanding, verdict: LookupVerdict) => { + setCheckingId(standing.row.id) + try { + await recordLookupCheck({ lookupId: standing.row.id, verdict }) + showToast(lookupPressedWords(verdict, standing.row.fact, name), 'success') + setAsked((n) => n + 1) + onChecked?.() + } catch (e) { + showToast(formatErrorMessage(e), 'error') + } finally { + setCheckingId(null) + } + } + + return { askFor, checkingId, checkFact } +} diff --git a/src/lib/research/builderProfile.test.ts b/src/lib/research/builderProfile.test.ts new file mode 100644 index 0000000000..b5a292a4e7 --- /dev/null +++ b/src/lib/research/builderProfile.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from 'vitest' +import { plainSentence } from '../valuesInPlace' +import type { BuilderShare } from './builderShare' +import { + filerWords, + filers, + filesAs, + filesAsWords, + jobStanding, + markLine, + openJobs, + openJobsWords, + ordinal, + ourBidsLine, + plumbersUsed, + plumbersUsedWords, + profileTiles, + type ProfilePermit, +} from './builderProfile' + +const TODAY = '2026-12-02' + +let n = 0 +const permit = (over: Partial = {}): ProfilePermit => ({ + id: `p${++n}`, + city: 'Elm City', + stage: 'applied', + project_name: null, + work_type: 'New commercial', + area_sf: null, + address: '900 Tanner Row', + filed_on: '2026-11-26', + declared_value: 2_400_000, + contact: 'Sable Creek Construction', + plumber: null, + plumber_permit_on: null, + verdict: null, + verdict_reason_code: null, + ...over, +}) + +const share = (over: Partial = {}): BuilderShare => ({ dollars: 7_400_000, dollarsShare: 0.074, permitsShare: 0.056, dollarsRank: 3, permitsRank: 4, ours: false, ...over }) + +describe('a job’s standing with us', () => { + it('says each place in the app’s own words', () => { + expect(jobStanding(permit()).words).toBe('Skim') + expect(jobStanding(permit({ verdict: 'look' })).words).toBe('Investigating') + expect(jobStanding(permit({ verdict: 'approach' })).words).toBe('Pursuing') + expect(jobStanding(permit({ verdict: 'not_for_us', verdict_reason_code: 'too_far' })).words).toBe('Passed: too far') + expect(jobStanding(permit({ verdict: 'not_for_us', verdict_reason_code: 'sl_too_small' })).words).toBe('Passed: too small, on a second look') + expect(jobStanding(permit({ verdict: 'not_for_us', verdict_reason_code: null })).words).toBe('Passed: no reason given') + expect(jobStanding(permit({ verdict: 'not_for_us', verdict_reason_code: 'np_no_answer' })).words).toBe('Not pursuing: could not reach anyone') + // The office said a plumber has it, and no plumbing permit is on the feed yet. + expect(jobStanding(permit({ verdict: 'taken' }))).toEqual({ place: 'closed', why: 'plumber', words: 'Has a plumber' }) + }) +}) + +describe('working on now', () => { + it('lists the permits with no plumbing permit, the newest first, whatever we answered', () => { + const rows = [ + permit({ id: 'old', filed_on: '2026-10-01', verdict: 'not_for_us', verdict_reason_code: 'too_far', stage: 'issued', declared_value: null, address: ' ' }), + permit({ id: 'new', filed_on: '2026-11-30', city: 'Fern City' }), + permit({ id: 'named', plumber: 'Lone Oak Plumbing', plumber_permit_on: '2026-11-01' }), + permit({ id: 'unnamed', plumber_permit_on: '2026-11-02' }), + ] + const jobs = openJobs(rows, TODAY) + expect(jobs.map((j) => j.id)).toEqual(['new', 'old']) + expect(jobs[0]).toEqual({ id: 'new', title: 'New commercial', money: '$2.4M', address: '900 Tanner Row', city: 'Fern City', filed: 'applied 2 days ago', standing: { place: 'skim', why: null, words: 'Skim' } }) + expect(jobs[1]).toMatchObject({ money: null, address: 'No address on the permit', filed: 'issued 62 days ago', standing: { words: 'Passed: too far' } }) + expect(plainSentence(openJobsWords(jobs, rows.length))).toBe('2 open jobs in 2 cities. 2 more have a plumbing permit.') + }) + + it('counts in words that fit one job, none, and no permit at all', () => { + const one = openJobs([permit()], TODAY) + expect(plainSentence(openJobsWords(one, 1))).toBe('1 open job. No plumbing permit is on any of them.') + expect(plainSentence(openJobsWords(one, 2))).toBe('1 open job. 1 more has a plumbing permit.') + expect(plainSentence(openJobsWords([], 3))).toBe('Nothing open now. A plumbing permit is on each of their 3 permits.') + expect(plainSentence(openJobsWords([], 0))).toBe('No permit in the last twelve months.') + }) +}) + +describe('the names it files under, and who files', () => { + const row = { key: 'sablecreekconstruction', name: null, sample_contact: 'Dana Whitlock, Sable Creek Construction' } + const rows = [ + permit({ contact: 'Dana Whitlock, Sable Creek Construction' }), + permit({ contact: 'Dana Whitlock, Sable Creek Construction' }), + permit({ contact: 'dana whitlock, Sable Creek Const. LLC' }), + permit({ contact: 'Sable Creek Const. LLC' }), + permit({ contact: 'SCC Builders' }), + permit({ contact: null }), + ] + + it('names every other spelling, the most used first, and never its own', () => { + expect(filesAs(row, rows)).toEqual(['Sable Creek Const. LLC', 'SCC Builders']) + expect(filesAsWords(filesAs(row, rows))).toBe('also files as Sable Creek Const. LLC · SCC Builders') + expect(filesAsWords([])).toBeNull() + expect(filesAsWords(['A', 'B', 'C', 'D', 'E'])).toBe('also files as A · B · C and 2 more') + // A name the office gave is the page's own, and each of the feed's spellings is then another one. Level counts go by the alphabet. + expect(filesAs({ ...row, name: 'Sable Creek' }, rows)).toEqual(['Sable Creek Const. LLC', 'Sable Creek Construction', 'SCC Builders']) + }) + + it('counts the people named beside the company, one spelling a person', () => { + expect(filers(rows)).toEqual([{ name: 'Dana Whitlock', permits: 3 }]) + expect(plainSentence(filerWords({ name: 'Dana Whitlock', permits: 3 }, 6))).toBe('Dana Whitlock, on 3 of the 6.') + // A line that is a person alone is the builder, not someone who files for it. + expect(filers([permit({ contact: 'Richard Kenly' })])).toEqual([]) + }) +}) + +describe('who they use', () => { + it('counts plumbers on the jobs that name one, and judges the tie from three', () => { + const rows = [ + ...Array.from({ length: 5 }, () => permit({ plumber: 'Lone Oak Plumbing', plumber_permit_on: '2026-11-01' })), + permit({ plumber: 'Tri-County Mechanical', plumber_permit_on: '2026-11-01' }), + permit({ plumber: 'Tri-County Mechanical, LLC', plumber_permit_on: '2026-11-01' }), + permit({ plumber_permit_on: '2026-11-01' }), + permit(), + ] + const used = plumbersUsed(rows) + expect(used).toMatchObject({ named: 7, unnamed: 1, tie: 'leans' }) + expect(used.list.map((p) => [p.name, p.jobs])).toEqual([['Lone Oak Plumbing', 5], ['Tri-County Mechanical', 2]]) + expect(plainSentence(plumbersUsedWords(used))).toBe('Lone Oak Plumbing on 5 of the 7 jobs that name a plumber. Tri-County Mechanical on 2.') + }) + + it('counts the rest past three names, and judges nobody on two jobs', () => { + const rows = ['A Plumbing', 'A Plumbing', 'B Plumbing', 'C Plumbing', 'D Plumbing', 'E Plumbing'].map((plumber) => permit({ plumber, plumber_permit_on: '2026-11-01' })) + const used = plumbersUsed(rows) + expect(used.tie).toBe('shops') + expect(plainSentence(plumbersUsedWords(used))).toBe('A Plumbing on 2 of the 6 jobs that name a plumber. B Plumbing on 1. C Plumbing on 1. 2 more on 2.') + expect(plumbersUsed(rows.slice(0, 2)).tie).toBeNull() + expect(plainSentence(plumbersUsedWords(plumbersUsed(rows.slice(0, 1))))).toBe('A Plumbing on the one job that names a plumber.') + }) + + it('says so where the permits name no plumber', () => { + expect(plainSentence(plumbersUsedWords(plumbersUsed([permit({ plumber_permit_on: '2026-11-01' }), permit()])))).toBe('A plumbing permit is on 1 of their jobs, and none names the plumber.') + expect(plumbersUsedWords(plumbersUsed([permit()]))).toBe('No plumbing permit on any of their jobs yet.') + }) +}) + +describe('the four tiles', () => { + it('reads the count, the two shares with a rank on each, the plumbers and our bids', () => { + const used = plumbersUsed([permit({ plumber: 'Lone Oak Plumbing' }), permit({ plumber: 'Tri-County Mechanical' }), permit({ plumber: 'Lone Oak Plumbing' })]) + expect(profileTiles({ bids: 0 }, share(), 5, used)).toEqual([ + { key: 'open', big: '5', words: 'jobs open now', more: null }, + { key: 'share', big: '7.4%', words: 'of the dollars declared · 3rd', more: '5.6% of the permits · 4th' }, + { key: 'plumbers', big: '2', words: 'plumbers on 3 jobs that name one', more: null }, + { key: 'bids', big: '0', words: 'bids from us in two years', more: null }, + ]) + }) + + it('leads with the permits where no value is declared, and fits one of each', () => { + const tiles = profileTiles({ bids: 1 }, share({ dollars: null, dollarsShare: null, dollarsRank: null, permitsShare: 0.0004, permitsRank: 21 }), 1, plumbersUsed([permit()])) + expect(tiles.map((t) => `${t.big} ${t.words}`)).toEqual(['1 job open now', 'under 0.1% of the permits · 21st', '0 plumbers named on their permits', '1 bid from us in two years']) + expect(tiles[1]?.more).toBe('No value declared on their permits.') + }) + + it('writes a rank as a place', () => { + expect([1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 111].map(ordinal)).toEqual(['1st', '2nd', '3rd', '4th', '11th', '12th', '13th', '21st', '22nd', '23rd', '101st', '111th']) + }) +}) + +describe('us and them', () => { + it('says our bids and the mark', () => { + expect(ourBidsLine({ bids: 0, won: 0, last_bid_on: null }, TODAY)).toBe('No bid in two years.') + expect(plainSentence(ourBidsLine({ bids: 5, won: 3, last_bid_on: '2026-08-26' }, TODAY))).toBe('5 priced, 3 won in two years, the last on Aug 26.') + expect(plainSentence(ourBidsLine({ bids: 1, won: 0, last_bid_on: '2025-08-26' }, TODAY))).toBe('1 priced, none won in two years, the last on Aug 26, 2025.') + expect(markLine({ mark: null, mark_reason: null, mark_by_name: null })).toBe('No mark.') + expect(plainSentence(markLine({ mark: 'good', mark_reason: 'Pays on time. ', mark_by_name: 'Dana' }))).toBe('Marked Good by Dana: Pays on time.') + expect(plainSentence(markLine({ mark: 'avoid', mark_reason: '', mark_by_name: null }))).toBe('Marked Avoid.') + }) +}) diff --git a/src/lib/research/builderProfile.ts b/src/lib/research/builderProfile.ts new file mode 100644 index 0000000000..9f6f42e4d0 --- /dev/null +++ b/src/lib/research/builderProfile.ts @@ -0,0 +1,233 @@ +/** + * Permits, a company's profile (punch list #465, step 2): one page a name, from rows the tab already + * reads. The name's row on Builders and its two shares, and its own commercial building permits of + * twelve months with where each stands with us. No React, no Supabase. + * + * Four things the page says the way the app counts them, where the card's drawing guessed: + * - A job is open while no plumbing permit sits on it. That is the count in the list's *Open now* + * column, so the tile, the list and the column are one rule. An answer of ours does not close it + * here: a job we passed is still theirs to talk about, and its chip says where it stands. + * - A chip's words are the app's own (`PLACE_WORDS`, `CLOSED_WORDS` and the count's pass reasons). + * - *Who they use* is counted on the jobs whose plumbing permit names a plumber, and says how many + * those are. A city that never names one has no plumbers to count. + * - *Also files as* is every other spelling of the company on the name's own permits. Two names the + * app has not folded are still two profiles. + */ +import { contactParts } from '../../../supabase/functions/_shared/permitLookup' +import { pluralNoun } from '../batchWords' +import { val } from '../valuesInPlace' +import { shareWords, type BuilderShare } from './builderShare' +import { CLOSED_WORDS, PLACE_WORDS, builderName, ourBidsWords, passReasonWords, placeOf, type BuilderRow, type ClosedWhy, type PermitPlace } from './permitBuilders' +import { TIE_MIN_JOBS, plumbersCounted, tieOf, type BuilderTie, type PlumberJobs } from './permitMarketShape' +import { reachDay } from './permitReach' +import { plumbingOnFile, shortMoney, type ResearchPermitRow } from './permitResearch' +import { filedWords, skimTitle } from './permitSkim' + +/** What the page reads of a permit. Every field is on the tab's own read. */ +export type ProfilePermit = Pick< + ResearchPermitRow, + 'id' | 'city' | 'stage' | 'project_name' | 'work_type' | 'area_sf' | 'address' | 'filed_on' | 'declared_value' | 'contact' | 'plumber' | 'plumber_permit_on' | 'verdict' | 'verdict_reason_code' +> + +const newestFirst = (a: Pick, b: Pick): number => (b.filed_on ?? '').localeCompare(a.filed_on ?? '') || a.id.localeCompare(b.id) + +// ---------- working on now ---------- + +/** Where a job stands with us, as its chip says it. */ +export type JobStanding = { place: PermitPlace; why: ClosedWhy | null; words: string } + +/** "Skim", "Investigating", "Pursuing", "Passed: too far", "Not pursuing: could not reach anyone", "Has a plumber". */ +export function jobStanding(row: Pick): JobStanding { + const { place, why } = placeOf(row) + if (place !== 'closed' || why == null) return { place, why: null, words: PLACE_WORDS[place] } + if (why === 'plumber') return { place, why, words: CLOSED_WORDS.plumber } + return { place, why, words: `${CLOSED_WORDS[why]}: ${passReasonWords(row.verdict_reason_code)}` } +} + +/** One row of *Working on now*. */ +export type ProfileJob = { + id: string + /** "New commercial, 6,200 sq ft" or the feed's project name. */ + title: string + /** "$2.4M", or null when the permit declares nothing. */ + money: string | null + /** The street, or what stands in for one. */ + address: string + city: string + /** "applied 6 days ago". */ + filed: string + standing: JobStanding +} + +/** The name's open jobs: its permits of twelve months with no plumbing permit on file, the newest first. */ +export function openJobs(permits: readonly ProfilePermit[], todayYmd: string): ProfileJob[] { + return permits + .filter((r) => !plumbingOnFile(r)) + .sort(newestFirst) + .map((r) => ({ + id: r.id, + title: skimTitle(r), + money: shortMoney(r.declared_value), + address: (r.address ?? '').trim() || 'No address on the permit', + city: r.city, + filed: filedWords(r, todayYmd), + standing: jobStanding(r), + })) +} + +/** Over the list: "5 open jobs in 2 cities", and how many more of the name's permits have a plumbing permit. */ +export function openJobsWords(jobs: readonly ProfileJob[], permits: number): string { + const cities = new Set(jobs.map((j) => j.city)).size + const open = `${val('open', String(jobs.length))} open ${pluralNoun('job', jobs.length)}${cities > 1 ? ` in ${val('cities', String(cities))} cities` : ''}` + const taken = Math.max(0, permits - jobs.length) + if (jobs.length === 0) return taken === 0 ? 'No permit in the last twelve months.' : `Nothing open now. A plumbing permit is on each of their ${val('taken', String(taken))} ${pluralNoun('permit', taken)}.` + return taken === 0 ? `${open}. No plumbing permit is on any of them.` : `${open}. ${val('taken', String(taken))} more ${taken === 1 ? 'has' : 'have'} a plumbing permit.` +} + +// ---------- the names it files under, and who files ---------- + +const sameName = (a: string, b: string): boolean => a.trim().toLowerCase() === b.trim().toLowerCase() + +/** How a name is counted on a list of spellings: the most used first, then by the alphabet. */ +function counted(names: Iterable): Array<{ name: string; permits: number }> { + const counts = new Map() + for (const written of names) { + const name = written.replace(/\s+/g, ' ').trim() + if (name === '') continue + const k = name.toLowerCase() + const c = counts.get(k) ?? { name, permits: 0 } + counts.set(k, c) + c.permits += 1 + } + return [...counts.values()].sort((a, b) => b.permits - a.permits || a.name.localeCompare(b.name)) +} + +/** The other spellings of the company on the name's own permits, the most used first. Never the page's own name. */ +export function filesAs(row: Pick, permits: readonly Pick[]): string[] { + const own = builderName(row) + const spelled = permits.map((p) => { + const { person, company } = contactParts(p.contact) + return company ?? person ?? '' + }) + return counted(spelled) + .map((c) => c.name) + .filter((n) => !sameName(n, own)) +} + +/** How many spellings the line names before it counts the rest. */ +export const FILES_AS_MAX = 3 + +/** "also files as Sable Creek Const. LLC · SCC Builders", with "and 2 more" past three. Null when there is one spelling. */ +export function filesAsWords(names: readonly string[]): string | null { + if (names.length === 0) return null + const more = names.length - FILES_AS_MAX + return `also files as ${names.slice(0, FILES_AS_MAX).join(' · ')}${more > 0 ? ` and ${more} more` : ''}` +} + +/** A person named on the name's permits, and on how many. */ +export type ProfileFiler = { name: string; permits: number } + +/** The people the name's permits name beside the company, the most permits first. */ +export function filers(permits: readonly Pick[]): ProfileFiler[] { + return counted( + permits.map((p) => { + const { person, company } = contactParts(p.contact) + // A line that is a person alone is the builder itself, not someone who files for it. + return company ? (person ?? '') : '' + }), + ) +} + +/** "Dana Whitlock, on 4 of the 5." */ +export function filerWords(f: ProfileFiler, permits: number): string { + return `${val('person', f.name)}, on ${val('on', String(f.permits))} of the ${val('of', String(permits))}.` +} + +// ---------- who they use ---------- + +export type ProfilePlumbers = { + /** The jobs whose plumbing permit names a plumber. */ + named: number + /** The jobs with a plumbing permit that names nobody the feed can tell from the builder. */ + unnamed: number + /** Each plumber by its jobs, the most first. */ + list: PlumberJobs[] + /** Null under three named jobs: too few to judge. */ + tie: BuilderTie | null +} + +export function plumbersUsed(permits: readonly Pick[]): ProfilePlumbers { + const names = permits.map((p) => (p.plumber ?? '').trim()).filter((n) => n !== '') + const list = plumbersCounted(names) + return { + named: names.length, + unnamed: permits.filter((p) => plumbingOnFile(p) && (p.plumber ?? '').trim() === '').length, + list, + tie: names.length >= TIE_MIN_JOBS ? tieOf(list[0]?.jobs ?? 0, names.length) : null, + } +} + +export const TIE_WORDS: Record = { uses_one: 'One plumber nearly every time.', leans: 'Leans to one plumber.', shops: 'Shops around.' } + +/** How many plumbers the sentence names before it counts the rest. */ +export const PLUMBERS_NAMED_MAX = 3 + +/** "Lone Oak Plumbing on 5 of the 7 jobs that name a plumber. Tri-County Mechanical on 2." The tie's words are the screen's to add. */ +export function plumbersUsedWords(p: ProfilePlumbers): string { + if (p.named === 0) { + if (p.unnamed > 0) return `A plumbing permit is on ${val('unnamed', String(p.unnamed))} of their jobs, and none names the plumber.` + return 'No plumbing permit on any of their jobs yet.' + } + const [first, ...rest] = p.list + if (p.named === 1) return `${val('plumber', first?.name ?? '')} on the one job that names a plumber.` + const out = [`${val('plumber', first?.name ?? '')} on ${val('jobs', String(first?.jobs ?? 0))} of the ${val('named', String(p.named))} jobs that name a plumber.`] + for (const next of rest.slice(0, PLUMBERS_NAMED_MAX - 1)) out.push(`${val('plumber', next.name)} on ${val('jobs', String(next.jobs))}.`) + const others = rest.slice(PLUMBERS_NAMED_MAX - 1) + if (others.length > 0) out.push(`${val('others', String(others.length))} more on ${val('jobs', String(others.reduce((n, o) => n + o.jobs, 0)))}.`) + return out.join(' ') +} + +// ---------- the four tiles ---------- + +/** "1st", "2nd", "3rd", "4th", "11th", "22nd". */ +export function ordinal(n: number): string { + const tens = n % 100 + if (tens >= 11 && tens <= 13) return `${n}th` + return `${n}${n % 10 === 1 ? 'st' : n % 10 === 2 ? 'nd' : n % 10 === 3 ? 'rd' : 'th'}` +} + +/** One tile: the number, the words under it, and a second line where there is one. */ +export type ProfileTile = { key: 'open' | 'share' | 'plumbers' | 'bids'; big: string; words: string; more: string | null } + +/** + * The four numbers at the top. The share tile leads with dollars; a name whose permits declare + * nothing leads with its permits, and says why. + */ +export function profileTiles(row: Pick, share: BuilderShare, jobs: number, plumbers: ProfilePlumbers): ProfileTile[] { + const permitsLine = `of the permits · ${ordinal(share.permitsRank)}` + const shareTile: ProfileTile = + share.dollarsShare == null || share.dollarsRank == null + ? { key: 'share', big: shareWords(share.permitsShare), words: permitsLine, more: 'No value declared on their permits.' } + : { key: 'share', big: shareWords(share.dollarsShare), words: `of the dollars declared · ${ordinal(share.dollarsRank)}`, more: `${shareWords(share.permitsShare)} ${permitsLine}` } + return [ + { key: 'open', big: String(jobs), words: `${pluralNoun('job', jobs)} open now`, more: null }, + shareTile, + { key: 'plumbers', big: String(plumbers.list.length), words: plumbers.named === 0 ? 'plumbers named on their permits' : `${pluralNoun('plumber', plumbers.list.length)} on ${plumbers.named} ${pluralNoun('job', plumbers.named)} that name one`, more: null }, + { key: 'bids', big: String(row.bids), words: `${pluralNoun('bid', row.bids)} from us in two years`, more: null }, + ] +} + +// ---------- us and them ---------- + +/** "No bid in two years." or "5 priced, 3 won in two years, the last on Aug 26." */ +export function ourBidsLine(row: Pick, todayYmd: string): string { + if (row.bids === 0) return 'No bid in two years.' + return `${val('bids', ourBidsWords(row))} in two years${row.last_bid_on ? `, the last on ${val('last', reachDay(row.last_bid_on, todayYmd))}` : ''}.` +} + +/** "No mark." or "Marked Good by Dana: pays on time." */ +export function markLine(row: Pick): string { + if (row.mark == null) return 'No mark.' + const reason = (row.mark_reason ?? '').trim().replace(/[.\s]+$/, '') + return `Marked ${val('mark', row.mark === 'good' ? 'Good' : 'Avoid')}${row.mark_by_name ? ` by ${row.mark_by_name}` : ''}${reason ? `: ${reason}.` : '.'}` +} diff --git a/src/lib/research/permitBuilders.ts b/src/lib/research/permitBuilders.ts index 99cec2b1ea..6dbc6ac67e 100644 --- a/src/lib/research/permitBuilders.ts +++ b/src/lib/research/permitBuilders.ts @@ -378,8 +378,8 @@ const REASON_WORDS: Record = { np_not_this_builder: 'not this builder, after a look', none: 'no reason given', } -/** A pass reason as the count words it. A second look writes `sl_` and the reason (permitSecondLook). */ -function passReasonWords(code: string | null | undefined): string { +/** A pass reason as the count words it, and as a company's profile does. A second look writes `sl_` and the reason (permitSecondLook). */ +export function passReasonWords(code: string | null | undefined): string { const c = code ?? 'none' if (!c.startsWith('sl_')) return REASON_WORDS[c] ?? c const base = c === 'sl_none' ? null : REASON_WORDS[c.slice(3)] diff --git a/src/lib/research/permitResearchIo.ts b/src/lib/research/permitResearchIo.ts index 6345ae37a8..6daabcd946 100644 --- a/src/lib/research/permitResearchIo.ts +++ b/src/lib/research/permitResearchIo.ts @@ -231,6 +231,28 @@ export async function loadPermitsOfBuilder(city: string | readonly string[], bui return (data ?? []) as SitePermit[] } +/** + * One name's commercial building permits of twelve months with where each stands with us (punch list #465): + * the tab's own read, a city at a time, held to the name's key. So a company's profile says a job's place by + * the rule every list here uses. The read works a city's permits out before it keeps the name's, so it is + * asked only of the cities the name files in. + */ +export async function loadBuilderStanding(cities: readonly string[], builderKey: string, todayYmd: string): Promise { + const since = ymdPlusDays(todayYmd, -BUILDER_PERMIT_DAYS) + const doing = "read this builder's jobs" + type Narrowed = PromiseLike> & { range(from: number, to: number): Narrowed; eq(column: string, value: string): Narrowed } + try { + const lists = await Promise.all( + cities.map((city) => + fetchAllRows((from, to) => (supabase.rpc('research_permits_v4' as never, { p_city: city, p_since: since, p_residential: false } as never) as unknown as Narrowed).eq('builder_key', builderKey).range(from, to), doing), + ), + ) + return lists.flat() + } catch (e) { + failed(e, doing) + } +} + /** The count since a day. Null before the migration is pushed. */ export async function loadPermitFunnel(city: string, sinceYmd: string): Promise { const { data, error } = await supabase.rpc('permit_funnel' as never, { p_city: city, p_since: sinceYmd } as never) diff --git a/src/lib/research/permitsLink.test.ts b/src/lib/research/permitsLink.test.ts index 48b517a140..fa8f12ec08 100644 --- a/src/lib/research/permitsLink.test.ts +++ b/src/lib/research/permitsLink.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from 'vitest' -import { lookAlikesHref, marketHref, permitsLinkCleared, permitsLinkForView, permitsLinkSheetOpen, permitsLinkViewOf, permitsLinkWithLooks, permitsLinkWithSheet, readPermitsLink } from './permitsLink' +import { builderProfileHref, lookAlikesHref, marketHref, permitsLinkCleared, permitsLinkForView, permitsLinkSheetOpen, permitsLinkViewOf, permitsLinkWithBuilder, permitsLinkWithLooks, permitsLinkWithSheet, readPermitsLink } from './permitsLink' const params = (search: string) => new URLSearchParams(search) describe('lookAlikesHref', () => { it('opens Builders with the chip on, in the city named', () => { expect(lookAlikesHref('San Antonio')).toBe('/prospects?tab=permits&view=builders&looks=1&city=San+Antonio') - expect(readPermitsLink(params(lookAlikesHref('San Antonio').split('?')[1] ?? ''))).toEqual({ builders: true, market: false, place: null, looks: true, city: 'San Antonio' }) + expect(readPermitsLink(params(lookAlikesHref('San Antonio').split('?')[1] ?? ''))).toEqual({ builders: true, market: false, place: null, looks: true, city: 'San Antonio', builder: null }) }) it('names no city when none is given, or one the pull does not read', () => { @@ -17,17 +17,17 @@ describe('lookAlikesHref', () => { describe('readPermitsLink', () => { it('opens on Skim with no chip when the address asks for nothing', () => { - expect(readPermitsLink(params('tab=permits'))).toEqual({ builders: false, market: false, place: null, looks: false, city: null }) + expect(readPermitsLink(params('tab=permits'))).toEqual({ builders: false, market: false, place: null, looks: false, city: null, builder: null }) }) it('reads Builders, the chip and the city', () => { - expect(readPermitsLink(params('tab=permits&view=builders'))).toEqual({ builders: true, market: false, place: null, looks: false, city: null }) - expect(readPermitsLink(params('tab=permits&view=builders&looks=1&city=austin'))).toEqual({ builders: true, market: false, place: null, looks: true, city: 'Austin' }) + expect(readPermitsLink(params('tab=permits&view=builders'))).toEqual({ builders: true, market: false, place: null, looks: false, city: null, builder: null }) + expect(readPermitsLink(params('tab=permits&view=builders&looks=1&city=austin'))).toEqual({ builders: true, market: false, place: null, looks: true, city: 'Austin', builder: null }) }) it('reads no chip off Builders, and no city the pull does not read', () => { expect(readPermitsLink(params('tab=permits&looks=1')).looks).toBe(false) - expect(readPermitsLink(params('tab=permits&view=ledger&looks=1'))).toEqual({ builders: false, market: false, place: null, looks: false, city: null }) + expect(readPermitsLink(params('tab=permits&view=ledger&looks=1'))).toEqual({ builders: false, market: false, place: null, looks: false, city: null, builder: null }) expect(readPermitsLink(params('tab=permits&view=builders&city=Kyle')).city).toBeNull() }) }) @@ -48,7 +48,7 @@ describe('Market on the address (punch list #405)', () => { it('opens Market, in the city named', () => { expect(marketHref('Austin')).toBe('/prospects?tab=permits&view=market&city=Austin') expect(marketHref(null)).toBe('/prospects?tab=permits&view=market') - expect(readPermitsLink(params('tab=permits&view=market&city=austin'))).toEqual({ builders: false, market: true, place: null, looks: false, city: 'Austin' }) + expect(readPermitsLink(params('tab=permits&view=market&city=austin'))).toEqual({ builders: false, market: true, place: null, looks: false, city: 'Austin', builder: null }) }) it('keeps Market on the address without the chip, which is Builders’ own', () => { @@ -66,6 +66,32 @@ describe('permitsLinkWithLooks', () => { }) }) +describe('a company’s profile rides the address on Builders (punch list #465)', () => { + it('opens Builders with the name’s key, and reads it back', () => { + expect(builderProfileHref('sablecreekconstruction')).toBe('/prospects?tab=permits&view=builders&builder=sablecreekconstruction') + expect(readPermitsLink(params('tab=permits&view=builders&builder=sablecreekconstruction'))).toEqual({ builders: true, market: false, place: null, looks: false, city: null, builder: 'sablecreekconstruction' }) + }) + + it('is read only on Builders, and an empty key is none', () => { + expect(readPermitsLink(params('tab=permits&builder=abc')).builder).toBeNull() + expect(readPermitsLink(params('tab=permits&view=market&builder=abc')).builder).toBeNull() + expect(readPermitsLink(params('tab=permits&view=builders&builder=%20')).builder).toBeNull() + }) + + it('opens over the list and closes back to it, and the chip is the list’s', () => { + expect(permitsLinkWithBuilder(params('tab=permits&view=builders&looks=1'), 'abc').toString()).toBe('tab=permits&view=builders&builder=abc') + expect(permitsLinkWithBuilder(params('tab=permits'), 'abc').toString()).toBe('tab=permits&view=builders&builder=abc') + expect(permitsLinkWithBuilder(params('tab=permits&view=builders&builder=abc&kind=sub'), null).toString()).toBe('tab=permits&view=builders&kind=sub') + }) + + it('leaves with Builders: another view drops it, and so does another tab', () => { + expect(permitsLinkForView(params('tab=permits&view=builders&builder=abc'), 'builders').toString()).toBe('tab=permits&view=builders&builder=abc') + expect(permitsLinkForView(params('tab=permits&view=builders&builder=abc'), 'market').toString()).toBe('tab=permits&view=market') + expect(permitsLinkForView(params('tab=permits&view=builders&builder=abc'), null).toString()).toBe('tab=permits') + expect(permitsLinkCleared(params('tab=follow-up&view=builders&builder=abc')).toString()).toBe('tab=follow-up') + }) +}) + describe('permitsLinkCleared', () => { it('leaves nothing of the Permits tab’s own on the address', () => { expect(permitsLinkCleared(params('tab=follow-up&view=builders&looks=1&city=Austin&kind=sub')).toString()).toBe('tab=follow-up&kind=sub') diff --git a/src/lib/research/permitsLink.ts b/src/lib/research/permitsLink.ts index 7d49294904..2739cb42ed 100644 --- a/src/lib/research/permitsLink.ts +++ b/src/lib/research/permitsLink.ts @@ -2,7 +2,8 @@ * Prospects → Permits on the address (punch list #307): the Needs you line *names on permits look * like a customer* opens Builders with the **Looks like a customer** chip already on, in the city * that has some. Builders and the chip ride the address, so a reload comes back to them. Market - * rides it the same way (punch list #405). The + * rides it the same way (punch list #405). A company's profile rides it on Builders (punch list #465): + * `builder` is the name's key, so a profile has an address of its own and Back leaves it. The * city is taken once when the tab opens and remembered by the browser from there, as every city * a person picks is. No React, no Supabase. */ @@ -11,6 +12,7 @@ import { permitCity } from '../../../supabase/functions/_shared/permitCities' const VIEW = 'view' const LOOKS = 'looks' const CITY = 'city' +const BUILDER = 'builder' /** * The views of the Permits tab that ride the address. Every other view opens from Skim. The three places an @@ -39,11 +41,13 @@ export type PermitsLink = { looks: boolean /** The city to open in, when it is one the pull reads. */ city: string | null + /** The key of the name whose profile is open. Only on Builders. */ + builder: string | null } export function readPermitsLink(params: URLSearchParams): PermitsLink { const builders = params.get(VIEW) === 'builders' - return { builders, market: params.get(VIEW) === 'market', place: PLACE_OF[params.get(VIEW) ?? ''] ?? null, looks: builders && params.get(LOOKS) === '1', city: permitCity(params.get(CITY))?.name ?? null } + return { builders, market: params.get(VIEW) === 'market', place: PLACE_OF[params.get(VIEW) ?? ''] ?? null, looks: builders && params.get(LOOKS) === '1', city: permitCity(params.get(CITY))?.name ?? null, builder: builders ? (params.get(BUILDER) ?? '').trim() || null : null } } /** Builders with the **Looks like a customer** chip on, in a city when one is named. */ @@ -54,6 +58,11 @@ export function lookAlikesHref(city: string | null | undefined): string { return `/prospects?${params.toString()}` } +/** A company's profile: Builders, with the name's key. It reads every city, so it names none. */ +export function builderProfileHref(builderKey: string): string { + return `/prospects?${new URLSearchParams({ tab: 'permits', [VIEW]: 'builders', [BUILDER]: builderKey }).toString()}` +} + /** Market, in a city when one is named. */ export function marketHref(city: string | null | undefined): string { const params = new URLSearchParams({ tab: 'permits', [VIEW]: 'market' }) @@ -64,15 +73,18 @@ export function marketHref(city: string | null | undefined): string { /** * The address for the view on screen: Builders and Market say so, and any other view (`null`) - * drops the key. The chip stays only on Builders. The city is dropped either way: the tab took - * it when it opened. + * drops the key. The chip and an open profile stay only on Builders. The city is dropped either + * way: the tab took it when it opened. */ export function permitsLinkForView(params: URLSearchParams, view: PermitsLinkView | null): URLSearchParams { const next = new URLSearchParams(params) next.delete(CITY) if (view) next.set(VIEW, view) else next.delete(VIEW) - if (view !== 'builders') next.delete(LOOKS) + if (view !== 'builders') { + next.delete(LOOKS) + next.delete(BUILDER) + } return next } @@ -84,10 +96,24 @@ export function permitsLinkWithLooks(params: URLSearchParams, on: boolean): URLS return next } +/** + * The address with a company's profile open, or with it closed (`null`). A profile lives on Builders, so opening + * one says so. The chip is the list's, so an open profile drops it. + */ +export function permitsLinkWithBuilder(params: URLSearchParams, builderKey: string | null): URLSearchParams { + const next = new URLSearchParams(params) + if (builderKey) { + next.set(VIEW, 'builders') + next.set(BUILDER, builderKey) + next.delete(LOOKS) + } else next.delete(BUILDER) + return next +} + /** The address with nothing of the Permits tab's own on it: the tab opens on Skim when its name is pressed. */ export function permitsLinkCleared(params: URLSearchParams): URLSearchParams { const next = new URLSearchParams(params) - for (const key of [VIEW, LOOKS, CITY]) next.delete(key) + for (const key of [VIEW, LOOKS, CITY, BUILDER]) next.delete(key) return next } diff --git a/to-dos/prospects-profiles/README.md b/to-dos/prospects-profiles/README.md index 5e29766504..217ce4b58a 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 · step 1 built 2026-12-02 in two PRs: the migration (v2.9261, `research_builders_v2`, pushed to prod on 2026-12-03) and the client (v2.9263, the two shares as bars, headings that sort, the three chips, *All five cities*) +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 built 2026-12-02 in two PRs: the migration (v2.9261, `research_builders_v2`, pushed to prod on 2026-12-03) and the client (v2.9263, the two shares as bars, headings that sort, the three chips, *All five cities*) · step 2's page built 2026-12-02 (v2.9266): a company's profile on an address of its own, opened from a name on Builders, with the other five ways in still to build 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 2, a company's profile. Step 1's migration (v2.9261) is on prod and its client is v2.9263. After the client's deploy it owes a look: time the first draw on *All five cities*, and hold three names' dollars to the Ledger. +next: The other five ways into a profile (step 2's last piece), then step 3. Step 1's migration (v2.9261) is on prod, its client (v2.9263) merges first, and step 2's page (v2.9266) after that client. Each owes a look after its deploy: time the first draw on *All five cities* and of a profile, and hold three names' dollars to the Ledger. 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 @@ -151,6 +151,8 @@ Smallest first. Each step is one pull request with its release note and its frag - **The migration is pushed** (2026-12-03, 04:21 UTC), read back by `npm run check:migration-drift`. - **Left to do:** the client's look after its deploy. The *Companies or People* switch is step 4's. 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. + - **The page is written** (v2.9266, 2026-12-02): `builderProfile.ts`, `PermitBuilderProfile`, the address `view=builders&builder=`, and the first way in, a name on Builders. Where it differs from the drawing is said in `docs/recent-features/v2.9266.md`: a job is open while no plumbing permit sits on it, the chips use the tab's own words, plumbers are counted on the jobs that name one, and the press *Call about all 5 jobs*, *Never called* and *Also files for 2 other companies* wait for steps 3 and 4. + - **Left to do:** the other five ways in. Each is a link to `builderProfileHref`. 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. 5. **Who holds the work (S).** The ten bars and the sentence, on Market beside the plumbers' part.