MaintStock Build Notes
How MaintStock is put together, where every piece lives, how to sign in to each one, and how to change, release, back up, or rebuild it without help. Written for Chris and anyone he brings in to help. Updated for version 26.1, Dec 5, 2026.
The short version
MaintStock is a website that phones add to their home screen. It has four parts:
| Part | What it does | Where it lives | Who signs in |
|---|---|---|---|
| The app files | The screens and all the logic. Plain HTML, CSS, and JavaScript. No build step. | The private GitHub repository topherbear8742/shop-stock (the main branch is what's live). | Nobody; they are just files |
| GitHub | Keeps every version of the files, runs the automatic tests on each change, and hands main to Netlify. | github.com/topherbear8742/shop-stock | Chris's GitHub account |
| Netlify | Publishes main to maintstock.com by itself after every merge (about a minute). Also the domain registrar for maintstock.com. | app.netlify.com | Chris's Netlify account |
| Supabase | The database, the sign-in system, photo storage, and the low-stock alert sender | supabase.com/dashboard, project shop-stock | Chris's Supabase account |
Everything a tech does goes from their phone straight to Supabase. Netlify only serves the files. If Netlify went down, phones that already have the app keep working. If Supabase went down, scans save on the phone and sync later.
Accounts and how to get in
No passwords are written here. Keep them in a password manager.
| What | Address | Notes |
|---|---|---|
| The app | https://maintstock.com/ | Each person signs in with their own email and password. Owners manage people on the Team tab. |
| Demo | https://maintstock.com/demo/ | Sample data on the visitor's device. No account needed. |
| Help pages | https://maintstock.com/help/ | Manual, troubleshooting, what's new, and these notes. No account needed. |
| GitHub | https://github.com/topherbear8742/shop-stock | Private. Every change is a pull request; the Tests check must be green before merging. Merging to main goes live. |
| Netlify | https://app.netlify.com | Site super-strudel-4e464c, linked to the GitHub repository (publish directory "."). Each pull request gets a Deploy Preview link. The old address https://super-strudel-4e464c.netlify.app still works. |
| Domain | Netlify, under Domains | maintstock.com was bought through Netlify on Oct 19, 2026. It renews yearly on the card in Netlify billing. Let it lapse and the app goes offline at that address. |
| Supabase | https://supabase.com/dashboard | Project shop-stock, reference id ocmzqdenveflbbcgjzpo, URL https://ocmzqdenveflbbcgjzpo.supabase.co |
Adding helpers:
- GitHub: add them as a collaborator on the repository (Settings, Collaborators). They open pull requests; Chris (or the developer) merges. On a personal GitHub account every collaborator gets full Write access: they could push straight to main, which goes live, so only add people Chris trusts with the live app. (Ray is a collaborator; Chris chose on 2026-11-07 to leave his access as it is.)
- Netlify: the free plan allows only one member. Helpers don't need Netlify; merging on GitHub deploys.
- Supabase: Organization, Team, Invite, role Developer. Developers can work in the database but can't change settings or billing.
- The app: add their email on the Team tab.
Free plan limits to know:
- Supabase pauses a free project after about a week with no activity. Daily use keeps it awake. If it's paused, open the project in Supabase and tap Restore project.
- Email limits: sign-in emails go through Resend (custom SMTP, see Signing in below), which allows 100 emails a day and 3,000 a month on its free plan.
- Supabase photo storage holds 1 GB on the free plan.
- Netlify makes new sites private. If visitors see "This site is private", go to Project configuration, General, Visitor access, and set production to Public.
The repository, file by file
Everything below is in the GitHub repository topherbear8742/shop-stock (clone it, or open it on github.com).
shop-stock/
index.html every screen (tabs, sheets, sign-in)
styles.css colors and layout, light and dark
app.js all app logic (scanning, offline queue, labels, reports, equipment, pool, help)
itemtypes.js the list of part types (Plumbing, HVAC...), supplier category matching and the guess from a part name (24.25)
gl.js GL codes: search, the code on each part and on Reorder, loading the coding guide (24.74)
poolchem.js pool chemistry math (doses from test results)
mmreport.js fills in the mold & moisture form PDF (where each answer goes on the page)
hvac.js HVAC troubleshooter: every check, answer and tool (edit NODES to change a check)
appliance.js Appliance tab: range, dishwasher and fridge checks, parts links, repair or replace, parts email
pm.js PM tab: units, plan, due list, and the scheduling (starterPlan is the starting plan)
makeready.js Make Ready tab: the whiteboard of apartments being turned, and Fill in from a photo or sheet (Excel/CSV import, 24.14)
supabase/functions/read-board reads a whiteboard photo with the Anthropic API (the AI key stays in Supabase secrets)
requests.js Help > Ideas and problems (feature requests)
today.js Today screen, Search everything, Unit history, and the Contacts tab (version 23.0)
files.js the one ZIP writer and CSV cell rule (Backup, on-call Excel, unit photo export, every CSV download; 24.98)
units.js unit-number examples in each property's format, for every unit box (24.83)
ctimport.js Contacts Import sheet: reads .xlsx/CSV into contacts (version 24.13)
unitgear.js the equipment card on Unit history, and the Appliance tab's Save to the unit's equipment (24.12); Appliances by unit (24.66)
city.js City complaints tab: city notices, deadlines, reinspections, photos, print, CSV and sheet import (24.17)
activity.js Activity > Everything: what each person did, by date (version 24.4)
i18n.js the language switch: swaps on-screen English for Spanish as it appears
i18n-es.js the Spanish word list (English -> Spanish); loads only when Español is picked
i18n-ksw.js the S'gaw Karen word list (24.36, short draft); loads only when Karen is picked, demo only for now
insp-report.js unit inspection items (edit ITEMS to change the inspection) and its PDF
finder.js Find unit tab: each property's buildings on a satellite map, GPS, Walk there (edit PROPERTIES)
oncall.js On call tab: this week, who's next, the year, the draft and Publish (24.35)
mileage.js Mileage tab: each person's monthly sheet and Send to the property manager (24.43)
mileage-form.js StoneCreek's mileage form math and spreadsheet; an exact copy is in supabase/functions/send-mileage/
region.js Regional screen, new-property setup checklist, Copy a parts list (24.38)
othershops.js Other shops: which other properties have a part, with Call buttons (25.15)
tips.js mouse-over tips on a computer (24.48)
upc.js barcode lookup on Add item (24.47); one key for any form of a box code (24.89)
handouts/ printable PDFs for owners (Team tab); their sources and render.js in handouts/source/
forms/mold-moisture.pdf the official NAA form (Revised 8.07.19), exactly as issued; never edit it
forms/mold-moisture-original.pdf an identical spare copy of the same form
config.js Supabase address and public key (safe to be public)
theme.js applies the Light/Dark choice before a page draws (app, demo and guides)
vendor/ the libraries the app uses, kept on our own site (see below)
_headers browser safety rules Netlify sends with every page (see below)
sw.js service worker: keeps the app on the phone so it opens with no signal
manifest.webmanifest name and icons for "Add to Home Screen"
icon.svg, icon-192.png, icon-512.png
netlify.toml tells Netlify never to cache sw.js, and not to serve tests/, docs/, tools/, .github/ or handouts/source/
maps/, hvac/ the property site maps (Find unit) and the HVAC wiring diagrams (standing pilot PDF, fan center picture)
privacy/ the privacy policy page
screenshots/ wide screenshots for the install prompt (manifest.webmanifest)
navtest/ Android bottom-bar test pages (keep them on the site)
AGENTS.md, CLAUDE.md short rules for AI coding agents
tests/ the automatic tests (see Automatic tests; not served on the site)
README.md developer overview and where every document is
CHANGELOG.md every version: what changed, its commit, pull request and tag
CONTRIBUTING.md the rules for making and releasing a change
docs/ developer documents: handoff, architecture and database, settings, releasing, backups (not served on the site)
docs/ray-scan-kit/ a separate, MIT-licensed scanning and stock kit made for Ray's own website; not part of the app
tools/ release and backup scripts and their tests (not served on the site)
demo/index.html copy of index.html for the demo (see Demo)
demo/demo.js fake database with sample data, used only by the demo
help/*.md sources of the help pages (manual, install guide, troubleshooting, release notes, build notes)
help/*.html the help pages, built from the .md files
help/guide.css styling for the help pages
help/guide.js Copy buttons and the Print link on the help pages
help/build.py turns help/*.md into help/*.html
help/img/ example screenshots for the manual and quick start (made by tools/screenshots.js)
supabase/schema.sql the whole database: run it to rebuild from nothing
supabase/functions/low-stock-push/ source of the alert sender (index.ts, webpush.js, board.js)
supabase/functions/send-mileage/ emails a mileage sheet to the property manager (index.ts, mileage-form.js) (24.43)
supabase/functions/lookup-upc/ asks UPCitemdb about a box barcode for the phone (24.47)
supabase/functions/send-report/ source of the report emailer (index.ts)
supabase/functions/send-welcome/ source of the welcome email (index.ts, welcome.ts)
supabase/functions/first-login/ first-time sign-in and forgotten passwords: codes, the welcome link, My details (24.45)
supabase/functions/_shared/signin.ts the welcome link token and sign-in codes, shared by send-welcome and first-login
supabase/reports.sql the reports tables and storage (version 17); also at the end of schema.sql
supabase/properties.sql report properties (version 21.5): report_settings.properties; also at the end of schema.sql
supabase/oncall.sql reports-only logins (version 21.6): staff role 'reports', is_member(); also at the end of schema.sql
supabase/inspections.sql unit inspections (version 18): kind column, inspection email and filter sizes; also at the end of schema.sql
supabase/pm.sql preventative maintenance (version 19): units, pm_tasks, pm_log; also at the end of schema.sql
The libraries the app uses are copies kept in the vendor folder, taken unchanged from the official npm packages:
- supabase-js 2.45.4 (vendor/supabase-2.45.4.js, from dist/umd/supabase.js)
- qrcode-generator 1.4.4 (vendor/qrcode-generator-1.4.4.js)
- jsPDF 3.0.4 (vendor/jspdf-3.0.4.umd.min.js)
- ZXing 0.21.3 (vendor/zxing-0.21.3.min.js, from umd/index.min.js)
- pdf-lib 1.17.1 (vendor/pdf-lib-1.17.1.min.js, from dist/pdf-lib.min.js), loaded only when a report PDF is made
Keeping them on our own site means no other website can change the code the app runs. The service worker keeps a copy of each one, so the app opens offline. To update a library, replace its file, change the name in index.html, demo/index.html and the SHELL list in sw.js, and test.
Browser safety rules (_headers): Netlify sends these with every page. They tell the browser to run scripts only from maintstock.com, to refuse to show the app inside another website's frame, and to let the app talk only to https sites and Supabase. Inline scripts and onclick attributes are blocked, so all code goes in .js files. If a new outside service is ever added (a new font host, a new script), it has to be allowed in _headers or the browser blocks it. In Chrome, the console (F12) says "Refused to load" when that happens.
How the app works inside
- Signing in: Supabase email and password. Being signed in isn't enough. The email must also be on the staff table (the Team tab). Every database rule checks is_staff().
- Saved on the phone:
- The parts list, equipment, and pools, so the app opens instantly and works with no signal.
- The offline queue: scans, counts, and pool tests that are waiting for signal.
- Each phone's own choices: scan mode, label type, and appearance.
- Scans are safe to repeat. Every scan gets a unique id. The database function apply_op ignores an id it has already seen, so a phone that resends after losing signal never double-counts. Equipment uses equip_op the same way. Pool tests use the id as their key.
- No answer counts as no signal (24.62).
withTimeout()rejects withcode: "offline", so a change that gets no answer in 10 seconds waits in the queue and is sent again (safe, because of the id above), instead of being dropped. flushQueue() removes each sent change from the list as it is in storage right then (byopId), never by writing back the copy it read before sending, so a scan made mid-sync isn't lost. - Live updates: Supabase Realtime pushes changes to items, equipment, stock_log, and pools to every open phone. Since 24.27 each phone listens only to its own shop (
filter: property=eq.<shop>; deletes can't be filtered and stay unfiltered), and a burst of changes redraws the screen once (renderSoon()). - Phone alerts (low stock, and Make Ready changes since 24.6; see "Make Ready alerts" below):
- When a scan drops a part below its keep-on-hand level, the app calls the low-stock-push edge function, which sends a phone notification to everyone who turned alerts on.
- The signing key for those notifications comes from the project's service key, so there is no extra secret to store.
- If the service key is ever rotated, alerts stop. Everyone must turn alerts off and on again in Help.
- Labels are drawn in the browser as a PDF with jsPDF. LABEL_FORMATS in app.js lists every label size. To add a size, add one line there.
- Camera scanning uses the phone's built-in barcode reader on Android, and ZXing on iPhone and computers.
- Pool doses come from poolchem.js:
- Chlorine, calcium, stabilizer, and baking soda are straight math from product strength and gallons.
- Acid and soda ash use a carbonate chemistry model, so the pH dose depends on alkalinity and stabilizer.
- Products are keyed (
liquid125,trichlor90,muriatic31...) and a pool saves its keys inpools.products(chlorine, acid, calcium, shock). To add a product, add it toPRODUCTSand a name pattern toMATCHin poolchem.js, plus its Spanish name in i18n-es.js. PoolChem.inParts()matches product keys to the shop's part names, so Edit pool lists that property's own chemicals first (24.30). Slow products (tablets) never shock: the pool's shock product does.
The database (Supabase)
| Table | Holds |
|---|---|
| staff | Who can sign in, and their role (owner or tech) |
| items | One row per part: name, bin, supplier, part number, keep on hand, on hand, on order, codes, photo, type (category, 24.25) |
| stock_log | Every take out, put away, return, count, order, and undo, with who and when |
| equipment | One row per loaner unit and its current status |
| equipment_log | Every equipment check-out and check-in |
| pools | Each pool's size, products, and target ranges |
| pool_tests | Every saved pool test with its doses |
| push_subs | Phones that turned on phone alerts |
| mr_alerts | Make Ready changes waiting to be sent as alerts (24.6) |
| alert_prefs | Each person's notification choices: Make Ready (24.6) and, since 24.91, chat, low stock, Friday reorder, on-call and mileage |
| units | Each apartment unit, its building and furnace filter (PM tab) |
| pm_tasks | The preventative maintenance plan (PM tab) |
| pm_log | Every PM visit: done or couldn't do (PM tab) |
| city_complaints | City notices, their deadlines, reinspections, fines and photos, per property (24.17) |
Functions:
- apply_op (scans)
- equip_op (equipment)
- is_staff and is_owner (used by every rule)
- check_setup (the read-only report behind Help > Run setup check)
Other pieces:
- Storage bucket: item-photos (public to view, team members can upload).
- Edge function: low-stock-push.
- Row Level Security is on for every table, so only team members can see or change anything. Only owners can change the Team list.
Where to look in the Supabase dashboard:
- Table Editor: view or fix rows.
- SQL Editor: run SQL.
- Authentication, Users: sign-in accounts.
- Storage: photos.
- Edge Functions: the alert sender and its logs.
- Database, Publications: live updates.
Settings that must stay this way:
- Authentication, URL Configuration:
- Site URL is https://maintstock.com
- Redirect URLs include https://maintstock.com/** and https://super-strudel-4e464c.netlify.app/**
- Password reset links depend on these.
- Database, Publications, supabase_realtime: includes items, equipment, stock_log, and pools.
Making a change and releasing it
No build tools are needed to change the app. Any text editor works (VS Code is free). The extra tools are Git, Python (rebuilds the help pages) and Node (runs the tests).
- Get the files: clone the repository (
git clone https://github.com/topherbear8742/shop-stock) or pull the latest main, and make a new branch for the change. - Make the change in the files.
- Open app.js and raise the version number on this line near the top:
const VERSION = "23.3 (Oct 26, 2026)";
- Open sw.js and change the cache name to match the new version:
const CACHE = "shop-stock-v23.3";
The two must change together, or phones won't pick up the update.
5. Add a section at the top of help/release-notes.md describing the change for the team (Help > What's new), and an entry at the top of CHANGELOG.md for developers, under ## [Unreleased], like ## [23.9] - 2026-10-28 - Title. The Release rules check fails if either is missing.
6. If index.html changed, copy it over demo/index.html, then make the demo edits again: add <base href="../"> right after <head>, change the title to MaintStock Demo, point the License link at ../, take out the Try the demo link and the supabase-js script line, and take out the config.js script line. Then put the scripts in the demo's order, with <script defer src="demo/demo.js"></script> in the middle (the scripts after it need the fake database): theme.js (the only one without defer, so the dark theme shows before anything draws), i18n.js, tips.js, vendor/qrcode-generator, files.js, units.js, pm.js, makeready.js, city.js, requests.js, itemtypes.js, upc.js, region.js, demo/demo.js, poolchem.js, ctimport.js, oncall.js, today.js, unitgear.js, activity.js, app.js. Every script but theme.js has defer (24.63; deferred scripts still run in this order). hvac.js, appliance.js, finder.js, mileage-form.js, mileage.js, insp-report.js and mmreport.js aren't in either page: app.js loads them when their screen first opens (needScript()), and Leaflet's stylesheet comes with Find unit. A new script goes in the same place as in index.html, before demo.js only if it doesn't use the database when it loads. Compare with the old demo/index.html to check nothing else moved.
7. If any help/*.md file changed, rebuild the help pages. On a computer with Python, run these two commands from inside the shop-stock folder (on Chris-PC, C:\Users\Chris\Mainststock). The first one is needed only once. On Windows type py; on a Mac or Linux type python3 instead.
py -m pip install markdown==3.11.2
py help/build.py
- Test on the computer: from inside the shop-stock folder, run the command below (Mac or Linux:
python3 -m http.server 8000), then open http://localhost:8000/demo/ in Chrome and try the change. The demo uses fake data, so nothing real is touched.
py -m http.server 8000
Add these to the end of the address to test special cases: ?shop=demo-oaks (you're at the second property, Sample Oaks: test every change there too), ?viewonly (a view-only login) and ?big (1,200 parts). This simple server doesn't send the safety rules in _headers, so a blocked script only shows up in the automatic tests or on the Deploy Preview.
9. Run the automatic tests (see Automatic tests below). They tap through every screen of the demo and list anything broken.
10. Deploy: commit, push the branch and open a pull request on GitHub. The quick Tests check (about 2 minutes) and the Release rules check run by themselves, and Netlify posts a Deploy Preview link to try. When every check is green, merge the pull request: Netlify publishes main to maintstock.com within a minute or two. GitHub then tags the version (v23.9 and so on), saves it under Releases with its CHANGELOG entry, and backs up the database for it. The full rules are in CONTRIBUTING.md and docs/RELEASING.md in the repository.
11. On a phone, open the app with signal (or switch back to it). It updates by itself within a few seconds; Help shows the version. Check for update on the Help tab forces it.
To undo a bad release fast, open Netlify Deploys, click the previous deploy, and choose Publish deploy. Phones go back on their next open. Then revert the pull request on GitHub (its Revert button), so the next merge doesn't bring the bad change back. The revert still needs a new, higher version number. Any older version can be looked at or downloaded exactly as it was from GitHub Releases (every version from 21.6 on).
Release rules check: tools/check-release.mjs, run on every pull request. It fails if the VERSION in app.js and the CACHE in sw.js don't match, if the version has no CHANGELOG.md or release-notes.md entry, if app files changed without a new version, if the version went down, if the help pages weren't rebuilt, or if a key or password was added. To run it before pushing: node tools/check-release.mjs --base origin/main.
Automatic tests
The tests/ folder holds a robot tester. It opens the demo (fake data only) in a hidden Chrome window, taps every button on every screen as a phone and as a computer, types odd things into boxes, presses Back on every window, checks the app still opens with no signal, checks the Help links, and times how fast things load on a slow phone. It writes a report sorted into Bugs, Acts strangely, Easier to use and Faster.
It runs by itself on GitHub (the Tests checks). A pull request runs only the quick part (file checks, feature steps, offline and help, about 2 minutes), to stay within GitHub's free Actions minutes (since 2026-10-31). After a merge to main, or with Actions > Tests > Run workflow, GitHub runs everything, split across six machines at the same time (phone taps and computer taps, each in two halves, layout and speed, and everything else), so it takes about 4 minutes; each part is its own check. A red check means it found a Bug; open the check, then Summary, to read the list, and download that part's test-report for the full page with screenshots. Only Bugs turn the check red. The other three lists are suggestions.
To run it on a computer, install Node.js (free, nodejs.org), then from the shop-stock folder run these once:
cd tests
npm install
npx playwright install chromium
Then, from the tests folder, run:
npm test
It takes 10 to 15 minutes (npm run test:quick takes about 5) and writes tests/report/index.html; open it in Chrome. To test a live site or a Netlify deploy preview instead of the files on the computer:
npm test -- --url https://maintstock.com
The tests never touch the real database: they use the demo, and anything trying to reach Supabase is blocked.
Feature checks: besides tapping at random, features() in tests/harness.js walks through features step by step and fails if a step doesn't do what it should (the Properties tab from version 22.17; Today, Search everything, Unit history, Contacts and Español from 23.0; Contacts import from 24.13; vendor details and Copy from another property from 24.58; staff and property manager contacts from 23.1; turning screens off from 23.2). Every new feature adds its own steps there. To run only those (under a minute):
npm test -- --only features
Terms of Use (version 24.65)
Everyone agrees to the Terms of Use (terms/index.html, maintstock.com/terms/) once per version, right after signing in.
- App side: app.js "Terms of Use (24.65)":
TERMS_VERSION,checkTerms()(called fromstartSignedInonce the Team row is known),termsSend(). The screen is#terms-gatein index.html and demo/index.html (keep both the same). It sits above everything (z-index 60) and has only I agree and Sign out. - Where it's saved: on the phone (
ss-terms,{ email: { v, at, sent } }) and in the database withaccept_terms(p_version, p_device)intoterms_acceptances(supabase/terms.sql). No signal, or the table isn't there yet: it's saved on the phone withsent: falseand sent on the next start. Before showing the screen the app asks the database whether this person already agreed on another phone. - Changing the terms: edit
terms/index.html, then change both its "Version" line andTERMS_VERSIONin app.js to the new date. Everyone is asked again. Spelling fixes don't need a new version. Have a lawyer look at big changes. - Who agreed: in the Supabase SQL Editor:
select email, accepted_at from terms_acceptances where version = '2026-11-11' order by accepted_at;. Owners can read their own property's people; nobody can change or delete a row. - Safety notes:
.safety-notelines at the top of HVAC (hvac.jsheader()), Appliance repair (appliance.jsheader()) and Pool (index.html). They point to section 3 of the terms. - Demo: skipped unless the address has
?terms(the harness uses/demo/?terms).
Changing the database
- In Supabase open SQL Editor.
- Paste the SQL and tap Run.
- Add the same SQL to the end of supabase/schema.sql with a comment saying what it's for, so a rebuild includes it.
- For a new table, also add the view_only_guard trigger (see View-only logins) so view-only logins can't change it.
- For a new table, also turn on Row Level Security with is_staff() rules like the other tables. Add the table to the lists inside check_setup so Run setup check watches it.
- For a new table, also add grant lines in the same SQL. Since Oct 30, 2026 Supabase no longer opens new tables to the app on its own, and without grants the app gets "permission denied for table ...". Use these, with your table's name in place of new_table:
sql
grant select, insert, update, delete on public.new_table to authenticated;
grant select, insert, update, delete on public.new_table to service_role;
Give anon (signed-out visitors) nothing. Leave out insert, update or delete for authenticated if the table should only be written by a database function, like stock_log. supabase/schema.sql already has these grants for every existing table, so a rebuild works.
Never edit on_hand or on_order by hand in Table Editor. Use Count in the app so the change is logged.
Setting up report email
Mold & moisture reports (version 17) are emailed by the send-report function in Supabase, through Resend (resend.com). Resend's free plan sends 3,000 emails a month and 100 a day, from your own maintstock.com address. The steps are in the Version 17 setup steps file that came with the release, and in short:
- Run supabase/reports.sql in Supabase SQL Editor.
- Make a free Resend account and add the domain maintstock.com.
- Add the DNS records Resend shows in Netlify, under Domains, maintstock.com, DNS settings.
- Make a Resend API key with Sending access.
- In Supabase open Edge Functions, then Secrets, and add the secret RESEND_API_KEY with that key.
- In the app, set Reports, Report settings, and send yourself a test.
Since version 24.71 Send several reuses a report's last emailed PDF (from report_emails) when the report hasn't changed since, and makes the others 3 at a time.
Since version 24.70 every real send is also copied (CC) to the property's Contacts whose kind is Property manager, Assistant property manager or Maintenance supervisor and who have an email (staffCc() in the function and in app.js).
Since version 24.69 the function also takes several reports in one call, { reports: [{ report_id, pdf_path }, ...], test } (up to 10), and sends them in one email when they all go to the same people; the Reports tab's Send several groups them by recipient first. Older versions of the function answer a batch with "Missing report.", so deploy it after a release that changes it.
The function's source is supabase/functions/send-report/index.ts. To redeploy it, in Supabase open Edge Functions, then send-report, then Code, paste the file, and tap Deploy. To send from a different address, add the secret REPORT_FROM, for example MaintStock Reports <reports@maintstock.com>. The address's domain must be verified in Resend.
How a report is stored: table mm_reports (one row per report: the answers in data, the photo list in photos, sent_at and sent_to), table report_emails (one row per email sent, written only by the function), table report_settings (one row: property, PM, CC), and the private storage bucket report-files (photos and every emailed PDF, under mm/report id/). Team members can add and update reports but can't delete them or their files. The blank form is forms/mold-moisture.pdf, and mmreport.js knows where each answer goes on it. If the lender sends a new revision of the form, the positions in mmreport.js have to be measured again.
Reports per property, camera rollback (version 24.33)
- Reports tab per property:
repShop()/repHere()in app.js. A report's property isdata.propertyId, else the row'sproperty(the insert trigger copiespropertyIdintoproperty).loadReports()reads only that property; drafts and Today's counts userepHeretoo. The read rule frommm-shared.sql(23.5) still lets every member read every mold report, so Unit history, Search and Activity filter the same way on screen. - Camera: the 24.31 in-app camera (
photoCamera()) is gone because it had no zoom. Report photo buttons click a file input withcapture="environment"again. Android's camera app may open on the last camera used; that's the trade-off Chris chose.
Activity and search per property (version 24.32)
- Read rules aren't enough to keep a screen to one property. The admin can read every property's
activity_log,board_readsandfeature_requests; everyone reads their ownactivity_logrows from any property; any member reads everyreport_emailsrow and every mold & moisture report. A screen that's meant to show one property must also filter bystate.propertyitself (skip it whenstate.propertyisall, the on-call phone). activity.jshere()adds.eq("property", ...)to every source.report_emailshas no property:select("*, mm_reports!inner(property)")and.eq("mm_reports.property", ...)filter it by its report. The property is in the reload key.today.jsSearch everything and Unit history drop reports whose property (data.propertyId, then the row'sproperty) isn't the shop you're in.- The demo at
?shop=demo-oaksmarks its sample history as Demo Apartments, so the harness can tell the two apart (secondProperty()).
Inspections: back camera, Filter list, Incomplete (version 24.31)
- (Removed in 24.33.) Report photos use an in-app camera.
photoCamera()in app.js opens#photo-camwithgetUserMedia({ facingMode: { exact: "environment" } })(thenideal, for a laptop with only a front camera), and returns a JPEG Blob,null(Cancel or Back) or"app".capture="environment"on a file input is only a hint: Android passes it to the camera app, which opens on the last camera used. The capture input is kept for Camera app. Used by inspection item photos, General photos and mold report Take photo. The photo camera has its own history entry, so Back closes only it;overlayOpen()includes it. - Filter list (
filterListSheet(),filterTotals(),filterParts()): readsmm_reportswherekind = 'insp'throughfetchAll(), selecting only JSON paths (pid:data->>propertyId,filter:data->items->filter...), so photos and signatures aren't downloaded. A unit's latest inspection wins (date, thenupdated_at). Units are matched case-insensitively. Parts match when the name has "filter" and the size with no digit on either side, only in the shop you're in. - Typed sizes are kept:
keepTypedSize()runs after every inspection save and callsaddFilterSize()(the 24.16add_filter_sizeRPC) when an Other size is valid and not on the property's list yet. - Incomplete is
InspReport.INCOMPLETEinPRIMARY; the reason isdata.incompleteWhy.InspReport.incomplete(d)is used by the form, the email check and the PDF. No database orsend-reportchange.
Efficiency rules (version 24.27)
Found in the 24.27 code review; follow them in new code.
- The database sends at most 1,000 rows per read (Supabase API "max rows").
.limit(5000)quietly returns 1,000. Anything that can pass 1,000 rows goes throughfetchAll()(app.js;C.fetchAllin modules), which reads 1,000 at a time. - Paged reads need an order that never ties. End the order on the table's key:
id, orop_idfor stock_log, equipment_log, pool_tests and pm_log. Ordering only byatornamelets a row fall on two pages or none. - Read in parallel. Independent reads at start-up go out together (
loadAll()), so opening the app waits for one round trip, not four. - Live updates redraw through
renderSoon(), neverrender()per row, so a bulk change doesn't freeze other phones. - Read rules check the shop once per query.
supabase/rls-speed.sql(24.27, waiting for Chris's go-ahead) usesproperty = (select public.my_shop())instead ofpublic.in_shop(property), which ran a staff lookup for every row (19.5 ms vs 0.5 ms for one Items load). New tables should use the same form for their read rule once it's applied. - The demo behaves like the database: it caps reads at 1,000 rows and honors live-update filters, and
/demo/?bigadds 1,200 filler parts and 1,100 scans of one, so the harness catches paging mistakes. - The service worker was network-first until 24.63; see the next section for why cache-first doesn't mix versions.
Make Ready steps that need confirming (version 25.12)
- What: each step in
mr_board.columnshasconfirm(true or false). Only a step withconfirmturns red when its date passes and it isn't done, leads its window with Done today, and blocks 100% ready until it's done or not needed. A step without it (scheduled out to a vendor) counts as taken care of once it has a date. - Older boards: a board saved before 25.12 has no
confirm;cleanCols()inmakeready.jstreats theprepkey (or a label starting with "Prep") as true and every other step as false. Saving Edit steps writesconfirmon every step. - Per property:
mr_boardhas one row per property (primary keyproperty), so each property keeps its own. No SQL change: the column is jsonb, andmr_alert_note()only reads each step'skeyandlabel. - Code:
stepClear(),isDue()andstepsDone()inmakeready.js(exported onMR.core). Tests:vendorSteps()intests/harness.js, at both demo properties. - Only owners and managers change vendor steps (26.1). Chris: "Managers make the make ready, and only they change vendors." In
render()a step withconfirmfalse is a plainspan.mr-ro(no button) for anyone withoutboardManage(), andstepSheet()refuses it with a message. The database matches:supabase/vendor-steps.sqladdsmr_vendor_step(property, key)(the same rule ascleanCols():confirmfalse, or noconfirmand not Prep; a key no longer on the board counts as a vendor step), andmr_set_stepand themr_dates_guardtrigger refuse a vendor step change from anyone who isn't an owner or manager at that property. The demo'smr_set_stepdoes the same. Tests: the 24.68 tech walk-through (both demo properties and Leasing) and the manager check.
Late syncs, Undo and sign-out (version 25.11)
- Late counts (
apply_opinsupabase/sync-fixes.sql): a scan is "late" when its time is more than 2 minutes before the database gets it (so a phone clock a little off changes nothing). A late count adds the take-outs, put-aways, returns and undos logged after its time; a late count older than the part'slast_countedonly goes in Activity; a late scan made beforelast_countedis logged with its change but doesn't move on hand again. - Undo names what it takes back: take-outs and put-aways keep their op id and every Undo sends it as
p_of(kept instock_log.undoes).stock_log.order_deltais how much each change moved On order, so undoing New stock puts that back. A second undo of the same op does nothing. Withoutsync-fixes.sqlthe app dropsp_ofand works the old way. - Saved scans wait for the sign-in:
classifyScan()keeps a scan in the queue when it was refused because the sign-in ran out or the database timed out, and refreshes the sign-in. Other refusals are dropped and named, as before. - Catching up:
catchUp()sends the queue and reads what changed when the app comes back on screen after a minute, when signal returns, and when live updates reconnect (at most every 30 seconds). - Updates: a service worker install that couldn't download an app file fails and deletes its half-filled cache, so the working version stays until the next try.
- Phone alerts: Sign out removes this phone's
push_subsrow and unsubscribes; at start-up a phone whose subscription isn't the signed-in person's is unsubscribed.
Weak signal and smaller updates (version 24.63)
- App files open from the phone first. Everything in
SHELL(sw.js) is served from the saved copy; the network is only asked when a file isn't saved yet. Versions can't mix: each release has a newCACHEname, the new worker saves the whole new version before it takes over, andapplyUpdate()waits for it to take over (up to 25 seconds) before reloading. Help > Check for update and the automatic update work as before. - Updates download only what changed. The install asks for each file with the old copy's ETag; Netlify answers
304 Not Modifiedfor an unchanged file. Libraries invendor/(version in the file name) are kept inshop-stock-filesand never asked for again, so a new library version needs a new file name. Maps, diagrams, forms and icons live there too and are checked the same ETag way.i18n-es.jsis inSHELL, so Spanish works on the first offline start after an update. - Code for occasional screens loads when they open (
needScript()in app.js): HVAC, Appliance (also fetched in the background a few seconds after start-up, for appliance ages on Unit history), Find unit (with Leaflet and its stylesheet), Mileage (also at start-up when a sheet still has to be sent), and the report PDF makers. All other scripts havedefer. ctimport.js still loads at start-up: Contacts, Make Ready, City and On-call check for it to show their Import buttons. - Start-up doesn't wait on the network. Your Team row is saved on the phone (
ss-me), so the app opens on your last screen and starts live updates before the database answers; the fresh row still follows. The parts read has a 20-second limit before the rest of start-up carries on. PM's plan isn't read when PM is turned off for the property. Saved reports load when Reports, Today, Contacts or Properties shows them; start-up reads only the report settings. - Less data after a sync. Refresh reads only parts changed since the last read (
updated_at, minus 10 minutes for phone clocks; the whole list again on each app open or after 6 hours). After saved scans are sent, only the parts they touched are read again. Item photos are warmed once per app open. A live update that changes nothing (this phone's own scan echoing back) doesn't redraw, and a scan redraws throughrenderSoon(). - Typing stays quick. Items search and the Scan box's suggestions wait for a 150 ms pause; each part's search text is lowercased once (
itemHay()); the Items pickers and counts rebuild only when parts change; a long list shows 100 parts and a Show 100 more button. Report drafts are kept in memory and written to the phone 400 ms after typing stops, and at once when the app is hidden or closed. - Smaller report photos: 1280 px on the long side at JPEG quality 0.6 (
REPORT_PHOTOin app.js), about a third of the size of the old 1600 px / 0.82. - Saved scans are sent every 20 seconds only while the app is on screen, and straight away when it comes back.
Shop map editor on phones (version 24.26)
Walls use var(--fg) (24.24 used an undefined var(--text), invisible in dark theme). Each wall has a transparent .sm-hit rect around it as a finger-sized target. New and copied pieces are placed by place() so they don't pile up; the selected piece has position boxes (feet from the left and top), Copy and Done with this one. Save map upserts and keeps the editor open; Close asks for a second tap if anything is unsaved.
Don't stock (version 24.79)
Chris: "make it so I can choose to no longer stock an item. Both from items and reorder." dontStock(it) in app.js sets par to 0 with setPar() (an items update, so it needs signal), keeps on_hand, and the toast's Undo restores the old par. needOf() is 0 for any part with par 0, so it leaves To order and never comes back on its own. Buttons: Don't stock on each To order line (.ro-nostock) and Don't stock this part (#f-nostock) on the part's window when par > 0. No database change; it's the same "keep 0 = not stocked" rule Quick count's Don't stock uses (24.59). Tests: in otherSuppliers().
Other suppliers (version 24.78)
Chris bought Kilz from Chadwell and Westlake, so it was two parts with two counts and two bin labels. He wants one part and the supplier picked at reorder, Chadwell by default.
- Database (
supabase/other-suppliers.sql, also at the end ofschema.sql):items.alt_suppliersjsonb, a list of{supplier, part}(check: an array, 10 at most), read and written under the existing items rules.merge_items(p_keep, p_drop)is security definer: refuses view-only logins and anyone who isn't the property's owner or the admin, needs both parts atmy_property(), then addsp_drop's main and other suppliers top_keep.alt_suppliers(no blanks, no repeats, neverp_keep's main one), unionscodes, addson_handandon_order, keeps the higherparand laterlast_counted, fills an empty photo, bin and notes, movesstock_log.item_idrows, and deletesp_drop. Theactivity_trailtrigger logs the update and the delete. - App (
app.js, "one part, several suppliers"):suppliersOf(it)is the main supplier thenaltSuppliers.orderFrom(it)is what Reorder uses: a pick instate.roSup(localStoragess-ro-sup, cleared when the part is on neither list) or the main supplier.groupBySupplier(),orderText(),saveCsv()andreceiveSheet()useorderFrom.orderFromPick()is the Order from select, only on parts with 2+ suppliers.otherSuppliersField()on the part's window adds or removes one by hand withsetAlts();toRow()never sendsalt_suppliers, so editing a part works without the column.dupesSheet()(Items > Tools, owners) pairs parts from different suppliers by word overlap (likeness()≥ 0.4, small words like oz and pk left out) and puts Chadwell first;mergeSheet()asks which listing stays (Chadwell preselected) and calls the RPC. If the column or function is missing, the message namessupabase/other-suppliers.sql. - Take photo (same release): the photo field has two hidden file boxes,
accept="image/*"(Pick photo) and the same withcapture="environment"(Take photo, phones only,TOUCH). Android 14+ shows its photo picker for the first, which has no camera. - Demo:
/demo/?dupesadds a Chadwell caulk that matches the Westlake one;demo.jsanswersmerge_items. Tests:otherSuppliers()in tests/harness.js at both properties (npm test -- --only suppliers).
Faster counting (version 24.59)
Chris was the only shop using inventory, and counting 574 parts one at a time wasn't happening. Three shortcuts, all in app.js, none needing a database change: each one saves a normal count (apply_op, type count, so it queues offline and shows in Activity), and keep-on-hand is the existing items.par.
- Quick count (
quickCountSheet(), Items > Tools): Out = 0; Low =lowCount(par)=min(par - 1, ceil(par / 2)), so the part is always below keep and lands on To order; Plenty =max(par, on hand); Exact count = typed; Don't stock =par0 and count 0 (a counted part with keep 0 is how "not stocked" shows). A part with keep 0 getskeepPicker()before Out/Low/Plenty; No level saves the count without one. Settingpar(setPar()) is an items update, so it needs signal like editing a part. - Count when you touch it (
touchCountSheet()):takeOut()calls it when the part has nolast_counted. It closes the camera, asks 0-10 or More, and (keep 0 only) a keep level. Once a part has a count it's never asked again; Not now is remembered in memory until the app reloads. - Running-low cards: the card's QR holds
LOW:plus the part's SS- code.handleCode()sends it tolowCardScan()in every mode, which counts the part as Low unless it's already below keep (then a toast says nothing changed). The camera closes after a card because the code isn't inbyCode.lowCardsSheet()prints them through the normal label flow withlineset (so no bin/part line and no photo). - The Items filter Not counted lists parts with no
last_counted. - Bin labels (24.77): Chris: "Make bin labels for everything in the shop. I want to be able to scan them to do item counts... Merely focused on speed." One label per part, QR
CNT:plus the part's SS- code (binLabel(), made withlineset, so no photo).handleCode()sendsCNT:tobinLabelScan()in every mode. 24.80: in Take out,binLabelScan()callstakeOut(it, 1, { fromBin: true })instead, whose message adds Count instead (undo, thenfastCountSheet()), andonCameraCode()keeps the camera open as for a part label; new labels sayTAKE OR COUNT. 24.81: Chris: "I think scanning a part in take out should just ask how many you are taking."actOn(id, { ask: true })(every scan, a typed code + Enter, and the shelf-label part list) openstakeSheet(): chips 1-10, a text box (#tk-qty, text so a USB scan landing there becomes the next scan; Enter on empty takes 1), Cancel, Count instead (bin labels), Take. Tapping a search suggestion still callstakeOut(it, 1).onCameraCode()now always closes the camera and passescamAgain, so the camera reopens after the take. Chris: "It is going to be too much work entering manually, on top of having to print and label each and every item that doesn't have one." Receive delivery's Label the new parts says parts in a labelled bin need none.fastCountSheet()is one empty text box (inputmode="numeric", nottype="number": a USB scan landing in a number box reads as 0) with Save, Same (saves on hand as the count) and Cancel. Digits save a normalcountop; anything else saves nothing and goes tohandleCode()as the next scan. When the label came from the camera,onCameraCode()passescamAgainand the camera reopens after the save. No database change. - Tests:
countShortcuts()in tests/harness.js, at both demo properties on a 360 px phone (npm test -- --only counts). In the demo, Drain auger and Rekey pins start never counted. 24.77 adds the bin-label checks there (24.80: Take out takes one and Count instead puts it back; then in Count, Enter, a code in the box, Same, an unknown part, the Print labels option).
Set up bins and map walls (version 24.24)
Items > Tools > Set up bins (binSetupSheet in app.js) lists parts with a bin box each and saves items.bin one part at a time as you leave the box, the same way Count list saves counts. tidyBin turns "k2-5" into "K2-05". The shop map layout JSON has a third kind, "wall" (no name or label, can be 0.5 ft thin), drawn as a solid bar; cleanMap keeps it. No database change.
Part photos on labels (version 24.23)
Labels print the part's photo (items.photo) at the right end when the label type has room (labelPhotoSize in app.js: the name and bin must keep 25 mm). For label printers the app turns the photo into black and white dots itself at 300 dots per inch (Atkinson dithering in labelPhoto), because the Brother prints black only and its print drivers make gray pictures muddy. Sheets get a small gray JPEG. Photos are fetched when the PDF is made, so it needs signal; a photo that can't be fetched just leaves that label without one. Photos stored in the item-photos bucket always work. A pasted link from another site only works if that site allows it (CORS). The Print part photos checkbox is remembered per phone (localStorage ss-labelphotos).
Pictures in the guides (version 24.22)
The pictures in the manual and on page 2 of the quick start guides are made by tools/screenshots.js from the demo (never the real database), on a phone-sized screen: help/img/
node tools/screenshots.js
py help/build.py
(On a Mac or Linux: python3 help/build.py.)
node handouts/source/render.js
You can retake just some by name (node tools/screenshots.js today scan); the names are in the SHOTS list at the top of the script. To add a picture to the manual, put a line like
on its own after a paragraph; two lines together show side by side, and the text in the brackets becomes the caption. In a handout, an img with src="SHOT/today" gets the picture when render.js runs. The test harness fails if a picture the manual or a handout names is missing.
Buttons and info look different (version 24.21)
Everything you can tap uses three colors from the top of styles.css: --btn-bg (a tint, light purple in the new look), --btn-line (an edge) and --btn-fg (the text), each set for light and dark. Cards, lists and information rows use --surface and --line. A new kind of button should use the btn variables (or just the class btn) so it never looks like information; a list row that opens something should be a button with class row, which gets the › by itself. The test harness checks this on the Help tab in both themes.
Boxes, links and the phone menu bar (version 24.28)
The shared box style in styles.css lists every typed input type (text, number, search, password, email, tel, url, date, month, time, datetime-local) plus select and textarea. A new input type that isn't on that list shows the browser's own gray box, so add it there. Plain links use a { color: var(--accent) }; links styled as buttons use a.btn.
Since 24.99 the menu bar is the rooms (.roombar, see Main menu below). Since the new look it sits along the bottom and its buttons are a fixed 64 px tall, so it never changes height, and the harness's "Boxes, links and menu bar" check measures it on several screens.
Main menu: five rooms (version 24.99)
Chris: "It's super busy and im having trouble finding things." Every screen lives in exactly one room, and the rooms never move.
ROOMSin app.js: Home (Today), Shop (Scan, Reorder, Items, Equipment), Units (Make Ready, PM, Find unit, Appliances by unit, Reports, City complaints, Resident notices), Guides (HVAC, Appliance, Pool, Help), People (Chat, Contacts, On call, Mileage).OFFICE: Activity, Team, Regional, Properties, only in the menu button. A new screen that's in no room lands in Office, so nothing goes missing. To move a screen, change these lists and the manual's Getting around.nav.tabsis still in index.html but never shown. It's the list of screens:applyOff()and the role code hide its buttons, and the rooms, the room pages and All screens only show screens whose tab button isn't hidden.#tab-<view>buttons still work as links (document.querySelector("#tab-pm").click()).renderBar()draws.roombar(five buttons,data-room,data-viewslists the screens it holds, badge = the first screen badge in the room) andrenderSub()draws#room-sub, the row of the current room's screens at the top ofmain.- Room pages are ordinary views:
#view-room-shopetc.,setView("room-shop").renderRoom()lists the room's screens asbutton.row, with the line fromTODAY.status()(today.js: the Today cards turned into one line per screen; tonealertshows in red) or theTAB_INFOline. Opening one runsTODAY.show()so the counts are loaded. - The menu button
#gear-openopensmoreSheet()("All screens"): rows grouped by room then Office, Find a screen (TAB_WORDS), Recent (ss-recent-views).
New look (26.0)
Chris picked every part side by side in light and dark (2026-11-22). The look is in one block at the end of styles.css ("25.8: Chris's new look", the name it was built under) plus the colors and fonts at the top.
- Colors: accent Amethyst
#7851a9(dark mode#bba0df, with dark text on it). Purple only for the open room, main buttons, the property name and the logo; everything else neutral. Shared green--in#17786b(dark#62c9b4) and red--danger#b0234a(dark#f48aa4) were picked to sit with it. Change all three color blocks in styles.css (light,prefers-color-scheme: dark,[data-theme="dark"]) and help/guide.css together. - Fonts: Public Sans and IBM Plex Mono, loaded by theme.js (not the help guides).
- Top bar:
#top-home(logo, goes Home),#top-prop(renderTopProp(): property switch with a chevron, or plain name),#top-title(renderTitle()).#synconly says View only. - Bottom menu:
.roombaris appended tobodyand fixed to the bottom; Home isn't on it. Icons areROOM_ICONSin app.js drawn withsvgIcon(). In-app browsers (Facebook, Gmail) may cover it with their toolbar, which is why 24.99 had it at the top; Chris chose the bottom anyway. - Buttons and lists:
.btn.primaryis an outline; pressed.modebuttons are filled;.listrows are boxes;#room-subchips are underlined. - Logo files: icon.svg, icon-mark.svg, icon-mark-dot.svg and the PNG icons are purple. A new manifest icon needs its
?v=raised so phones fetch it.
Count asks the same way too (version 25.4)
Chris picked "One count box for every scan". The stepper countSheet() window is gone: countSheet(it, camAgain) now just calls fastCountSheet(), so a part label, a bin label, a search tap and Items' Count all open the same box. fastCountSheet() gained buttons 0-10 (aria-label "Count 7", one tap saves) above the text box. onCameraCode() passes camAgain for any known part in every mode, so the camera reopens after a count too. The count message no longer offers Print N labels (bin labels replace part labels). Checks: countShortcuts() "a part label in Count" (both demo properties). No database change.
Returned, new stock or count in Put away (version 25.18)
Parked during the feature freeze (Nov 21) and built when it ended (Chris, Dec 5: "Build both parked ideas"). Amy and Ron only put back unused parts; Chris puts away deliveries. Since 25.3 a bin label in Put away opened the put-away window on New stock, so a return logged with one tap lowered On order (an order still coming looked received) and was left out of suggested levels, which net return against out. putAwaySheet(it, { fromBin: true }) now shows a three-button row, group label "Returned, new stock or count?" (data-kind return, in, count). It starts on return when it.onOrder is 0 and on in when an order is coming, so a marked-ordered delivery still puts away with one tap. count closes the window (qtySheet() now returns close) and opens fastCountSheet(), replacing the bottom Count instead button in Put away (Take out keeps it). A part label, box barcode or search tap still starts on New stock with the two-button row. Per property with no setting: it only reads the part's own On order. Checks: countShortcuts() (both demo properties): three buttons, starts on Returned with nothing on order, Enter returns 1, New stock + 3, Count opens the count without changing stock, and starts on New stock after an order is marked (through the demo client, so the live update reaches the app). No database change.
Take out and Put away ask the same way (version 25.3)
Chris: "Why does taking out a part have a different procedure than putting away. They should both be easy to understand." qtySheet(it, o) in app.js is the one how-many window: thumb photo, an info line, an optional top (Put away's New stock / Returned switch), buttons 1-10 (aria-label "Take 3" / "Put away 3", one tap saves), extra buttons (Put away: #pa-order "All N on order", #pa-pack "1 pack (N)"), a text box (Enter on empty saves o.def(); a non-number goes to handleCode() as the next scan), Cancel, Count instead (bin labels), and the big button. takeSheet() (#tk-qty, #tk-go, default 1) and putAwaySheet() (#pa-qty, #pa-go, default 1: Chris, "scan the bin label in put away to put away a single part, just like take out"; Returned hides the extra buttons) both call it. binLabelScan() sends a CNT: label to putAwaySheet(it, { fromBin: true }) in Put away (it used to open fastCountSheet()); only Count opens the count. actOn() lost its ask option: a search-suggestion tap asks too, in both modes. onCameraCode() passes camAgain for any known part outside Count, so the camera reopens after a put-away. The old stepper put-away window and its "+1 pack" are gone. Checks: countShortcuts() (both demo properties) "Put away asks the same way". No database change.
One unit box on Scan (version 25.1)
Scan used to have two unit boxes: 24.66's Unit # + Go (TODAY.unitBox("sc"), prepended to #view-scan) and 24.38's For unit (#forunit, Take out only). Now only #forunit is left, under the mode buttons, in every mode. renderForUnit() in app.js sets data-mode on the box: out in Take out (saves take-outs to state.forUnit, repeat-call note, #forunit-open "Open unit 2601 ›"), look in Put away, Count and for Reports-only logins (#forunit-go or Enter opens TODAY.unitHistory, state.forUnit isn't shown or changed). Placeholder and keyboard come from UNITS.fit. Checks: features() "Parts per unit" and "Unit # box".
Calmer look (version 25.0)
Stage 2 of the redesign (stage 1 is Main menu above). Based on the mockups Chris picked, with the design rules from Impeccable (Operate mode: clear hierarchy, familiar controls) and Hallmark's floor (no labels in tracked capitals), used as reading only.
- No capitals: headings, the menu, the Scan mode buttons, list headings and the All screens rows are in normal case (
text-transform: uppercaseis left only on the logo and the DEMO ribbon). The harness's "Calmer look" check fails if any h2, h3, menu button, mode button or room chip is in capitals. - Home (today.js
render()): Unit #, search, Do these first, then At a glance (#td-cards, a.listofbutton.row.td-cardrows,data-cardas before; name,.td-subline, number in.num b), then the Unit photos buttons.card()builds the rows;status()still readsband.td-sub. Red (.alert) only when something is late; there is no green any more. - Buttons keep the 24.21 rule (blue tint and edge for anything you tap): fewer of them on Home is what makes it calmer, not a new button color.
Screen sizes (version 24.51)
Chris: "I need this to have responsive design." MaintStock is one layout that adapts; there is no separate phone or desktop site.
- Page width:
--pagein styles.css (:root) sets the width of the header row, the tab bar andmain: 900 px, and 1320 px from 1000 px wide. A phone or tablet uses the whole screen. - Menu bar: since 24.99 the same five buttons at every size (see Main menu). Before, a phone had 4 buttons + More and a computer showed every tab in wrapped rows.
- Two-column lists: from 1000 px, a
main .listwhose children are all.rowand that has at least 4 rows shows two columns. Lists with day or type headings (Activity, Items sorted by type) or Team groups stay one column so they read in order. Lists inside windows stay one column. - Windows:
.sheetis 560 px wide, 640 px from 1000 px. Nothing in a window may be wider than it: grid columns areminmax(0, 1fr)(plain1frgrows to fit its widest box, which pushed windows 20-60 px past a 320 px phone: two date boxes side by side, "Sample Oaks" on a property button), and.sheet-body > *,.field,.grid2 > *and every input getmin-width: 0..grid2and.oc-datesstack to one column at 360 px or less. - Make Ready board:
fitBoard()(makeready.js) adds.mr-cardsto.mr-wrapwhen the screen is 700 px or less or the table is wider than the board, and re-checks with a ResizeObserver whenever the board's width changes (window resized, tablet turned, tab shown). The card styles are the 24.11 phone ones, also written as.mr-cards ...rules. - Harness:
__hx.fits(scope)lists sideways page scroll, things poking off the screen or cut off by their box, a window wider than the screen, and a vertical-scrolling box (window body) that also scrolls sideways. Boxes that scroll sideways on purpose are skipped (nav,.tablewrap,.table-wrap,[data-hscroll]).responsive()(--only responsive, run after each merge) checks every screen at 320, 412, 768, 1024, 1366 and 1920 px at both demo properties (fits, squeezed words, tab bar, page width from 1000 px), and opens each screen's windows at 320 px (both properties), 768 and 1366 px.screenSizes()runs on every pull request: small-phone windows, tablet tabs and board cards, laptop width, two-column Items, the board table, and the switch to cards when the window is made narrow, at both properties. - When you add a screen: check it at 320 px and 1920 px (
node tests/harness.js --only responsive --quick). Useminmax(0, 1fr)in grids,min-width: 0on flex and grid children that hold text or inputs, and wrap a table that must scroll sideways in.table-wrap.
Rows with a number box on phones (version 24.46)
A number box inside a row needs a selector stronger than the shared box rule (input[type="number"] is width 100%, and wins over a lone class), or it stretches across the row and crushes the text beside it to a few letters a line. Use .parent input.myclass (Suggested levels: .sugrow input.sug-in; Reorder and Print labels: .pickrow .qty).
- Suggested keep-on-hand (
suggestSheet()): each part is a.sugrowcard, top to bottom:.name,.meta(bin, part #),.sug-set(checkbox labeled Change to, the.sug-inbox, "now N"),.meta.why. - Reorder and Print labels (
.pickrow: checkbox, item row,.ro-qty): at 520 px wide or less.ro-qtydrops under the item row (styles.css media query), so names and photos get the width. - Harness:
__hx.squished(scope)lists text with more lines than words or a 4+ line column under 5 letters wide. The phone crawl runs it on every window, the layout pass on every screen, andsuggestLayout()checks Suggested levels at both demo properties on a 360 px phone.
Welcome email (version 24.20)
When an owner adds someone on the Team tab, the app calls the send-welcome edge function, which emails that person how to start, through Resend (the same RESEND_API_KEY as report email). Owners can send it again from Change under a person's name, in English or Spanish.
- Source: supabase/functions/send-welcome/index.ts (checks and sending) and welcome.ts (the email's words and canWelcome(), the rule for who may send it; no imports, so tools/test/welcome.test.mjs runs it under Node).
- Who can send: an owner who isn't view only, to someone on the Team list at a property they manage (the admin and anyone with all properties: everyone). The address always comes from the staff table, so it can't email anyone else.
- What it says: the person's own property name (report_settings.properties by staff.property; never a fixed property), a Set up my password button (24.45, see First-time sign-in), home screen steps, links to the quick start PDF, manual, install guide and troubleshooting. It attaches handouts/MaintStock-Quick-Start.pdf (Spanish: MaintStock-Guia-Rapida.pdf) and handouts/MaintStock-User-Guide.pdf, fetched from the live site; if a fetch fails it still sends with the links. Reply-to is the owner who sent it.
- Secrets: RESEND_API_KEY (required, already set for reports). Optional WELCOME_FROM (default
MaintStock <welcome@maintstock.com>) and SITE_URL (default https://maintstock.com). - Deploy: both files together, plus ../_shared/signin.ts (24.45; the CLI bundles it). With the Supabase CLI:
npx supabase functions deploy send-welcome. In the dashboard: Edge Functions, Deploy a new function, name it send-welcome, add both files, Deploy. Leave Verify JWT on. - Check it: Help, Run setup check (owners) shows Welcome email. An empty request answers "Missing email."
- People added in SQL don't get it automatically (there's no database trigger); send it from Change.
- The guides on the Help tab (Guides to save or print) are the same PDFs in handouts/, saved with saveHandout() so nothing opens outside the app. Rebuild them with node handouts/source/render.js after changing the manual or the quick start source.
First-time sign-in (version 24.45)
First time here?, Forgot password and the welcome email's Set up my password button all open one screen (#first-form): email, new password twice, then Save. Passwords are set by the first-login edge function with the admin API, never by Supabase's own confirm or reset emails.
- Source: supabase/functions/first-login/index.ts and supabase/functions/_shared/signin.ts (token, codes, contact matching and the code email; no imports, so tools/test/signin.test.mjs runs it under Node). send-welcome imports the same file to make the link.
- Welcome link:
https://maintstock.com/#setup=<token>(&lang=esopens the app in Spanish). Token = base64url JSON {e: email, s: the login's last_sign_in_at when sent, x: expiry 14 days} + "." + HMAC-SHA256 keyed with SUPABASE_SERVICE_ROLE_KEY. No table: a token dies when it expires or the login signs in (s no longer matches). Rotating the service role key kills every unused link (people then use Email me a code). - Codes:
codemakes an auth login if the staff member has none (email confirmed, no password), then emails a 6-digit code through Resend. app_metadata keeps code_hash (HMAC of login id + code), code_at and code_tries: one code a minute, 20 minutes, 5 tries.setclears them. - Code limits (24.62):
codeBlocked()in _shared/signin.ts, checked before each code email: 5 code emails per login per rolling 24 hours (app_metadatacode_sends, ms times), 15 wrong codes per login per 24 hours across all its codes (code_wrong, so a new code doesn't reset the guessing), and 60 code emails an hour for all logins together (read from every login'scode_sends). Without these, anyone could request a code every 45 seconds for a team member's email and use up the Resend sends. A good code clearscode_wrong. - Only the Team list: both
codeandsetlook the email up in staff (service role) first, so nobody else can make a login. - Check your details:
details(needs the person's own sign-in) saves staff.name and their entry in report_settings.properties[].contacts at their own property (matched by email only since 25.20; view-only logins are refused). The on-call login is skipped. The app opens it after the first sign-in and from Team > My details. - App side: app.js "first-time sign-in and forgotten passwords": showFirst(), firstCall(), myDetails(). boot() holds the app (state.holdStart) while the screen is up. The old
type=recoveryreset links still open the plain new-password form. - Deploy:
npx supabase functions deploy first-loginandnpx supabase functions deploy send-welcomefrom the repo folder (the CLI bundles ../_shared). Leave Verify JWT on: the app calls with the public anon key. Secrets: RESEND_API_KEY (already set), WELCOME_FROM (optional). - Check it: Help, Run setup check (owners) shows First-time sign-in. An empty request answers "Missing action."
- Demo: the code is always 123456 (__demoDb.first_codes); a link token ending ".demo" works.
Security pass 8 (version 25.25)
Pass 7's 60 emails a day for everyone could be used up by one login (40 report + 20 mileage emails a day, tests included, and a test goes only to the sender). Database side: supabase/security-pass-8.sql (also at the end of schema.sql).
- Tests and a fair share.
quota_take(p_kind, p_email, p_n, p_limit, p_by, p_test)(new, no defaults) checks, for the four email kinds and after the kind's own limit: test emails by this login (tests_per_login5, report and mileage tests together, one per email), emails by this login (mail_per_login40, all four kinds), test emails by everyone (tests_per_day15), then the 60 (mail_per_day). Answers:test_day,mail_login,test_all(each withlimit),mail_day. Report tests are counted fromreport_emails.test; mileage tests and the sender of welcome and order emails fromquota_holds.testandquota_holds.by_email(new columns; welcome and order holds keep the property inemailfor their own limit). Only report and mileage emails can be tests, and they always count forp_email. Live numbers when the limits were chosen: the most one login sent in any 24 hours was 35 report emails, none tests; every other login 2 or fewer; at most 2 test report emails and 1 test mileage email by one login in a day. - The old call.
quota_take(p_kind, p_email, p_n, p_limit)stays and calls the new one withp_bynull andp_testfalse (25.24 functions, and low-stock-push'slow_push/low_caller). Because neither has defaults, PostgREST picks by the arguments sent. The four email functions call the new one throughtakeMail()and fall back to the old one onPGRST202(database without pass 8). Their messages come frommailFull(q), the same words in send-report, send-mileage, send-welcome, low-stock-push and demo.js. - Places given back. send-welcome lets its hold go unless the email went; Send it now lets it go when
sendOrderEmails()sent 0 or failed; send-mileage also when the email service can't be reached. send-report already let it go in every case. - Sign-in codes. When the limits for everyone together are full, first-login's
codegives the usual answer (CODE_SENT, 200, afterpadded()) and sends nothing, for any email: an outsider could tell whether a guess tipped the count over (only team members' codes count).codesBusy()only goes to the logs now. CODE_SENT and the screen's note tell people to ask their manager for a new welcome email if no code comes. - To change a number: edit the constants in a new SQL file and the matching words in
mailFull()(the functions showq.limitfrom the database, so only the fallback number in the words changes) and demo.js. - Check it: the comment block at the end of security-pass-8.sql;
node --test tools/test/(security-pass-8, -7, -3); harnessfeatures()"Security pass 8".
Security pass 7 (version 25.24)
Resend's free plan sends 100 emails a day for everything (sign-in codes, reports, mileage, Make Ready, chat, welcome, the Friday order email and Supabase Auth's own mail). Database side: supabase/security-pass-7.sql (also at the end of schema.sql).
- Sign-in codes: 25 a day for everyone.
signin_reserve_send()keeps its arguments and addsall_day: 25 code emails in 24 hours across every login'scode_sends(on top of 5 per login a day and 60 an hour for everyone). first-login checks the same limits first (codesBusy()in _shared/signin.ts,CODES_PER_DAY_ALL); since 25.25 it answers as usual and sends nothing (see Security pass 8). Keep the two numbers the same (tools/test/signin.test.mjs checks it). - Report, mileage, order and welcome emails: 60 a day for everyone.
quota_take()keeps its arguments; forreport_email,mileage_email,order_emailandwelcomeit takes a shared lock (maintstock:mail_day) before the kind's own, checks the kind's own limit first, then counts the last 24 hours: distinct report emails inreport_emails(rows of one email shareprovider_id), runningreport_emailholds (under 15 minutes) and the other three kinds' holds. Each call is one email. Full:{ ok: false, left: 0, mail_day: true }; send-report, send-mileage, send-welcome and low-stock-push then answer 429 withMAIL_DAY_FULL(same words in all four). Not counted: Make Ready and chat emails, the scheduled Friday order email, sign-in codes and Supabase Auth mail, which share the other 40. To change a number, editmail_per_day/all_per_dayin a new SQL file (andCODES_PER_DAY_ALL). - Filter sizes.
add_filter_size(p_size)(one argument, no property check) can't be run byauthenticatedoranonany more.addFilterSize()in app.js only callsadd_filter_size(p_size, p_property)and returns the error (no property picked, or the call failed) instead of falling back. The demo refuses the one-argument call too (__demoFilterCalls,__demoFilterFailfor the tests). - Workflows. Every
uses:in .github/workflows is pinned to a full commit SHA with its version in a comment (# v4.4.0), includingsupabase/setup-cliin the backup jobs that hold the database password, service role key and backup passphrase. To update one, look up the tag's commit (git ls-remote --tags https://github.com/<owner>/<action>.git) and change the SHA and comment together. - Check it: the comment block at the end of security-pass-7.sql;
node --test tools/test/(security-pass-7, signin); harnessfeatures()"Security pass 7".
Security pass 6 (version 25.23)
Database side: supabase/security-pass-6.sql (also at the end of schema.sql); the 25.23 app works before and after it, and it needs no edge function deploy.
- Sizes. Bucket limits: report-files 16 MB, unit-photos 1 MB, city-files 2 MB, item-photos 500 KB. Each upload rule (
photo_upload_ok,report_upload_ok,unit_photo_upload_ok,city_upload_ok) keeps its old conditions and addsupload_bytes_today('<bucket>') < cap: the sum ofmetadata->>'size'of the caller's objects in that bucket created in the last 24 hours (item photos 10 MB, report files 150 MB, unit photos and city files 50 MB). The size is only known once a file is stored, so a person can go past the total by at most one file. If the app ever makes bigger files (more than 30 photos on a report, bigger photos), raise the bucket'sfile_size_limitand the cap in the same SQL file. The numbers they were picked from are in the file's header. - Item photo rules.
logos/uploads and renames needis_admin(). A folder-less name (25.21 and older phones) is taken only before 2027-01-05 00:00 Omaha time, and never whenphoto_name_clash()says it's a Windows device name or matches another photo in other capitals. Renames (the update rule's WITH CHECK) go throughphoto_move_ok(name, id): a property folder needsshop_owner(folder)or the admin and room for one more (the moved photo isn't counted), folder-less names are admin only. - Inspection property.
mm_reports_property(): forkind = 'insp'the form'spropertyId(or property name) counts only whencan_see_report(p, '')oris_admin()allows it, or there's no JWT. Otherwise new =my_property(), edit =old.property, anddata.propertyId/data.propertyare rewritten to match. Mold reports work as before. App:inspProps(d)gives the inspection's Property buttons (propPicker(d, onPick, list)); demo:inspProperty()instamp(). - Backup names.
badName()(tools/storage-paths.mjs) also refuses Windows device names and parts ending in a dot or space;caseClashes()finds names that differ only in capitals, whichstorage.mjs backupwarns about without failing. - Check it: the comment block at the end of security-pass-6.sql;
node --test tools/test/(security-pass-6, storage-names); harnessfeatures()"Security pass 6".
Security pass 5 (version 25.22)
Storage object names become file paths in the nightly backup, so they're checked on both sides. Database side: supabase/security-pass-5.sql (also at the end of schema.sql); the app works before and after it.
- Name rules.
photo_upload_ok(p_name)(item-photos):<property>/<base36 time>-<base36 random>.jpgat your own property (in_shop),logos/<property>-<base36 time>.jpg, or a folder-less[A-Za-z0-9-]name ending.jpg(photos from before 25.22 and the parts list import).report_upload_ok(p_name)(report-files):mm/<report uuid>/p-<time>-<random>.jpgormm/<report uuid>/sent-|test-<toISOString with : and . as ->.pdf. A new upload path in the app needs its pattern added to these functions (and toUPLOAD_NAMESin demo.js), or the upload is refused. The update rule on item-photos has the same patterns in its WITH CHECK. - Photo limit per property.
uploadPhoto()saves part photos understate.property + "/"(top level when the app has no properties). Each property folder holds 1,500; folder-less names share 1,500 (871 on 2026-12-05); logos 200; 40 per person a day. - storage.mjs.
objectFile()intools/storage-paths.mjsis the only way an object name becomes a path (backup folder, cache, restore). Refused names are skipped with a warning and the run exits 3 after finishing; db-backup.yml keeps that night's backup and fails at the end (Fail if storage files were skipped). Links in the cache or restore folder are never followed. - Cache unlock.
tools/unlock-cache.sh(db-backup.yml) only unpacks a file that starts with a passphrase packet and that gpg reports as one checked decryption (DECRYPTION_OKAY,GOODMDC, onePLAINTEXT, no error), holding only plain files and folders. Otherwise the cache is dropped and everything is downloaded once. - Check it: the comment block at the end of security-pass-5.sql;
node --test tools/test/(storage-names, unlock-cache, security-pass-5).
Security pass 3 (version 25.21)
Chris approved fixing everything the security pass found. Database side: supabase/security-pass-3.sql (also at the end of schema.sql); apply it before deploying low-stock-push, send-welcome and first-login.
- Team rows only the admin changes.
staff_guard()runs before insert, update and delete. For anyone but the admin it refuses: changing any email; changingall_props,propsoradmin; and updating or deleting someone else's row that hasall_props,propsoradmin. Your own row is exempt from that last rule, soswitch_property()and your own name still work.authenticatedhas no UPDATE onstaff.email.owns_person()(used by thealert_prefs_ownandterms_readpolicies) only covers people at the owner's property with no other properties and not the admin. App:adminOnly()in app.js hides every change but Send welcome email on those rows ("Only the admin can change them");theirOwn()in makeready.js shows them in Alerts as "Picks their own alerts". - Counts only through apply_op.
authenticatedhas no UPDATE onitems.on_handoritems.last_counted;apply_opandmerge_items(SECURITY DEFINER) change them. A newitemscolumn needs its owngrant update (<column>) on public.items to authenticated;in the same SQL file, or the app can't save it.on_orderstays writable and shows in Activity;apply_opsetsmaintstock.stock_opso its own on_order changes (already in stock_log) aren't logged twice. - Equipment moves only through equip_op. Trigger
equipment_loan_guardrefuses changes to location, borrower, out_by, out_at and due_back unlessequip_opsetmaintstock.equip_op(or there's no JWT: SQL Editor, service role). Status changes are in Activity unlessequip_opmade them. - One answer for a failed code. first-login's
setwith a code answers 400 "That code didn't work. Tap Send a new code for a new one." for every failure (tryProblem()in_shared/signin.ts), after the same short random wait. The real reason is only in the function's log ("code refused: ..."). - CSV cells.
FILES.csvSafe()puts'before text starting with = + - @ tab or carriage return that isn't a plain number (csvCellandsaveCsv);FILES.csvUnsafe()takes it off in Import list. - Unit photos:
authenticatedcan only updateunit,updated_by,updated_at. Mold reports:sent_atandsent_tocan't be set on insert (send-report sets them). Editing and sending again after a send still works on purpose. - Repeat notes.
chat_messages.pushed_at: low-stock-push'schatclaims a message (update ... where pushed_at is null) before pushing.quota_take()has three new kinds that count onlyquota_holds:low_push(keyitem:<id>, 1 an hour),order_email(keyprop:<property>, 10 a day) andwelcome(keyprop:<property of the person welcomed>, 20 a day). - Check it: the comment block at the end of security-pass-3.sql has the checks (grants, triggers,
quota_holds_kind_check).
Pass 4 (still 25.21). Sections 6 to 8 at the end of security-pass-3.sql; deploy low-stock-push and send-mileage after it (first-login needs no SQL).
- Locked backup cache. db-backup.yml caches only
storage-enc/files.tar.gpg(storage-cache tarred and locked withBACKUP_PASSPHRASE, AES256) understorage-enc-*, and unlocks it beforetools/storage.mjs. Any branch's workflow can restore main's caches, so nothing unlocked goes in. It deletes the old unlockedstorage-files-*caches withgh cache delete(job permissionactions: write; release.yml grants it to the called backup job). - More limits.
quota_takekindslow_caller(low-stock-pushlow: 10 an hour per caller, after the per-part one; over it the part's hold is released) andmileage_email(send-mileage: 20 a day per person, released if Resend refuses). - Same time for Email me a code. first-login's
codeanswers{ sent: true }after the same padded wait (CODE_WAIT) for anyone; a team member's login, code and email (sendCode()) run inEdgeRuntime.waitUntil, and their problems go to the log. - Sign-out from #first and #setup=. boot() calls
signOutHere("local"), the Team tab's sign-out (alerts off, shop copy and personal drafts cleared, unsent work named first). Bare#firstasks first (firstSignOutSure()). Anything that stops it leaves the person signed in and opens the app. - Stamps.
city_complaints_stampandunit_photos_stampset created_by / updated_by from the JWT email (no JWT: kept as written).equipment_loan_guardalso runs on insert: a new row must beinwith empty loan fields.
Security pass 2 (version 25.20)
Chris approved these in writing ("All 18"). Database side: supabase/security-pass-2.sql (also at the end of schema.sql); apply it before deploying the edge functions, which call it.
- Code tries and sends in one step. first-login no longer reads app_metadata, compares and writes it back.
signin_use_try()locks the login's auth.users row, checks the code exists, is under 20 minutes old, has tries left and the day's wrong codes aren't used up, then adds a try and acode_wrongtime before the code is compared; it returnsok:<hash>and first-login compares withsame()(constant time). A right code clears code_hash, code_at, code_tries and code_wrong as before.signin_reserve_send()does the 45-second gap, 15 wrong a day, 5 codes a day and 60 an hour for everyone (one send at a time,pg_advisory_xact_lock) and saves the new hash. Both are service_role only.codeBlocked()stays in signin.ts for the tests and to keep the limits in one place. - Same answer for any email.
codeanswers{ sent: true }whether or not the email is on the team, and for limits that only a team member can hit; only the everyone-per-hour limit shows (it's the same for any email).setwith a code answered "Tap Email me a code first." for someone not on the team (since 25.21 every code failure gets one answer; see Security pass 3). The screen says "Ifis on the MaintStock team, a 6-digit code is on its way." - check_token.
{ action: "check_token", token }answers{ ok: true, email }or{ ok: false }and changes nothing. boot() calls it for a#setup=link before signing out someone else on the phone; a bad link (or no signal) leaves them signed in. - Team emails are lower case. Trigger
aa_staff_email_lower(named to run before staff_guard, staff_title_sync and view_only_guard) and unique indexstaff_email_lower_keyon lower(email). Edge functions find staff with.eq("email", <lowercased>), never.ilike(where_and%are wildcards). - send-report picks the property from the report row's
propertycolumn (the database sets it from the form), and each PDF must passreport_pdf_ok(): a file the caller uploaded under that report'smm/<id>/. Send several reuses only the person's own earlier PDFs. - Daily limits (send-report 40, read-board 20):
quota_take()counts the day's report_emails or board_reads plusquota_holdsunder 15 minutes old, under a per-person advisory lock, and adds a hold; the function logs as usual and callsquota_release(). A hold left by a crash stops counting after 15 minutes. read-board counts every read Anthropic answered (refused, too long or unreadable too). - Phone alerts:
push_subs_check(endpoint https on Google FCM, Apple, Mozilla or Windows push, and the same assub.endpoint) andpush_subs_cap(newest 5 per email; the phone just added stays).pushEndpointOk()in webpush.js skips any other address. VAPID subject:mailto:alerts@maintstock.com. - Sign out (app.js "signing out on a shared phone"):
unsentOnPhone()andsignOutSure()list report drafts, typed notes and waiting unit photos;clearPersonal()removes PERSONAL_KEYS and DRAFT_PREFIXES from localStorage, the IndexedDB databases ms-report-photos and maintstock-unit-photos, and the shop-stock-photos cache (the last two not in the demo).clearShopCache()is unchanged because switching property also runs it. A waiting Make Ready queue stops sign-out. - Imports (
ctimport.js): 5,000 rows and 50 columns (MAX_ROWS,MAX_COLS). Past that, empty cells and formatted-only rows are skipped and text stops the import with a message. - jsPDF 3.0.4 replaced 2.5.1 (same
window.jspdf.jsPDF). - Check it: the comment block at the end of security-pass-2.sql has four checks. Before deploying low-stock-push, check the phones already signed up pass:
select bool_and(public.push_endpoint_ok(endpoint) and sub ->> 'endpoint' = endpoint) from public.push_subs;should be true.
Sign in with Google (version 24.66)
A white Sign in with Google button (#login-google, .gsi-btn; the G is a data: SVG in styles.css, nothing loads from Google) sits under Sign in, after an "or" line. It uses Supabase's Google provider (settings in docs/SETTINGS.md; the client secret lives only in Supabase).
- Going:
signInWithOAuth({ provider: "google", options: { redirectTo } })with redirectTo =location.origin + location.pathname, plus?app=1when started from the installed app (display-mode standalone ornavigator.standalone). supabase-js sends the whole page (same window,location.assign) to/auth/v1/authorize, then Google. No popup: on an iPhone home-screen app a new window would finish in Safari. CSP needs no change: a top-level navigation isn't limited byform-actionorconnect-src. With no signal the button says so and doesn't leave. - Coming back: supabase-js 2.45.4 uses the implicit flow (
flowType: "implicit"by default):#access_token=...&provider_token=.... It reads the hash on load (detectSessionInUrl) and saves the login.googleBack()in app.js looks at the address before createClient; aftergetSession()boot() cleans the address withhistory.replaceState(supabase-js leaves a bare#).state.viaGooglechanges two things only: a missing Team row says "That Google account isn't on the MaintStock team..." and a Team row with no name opens Check your details. Everything else (staff lookup, view only, property, reports-only) is the same startSignedIn() as a password. - Errors: Supabase puts
error,error_codeanderror_descriptionin both the query and the hash.googleError()mapssignup_disabled(no login for that email; sign-ups are off) to "First time? Tap First time here? Set up my password once, then Google works",access_denied(Cancel on Google's page) to "cancelled", plus banned, unverified email and a catch-all. The address is cleaned before supabase-js starts, any local login is dropped and the sign-in screen shows the message. Tokens that came back but didn't make a login (no signal for the user check) say "didn't finish". - iPhone home-screen app: going to another site from a home-screen app opens it inside the app with a small browser bar; when Google redirects back to maintstock.com it's back in the app, with the app's own storage. On some iOS versions, or when the page is opened from Safari, it can finish in Safari, which has separate storage, so only Safari is signed in. When
?app=1comes back outside an installed app, the app says "You're signed in here in the browser. To use the MaintStock app on your home screen, open its icon and tap Sign in with Google there too." Android: the installed app shows Google in a Chrome tab over the app and returns into it. - Linking: with sign-ups off Google can't make logins. Supabase links Google to an existing login with the same verified email, so a new person does First time here? once first.
- Deploy previews: not in Supabase's Redirect URLs, so Google sends them back to maintstock.com (see docs/SETTINGS.md).
- Demo:
signInWithOAuthnotes the call in sessionStoragedemo-oauthand comes back with a pretend#access_token=demo.... The harness block "24.66 (Google sign-in)" checks the button (both themes, Spanish), the call, the return, and the error messages and address cleanup.
Backups and restoring
- Automatic database and file backups: the Database backup workflow on GitHub backs up every table (including sign-in accounts), the database layout, and every stored file (item photos, report photos, every emailed report PDF). It runs every night and after every release. Each backup is locked with the backup passphrase, which is kept in Chris's password manager; without it a backup can't be opened. Nightly backups are kept 90 days; each release's backup is attached to that version on GitHub Releases and kept forever.
- Every backup is tested: right after each backup, GitHub restores it into a brand-new scratch Supabase and checks that every table has the same number of rows and every file came back. A red run means a backup didn't restore. Supabase sometimes adds its own internal tables or columns to the live project before the scratch copy has them; the test leaves out just those (it lists them in the run's Summary) and still checks every MaintStock table, sign-in account and stored file (tables since 24.55, columns since 2026-11-24).
- Setting it up and restoring: docs/BACKUP-AND-RESTORE.md in the repository has the four GitHub secrets it needs, how to download and unlock a backup, and the restore steps.
- Everyday parts backup: in the app, Team, Download backup (owners). It gives a zip of CSV files: items, activity, team, equipment, equipment history, pools, and pool tests.
- Restore parts: Items, Tools, Import list, choose items.csv from the backup.
- Supabase's own backups: the free plan doesn't include backups you can restore yourself, which is why the GitHub backups matter.
- The app itself: every version from 21.6 on is tagged on GitHub with a Release, and every Netlify deploy is also kept under Deploys.
- Settings: every setting needed to rebuild (Supabase, Netlify, Resend, GitHub), without the secret values, is listed in docs/SETTINGS.md.
Rebuilding from nothing
If the Supabase project were lost:
- Create a new Supabase project.
- In SQL Editor, paste all of supabase/schema.sql and tap Run. Change the owner email at the bottom first if needed.
- In Edge Functions, deploy a new function named low-stock-push from supabase/functions/low-stock-push (index.ts plus webpush.js).
- In Authentication, URL Configuration, set the Site URL and Redirect URLs as above.
- In Project Settings, API, copy the project URL and the anon (publishable) key into config.js.
- Deploy the folder to Netlify.
- Sign in as the owner, then import items.csv from the latest backup.
- Add the team again on the Team tab. Each person sets a new password.
- Run Help, Run setup check, and fix anything red.
If Netlify were lost, create a new Netlify site linked to the GitHub repository (publish directory "."), move the domain, set it to Public, and update the Supabase redirect URLs.
HVAC troubleshooter
The HVAC tab is all in hvac.js. Nothing is stored in Supabase. app.js only builds the tab the first time it opens (mountHvac) and gives it the Items list for parts, so it works with no signal.
To change a check: open hvac.js and find NODES. Each step has an id (like "f.fs1"), q (the question), how (how to check, optional), warn (a yellow safety box, optional), and a (the answer buttons, each a label and the id of the next step). An answer has end (the likely cause), fix (what to do), and optionally parts (words to search the Items list for), epa (adds the EPA 608 note), pro (when to call a contractor), danger (a red safety box), and link (a button to another step). EQUIPMENT at the top lists the problems shown for each kind of equipment and the step each one starts at.
To add a problem: add its steps to NODES, then add a line to the right list in EQUIPMENT. Every answer must point to a step that exists. An answer can also point to "tool:
Knowledge base (25.17): Chris's HVAC troubleshooter knowledge base (Nov 29, 2026) is folded in as steps, not as a probability engine. Its safety gates G1 to G11 are the s.* steps behind Safety first (s.1, the red button on the first screen). Its era questions are id.1 and id.2. New equipment: ipilot (i., spark pilot), hp (h., heat pump), elec (e., electric furnace or air handler with a fan center), mini (m.), oil (o.*). Furnace, AC and thermostat additions keep their f., p., a. and t. prefixes. Its test scenarios (sections 17.2 and 18.11) are route checks in the harness's static checks (kbRoutes), so a change that sends one of them somewhere else fails the Tests check. Reference numbers are in Quick specs, the extra code charts in CODES.brands, and serialYear() reads the year from a serial (How old is it?). Spanish for every new phrase is in i18n-es.js under "25.10 HVAC troubleshooter knowledge base"; a changed phrase needs its Spanish key changed too, or it shows in English.
Diagrams: a step or answer can have doc: ["/hvac/file", "Button name"], which shows a button that opens the file (PDF or picture). Add the file to the SHELL list in sw.js so it works with no signal. Pictures are drawn in tools/diagrams/ (an HTML page with an SVG drawing each); run node tools/diagrams/render.js to rebuild them into hvac/. Diagrams and fixes found on a real job go into the HVAC tab (Chris, Nov 10, 2026).
Tools (capacitor, superheat, split and rise with strip heat, amps, codes, specs, How old is it?) are near the bottom of hvac.js. The refrigerant pressure charts are in PT, and the blink codes are in CODES.
Bump VERSION in app.js and CACHE in sw.js after any change, so phones pick it up.
Appliance repair
The Appliance tab is all in appliance.js, built like hvac.js and reusing its styles (plus a few appl-* classes). Nothing is stored in Supabase; the current job (model, serial, unit, work order) and the phone's prices are in localStorage (ss-appl-*). app.js builds it the first time it opens (mountAppliance) and passes findParts, openItem, toast, who, propertyName, and supervisors (owners whose property or props include this one, the admin last).
- NODES and EQUIPMENT work like the HVAC ones. An answer can also have part (the part name shown with the model links and in the email) and rr (a yellow repair or replace hint).
- SITES builds the parts links. PartSelect (/Models/
/), RepairClinic (Shop-For-Parts?query=) and AppliancePartsPros (search.aspx?model=) were checked in Oct 2026. No parts site has a free lookup API, so the app links to their own pages. HD Supply and Chadwell are Google site: searches. If a site changes its address, fix its url there. - repairOrReplace() holds the rules and KINDS the usual life (NAHB) and starting price. ageFromSerial() decodes GE, Whirlpool (2010+), Frigidaire and LG serials. GE (12 years), Frigidaire and LG (10) repeat, so it returns
years, every year the code fits back to FIRST_YEAR (GE 1977, Frigidaire 1990, LG 2000), andsurewhen there's only one (24.41). How old is it? shows no green answer until the tech taps a year; the pick is kept on the job asmade/madeFor(the serial it belongs to) and Save to the unit's equipment uses it. - Scanning tags: app.js passes scanCode(msg, onCode), which borrows the Scan tab's camera (openCamera with a capture callback, which also looks for Data Matrix, PDF417, Code 93 and ITF). parseTag() reads codes that name themselves (MODEL ..., S/N ..., or a QR web address with model and serial); otherwise the code goes into whichever box the tech tapped Scan for. Photo of the tag (22.6) reads a still photo with readPhoto(). Since 24.96
photoBtn()makes two file boxes on a touch screen: Take photo of the tag (capture="environment", camera only) and Pick from photos (nocapture, so the camera roll); a computer gets one Choose a photo of the tag. readPhoto() tries the native BarcodeDetector on the full photo (all codes), else ZXing at two sizes and a center crop. During a capture app.js calls tuneForTags() (continuous focus, 2x zoom where supported). - Email parts request opens a mailto: link, so it needs no server change and goes out from the tech's own email.
- Reports-only logins see this tab (REPORTS_TABS in app.js).
Find unit
finder.js holds the Find unit tab and its data. It doesn't use the database.
- PROPERTIES: one entry per property.
unitsays how a unit number names its building."bldg2"means building + two-digit unit (Club at Highland Park)."addr"means building street number + unit, like 3515-33.mapis the office site map image in maps/ with its pixel size.buildingslists each building:nis the number,addrits address number,pxthe spot on the office map (pixels from the top-left), andat[latitude, longitude] for GPS. - Club at Highland Park's spots came from the office site map (maps/chp-site-map.jpg), matched against OpenStreetMap building outlines. Each
atis the middle of that building's half of the structure. - Adding a property: put its site map in maps/ (JPG, about 1500 px wide) and add it to the SHELL list in sw.js. Then fill in its
mapandbuildings, and bump the version. - Swapping in a better map (Terrace Gardens, 24.3): when the new map has the same layout, don't re-place every spot by hand. Find a few landmarks on both pictures (the dark building blocks work well), fit an affine transform from old pixels to new (least squares, numpy), run every
pxthrough it, then draw the new spots on the new picture and look before shipping. Updatemap.w/map.hto the new picture's size; the Tests check fails if they don't match the file or a spot lands off the picture. GPSatvalues don't change. - The map uses Leaflet 1.9.4 (vendor/leaflet-1.9.4.js and .css) with Esri World Imagery and transportation tiles, loaded from server.arcgisonline.com. The service worker keeps tiles you've seen. GPS needs
geolocation=(self)in _headers. - Reports-only logins see this tab (REPORTS_TABS in app.js).
Preventative maintenance
The PM tab is all in pm.js. The top half (addMonths through starterPlan) is the scheduling with no screen code; it runs in Node for testing (node -e "console.log(require('./pm.js').expandUnits('101-103'))"). The bottom half draws the tab.
Tables (supabase/pm.sql, also at the end of schema.sql):
| Table | Holds |
|---|---|
| units | One row per apartment: unit number (the key), building, furnace filter (a part on Items) and how many, notes, and whether it's on the PM list |
| pm_tasks | The plan: one row per recurring task, with who it's for (unit, building, common), how many months apart, first due month, common-area locations, parts, and steps |
| pm_log | Every Done and Couldn't do: task, unit or place, status, note, parts taken, who, and when |
The team can add and edit units and tasks; only owners can delete them. pm_log can be added to by the team, and a tech can delete only their own entry (that's how Undo works).
How it fits in app.js: a few lines marked "PM": setView and render call PM.show and PM.render, loadAll calls PM.load, applyOp and applyLocally hand pmdone and pmundo changes to pm.js so they ride the same no-signal queue as scans, and Run setup check looks for pm_log. Parts come off the shelf through the normal apply_op scan out, so they're in Activity and on Reorder.
Due dates are worked out on the phone: the last Done in pm_log for that task and unit plus the task's months, or the end of the First due month if it was never done. The phone loads the last 800 days of pm_log, enough for tasks up to every 2 years. A task done less often than that will show as never done after 800 days; raise LOG_DAYS in pm.js if one is added.
Shop map
Version 20 adds a drawing of the shop (Items > Tools > Shop map) and a Where is it? button on each part. The drawing is one row in the shop_map table, as JSON: the shop's size in feet and a list of boxes (racks with a letter and shelf count, doors and other landmarks, and from 24.24 walls). Everyone on the team can read it; only owners can change it. The app keeps a copy on each phone, so the map works with no signal once it has been opened.
The rack is found from the start of the part's bin name: K2-05 is rack K, shelf 2 from the top, bin 05 from the left.
One-time database step: in Supabase open SQL Editor, paste the whole of supabase/shop_map.sql, and tap Run. It's also at the end of supabase/schema.sql, so a rebuild includes it. Until it's run, the map says it isn't set up yet.
Pack parts (version 23.10)
items.pack_size (integer, default 1) marks a part sold in packs but used one at a time. on_hand, par and on_order stay in single pieces everywhere, so scans, counts, apply_op, low-stock alerts and usage reports didn't change. Only ordering converts: on the Reorder list qtyFor() is in packs (packsFor() rounds the pieces needed up to whole packs) and Mark ordered records packs × pack_size pieces; Receive delivery takes packs and adds packs × pack_size pieces. Labels for a pack part print "EACH" after the code (codeLine in app.js). packFromName() reads the pack size from a name like "10/pk", "25pr/bx", "12/cs", "Package Of 10", "10-Pack" or "(12-Count)"; it fills in new parts and parts added by Import list. The column is at the end of supabase/schema.sql. Download all items has a Pack size column, and Import list reads one.
Make Ready board
Version 21 adds the Make Ready tab (makeready.js). Each apartment being turned is one row in the make_ready table: unit, unit_type, move_out (shown as Vacant), keys_in, ready_by, move_in, full_ready, notes, done_at (set when it's turned and off the board) and steps. steps is JSON with one entry per column, like {"paint": {"d": "2026-10-21", "s": "done", "n": ""}}: d is the date, s is "" (scheduled), "done" or "na", and n is a short note. The step columns are one row in mr_board, as a list of {key, label}.
Everyone on the team can read, add and change rows. Steps are saved through the function mr_set_step, which checks the values and changes only that one step, so two people updating different steps at once don't overwrite each other. Only owners (and, since 24.60, managers) change the columns or delete a row; an owner can set a tech to look at the board only (see Who can change the Make Ready board). Both tables send live updates, so every phone sees changes right away.
Phone cards and Tools (version 24.11)
render() still builds one table. Under 700 px wide, CSS in styles.css turns each row into a card: thead hidden, each tr a grid, each td a labeled block. The labels are real spans (.mr-lab, hidden above 700 px) rather than CSS attr() text, so the Spanish translator sees them. Notes (order 9) and 100% ready (order 10) go to the bottom of the card, and empty notes (.mr-empty) are hidden. The PDF printout is separate code and doesn't change. The toolbar keeps + Add apartment, Fill in from a photo (or sheet, since 24.14), Finished turns and Tools (#mr-tools); toolsSheet() holds Print (#mr-print), Alerts (#mr-alerts), Edit steps (#mr-cols, owners) and Refresh (#mr-refresh).
Same release: the Team tab gives each person one Change button (teamRow in app.js) that opens a window with their Screens, View only, role and Remove buttons, each with a line of explanation; the existing two-tap handlers are reused, and a capture listener closes the window on the confirming tap (or right away for Screens, which opens its own window). PM's Due list drops the Overdue / Next 30 days / Everything buttons; the three boxes (tile() in pm.js) are Overdue, Due in 30 days and Everything, and "done this month" is a line under them.
Each property's own checklist (version 24.15)
The printed apartment checklist (printUnit in makeready.js) used to put report_settings.property_name in the Property box. That old field always holds the first property, so every property printed "Club at Highland Park". shopProp(settings, property, hasShops) now picks the property you're in: the staff property; before per-property shops the first property; on the on-call phone ("all") with several properties, none. shopLabel() gives its name (falling back to property_name). The board printout and pm.js's printouts use it too.
Each property can have its own list, saved with the property as mr_checklist in report_settings.properties (no database change): [{ "en": "Kitchen", "es": "Cocina", "items": [["Fridge cools", "Refrigerador enfría"]] }]. cleanChecklist() checks it (blanks dropped, up to 20 sections of 40 items, 70 characters a line, Spanish from the standard CHECKLIST when the English matches) and returns null for nothing usable, so the standard list prints. Make Ready Tools > Edit checklist (#mr-checklist, checklistSheet) shows for canEditProps() (the admin; the owner before per-property shops). It saves through saveChecklist(id, list) in app.js, which uses saveProp; saving the standard list removes the key. The PDF breaks pages when the list runs long and keeps final notes and signatures together.
The same fix everywhere else, and the second-property test (version 24.15)
Anything that shows or prints a property must use the property you're in, never the old single fields. property_name, property_address, pm_name, pm_email and cc_emails on report_settings are written by saveProp from the first property only, so they're kept for older code and setups without a property list. In 24.15: new reports start on the shop's property (lastProp() in app.js; the last-picked property only counts on the on-call phone or before per-property shops), Help > Check setup describes per-property routing, and downloads carry the shop's name (shopTag() in app.js, fileTag() in makeready.js and pm.js).
To test as someone at a property other than the first, open /demo/?shop=demo-oaks: the demo owner is then in Sample Oaks' shop while Demo Apartments stays first. The harness's secondProperty() run (in npm test -- --only features) goes through every screen, the Make Ready and PM printouts, new reports, Contacts and downloads there, and fails if the first property's name appears. A static check counts property_name / property_address reads per file against ALLOWED in tests/harness.js; a new read fails until someone checks it and raises the count.
Each property's own filter sizes and inspection email (version 24.16)
Filter sizes and the inspection email were the last settings shared by every property (report_settings.filter_sizes, insp_emails). Each property now keeps filter_sizes and insp_emails in report_settings.properties, edited on the Properties tab. A property that hasn't saved its own uses the shared columns, which Report settings still edits.
Techs can't write report_settings, so Save size for the team calls add_filter_size(p_size, p_property) (supabase/property-filter-sizes.sql, security definer). It checks that the caller works at that property (its shop, a ticked property, all properties or the admin), takes the property's list (or the shared one when it has none), adds the size and saves it into that property's entry. The one-argument version is kept for older phones. If the new function isn't there yet, the app falls back to it.
Inspections are emailed to the property's insp_emails, then the shared insp_emails, then the property manager: in send-report (deploy it after this change) and in recipients() in app.js, which shows who it goes to. Find unit opens on your own property and shows .fd-nomap for a property with no map in finder.js.
Who can change the Make Ready board, and managers (version 24.60)
Chris wanted to set who is a manager and who is a tech, and pick who can change the board (a tech had changed scheduled dates that were right). supabase/board-permissions.sql adds two staff columns: manager (default false) and mr_edit (default true, so nobody lost anything when it went in). board_edit(p) is true for someone on the team at property p (not Reports only) who is an owner, a manager or has mr_edit; board_manager(p) for an owner or a manager there. The make_ready insert and update rules use board_edit(property), its delete rule and the mr_board insert and update rules board_manager(property). mr_set_step is security definer, so it skips the table rules: it checks board_edit(my_property()) itself and raises 42501 with a plain message. Owners (and the admin) change both columns through the existing staff_write rule; the staff_guard trigger is unchanged. View-only logins (24.5) are still refused everything by view_only_guard.
In the app, boardEdit() and boardManage() in app.js (from state.manager / state.mrEdit, read at sign-in) are passed to makeready.js as C.boardEdit / C.boardManage. lockWrites() refuses make_ready / mr_board writes and mr_set_step on the phone first. render() swaps each tappable cell for a plain span.mr-ro when the person can't change the board (the 24.21 rule: only tappable things look tappable), drops + Add apartment, Fill in from a photo and Put back, and shows #mr-ro-note. Edit steps and Delete from the board use canManage(). The Team tab's Change window has the two switches for techs (flip() in teamRow) and the list shows Manager (personRole()) and Make Ready view only. See the app as a tech copies the picked person's manager and mr_edit. Demo: Jordan is a manager, Sam view only; /demo/?boardview and /demo/?manager sign in as those.
To run it: Supabase SQL Editor (or supabase db query -f supabase/board-permissions.sql on Chris-PC). Check: select policyname from pg_policies where tablename in ('make_ready','mr_board') and (qual like '%board_%' or with_check like '%board_%'); lists five rules. Until it runs, the new Team buttons say the database isn't set up, and everyone can still change the board.
Roving HVAC tech (version 24.73)
Chris: a position for roving HVAC with the same permissions and screens as Eh Bleh. supabase/roving-hvac.sql adds roving_hvac to staff_title_ok and to the titles staff_title_sync keeps off manager (with Leasing). In app.js TECH_TITLES lists both. When the admin (canEditProps()) picks it, copySetup(p, like) copies all_props / props and the hidden screens (personOff(like) saved as offFor under p's own property, the same way as Team > Screens) from another staff row with roving_hvac. Eh Bleh's row was given the title when the SQL was run, so he is the one copied. Check: select pg_get_constraintdef(oid) like '%roving_hvac%' from pg_constraint where conname = 'staff_title_ok'; is true.
Job titles (version 24.72)
Chris wanted titles like manager for leasing, assistant manager, roving manager, maintenance supervisor, regional manager and regional maintenance supervisor, and picked: Leasing marks steps done like a tech, every other title runs the Make Ready board. supabase/job-titles.sql adds staff.title (check staff_title_ok: pm, apm, leasing, roving_pm, maint_sup, regional_pm, regional_maint, or null for a maintenance tech) and the staff_title_sync trigger, which sets staff.manager from the title whenever the title changes (true for all but Leasing). So the 24.60 board_manager() rules and the 24.68 date guard follow the title with no other change. Owners change title through the existing staff_write rule.
In app.js JOB_TITLES, titleName(), titleRuns() and titleSheet(p); the Change window's Job title button replaces Make manager. personRole() shows the title. The Regional tab uses seesRegion() (admin, owner, or a regional_pm / regional_maint title), not roamsShops() (Chris: only regionals and owners). Otherwise titles are labels: shop access is still property / props / all_props, and team management is still the owner role. Demo: Jordan apm, /demo/?leasing.
To run it: Supabase SQL Editor (or supabase db query -f supabase/job-titles.sql on Chris-PC). Check: select count(*) from information_schema.columns where table_name = 'staff' and column_name = 'title'; is 1. Until then the Job title window says the database isn't set up.
Scheduled vs actual Make Ready dates (version 24.68)
Chris: techs must not change scheduled dates, only record when a step was actually done, so "scheduled the 16th, done the 23rd" shows. A step's JSON is now {d, s, n, c}: d the scheduled day, s '' / done / na, n the note, c the day it was actually done (kept only when s is done). Old done steps have no c, and doneOn() falls back to d for them. daysLate() is c - d in days when both are set.
supabase/mr-actual-dates.sql (needs 24.60's board_manager()):
- mr_set_step validates c and, when the caller isn't board_manager(my_property()), puts the stored d back, so an older phone can't move a scheduled day.
- mr_dates_guard() (security definer, BEFORE INSERT OR UPDATE on make_ready) lets through server jobs (no auth.uid() and no email) and owners and managers. For everyone else it refuses an insert, a change to unit, unit_type, move_out, ready_by, move_in or property, and any step whose d changed (errcode 42501, plain message). Keys in, notes, 100% ready, s, n and c still pass.
- mr_alert_note() (board-alerts.sql) is replaced: the done line uses coalesce(c, d) and adds "(due M/D, N days late)", and a change to c alone says "Prep done date 11/23".
In makeready.js the step sheet shows #mr-step-sched to canManage() and #mr-sched-ro text to others; #mr-step-done (Day it was actually done) shows when Done is picked. The apartment sheet hides the unit, type and date fields from non-managers (#mr-dates-ro) and leaves unit out of their update. + Add apartment and Fill in from a photo are canManage() only. Demo: /demo/?boardtech.
To run it: Supabase SQL Editor (or supabase db query -f supabase/mr-actual-dates.sql on Chris-PC). Check: select tgname from pg_trigger where tgname = 'mr_dates_guard'; returns one row. Until it runs the app already hides the date boxes from techs, but the database would still take a date change from an older phone.
Owners stay inside their own property (version 24.61)
Owner rules use shop_owner(property) (an owner at that property). Two rules still used is_owner() (any owner anywhere): alert_prefs_own and the item-photos update/delete rules on storage.objects. supabase/owner-scope.sql adds owns_person(email) (the admin, or an owner at a property that person works at: their shop, a ticked property or all properties) for alert settings, and limits photo replace/delete to the admin or the owner who uploaded the file (owner_id); the app never does either. New owner-only rules must use shop_owner(property) or owns_person(email), never is_owner() alone. The harness's static check guards these three.
Make Ready alerts (version 24.6)
Every change to a make_ready row (insert, update, delete, from any screen or function) fires the trigger mr_alert_note() (supabase/board-alerts.sql), which writes one line to mr_alerts in plain words: property, unit, what changed ("Paint done 10/30; Keys in"), who (from the sign-in), and when. Step names come from the property's mr_board columns. A change that only touches updated_at/updated_by writes nothing. The trigger catches its own errors, so an alert problem never stops a save.
After each change (and each time the board opens) makeready.js calls the low-stock-push edge function with action: "board", at most once every 3 seconds. Since 24.56 the maintstock-board-alerts scheduled job also calls it every minute while a line is due, so alerts don't depend on that phone keeping signal (see Scheduled jobs). The function looks at the unsent lines of each property. When the first one is 2 minutes old, it claims them all in one UPDATE (sent_at = now; two calls at once can't both get the same line) and sends them. For lines still inside their 2 minutes, it keeps running in the background (EdgeRuntime.waitUntil) until they're due; if that background wait is lost, the next call sends them.
Who gets them (board.js in the same folder, plain JS so the harness tests it): everyone whose current property is that one, or who has it ticked, or has All properties, except the Reports-only login. Each person gets only other people's changes. alert_prefs (email, mr_push, mr_email; no row = both on) turns either off. Everyone edits their own row in Make Ready > Alerts; owners edit anyone's. Phone notes go to that person's rows in push_subs (tag mr-board, so a new note replaces the last one; tapping opens #makeready). Emails go one per person through the Resend batch API with RESEND_API_KEY, from BOARD_FROM or "MaintStock Make Ready alerts@maintstock.com". Resend's free plan allows 100 emails a day. Sent lines are deleted after 30 days.
One-time setup: run supabase/board-alerts.sql in Supabase (SQL Editor), then redeploy low-stock-push (npx supabase functions deploy low-stock-push). Until the SQL runs, Alerts says it isn't set up yet and the board works as before.
Scheduled jobs (version 24.56)
supabase/scheduled-jobs.sql turns on two Postgres extensions Supabase includes on every plan: pg_cron (runs SQL on a timer) and pg_net (lets SQL make a web request). Four jobs, all named maintstock-…, times in UTC (Omaha is UTC-6 in winter, UTC-5 in summer):
| Job | When | What |
|---|---|---|
| maintstock-board-alerts | every minute | If a Make Ready line in mr_alerts has waited 2 minutes unsent, calls low-stock-push with action board. When nothing waits it makes no call. |
| maintstock-reorder-reminder | Fridays 13:30 | action reorder: counts To order parts per property (par minus on hand minus on order, the Reorder tab's sum) and sends one "Friday reorder" note per person (board.js teamFor, minus Reports-only and view-only logins), tag reorder, opens #reorder. Since 25.9 it also sends the Friday order email (below). |
| maintstock-mileage-reminder | 22nd and 23rd, 15:00 | action mileage: a note to the owner of each mileage_sheets row for the current period with trips and no submitted_at, tag mileage, opens #mileage. The day is worked out in Central time. |
| maintstock-job-cleanup | nightly 08:40 | Deletes cron.job_run_details older than 7 days. |
| maintstock-chat-emails | every minute | (24.91, notify-prefs.sql) Chat emails a room's quiet burst missed. |
| maintstock-scan-reminder | Mon-Fri 20:30 and 21:30 | (25.19, scan-reminder.sql) action scan: the 3:30 PM scan reminder. See Scan reminder below. |
How a job reaches the function: public.cron_call(action) reads three Vault values (maintstock_project_url, maintstock_anon_key, maintstock_cron_key) and posts to /functions/v1/low-stock-push with the anon key (so the gateway's JWT check passes) and the header x-maintstock-cron. The function asks public.cron_key_ok(key) (service role only) before doing anything; a wrong key gets 403. The scheduler key is random, made by the SQL file, and never leaves the database. Only the database owner can run cron_call. The helpers that decide who gets what are in supabase/functions/low-stock-push/reminders.js (tests: tools/test/reminders.test.mjs). public.scheduled_jobs() (owners only) gives Run setup check each job's on/off and last result, plus how many pg_net calls failed in the last day.
Friday order email (25.9). supabase/functions/low-stock-push/orderemail.js (tests: tools/test/order-email.test.mjs). For each property in report_settings.properties with order_emails (a comma list, set on the Properties tab), one Resend email from ORDER_FROM (default "MaintStock Reorder alerts@maintstock.com") listing that property's To order parts by main supplier: part # alone in its own cell, quantity in packs (the Reorder tab's packsFor), name, have/keep/bin; then a part #-tab-quantity block for quick-order boxes; then a Mark these N ordered link https://maintstock.com/#ordered=<property>&s=<supplier>&ids=<first 8 hex of each id, joined by .>. No parts: a one-line "nothing to order" email. Items are read with only the columns the email needs (no photos) to keep egress down. No database change: order_emails is a key in the properties JSON. Action order_email (signed in, owner or admin, not view-only) sends the caller's current property's email now (Properties > Send it now).
The app (app.js, top of the file) saves an #ordered= link in localStorage (ss-ordered-link, 3 days) and clears it from the address bar, so it survives signing in and Google's redirect. After loadAll, openOrderedLink() switches shops once if the link is for another property this login can use (tried stops a loop), else refuses; then on To order it unchecks that supplier's other parts (state.roOff), checks the matched ones, outlines the group (.ro-from-email) and says how many it checked and how many were already ordered. Mark ordered is unchanged (tap, tap again). Each To order line also has partCopy() (.ro-copy), which copies just orderFrom(it).part.
One-time setup (from Chris-PC with the Supabase CLI, after the owner's go-ahead): deploy low-stock-push first (npx supabase functions deploy low-stock-push), then run supabase/scheduled-jobs.sql (npx supabase db query --linked -f supabase/scheduled-jobs.sql). Running it again is safe and updates the jobs. To pause one: select cron.unschedule('maintstock-reorder-reminder');. Recent runs: select * from cron.job_run_details order by start_time desc limit 20;, or Supabase > Integrations > Cron. After restoring into a different project, update the two Vault values for the project address and anon key (select vault.update_secret(id, 'new value') from vault.secrets where name = 'maintstock_project_url';).
Scan reminder (version 25.19)
Chris (2026-12-05) after the adoption freeze: Amy and Ron forget to scan parts out, so each workday at 3:30 PM Omaha time the people who take parts get a phone note Took any parts today? / "Scan them now. Tap to open Scan." (tag scan-reminder, so a new one replaces yesterday's; opens #scan, which app.js turns into Scan in Take out).
- When. pg_cron only knows UTC and Omaha moves between UTC-6 and UTC-5, so
maintstock-scan-reminderruns at30 20,21 * * 1-5. The function'sisScanTime()(reminders.js) works out the weekday and hour in America/Chicago and only sends when it's Monday to Friday in the 3 PM hour; the other run returns{ skipped: "not 3 PM in Omaha" }. Exactly one run sends, also on the days the clocks change (tested). No holiday calendar. - Who.
stockProperties(items): properties with at least one part that has a keep-on-hand level (par > 0), so a property that hasn't set up its shop isn't nagged.scanNotes(): everyone on those properties' teams (board.jsteamFor: home property, ticked properties, all properties), one note each, whose job title is inSCAN_TITLES(blank = maintenance tech,maint_sup,roving_hvac), not view-only, not the on-call phone. Then each person's ownscan_pushchoice (wants()in chat.js; no row or column = on). Owners with no job title get it too; they can untick it. - Notifications window. notify.js kind
scan(scan_push, App only), hidden for people whose title isn't inPARTS_TITLES(keep it the same asSCAN_TITLES), view-only logins, and when Scan is turned off for the person. - Database (supabase/scan-reminder.sql, also at the end of schema.sql):
alert_prefs.scan_push boolean not null default trueand the job. Safe to run again. Skips the job where scheduled-jobs.sql hasn't been run. - One-time steps: 1) deploy low-stock-push (25.19 or newer); 2) run supabase/scan-reminder.sql. Check:
select schedule, active from cron.job where jobname = 'maintstock-scan-reminder';and Help > Run setup check, Scheduled jobs. Pause it for everyone:select cron.unschedule('maintstock-scan-reminder');. Each run's result is in Edge Functions > low-stock-push > Logs ("scan reminder N people, N sent"). - Cost. Two calls a weekday; each reads only
id, property, parof parts with a level, the staff list and alert_prefs. No email. - Tests: tools/test/reminders.test.mjs (time in winter, summer, weekends, both clock-change days; who gets it; the job in the SQL). Harness static checks (who sees the line, starts on) and features() "Chat" steps (7 Notifications rows, the line starts ticked, unticking saves
scan_push: false,#scanopens Take out).
Board photos (version 23.6)
Fill in from a photo (makeready.js, photoSheet and reviewSheet) shrinks the photo on the phone to 2000 px and sends it to the Supabase edge function read-board (supabase/functions/read-board/index.ts) with the board's step columns. The function checks the person is on the team, sends the photo to the Anthropic API (the model named in read-board/index.ts, unless the BOARD_MODEL secret says otherwise) with a fixed list of fields to fill in, and returns the rows as read. Dates come back as written ("10/14"); the phone adds the year that puts the date closest to today (mdToIso). Nothing is saved by the function: the phone shows every row to fix and saves only the ticked ones, as new rows or as updates to apartments already on the board. The API key lives only in Supabase secrets, never in the app. Each read is logged in board_reads (who, when, how many rows; only the function can see it) so a person can read 20 photos a day.
Importing an Excel or CSV board (24.14). The same window has Import Excel or CSV (#mr-sheet-file). CTIMPORT.readFile (ctimport.js, the reader the Contacts import uses; no library) turns the file into rows of text on the phone. sheetRead() in makeready.js finds the header row (the first of the top 30 rows with an apartment column and two other known columns), matching words with SHEET_FIELDS and step columns by the board's step labels (same name, or one starts with the other). It returns rows in the photo reader's shape, so draftsFrom, reviewSheet and rowBody are shared. Extras for sheets: Excel day numbers and 2026-10-14 dates are turned into M/D/YYYY (sheetDate); Done/X/✓ and N/A in a step set its state (step s, which rowBody keeps); separate Bldg and Unit columns become building + 2-digit unit; rows without an apartment number (titles, totals) are skipped; unknown columns are listed on the check screen. Nothing goes to a server until Add, and no board_reads row is written. Test file: tests/fixtures/make-ready-sheet.xlsx (made by tests/fixtures/make-make-ready-sheet.py).
One-time setup (owner):
- At console.anthropic.com, sign in or sign up, add some credit under Billing (reading one board photo costs roughly 10 to 25 cents), and create a key under API Keys. Copy it.
- In Supabase open Edge Functions, then Secrets, and add a secret named
ANTHROPIC_API_KEYwith the key as its value. - Deploy the function from the shop-stock folder:
npx supabase functions deploy read-board. - In Supabase open SQL Editor, paste the whole of supabase/board-photo.sql, and tap Run (it's also at the end of supabase/schema.sql).
Until the key is set, the button says "Reading board photos isn't set up yet".
Version 24.10: when Anthropic turns a photo read down, read-board writes "read-board failed" with the error number, type and message to its log (Supabase, Edge Functions, read-board, Logs; never the key), and 400, 403 and 404 get their own messages instead of "The photo couldn't be read".
Version 24.8: the photo window has Take a photo (an input with capture="environment", straight to the camera) and Upload a photo (no capture, so the phone offers its gallery and Files). board_reads gets a property column and a read rule (your own reads, an owner's property, the admin everywhere, as activity_log), and activity.js lists it as "Read a Make Ready board photo"; that part of board-photo.sql runs once in the SQL Editor, and read-board is redeployed so it records the property. Marking 100% ready (toggleReady, and a photo row read as ready in rowBody) also sets done_at, so the apartment moves to Finished turns; Undo and Put back clear both. Turned, take it off the board only shows for apartments marked ready before 24.8 and refuses one that isn't ready (in the app only; Delete is still there for owners).
Ideas and problems
Version 21 adds Help > Ideas and problems (requests.js). Each one is a row in feature_requests: kind ("feature" or "problem"), body, by_email (always the sender's own login), status ("new", "planned", "done" or "not now"), reply. Anyone on the team can add and read them. Only owners change the status or reply, or delete one.
One-time database step for both: in Supabase open SQL Editor, paste the whole of supabase/makeready.sql, and tap Run. Then do the same with supabase/requests.sql. Both are also at the end of supabase/schema.sql, so a rebuild includes them. Until they're run, the Make Ready tab and the Ideas and problems list say they aren't set up yet.
Android's bottom button bar
On Android the installed app's bottom bar (Back, Home, Recent) is dark charcoal, the manifest's background_color (checked on a phone 2026-10-26 with plain test pages in navtest/). Don't put viewport-fit=cover back in a page's viewport tag: with it, Chrome lets the page draw under the bar and paints the bar with the light theme's page color, even in dark mode. chrome://webapks on the phone shows the colors Chrome saved for the installed app.
Version 23.4: opened from its home screen icon, the installed app still had a light bar, because Chrome colors it from the page's own background (the html element). The test pages had only been opened from links, which run in Chrome itself with Chrome's dark bar. theme.js, which every page loads first, now sets the html element's background to #12181b, and body has min-height 100vh so the light theme still fills the screen. Keep both.
Turning screens off
Version 23.2. Each property in report_settings.properties can have off (a list of screens hidden for everyone at that property) and offFor (an email mapped to the screens hidden for that one person). A person's list is saved under their own property but read from every property, so it follows them when they switch shops. No database change was needed, and only the admin can save it, like the rest of the property list. In app.js, OPTIONAL_TABS lists the screens that can be turned off (Today, Help, Team and Properties can't). isOff(view) answers for the signed-in person; applyOff() hides those menu buttons after sign-in and whenever the property list changes; setView() refuses a turned-off screen whatever link asks for it; and today.js asks C.isOff() before showing a card, a search result or a unit history entry. Hiding is only on screen: the data and the database rules are unchanged, so turning a screen back on brings everything back.
On-call schedule (version 24.35)
Chris (2026-11-03): put the on-call schedule in the app, everyone can view, only he edits ("let me assign who can edit"); all four properties share one schedule; notify people when it changes, but "Nobody should be notified or see changes until I have published them"; people join and quit; make 2027 from his 2026 sheet with nobody covering the same holiday as in 2026.
oncall.js(window.ONCALL), screen#view-oncall, Today card fromONCALL.snapshot(). Pure helpers inONCALL.core(dates as YYYY-MM-DD strings, no time zones):holidaysOf(year)(federal holidays by rule),holidayKey()(matches the sheet's spellings, like "President's Day "),sheetRead()(import),fillYear(),toCsv().- Draft and live.
oncall_shifts.stageisdraftorlive;oncall_settingsrow 1 is live (people, editors, changed_at/changed_by = last publish), row 2 is the draft's people. The read rule hands editors both stages and everyone else only live rows for a property they cover (oncall_sees(props), empty props = every property). Editors only ever insert, update or delete draft rows.oncall_publish()(security definer) replaces the live rows with a copy of the draft and copies row 2's people to row 1, underset_config('oncall.publishing','1')so theoncall_settings_guardtrigger lets row 1 change.oncall_discard()copies live back to draft. When an editor loads and the draft is empty but the live schedule isn't, the app callsoncall_discard()first, so Publish can never wipe the live schedule. - Editors.
oncall_editor()=staff.admin, or an email in row 1'seditors, and neverview_only. Onlyis_admin()may changeeditors(trigger). The app'scanEdit()mirrors it (canEditProps()for the admin; before a setup has separate shops that is the owner, but the database still wantsstaff.admin). - Notification. Only on Publish, when the box is ticked:
low-stock-pushactiononcallchecks the caller is the admin or an editor, then pushes "On-call schedule updated" + a one-line summary (changeLine(): how many weeks differ from live and their span) to every staff member's subscribed phones except the sender's. The Today card and the screen show "Updated" until this phone opens the schedule (ss-oncall-seenin localStorage). - Fill a year. Slots: Friday-to-Thursday from the day after the last week that runs into the year (else the first Friday), skipping weeks that overlap an existing one. Order: People sorted by their last week before the first slot (never = first), then list order; repeated. Each holiday (the year's, plus a next-year holiday that falls in the last slot) has an owner from the year before (Holiday column, else the week the date fell in). Each holiday slot may swap with the slot before or after; the score is [repeats, turns closer than n−3 weeks apart, holiday count spread, most big holidays (New Year's, July 4, Thanksgiving, Christmas), number of swaps], compared in that order. Up to 12 holidays: every combination (3^12); more (Redo across two years): coordinate descent from no swaps. Swapped weeks get the note "Switched with X to share out the holidays".
- Redo from a date =
fillYear({ from, to }): removes the draft weeks from the first week starting on or afterfromthrough the week holding the schedule's last day, and refills from People. - Import reads the first sheet whose rows have Tech + On-call Start headers (
CTIMPORT.readFile(file, want)); weeks equal to one already in the draft (same start and person) are skipped; overlapping ones are replaced. - Offline: the live schedule and people are cached in
ss-oncall; the draft isn't. - Publish one year at a time (24.37):
oncall_publish(p_year)(supabase/oncall-publish-year.sql);publishSheet()offers the years when changes span more than one. - Database file:
supabase/oncall-schedule.sql(end of schema.sql). Tables have RLS, explicit grants andview_only_guard. Not in Activity: only the admin and editors change it, and Publish is the event that matters.
Today, search, unit history and contacts
All in today.js (version 23.0). Today reads what the other tabs already loaded (PM.snapshot(), MR.snapshot(), FR.snapshot(), the parts, equipment and reports), so it adds no database queries of its own. Unit history also looks up older reports, Make Ready rows and equipment moves for that unit in Supabase when there's signal. Contacts are stored with each property in report_settings.properties (a contacts list on each property), so only the admin can change them, and no new table was needed. The contact types are the KINDS list near the top of today.js: the property's own people first (Property manager is shown as the main contact), then vendors. Add a type there, and its Spanish in i18n-es.js.
Import sheet (version 24.13). ctimport.js (window.CTIMPORT) reads the blank sheet forms/contacts-sheet.xlsx once it's filled in, or any CSV with a Name and Phone header. There's no spreadsheet library: an .xlsx is a zip of XML, so readXlsx() finds the files in the zip's directory, inflates them with the browser's DecompressionStream("deflate-raw"), and pulls cell text out of the first visible sheet (shared strings and inline strings) with regular expressions, so it also runs in Node. parse() finds the "Property:" cell and the header row by its words, maps "What they're for" to KINDS (exact name, then a few aliases, else Other with "For: ..." in the notes), puts who to ask for and the account # in notes, and runs each row through today.js's checkContact() so imports follow the same rules as typing. merge() matches on name + type: a match is updated with the sheet's non-empty fields, anything else is added; nothing is removed. Saving goes through C.saveContacts like a single contact. To change the blank sheet, edit forms/contacts-sheet.xlsx (keep the header words), then rerun python3 tests/fixtures/make-contacts-filled.py for the test copy. Old .xls files aren't supported.
Vendor details and Copy from another property (version 24.58). A contact can also hold address, ins (insurance end date, YYYY-MM-DD), yardi (Yardi vendor code) and nvid (NetVendor ID), still inside report_settings.properties[].contacts, so no database change. cleanContact() reads them, checkContact() checks the date and lengths, and slim() drops the empty ones so older contacts save exactly as before. insState() gives "ok", "soon" (ends within 30 days) or "expired"; vendorBits() draws the address, the insurance line (.ct-ins.soon orange, .ct-ins.expired red, data-ins for tests) and the codes. The admin's Today Contacts card counts vendors with soon/expired insurance. copySheet() (button #ct-copy, admin only, shown when another property has non-staff contacts) lists another property's contacts minus STAFF_KINDS, ticks the ones with vendor details, and saves through C.saveContacts + CTIMPORT.merge(), so a contact with the same name and type is never added twice and every copy gets a new id (each property owns its copy). merge() now also fills in the four vendor fields. New KINDS: General contractor, Painting, Cleaning & make ready, Carpet & flooring, Landscaping, Pool, Trash & hauling, Laundry (Spanish in i18n-es.js). Club at Highland Park's 21 approved vendors were added on Nov 10, 2026 from Kaitlyn's NetVendor screenshots, with a REST update of report_settings (id 1) that read the list first and only appended to CHP's contacts.
Barcode lookup (version 24.47)
Chris asked for the app to "figure out what an item is from its barcode ... when adding new items", and picked a free lookup (option 1, daily limit) over a paid one.
- Source: UPCitemdb's free trial endpoint,
https://api.upcitemdb.com/prod/trial/lookup?upc=<code>. No key, no account. About 100 lookups a day per internet connection (IP), with a short burst limit; answers 429TOO_FAST/EXCEED_LIMITwhen used up, 400INVALID_UPC, anditems: []when not found. Its data comes from stores, so contractor-only parts (Chadwell, HD Supply) are often missing. To move to the paid plan later, changeAPIin upc.js andAPIin the function, and add the key header in the function only (never on the phone). - upc.js (
window.UPC; loaded before app.js in index.html and demo/index.html, cached by sw.js, required by tools/test/upc.test.mjs):forLookup()(digits only, 8/12/13/14 long, check digit right; an 8-digit code starting 0 or 1 is taken as UPC-E and expanded to UPC-A),parse(status, body),notes(),typeOf(r, ItemTypes). - Route (24.49):
lookupUpc(code)in app.js asks thelookup-upcedge function (12 s), which asks UPCitemdb from Supabase. UPCitemdb answers browsers withAccess-Control-Allow-Origin: https://www.upcitemdb.com, so a phone on maintstock.com can't call it directly (24.47 tried that first; found 2026-11-07 with curl from the ThinkPad). So the roughly 100 a day (X-RateLimit-Limit: 100) is for Supabase's connection, which other Supabase projects may share. Found results are kept on the phone 30 days (localStoragess-upc-<code>,demo-ss-upc-…in the demo). The demo skips the phone request and its fakelookup-upcanswers. - If the free limit runs out often: move to UPCitemdb's paid plan (a key, much higher limits). Only
supabase/functions/lookup-upc/index.tschanges (endpoint and key header from a Supabase secret); the phone and upc.js stay the same. - Asks first (24.49): a found answer goes to
askFirst(r): the name, barcode and the first picture that loads, with Use this (#f-upc-use, runsfillFrom(r)) and Not it. Chris chose this after the free list gave almonds for a Target water bottle (085239000083, filed that way in UPCitemdb itself).fillscounts fills so a slow photo from an older lookup can't add a second Undo. - Wrong matches (24.49):
parse()takes the looked-up code and only accepts an item whoseupc/ean/gtinequals it (leading zeros stripped); UPCitemdb's free list returned an unrelated dress for a Cherry 7UP can.typeOf()uses only the store category. The message ends with the barcode in brackets. Phone cache key isupc2-<code>. - Edge function lookup-upc (POST
{ code }→{ status, body }, UPCitemdb's answer untouched): signed-in staff only (not the on-call login), digits only, 8 s timeout, no secrets, nothing stored. An empty request gets 400 "Missing code" (Help > Check setup uses this). Deploy:supabase functions deploy lookup-upc. - Add item window (
itemSheet(), new parts only):upcFieldat the top (#f-upc-msg,#f-upc-scanopens the camera withopenCamera({ onCode })and adds the code to Box barcodes,#f-upc-look); Box barcodes looks up on Enter and on change; a preset code from Add as new item is looked up on open.fillFrom()fills only empty boxes (name through its input event, so pack size and type guesses run; type fromtypeOf()unless picked; notes; the first picture that loads,firstPicture(), throughphotoFromLink()so it's copied into item-photos when the store allows CORS). Use this name, Undo. Nothing is saved until Add item, so the part gets the property you're in like any new part. - Tests: tools/test/upc.test.mjs; harness
barcodeLookup()at both demo properties (npm test -- --only barcode).
Barcode kinds and matching (version 24.89)
Chris's toilet seat box (MFG# W201SC) wouldn't scan, and he asked that "the app needs to be able to scan a variety of codes" because every maker and supplier uses its own. That box's barcode turned out to be artwork: 18 digits printed under UPC-style guard bars, every space the same width (a real UPC's spaces vary), and no decoder (ZXing in the app, zxing-cpp with every format on the photo) reads it. Nothing can scan it, so 24.89 adds a hint in the camera and makes everything readable scan and match.
- Kinds:
SCAN_FORMATSin app.js (nativeBarcodeDetector, Android Chrome) and the ZXing hint list (iPhone and computers) now look for QR, UPC-A/E, EAN-13/8, Code 128 (GS1-128), Code 39, Code 93, Codabar, ITF (ITF-14), Data Matrix, PDF417 and Aztec on every scan, plus GS1 DataBar (RSS-14, RSS Expanded) in ZXing. Before 24.89 the last six were only on for a capture (appliance tags). The native detector is still used only when it has qr_code and upc_a. - Matching:
UPC.clean(raw)takes off an AIM prefix (]C1,]E0,]d2…) and control characters (the GS separator in GS1-128 sent by a keyboard-wedge scanner).UPC.keys(code)gives the GTIN as"G" + 14 digitsfor a valid UPC-A/EAN-13/GTIN-14, an EAN-8 and a UPC-E (both readings), or a GS1 string with AI 01 ((01)…or bare01…followed by more data).putItem()keepsstate.byKey(key → part id, first part wins) next tostate.byCode;itemIdFor(raw)tries the exact code, the cleaned code, then the keys.handleCode(), the camera's "known part" check and Today's search use it. Codes without a valid check digit, SS- codes, supplier codes and QR text have no keys and still match exactly. A case code (indicator 1–8) is a different GTIN from the unit, on purpose. - Camera hint:
SLOW_SCAN_MSGreplaces the camera line after 12 seconds with no read (slowTimer, not during a capture; cleared incloseCamera()). - Zebra DS2208: a USB scanner only sends what its own settings allow. Interleaved 2 of 5, Code 93 and Codabar are off by default; turn them on with 123Scan or the DS2208 Product Reference Guide. The app needs nothing.
- Live data: the W201SC box's printed digits (019552875372585865) are linked to CHP's "White slow close elongated plastic toilet seat…" (Chadwell 204125), so typing them works.
- Tests: tools/test/upc.test.mjs (same key for every form; no key for non-product codes); harness
barcodeLookup()steps 5 and 6 (EAN-13, 14-digit,]E0, GS1 with brackets and with a GS separator all find the part at both demo properties; a bad check digit opens New code; the camera hint after 12 seconds).
GL codes (version 24.74)
Chris asked for the 2026 GL codes and a way to "search my item and tell us what GL code to use", inside MaintStock. The source is StoneCreek's Yardi GL Coding Guide 2026 (an Excel sheet: income 4000s, expenses 6000s, capital 7000s, each with a description of what goes in it). He picked a lookup plus a code on every part and on Reorder, kept in the database.
- The codes are never in the repository. The guide is marked internal use only, and Netlify serves every file in the repository (including
supabase/). The list lives ingl_codes(readable by signed-in team members throughis_staff(), written only by the admin) and on each phone (localStoragess-gl-codes, so it works offline). The demo has 15 made-up sample codes; tests use a made-up sheet. Examples in the docs use made-up numbers. - Loading a guide: Items > Tools > GL codes > Load GL guide (admin only,
#gl-load). The file is read on the device byCTIMPORT.readFile();GL.core.parseSheet()takes a0000-0000code in the first column as an account (name, description in the next two), a row with words only in the first cell as a section ("INCOME", "Utilities", "Repairs & Maintenance (RM)" becomes "Repairs & Maintenance"), and skips header rows. Rows with no code (the guide's "Administrative Expenses: do not use") are left out. Save upserts by code and deletes codes no longer in the sheet. - Search (
GL.core.search()): each account's description is split into phrases at commas, semicolons, colons and " - ". What's typed is lowercased, plurals are trimmed (stem()), everyday words get the guide's words (SYN: fridge, LVP, sheetrock, A/C...) and some phrases are rewritten first (PHRASES: "air filter" -> HVAC filters, "smoke detector" -> smoke alarm, "blinds" alone -> blind replacements). Words that match no account at all (a brand, a model number) are dropped. Score: the best phrase (with a bonus when the phrase is mostly the searched words, so "ladders" beats "pool ladders"), the account name, the whole account, and extra phrases that match. Renovation-only and building-wide accounts lose 2.5 unless the search says renovation/building; "do not use" accounts lose 3 unless searched by name. A GL number (two or more digits) lists the codes starting with it. - A part's code (
GL.forItem()):items.gl_codewhen picked; otherwiseGL.core.guess(): a whole unit (WHOLE: fridge, range, dishwasher, microwave, garbage disposal, range hood, furnace, condensing unit, water heater, a full blind) whose name has none of thePART_WORDS(shelf, handle, pad, kit, arm, assembly...; words after "with" don't count, so "disposer with power cord" is a whole unit) goes to its unit-turn replacement account, found by account name (Chris, 2026-11-13: every whole appliance is Appliance Replacement, garbage disposals included; the guide lists range hoods there too); a part of an appliance of type Appliance goes to Appliance RM; vanes and slats go to Window Coverings; cleaners (not drain, pipe or coil cleaner) go to Janitorial Supplies and stove-top fire stops to Fire Systems, as the guide says; anything else gets a repair account only (no income, capital or do-not-use) from the name when it scores 9 or more (words only in other accounts still count as known, so "condenser pad" isn't read as just "pad"); else the account for the part's type (TYPE_WORDS, matched against account names, so no codes are written in the code). Guesses are cached per name and type. The part's window (GL.field()) shows the code under Type with Change (an inline picker,#f-gl-pick/#gl-pick-q: a second window would replace the part's window, sinceopenSheet()shows one at a time) and Use suggested (#f-gl-auto).toRow()sendsgl_codeonly onceglColumnis on (a loaded part had the column), so the app keeps saving parts if the release goes live beforesupabase/gl-codes.sql. - 25.2 check and fixes (2026-11-21): every part at every property (1,464 rows, 5 properties) was run through
guess()against the live guide; 98 names (166 rows) were wrong or needed Chris's call. Their codes were saved on the parts (items.gl_code, backup of the rows before at/mnt/project-files/gl-check/backup-before-fix.json, full listgl-code-check.csvthere).guess()now: drops the brand "Maintenance Warehouse" (BRANDS) before searching; checksRULESfirst (name pattern, optional part type -> account found by name: locks with a key or lock button -> Unit Locks Keys, passage knobs and interior/bi-fold doors -> Unit RM, pipe fittings and toilet seats -> Plumbing RM, copper fittings on HVAC parts -> HVAC RM, portable ACs, hand trucks, golf cart parts and shop vacuums -> Furniture Fixtures and Equipment, dehumidifiers and air movers -> Carpet Water Extraction, wall heaters and air conditioners -> HVAC Replacement, commercial water heaters -> Building Water Heater, hand tools and tape -> General Repairs, pest products -> Extermination, flags -> Building RM Interior, safety signs -> General Repairs, bath fans -> Electrical RM, every Pool part -> Pool RM; and, before those, Unit RM first: what the guide lists under Unit RM and another account too, towel bars/rings, toilet paper holders, door stops, screen doors and patio door handles, goes to Unit RM because it's the line with the lowest spend, Chris 2026-11-21); any Appliance-type part that isn't a whole appliance -> Appliance RM (duct, vent and ice maker count as part words). With those rules every one of the 1,464 parts gets the code it now has saved. Tests:tools/test/gl.test.mjs"25.2" case. - Reorder:
glTag()addsGL 1234(picked) orGL 1234?(suggested) to each To order line;saveCsv()adds GL code, GL account and picked/suggested.orderText()(Copy list) is unchanged; it goes into supplier carts. - Database:
supabase/gl-codes.sql(also at the end of schema.sql):gl_codes,items.gl_code(default '', checked0000-0000), andcopy_parts()copiesgl_code. Check:select count(*) from gl_codes;and Items > Tools > GL codes. - Tests:
tools/test/gl.test.mjs; harnessglCodes()at both demo properties (npm test -- --only gl).
Mileage (version 24.43)
Chris sent StoneCreek's mileage form ("SC Mileage Tracking Form 2026 - Updated 7-16", Excel) and asked for it in the app, keeping its payout calculations, with a way to add trips and submit to the property manager. Then (2026-11-05): StoneCreek now wants only a total per property ("a line for mileage associated with club ... and another line for mapleview"), though the form's directions weren't updated. So trips are logged one by one in the app, each with the property it was for, and the form gets one line per property.
- The form:
forms/sc-mileage-form-2026.xlsxis StoneCreek's file, unchanged. Tab "Mileage Policy" (the SOP) and tab "SC Mileage Tracking Form": D2 name, D3 home address, D4 work address, J2 rate per mile (0.76), rows 7 to 49 the trip lines (B date, C Location/Address, D Reason, E Total Miles, F = E x $J$2), E51 = SUM(E3:E50), F51 = E51 x $J$2, I8:I19 = SUMIFS($F:$F,$B:$B,">="&DATE(2026,m,1),$B:$B,"<="&DATE(2026,m,last)), I20 = SUM(I8:I19). (The form also has F5 = E5*0.7 and an I22 cap warning on an empty J3; both are left as they are.) - mileage-form.js (
MILEAGE_FORM): the same math in JavaScript (totals(sheet, names): every trip with its pay, andform, one line per property in the order first driven for, dated the 23rd (the sheet's last day), C = the property's name, D = "Mileage foractivities", E = its total miles; yearByMonth()), the trip check (cleanTrip(): a trip is{ d, p, why, miles }; date on the sheet, the 24th of the month before through the 23rd (periodOf(),periodRange(),periodLabel(); 24.44), a property, miles 0 to 1,000 with up to 2 decimals, optional note),RATES(add each new year's IRS rate; a later year uses the latest listed), the SOP text, andfillXlsx(template, sheet), which reads the zip (DecompressionStream), changes only the tracking tab's XML and workbook.xml, and writes a new zip (unchanged parts copied still compressed, changed ones stored, CRC-32 in the file). Cells keep their styles; text goes in as inline strings; every formula stays and its cached value is filled in (so phone previews show the dollars); the headings get the sheet's year and rate and the SUMIFS dates get the sheet's year (February's last day included); workbook.xml getsfullCalcOnLoad="1"and loses the template's SharePoint path. No library, so the app, the harness (Node) and the edge function (Deno) all run this one file. supabase/functions/send-mileage/mileage-form.js must be an exact copy (the harness checks): after changing mileage-form.js, copy it over and redeploy send-mileage. - mileage.js (the tab): one sheet per person per month, running the 24th of the month before through the 23rd and named (
month) by the month it ends in; the current sheet switches on the 24th (24.44) (property= whose manager gets it: where you were working when the month began; Send to the manager of changes it); a trip's property is picked with buttons (the property you're working at first); ‹ › months (up to next month); chips with total miles, reimbursement and rate; status (sent to whom and when, changed since sending, or due by the 23rd, red when late); the trip date is limited to the sheet's 24th through 23rd; + Add trip with Same as a recent trip; On the form (the per-property lines and TOTAL); tap a trip to change or delete it; your details (remembered on the phone inss-mileage-me, copied to later unsent sheets); the year's monthly subtotals; Download form; Send to manager; Rules. Sheets are kept on the phone (ss-mileage, with the email they belong to) and saved in the background (insert the first time, then update only the form columns); with no signal they wait and save ononline. If another phone made the same month first, this phone's lines are added to that sheet. Sign-out refuses while something is unsaved, then clears both keys. The on-call phone doesn't get the tab; view-only logins and See the app as a tech can look but not change. - Table mileage_sheets (supabase/mileage.sql, also at the end of schema.sql): id, email (from the sign-in), property (defaults to my_property()), month (YYYY-MM), name, home_address, work_address, rate, trips (jsonb, at most 300, each { d, p, why, miles }), submitted_at, submitted_to, sends (jsonb list of { at, to, test }), created_at, updated_at; unique (email, month). property is whose manager gets it (the phone can change it). Rules: read, update and delete only your own rows (delete only unsent); insert only your own at a property you work at (in_shop). Column grants: the phone can only write the form fields; only send-mileage (service role) sets the sent fields. view_only_guard. No activity_trail on purpose (home addresses, personal pay).
- Edge function send-mileage (POST { sheet_id, test }): checks the sign-in, not view only, the sheet is yours and has trips (and a name for a real send), 20 sends a day; finds the sheet's property in report_settings.properties and sends to its pm_email only (and names each line from the properties list) (test: only to you); fetches the form from SITE_URL (default https://maintstock.com)/forms/sc-mileage-form-2026.xlsx and fills it with mileage-form.js; emails it through Resend (REPORT_FROM, RESEND_API_KEY, the same secrets as send-report) with a table of the lines and totals, copy and reply-to the sender; records the send. The phone can't choose the address or the content.
- One-time setup (the admin, after the PR is merged): run the whole of supabase/mileage.sql in Supabase SQL Editor (safe to run again), and deploy send-mileage with both files in its folder (
supabase functions deploy send-mileage). Help > Check setup then says "Mileage is set up and the send-mileage function is answering." - A new year's form: if StoneCreek changes the layout, replace the .xlsx, check the cell addresses above in fillXlsx(), and run the harness. If only the rate changes, add it to RATES (and copy mileage-form.js to the function folder).
- Tests: static checks (math, trip check, monthly subtotals, file name, the function copy and its rules, schema.sql), the "Mileage" steps in features() (including reading back the downloaded .xlsx), and the second property's manager and file name in secondProperty().
Chat (version 24.90)
Chris (2026-11-18) asked for "a live chat so people using the app can talk to each other in real time", one room per property. It runs on Supabase Realtime, which the app already uses for scans and the Make Ready board, so there's no new service or cost.
- chat.js, table chat_messages (supabase/chat.sql, also at the end of schema.sql). Columns: id (bigint identity), property (the room; defaults to my_property()), by_email and by_name (filled in by the database), body (1 to 1,000 characters), created_at (filled in by the database).
- chat_member(p): on the team (not Reports only) and working at p:
property = p,p = any(props),all_propsoradmin. Read and insert use it. Delete: chat_member and (your own message, the admin, or an owner at that property). No update grant, so nobody edits a message. anon gets nothing. - chat_stamp (before insert, security definer) sets by_email from the sign-in, by_name from the Team row (or the email's first part), created_at = now(), trims the body, and refuses a 31st message in one minute from one person (errcode 54000, "Too many messages"). The phone can't post as someone else or back-date a message. view_only_guard is on the table. No activity_trail: the messages record who and when themselves.
- Live updates: chat.sql adds the table to the supabase_realtime publication. chat.js keeps one listener for every room (no filter): Realtime checks chat_read for each phone, so a phone only gets rooms it can read, and unread counts work for every room. Deletes carry only the id (Postgres sends only the key).
- Data size: a room opens with its newest 40 messages (
PAGE); Show older reads 40 more (created_at < oldest). At start-up, one small read (id, property, by_email, created_at, at most 200) counts messages since this phone last looked. The phone keeps the last 40 of each room (localStoragess-chat), the time it last looked at each room (ss-chat-read; a room never opened starts at "now") and unsent text per room (ss-chat-draft). All three clear on sign-out and on a property switch (clearShopCache). - Rooms (
roomsFor): the shop you're in first, then your tick-box properties, or every property (shopChoices) for the admin and All properties. One room ("") when there are no separate shops (the demo without ?shop). The Room list only shows with more than one room. - Finding it: Chris: "Make sure chat is easy to find." The speech-bubble button
#chat-openin the header (next to Search) opens Chat from every screen and carries the count (#chat-head-count, set byonUnread). applyOff() hides it for the on-call phone and when Chat is turned off. - Unread: the count goes on the Chat tab button (
#chat-count), on People along the top (renderBar, since 24.99), and on the Chat tile in More. A message arriving on another screen shows a toast with Open chat, unless the camera is open or another toast is showing (a scan's Undo stays put). The app catches up (recount, and reload of the open room) on visibilitychange and online. - The tab redraws keep the message box (same element), the cursor and what's typed. Enter sends only with a fine pointer (a computer); on a phone Enter is a new line.
- Not built yet: photos in chat, editing. Phone notifications and emails arrived in 24.91 (see Notifications below).
- 24.91: the speech bubble flashes (
.unread, CSSchat-flash, orange--chat-flashsince 24.92; lit without animation under prefers-reduced-motion) and the browser tab's name starts with the count, like "(2) MaintStock", both fromonUnread. 24.92:tabAlert()flashes the title ("💬 New message") once a second while the tab is hidden and swaps the favicon toicon-mark-dot.svgwhile anything is unread. It also sets the app icon number (navigator.setAppBadge); sw.js adds 1 per chat push while the app is closed, keeping the count in themaintstock-badgecache (iPhone Home Screen apps and installed desktop apps; Android shows its own notification dot). - One-time database step: in Supabase open SQL Editor, paste the whole of supabase/chat.sql and tap Run. It's safe to run again. Run it after multi-properties.sql and view-only.sql. Until it's run the tab says "Chat isn't set up yet." and Help > Setup check warns. Check:
select tablename from pg_publication_tables where pubname = 'supabase_realtime' and tablename = 'chat_messages';returns one row. - Demo: sample messages in
chat_messages(Sample Oaks has its own with ?shop=demo-oaks); the first message you send gets "Got it, thanks!" from Alex after 2.5 seconds (sessionStorage demo-chat-reply-mschanges it), and__demoSay(body, by, name, property)posts as someone else. - Tests: CHAT.core in the static checks, the "Chat" steps in features() (send, live reply, count on Chat and More, Open chat, typing kept, draft kept, delete, a tech can't delete others, view only can't write), and the room, saving and room list in secondProperty().
Notifications (version 24.91)
Chris (2026-11-18): "Yes, message notifications. But i want users to be able to select which app/email notifications they receive."
- notify.js: the Notifications window (Help > Notifications, Chat > 🔔 Notifications, and a pointer in Make Ready > Alerts).
NOTIFY.core.KINDSlists each kind with its alert_prefs columns. Each person reads and saves only their own row (alert_prefs RLS: your own row, or owners for Make Ready). It saves every column it shows, so two phones agree. Kinds are hidden for the on-call phone (on-call only), view-only logins (no Friday reorder) and screens turned off for the person. - Database (supabase/notify-prefs.sql, also at the end of schema.sql): alert_prefs gets
chat_push(default true),chat_email(default false),low_push,reorder_push,oncall_push,mileage_push(default true). Since 25.19 alsoscan_push(scan-reminder.sql, default true). No row or no column means the default. chat_messages getsemailed_at(messages from before the step are marked as emailed), an index on unemailed messages, and chat_stamp now clears emailed_at so a phone can't skip an email. A scheduled job maintstock-chat-emails runs every minute and only calls the function when a message has waited 3 minutes for its email (skipped where scheduled-jobs.sql hasn't been run). - low-stock-push (supabase/functions/low-stock-push/index.ts and chat.js): after a message is sent, the sender's phone calls it with
{action: "chat", id}. It checks the message is the caller's and under 10 minutes old, then sends a phone note ("Sam · Club at Highland Park", the message, tagchat-<property>so a room's notes replace each other, opens#chat) to everyone who can read that room (roomTeam, the same rule as chat_member) except the sender, if theirchat_pushis on. Then it waits 3 minutes and sends the emails. Emails: once a room has been quiet for 3 minutes, its unemailed messages are claimed (emailed_at set) and each person withchat_emailon gets one email with the messages they didn't write (Resend batch, fromCHAT_FROMor "MaintStock Chat alerts@maintstock.com"). The scheduled job catches any email the wait missed. - The other notes now check the person's choice before sending: low stock (
low_push), Friday reorder (reorder_push), on-call (oncall_push), mileage (mileage_push), Make Ready (mr_push,mr_email, as before). - One-time steps: 1) deploy low-stock-push (Supabase, Edge Functions, or
supabase functions deploy low-stock-push); 2) in SQL Editor paste the whole of supabase/notify-prefs.sql and Run (after chat.sql, board-alerts.sql and scheduled-jobs.sql; safe to run again). Until step 2, Notifications saves only the Make Ready choices and says so. Check:select column_name from information_schema.columns where table_name = 'alert_prefs';lists chat_email, and Help > Setup check shows "Chat emails" under Scheduled jobs. - Resend's free plan sends 100 emails a day, which is why chat emails start off and are bundled.
- Demo: alert_prefs keeps the choices; a sent message is recorded in
__demoDb.chat_pokesinstead of a notification. - Tests:
NOTIFY.corein the static checks; Notifications steps in the "Chat" part of features() (6 rows, starting ticks, Save, reopen, the poke, view only has no Friday reorder); tools/test/chat-notify.test.mjs for who gets the note and the email.
Top bar (version 24.91)
Chris: "the number of items doesn't need to be displayed on the top bar of the app. Adding the messages button cut it off, as well as the online status." renderSync() no longer shows "515 items · live". #sync shows only the property (with the switch button for people at more than one), View only, Reports only, "No signal" and "N scans waiting for signal", and hides when there's nothing to say. Help > status still shows Connection and Parts on this phone.
City complaints (version 24.17)
From Maple View's idea ("A tab for city complaints"). Chris picked city notices plus reinspections. Maple View keeps a "City Complaint List" tab in its Day to Day workbook (Date of Complaint, Unit of Complaint, Deadline from city, Issue of Complaint, Completion Date, Notes), so the tab uses the same words and can import that sheet.
- city.js, table city_complaints (supabase/city-complaints.sql, also at the end of schema.sql). Columns: id (made on the phone, so photos can be filed under it before the row is saved), property (defaults to my_property()), received (Date of complaint), agency (From), case_no, place (Unit or area, free text), issue, fix_by (Deadline from city), reinspect_on, result ('', passed, failed), fine, status (open = Needs work, fixed = Fixed waiting on the city, closed = Closed by the city), fixed_on (Completion date), closed_on, notes, photos (jsonb list of storage paths, up to 12), name (generated "place: issue", the Activity label), created_by, updated_by, created_at, updated_at.
- Rules: anyone on the property's team (in_shop) reads, adds and updates; only the property's owners (shop_owner) delete. view_only_guard and activity_trail triggers; explicit grants; anon gets nothing. The on-call phone (Reports only) can't see it and doesn't get the tab (it's not in REPORTS_TABS).
- Photos: private bucket city-files (JPEG, 2 MB since 25.23, 5 MB before). Path
<property>/<complaint id>/<random id>.jpg. city_upload_ok(name) checks the first folder is a property you're working at, the path shape, 100 uploads per person per day, and (25.23) 50 MB per person per day. Read and remove policies check the first folder with in_shop. The phone shrinks each photo to 1600 px, uploads new ones when Save is tapped, shows them with 1-hour signed links, and removes deleted ones from storage after the row is saved. A bigger view opens inside the same window (never a bare image link, so Back doesn't leave the app). - Pure helpers in CITY.core, tested by the harness in Node: urgency (late = Needs work past the deadline; soon = deadline within 7 days; reinspect = a visit within 3 days that isn't closed or passed), sortRows, counts, clean (checks before saving: an issue is required, the fine must be dollars, the deadline can't be before the complaint; Fixed and Closed fill their dates with today), sheetRead / sheetDay (header names in SHEET_FIELDS, tried in order; Excel day numbers, ISO and M/D/Y dates; a completion date means Fixed, a closed date or a status like Closed means Closed), sameAs (same date, unit and issue = already here), toCsv.
- Import uses CTIMPORT.readFile(file, want) (ctimport.js). Since 24.17,
wantlets it pick the first visible tab whose rows pass the test, so a workbook with the complaint list on its second tab works. Withoutwantit reads the first visible tab as before (Contacts and Make Ready imports are unchanged). - The list is kept on the phone (localStorage
ss-city, with the property it's for, cleared on a property switch), so it shows with no signal. Adding and changing need signal. - Today (today.js): a City complaints card (red when one is past the deadline), up to 3 late ones under Do these first, a City complaints group in Search everything (opens the complaint), and a unit's complaints on Unit history (matched with sameUnit or mentions on place). Today loads the list the first time it opens.
- Activity: area "City complaints"; field names in FIELD (activity.js); the photos list shows as a count.
- One-time database step: in Supabase open SQL Editor, paste the whole of supabase/city-complaints.sql and tap Run. It's safe to run again. Until it's run the tab says "City complaints aren't set up yet." Run it after activity.sql and view-only.sql (they make log_activity and view_only_guard).
- Tests: static checks of CITY.core and schema.sql, the "City complaints" steps in features(), a view-only check, and the printed list and CSV name in secondProperty().
Resident notices (version 24.95)
Chris (2026-11-19): "Here is the CHP logo we use on printed notices. Can you build a notice generator into the app. It should always have the logo at the top."
- notices.js (
window.NOTICES), loaded on first use byneedNotices()in app.js (in the service worker SHELL, so it works offline). Screennotices("Resident notices"), in the Units room. Not in REPORTS_TABS. In OPTIONAL_TABS, so Screens in use can turn it off. - Templates are
core.TEMPLATES(id, name, info, title, default where, body). Body tokens:{when}(whenWords: "on Wednesday, November 25, 2026 from 9:00 AM to 1:00 PM"),{where}/{Where}(the Where box, else the template's own words),{office}("the office at"). Plain words, no promises about the law; the team edits any of it. To add one, add an entry to TEMPLATES (the harness counts them against the tiles). - The message follows the boxes until it's typed in (
edited); Start the message over clears that. - PDF: jsPDF, letter, inches.
draw(pdf, n, p, logo, box)lays out one notice in a box; Two per page draws two at scale 0.62 with a dashed cut line at 5.5 in. Logo centred, at most 4.6 x 1.6 in, never stretched (fitBox). The message shrinks 0.5 pt at a time down to 9 pt to fit above the signature and small print (footerLines: name · address, "Questions? Call the office at …"). File nameNotice <heading> <property> <day>.pdf. Print opens the blob in a new tab (CSP doesn't allow blob frames); if the browser blocks it, the file is saved instead. - Logos:
report_settings.properties[].logo= public URL ofitem-photos/logos/<property>-<base36 time>.jpg.pickLogo()draws the picked image on white, at most 1200 px wide, JPEG 0.9, uploads (photo_upload_ok()rule: JPEG, 500 KB, 40 a day, 200 logos; admin only since 25.23), thensaveLogo(id, url)(app.js,savePropwith an edit function, admin only). Removing a logo only clears the link (the old file stays; an owner can delete it in Storage). The Properties Edit window showslogoField()and keeps its copy oflogocurrent so Save doesn't put the old one back. - On the phone:
ss-logos{ property: { url, d (JPEG data link), w, h } }, filled when the logo is first seen (fetched with CORS, no Supabase key needed; the bucket is public) or picked;ss-notices{ property: last 8 notices }. - CHP's logo is the picture from Chris's "Logo Document.docx" (444 x 138 px PNG, white text on grey), saved as JPEG and uploaded to
item-photos/logos/chp-….jpgon 2026-11-19. It's small: printed at about 4.6 in wide it's roughly 100 dpi. If a sharper copy turns up, the admin replaces it with Change logo. - No database change.
- Tests:
notices()in tests/harness.js, run at Demo Apartments (hasdemo/sample-logo.jpg) and Sample Oaks (no logo, then Add logo).--only noticesruns just these.
Unit equipment card (version 24.12)
unitgear.js, table unit_equipment (supabase/unit-equipment.sql, also at the end of schema.sql). Unit history (today.js) calls GEAR.section(unit, reopen) once per window and puts the card under the buttons; the card loads its own rows (.eq("unit", canon(u)), plus .eq("property", ...) when the person is in a property's shop) and redraws itself, so Unit history's own redraws keep it. Each unit's rows are cached on the phone (localStorage ss-gear-<property>-<unit>), so the card still shows with no signal; adding or changing needs signal (it says so).
- Kinds are the KINDS list in unitgear.js, with each one's usual life in years (Refrigerator 13, Range / oven 15, Dishwasher 10, Water heater 10, Furnace 20 and so on). A row at or past it shows "Past its usual life" in the warning color. Add a kind there; the database only checks its length.
- Paint and Locks reuse the columns: for Paint, model is the color and serial the sheen; for Locks, model is the lock type and there's no serial, year or warranty. Lock rows say never to write key codes (Chris declined a key log on 2026-10-26).
- The year made is typed, or read from the serial number with APPLIANCE.ageFromSerial for the brands the Appliance tab knows (shown as "Made about", or "Made 2021, 2009, 1997 or 1985" when the code repeats, 24.41).
- The add/edit window replaces the Unit history window (one sheet at a time) and reopens it on Add, Save, Remove or Cancel. Remove takes two taps. Every add, edit and removal is in Activity (activity_trail trigger; the label is the generated
namecolumn, "2601: Refrigerator"). - Appliance tab, This job: Save to the unit's equipment (hooks.saveToUnit in app.js, hidden for the on-call phone) calls GEAR.saveJob. Same kind with the same serial, or one with no serial yet: it edits that row. A different one of the same kind: it asks "It replaced it" (edits the old row, sets Put in to today, clears the warranty) or "Add another". The year picked on How old is it? becomes the year made (else it is worked back from the job's age).
- Find parts for this model on a saved fridge, range or dishwasher calls APPLIANCE.useJob(job), which fills This job and shows it.
- Tests: "Unit equipment card" and "Unit equipment from the Appliance tab" in features(), plus a static check that schema.sql has the table, rules, grants and triggers.
Unit # lookup and Appliances by unit (version 24.66)
No database change: it reads unit_equipment with the same read rule (in_shop(property)).
- Unit # (
TODAY.unitBox(prefix)in today.js): a form with a text box and Go, at the top of Today (#td-unit), Scan (#sc-unit, prepended by app.js) and Appliances by unit (#ug-unit). Submit (Go or Enter) callsunitHistory().fitUnitBoxes()sets the keyboard:inputmode="numeric"when every known unit at the property is plain digits (finder.jsbldg2or Terrace's quiet addresses, else PM's units plus the appliance list),textotherwise (Maple View 3515-33, Fox Ridge 10834-23, B12).inputmodenever blocks typed letters. - Unit history: the equipment card (
GEAR.section) is now the first child of.uh, then the unit facts, buttons, PM and History.spelled()opens a unit as it's written on file (Apt 0101 opens Unit 101).knownUnit(u)is true when PM's unit list, the appliance list or the property's map (finder.jslookup, which unitHistory loads withneedFinder()when it isn't loaded yet) has it, false when none does (shows#uh-unknown), null when the property has no unit list at all (says nothing). - Appliances by unit (view
unitgear,#view-unitgear, in OPTIONAL_TABS so it can be turned off per property or person; not on the on-call phone):GEAR.loadAll(force)reads every row at the property (fetchAll,.eq("property", ...)in a shop), at most every 10 minutes, and keeps it in localStoragess-gear-all-<property>with when it was read. Adding, changing or removing on a card callslistChanged()(read again); a card's own load is merged into the list (mergeUnit). With no signal it shows the saved list with.ug-offline; never read on this phone: "needs signal the first time". A unit's card with no saved copy of its own falls back to the saved list (readCache). - Filters: search (unit, type, brand, model, serial, notes; a unit typed like 0909 matches by
canon), type (#ug-kind), quick filtersdata-ugfall / warranty (warranty_until today or later) / old (madeYear10 or more years ago; paint and locks never). Sort#ug-sort: by unit (headingsUnit 2304 · 2), by type, oldest first. Rows marked replaced (24.63) are left out. 100 rows at a time (#ug-more, like Items).#ug-csvdownloads what's showing:MaintStock appliances by unit <property> <date>.csv(shopTag()). - Search everything: units come from PM's list plus the appliance list; each unit row's name is
Unit 2304 · Refrigerator Hotpoint 2026(GEAR.summary: first by kind order, brand or model, year made or put in,+N more), subtitle "Appliances, history, reports, PM, Make Ready". Appliances in units lists rows whose type, brand, model or serial has every word typed. Today'sshow()and every search box callGEAR.loadAll(). - Demo: units 102, 105, 909 and 203 have appliances at Demo Apartments; with
?shop=, every sample row gets its property and Sample Oaks has B12, A03 and C07. New rows get the shop's property, like the database default. - Tests: the "24.66 (unit equipment)" block in features(), run at Demo Apartments and again at Sample Oaks.
Activity by person and date (version 24.4)
activity.js, wired into the Activity tab in app.js. The Show list picks "Parts scans" (the older live list in app.js, renderActivity and loadLog, which now also takes the From and To dates) or Everything / one area, which activity.js draws into the same #activity-list. Owners and the admin start on Everything, others on Parts scans; the pick is saved per phone (ss-act-show).
Everything reads, for the person and dates picked, up to 500 rows each from stock_log, equipment_log, pool_tests, pm_log, mm_reports (by created_by and created_at), report_emails, feature_requests and activity_log, turns each into one line (SOURCES and describeTrail in activity.js), sorts them newest first and shows 300. Download CSV pages through everything with fetchAll. Dates are local days: From's midnight up to the midnight after To (ACT.core.dayRange).
activity_log is new (supabase/activity.sql, also at the end of schema.sql). The trigger function log_activity() runs after each insert, update or delete on items, equipment, pools, units, pm_tasks, make_ready, mr_board, shop_map, staff, report_settings, mm_reports, feature_requests and pm_log; the trigger's argument says which actions to log for that table (for example only deletes for pm_log, because doing a PM visit is already in pm_log). It records who (the signed-in email from the JWT; blank for SQL run in the dashboard, shown as "System"), the property, a label, and only the columns that changed. Columns that change as a side effect of something already logged (items.on_hand from a scan, equipment.status from a check-out), timestamps and updated_by are left out, and an update with nothing else changed writes nothing. To log a new table, add it to the list at the end of activity.sql, a noun and area in NOUN in activity.js, and its friendly column names in FIELD; the demo's copy of the rules is TRAIL in demo/demo.js.
Who sees what: activity_log's read rule allows your own rows, owners of that property and the admin. The screen matches it: a tech's person list in Everything only has themselves. The other log tables keep their old read rules (the team already sees every scan in Parts scans).
Mouse-over tips (version 24.48)
tips.js (loaded right after i18n.js) gives buttons a one-line tip that shows when a mouse rests on them. TIPS maps an element's id ("#help-sync") or its English words ("Copy list") to the tip. A MutationObserver gives each button, a.btn, [role=button], select and checkbox with no title its tip as its title; a symbol-only button with an aria-label gets that. On pointerover from a real mouse (and (hover: hover) and (pointer: fine)) the bubble (.tip in styles.css, #tip) opens after 350 ms, from any element with a title, including titles the app set itself. While it shows, the title moves to data-tip-on so the browser's own tooltip doesn't double it; it's put back when the mouse leaves. Keyboard Tab (:focus-visible) shows it too; click, Esc, scroll and wheel close it. Taps never open it.
To add or change a tip: edit TIPS in tips.js (the key must match the button's English exactly, or use #id), add the Spanish to i18n-es.js under "Mouse-over tips" (the harness fails on a tip with no Spanish), and release. Add data-no-tip to an element to keep tips off it and everything inside it. In Spanish, tips.js maps a button's Spanish words back to English with I18N.t() to find its tip.
Hover color: the @media (hover: hover) block in styles.css (24.48, made stronger in 24.52 because Chris couldn't see the first shade) fills plain buttons with --accent / --accent-fg, darkens filled buttons (brightness(.8), 1.25 in the dark theme), fills .btn.danger red, and gives tiles, rows and tabs --btn-hover (a strong blue tint, set per theme). Keep the change obvious: a faint shade reads as no change. New tappable styles should be added to that block.
Spanish (language switch)
The app is written in English. With Español picked (Help > Language, saved per phone as ss-lang), i18n.js swaps each bit of English on screen for its Spanish as it appears, using i18n-es.js: an exact list ("Save" -> "Guardar") and patterns with {0}, {1} for the parts that change ("{0} on hand" -> "{0} en existencia"). Anything not in the list stays in English. Text marked translate="no" (names, notes, what people typed) is never touched. Reports, PDFs and emails are made from the code, not the screen, so they stay in English. Since 24.63 picking a language switches in place (I18N.use(l), which fires an i18n-change event the app redraws on): every swap keeps the English it replaced, so English comes back without a reload, and nothing typed, queued or open is lost. I18N.set(l) still reloads (the welcome link's &lang=es uses it). A <textarea>'s words are never translated, but its placeholder and aria-label are. On-screen dates asked for with a [] locale follow the app language (es-US); dates the app writes in English itself ("Thu Nov 12") use the word list's dates day and month names. While the Spanish list loads at start-up, html.i18n-wait hides the page for up to 2.5 s so English doesn't flash.
To fix or add a Spanish phrase: open i18n-es.js, find the English (exactly as it appears on screen), and change or add the Spanish beside it. Keep the {0}, {1} placeholders. Then bump the version like any release.
Karen (24.36). i18n.js keeps a list of languages (LISTS: code -> word list file and the global it sets). Karen is ksw (S'gaw Karen, written in Myanmar script), word list i18n-ksw.js. Languages in PREVIEW only load under /demo/; on the real app a phone set to one of them gets English. Karen stays in PREVIEW until Eh Bleh (a native speaker) has checked the words (review sheet: project files karen-review/MaintStock-Karen-words.xlsx). The list is a short draft written without a native speaker, so it only covers the main screens and common buttons; a short list of right words beats a long list of wrong ones. styles.css :lang(ksw) puts Myanmar fonts first and turns off letter spacing and capitals, which break the stacked letters. Android has Noto Sans Myanmar built in, so no font file is shipped.
To turn Karen on: put the checked words in i18n-ksw.js (the English side must match the screen exactly; the harness fails on an English phrase the app doesn't have), remove "ksw" from PREVIEW in i18n.js, add <button class="btn" type="button" data-lang-pick="ksw" lang="ksw">ကညီကျိာ် Karen</button> to the Language group in index.html (the harness checks both go together), and release. Welcome emails have no Karen version.
Adding another language: a word list file like i18n-es.js setting its own global, an entry in LISTS, a button in the demo first (and PREVIEW), and harness steps like the Karen ones.
Demo
maintstock.com/demo runs the real app against demo/demo.js instead of Supabase. demo.js builds the sample data in the browser:
- 43 parts
- 14 loaner units
- 3 sample techs
- 90 days of history
- 3 pools
Nothing reaches the real database, and reloading starts the demo over. Demo data saves on the device under names starting with "demo-", so it never mixes with real scans on the same phone. To change the sample data, edit the lists near the top of demo.js. Test switches: /demo/?shop=demo-oaks (the second property), /demo/?viewonly (a view-only login), /demo/?big (1,200 parts).
Handouts (version 24.2)
The Team tab's Handouts to print (owners only, hidden in the demo) saves the PDFs in handouts/. To change one, edit its HTML in handouts/source/ (features.html, quick-start.html, quick-start-es.html; the Full user guide is printed from help/manual.html, so update the manual instead), run py help/build.py (Mac: python3) and then node handouts/source/render.js from the repository root (needs Playwright and Chromium), check the PDFs, and release as usual. A new handout needs its PDF in handouts/, a button with data-handout="<file name>" in index.html and demo/index.html, and Spanish for the button in i18n-es.js. The resident thermostat guides (24.88, Thermostat-Guide.pdf, Guia-del-Termostato.pdf) are data-guide buttons on the Help tab for everyone, not Team-tab handouts; their HTML is written by python3 tools/thermostat-handout.py handouts/source (edit the text and drawings there, not the HTML), then render.js prints them. They must stay one page (the harness checks). handouts/source/ isn't served. The PDFs are public files whose buttons only owners see, so never put anything private in one.
Other documents
- User manual, Troubleshooting guide, What's new: Help tab or maintstock.com/help.
- Developer documents in the GitHub repository: README.md (overview and index), CHANGELOG.md (every version), CONTRIBUTING.md (rules for changes), and in docs/: ARCHITECTURE.md (how it's built and every database table), SETTINGS.md, RELEASING.md, BACKUP-AND-RESTORE.md.
Unit inspections
Unit inspections (version 18) are stored in the same mm_reports table as mold reports, with kind = 'insp', so they share the photo storage (under mm/inspection id/), the no-delete rules, the email log and the send-report function. supabase/inspections.sql adds the kind column, two settings (insp_emails: where inspections are emailed, blank means the property manager; filter_sizes: the team's filter size list), and the add_filter_size function that lets any team member add a size.
To change the inspection's items or their choices, edit ITEMS at the top of insp-report.js. Each item has an id (stored with the answers, so don't rename one that's been used), a title, and its choices. A choice marked true needs attention: it shows red and is counted on the PDF. The form, the PDF and the counts all follow ITEMS. Bump VERSION in app.js and CACHE in sw.js so phones pick it up.
Report properties
Version 21.5 adds report_settings.properties (supabase/properties.sql): a list of { id, name, address, pm_name, pm_email, cc_emails }. Each report stores the picked property's id in data.propertyId (and its name in data.property). send-report looks the property up by id, then by name, and emails that property's manager and copies; with no property list it uses the old single pm_email and cc_emails. Saving Report settings also copies the first property into the old fields. The mold form, forms/mold-moisture.pdf, is the official NAA form exactly as issued (the same file as forms/mold-moisture-original.pdf) and must not be edited; "Who assessed the situation?" prints on an attached page made by mmreport.js.
Reports-only logins
Version 21.6 adds a third staff role, 'reports' (supabase/oncall.sql), for the shared on-call phone. is_staff() now means "on the team and not reports-only", so every inventory, PM, Make Ready, pool and equipment policy and function shuts that login out with no other change. The report tables (mm_reports, report_settings read, report_emails read, the report-files bucket and report_upload_ok) use the new is_member() (anyone on the team) instead. staff_read also lets anyone read their own row so the app learns its role. In app.js, startSignedIn calls startReportsOnly() for that role: it hides every tab but Reports, HVAC, Appliance, Find unit and Help (REPORTS_TABS), hides New unit inspection, skips loading items, and the reports list leaves out inspections. Owners switch roles on the Team tab (Make owner, Reports only, Make tech).
View-only logins (version 24.5)
supabase/view-only.sql adds staff.view_only. It sits on top of any role: a view-only owner, tech or Reports-only login sees exactly what that role and their properties allow, and can't change anything. The lock is in the database. A trigger, view_only_guard, runs before every insert, update and delete on every public table (push_subs, board_reads and activity_log are left out; activity_log is written only by the log_activity trigger, which must still record a view-only person switching property) and refuses the change when the signed-in person is view only. Because it's a trigger, it also stops changes made inside the security definer functions (apply_op, equip_op, mr_set_step, add_filter_size), which skip the row rules. The one change it lets through is a view-only person's own staff row when only property changes, so switch_property still works for someone with several properties. Three restrictive policies on storage.objects refuse their uploads, file changes and deletes. The send-report and read-board edge functions refuse them (403). The admin can't be view only (check staff_view_only_admin), so nobody can lock the admin out.
In app.js, lockWrites() wraps the Supabase client: for a view-only login, insert, update, upsert and delete, every rpc except check_setup and switch_property, every edge function except low-stock-push, and storage uploads return the error "This login is view only…" without going to the server, and runOp refuses before anything is queued offline. The Scan screen is off for them (isOff), a banner says View only, the sync line starts with "View only ·", and the obvious add and save buttons are hidden (body.view-only in styles.css). Since 24.9 any button built in JavaScript that only changes things gets the class vo-hide, which the same rule hides (Mark ordered, Receive delivery, + Add apartment, Fill in from a photo or sheet, Edit steps, PM Done and Done for all); give new buttons like that the class too. Owners turn it on and off with View only / Allow changes on the Team tab (two taps). Try it in the demo at /demo/?viewonly.
Any new table needs the trigger, in the same SQL that creates it:
create trigger view_only_guard before insert or update or delete on public.new_table for each row execute function public.view_only_guard();
See the app as a tech (version 24.40)
Team > See the app as a tech (#as-tech, owners and the admin; canSeeAsTech()) opens pickAsTech(): Any tech, or a tech who works at the current property (worksHere()). seeAsTech(who) saves the real role, admin, allProps and props in state.real, sets the tech values, and refreshRoleView() redoes what startSignedIn() does for tabs (unhide, Team, Properties, Regional, applyOff()), the yellow bar (renderAsTechBar(), before #banner), the header line (renderSync()) and the open screen. isOff() reads the picked person's own screen list (personOff(state.asTech.email); blank for Any tech) instead of yours. endAsTech() puts state.real back. It's in memory only, so a reload ends it; startSignedIn() re-applies it if a new sign-in token arrives while looking. Screen only: requests still go out as the real login, so the database allows what the real role allows. Any new owner-only or admin-only button should keep checking state.role / state.admin / canEditProps() at render time (not once at start-up) so this view hides it.
Separate shops per property
Version 22.1 (supabase/property-shops.sql, also at the end of schema.sql) gives staff a property column (an id from report_settings.properties: chp, fox-ridge, terrace-garden, mapleview; "all" only for Reports-only logins) and an admin flag (Chris). Every shop table (items, stock_log, equipment, equipment_log, pools, pool_tests, units, pm_tasks, pm_log, make_ready, mr_board, shop_map, feature_requests) has a property column that defaults to my_property(), so the app never has to send it. Policies use in_shop(property) (on the team, not reports-only, at that property) and shop_owner(property) instead of is_staff() and is_owner(). apply_op, equip_op and mr_set_step only touch the caller's property's rows, and the log rows copy the parent's property. shop_map and mr_board are one row per property (primary key property); units are unique per (property, unit) and equipment codes per (property, code). staff_read: your own row, your property's team, or everyone for the admin. staff_write: the admin, or an owner for their own property's non-admin people.
mm_reports.property is set by a trigger from data.propertyId (or the property name). can_see_report() lets you read your property's reports, the ones you wrote, or all of them with property "all". report_emails and report-files reads follow the report. Report settings updates are admin-only. send-report checks the same rule; low-stock-push only alerts phones of people at the part's property.
In the app, startSignedIn reads property and admin (state.property, state.admin, state.hasShops; hasShops is false on a database without the column, which keeps the old single-shop behaviour). If the phone's saved shop (ss-property) is for another property it clears the shop caches and reloads. The Team tab groups people by property for the admin, with a property box per person, a property box on Add, and I'm working at + Switch, which updates the admin's own staff.property and reloads.
Version 22.2 (supabase/all-properties.sql) adds staff.all_props. With it, a tech or owner can call switch_property(p), which sets their own staff.property (the shop they're working in now; the admin uses it too), and can_see_report() lets them read every property's reports. The staff_guard trigger stops anyone but the admin from changing all_props or admin. On the Team tab the admin's per-person property box has All properties: for a Reports-only login it sets property 'all', and for anyone else it sets all_props. send-report follows the same report rule.
Version 23.5 (supabase/mm-shared.sql, also at the end of schema.sql) shares mold & moisture reports with every property: the mm_reports read and update policies allow any row with kind = 'mm' to anyone on the team (is_member()), and keep can_see_report() for unit inspections (kind = 'insp'). Photos (report-files) and report_emails follow, since their rules check that the report can be seen. In the app, unit history (today.js) skips reports whose property (mm_reports.property, or data.propertyId) isn't the shop you're working at.
Version 22.3 (supabase/multi-properties.sql) adds staff.props, a list of property ids. switch_property() and can_see_report() also allow any property in it, and staff_guard() keeps it admin-only. On the Team tab the admin gets a tick box per property plus All properties: one ticked sets property and clears props, several set props (and keep property if it's still ticked), All sets all_props (or property 'all' for Reports only). send-report follows the same rule.
Parts per unit, Regional screen and new-property setup (version 24.38)
Chris picked these from a feature check ahead of the 14-property rollout. SQL: supabase/portfolio.sql (also at the end of schema.sql).
Parts per unit. #forunit on the Scan screen shows only in Take out (renderForUnit(), called from setMode()). setForUnit() cleans the unit (unitClean(): drops Apt/Unit/#/spaces, capitals, 20 characters) and keeps it in ss-forunit with a time; it's dropped after two hours. takeOut() puts unit on the op and undo() passes it to the undo, so apply_op saves stock_log.unit on both and the parts net out. applyOp() adds p_unit only when the op has one; on PGRST202 (the database's apply_op has no p_unit yet) it sets state.noUnitCol and resends without it, so scans never fail before the SQL is run. Queued ops keep unit, so offline take-outs are saved with it when they sync. loadUnitPast() reads the unit's out/undo rows from the last 30 days (TODAY.core.variants() matches 909 / 0909); unitVisits() groups those older than 6 hours by day and nets undos; anything left shows the yellow Repeat call? box. Unit history (today.js) reads the unit's rows too (up to 300) and shows a Parts line per day and person, plus a Repeat calls note when parts were taken on 2+ days in 30. Activity and Parts scans show Unit 2601 in the line and the CSV.
Regional screen (region.js, #tab-region / #view-region). Shown when roamsShops() (admin, all_props, or 2+ props); hidden for Reports-only. Not one of the screens that can be turned off. REGION.load() calls region_summary() (cached for a minute; Refresh forces it). REGION.core.stats(row, property.off) turns a row into the labeled numbers and leaves out screens the property turned off; tone bad (red) for out of stock, past ready-by, past deadline and overdue equipment. Open its shop calls switchShop(). Copy summary uses summaryText(). A missing function shows "isn't set up yet" instead of an error.
Setup checklist and copying parts. REGION.core.setupSteps(property, summaryRow, hasFindMap) is the 11-line checklist (Find unit map = the id is in FINDER.PROPERTIES). setupButton(id) (Properties tab rows and Regional cards, admin only, once the summary is in) opens setupSheet(id). startField() is the Start its parts list from box on Add a property (propSheet() in app.js, admin with shops only); after saving, copyParts(from, to, levels) runs and the checklist opens. copySheet(toId) copies into an existing property (two taps). copy_parts() is admin only, skips names already in the target (case-insensitive), and gives each copy a new SS- code from the same alphabet as newCode(); box barcodes (codes not starting SS-) are kept. If the copy is into the shop you're in, the parts list reloads.
Change name. Team > Change > Change name (renameSheet() in app.js) updates staff.name with the staff_write rule (admin, or an owner at that person's property who isn't changing the admin). The button shows for owners, on every row except the admin's (the admin's own row has it). No database change.
Demo. apply_op keeps the unit; two older take-outs are tagged unit 101; region_summary counts the shop you're in from the sample data and makes up the other sample property's numbers; copy_parts records names in __demoDb.copied_parts. Harness: portfolio() (features run) and a REGION.core static check.
24.97: contacts and a fuller checklist. Add a property's Start its contacts from (startField().ctField in region.js) copies TODAY.startContacts(from): every contact not in STAFF_KINDS, cleaned with checkContact(), pref off and new ids via CTIMPORT.merge([], …). app.js propSheet() puts them on the new property before its one saveProp(). setupSteps(p, s, mapped, unitFmt) adds unitfmt (unit_example, or UNITS.KNOWN / 3+ units seen), staffcts (a Contacts entry of kind Maintenance supervisor, because send-report copies that kind and Assistant property manager on every report) and pmunits (from region_summary().pm_units, supabase/setup-units.sql; the line is left out while the count is missing).
Other shops (version 25.15)
Chris asked for it after a Saturday morning calling every property for one switch. othershops.js (window.OTHERSHOPS, init from app.js with state, el, toast, openSheet, propList, demo). canUse(): signed in, not Reports-only, at a property (or the plain demo), and 2+ properties. Entry points: #f-othershops in itemSheet() (existing parts only) and #td-others in today.js results() (always, as the last group, under "Nothing matches" when this shop has nothing; uses the scanned part when a label code was typed). The window calls find_part_elsewhere() (supabase/find-elsewhere.sql): security definer, read-only, every other property, matched by normalized supplier part # (incl. alt_suppliers), non-SS box barcode, or same name (from a part) / every word (typed). OTHERSHOPS.core.group() makes one card per property, ordered counted-with-stock, never counted, counted 0. Call buttons from callsFor(): Maintenance supervisor contacts (phone, after hours), then the property's office phone, deduplicated, at most 3. The demo answers find_part_elsewhere with the other sample property's made-up counts. Tests: otherShops() at both sample properties, plus static checks of the helpers.
Switch property from the header (version 24.18)
Chris asked to change properties from the bar up top. renderSync() (app.js) draws the property part of the header status (#sync) as a button (#prop-switch, the short name and a ▾) when roamsShops() is true: the property column exists and the person is the admin, has all properties, or has two or more in staff.props. Anyone else gets the old plain text. The button opens the Switch property sheet (pickShop()), one button per property from shopsICanUse() (the same list as the Team tab's I'm working at box), with the current one marked You're here. Picking another calls switchShop(id), the same code as Team > Switch: refuses while scans wait for signal, calls switch_property, clears the shop caches and reloads. No database change. In the demo, switch_property succeeds and the app reopens /demo/?shop=<id>, since the demo keeps nothing between loads. Harness: features() checks a one-property login gets no button; secondProperty() opens the list, checks both properties and You're here, switches to the first property and checks the header and the list follow.
Unit photos (version 24.93)
Photos tied to a unit and property (unitphotos.js), shown on Unit history. One-time database step:
- Open Supabase, SQL Editor, New query.
- Paste all of
supabase/unit-photos.sqland tap Run. It's safe to run again. - Check:
select id, public, file_size_limit from storage.buckets where id = 'unit-photos';givesunit-photos | false | 1048576(1 MB, with 50 MB per person a day, sincesupabase/security-pass-6.sql(25.23) was applied on 2026-12-05; before that it was2097152).
Export (24.94): Today > ⬇ Export photos and Unit history > ⬇ Download all build a ZIP on the phone (no library: FILES.makeZip in files.js, stored, not compressed), up to 400 photos, with photos.csv. Each export downloads the full photos, about 120 KB each, which counts toward Supabase egress (the free plan allows 5 GB a month).
Until it's run, Unit history says "Unit photos aren't set up yet" and photos taken wait on the phone. Storage: about 110 KB a photo (1200 px at JPEG 0.6 plus a 240 px preview). The free plan's 1 GB held about 180 MB of other files in November 2026, so roughly 7,000 to 8,000 unit photos fit before the Pro plan ($25 a month, 100 GB) is needed. Check Storage size in Supabase, Reports, now and then. Previews are cached on each phone by path, so looking at photos again uses little egress.
Unit number examples (version 24.83)
units.js (window.UNITS) decides what a unit number looks like at each property, so every unit box's example ("Like 2601") and keyboard match. It's loaded before pm.js in both index.html and demo/index.html and kept in sw.js SHELL. The example comes from, in order: the property's How unit numbers look on the Properties tab (unit_example on the property in report_settings.properties, no database change); the units this phone has seen at that property (pm.js, makeready.js and unitgear.js call UNITS.learn(source, units) when they save their cache, app.js calls UNITS.learnReports() when reports load, and primeUnits() reads up to 300 unit numbers from units and make_ready after sign-in when it has fewer than 3), where the most common shape (2601 and 1210 are both 9999) wins; then KNOWN in units.js for the four mapped properties; then 101. To add a property's built-in example, add it to KNOWN (the harness checks Find unit can find each mapped property's examples). A unit box uses UNITS.fit(input, propertyId, text) or UNITS.example() / pair() / inputMode(); a report or trip with a property picker passes the picked property. UNITS.building(u) names the building in a number (2601 -> 26, 351504 -> 3515, 10834-23 -> 10834) for PM's Add units, and UNITS.range() gives Add units' example range, which pm.js expandUnits reads back. finder.js lookup also reads the building and unit typed together (351504) when the front is a building on that map.