Commit Graph

378 Commits

Author SHA1 Message Date
Tyler 19377ea6cf feat(tuxedo): Apple-quality motion choreography
Deploy to route.crispygoat.com / deploy (push) Successful in 4m42s
Adds four new motion primitives in src/components/ui/ScrollAnimations.tsx
and wires them into the hero, PullQuoteBand, TheCorn, FounderStrip,
HarvestEditorial. Existing FadeOnScroll/ScrollReveal/ParallaxLayer are
left untouched so other pages (and the rest of Tuxedo) keep their
current vestibular-safe motion.

New primitives (all reduced-motion safe):
  AppleReveal       opacity 0→1 + Y 18→0 + blur(6px)→0
                    power3.out (≈ cubic-bezier(0.16, 1, 0.3, 1))
                    0.55s primary, 0.4s secondary, fires at 'top 88%'
                    one-shot toggleActions, supports immediate mount
  AppleStagger      wraps a set of [data-apple-stagger] children, fires
                    them with 0.06s stagger; ideal for editorial cascade
                    (eyebrow → h2 → rule → lede → supporting copy)
  AppleStickySection pins the first child to the top while siblings
                    scroll past; adds 6% scroll-linked yPercent drift for
                    depth. PullQuoteBand now uses this for the pre-storm
                    field photograph.
  AppleCountUp      refined count-up: power3.out, 1.6s. Replaces the
                    HarvestEditorial 2s linear-feeling counters.

Hero upgrades:
  - Title split into <span class='hero-word'> so each word cascades
    in with its own blur-up; logo → eyebrow → rule → lede → CTAs →
    stats get the block-level Apple reveal with 0.08s stagger.
  - Scroll-fade holds through the FULL hero scroll length
    (start top top, end bottom top, scrub 0.6) instead of fading by
    40% which made the type disappear before users finished reading.
  - Scroll-indicator fade uses scrub 0.5 (was 1.0) so it's physically
    tied to the scrollbar.
  - Logo uses plain div (was framer-motion); the GSAP pass animates
    all hero-reveal elements with a single consistent curve.

Editorial sections unified:
  TheCorn, FounderStrip, HarvestEditorial headers now use AppleStagger
  for their eyebrow → headline → rule → lede cascades. The harvest
  data strip uses AppleCountUp.

Also brings 'Upcoming Stops' into the magazine type system:
  font-display + clamp() H2, tracking-[0.32em] eyebrow, leading-[1.65]
  body — matches TheCorn/HarvestEditorial instead of the raw
  text-3xl/font-black treatment.
2026-07-07 09:36:35 -06:00
Nora c71354d2ae tuxedo: align storefront subpages with Field Almanac editorial voice
Deploy to route.crispygoat.com / deploy (push) Successful in 4m25s
Reskin /tuxedo/contact, /tuxedo/faq, /tuxedo/stops, and
/tuxedo/stops/[id] so they match the homepage's editorial
magazine language (Fraunces display serif, stone-50/stone-950
alternation, amber rims, hairline rules, tabular numerals).

- About page rewritten as inlined editorial sections sharing
  one WP_IMAGES library with the homepage; the four lazy-loaded
  Tuxedo about components are removed (Indian River has its own
  variants).
- Contact page now uses a dark hero with heroField half-bleed,
  a hairline-ruled info strip (address/phone/email), a two-column
  form section with bottom-border editorial inputs, and a closing
  Fraunces italic quote. /tuxedo/contact was 404ing in prod because
  page.tsx was missing — created and removed the duplicated render
  from layout.tsx.
- FAQ page uses a cream hero with Fraunces headline, an editorial
  bottom-border search, hairline-ruled accordion rows (no card
  wrappers), and a dark closing CTA with Contact pill.
- Stops list uses a dark hero with heroField bleed and a cream
  hairline-ruled sidebar list: tabular date numerals on the left,
  city/location middle, mono time + cutoff right, chevron for
  upcoming rows.
- Stop detail uses a dark hero pairing the city/state headline
  with a giant tabular day stamp, a cream hairline-ruled 4-col
  info strip (Date/Time/Location/Order by), and the editorial
  products header. Removed the dual-brand isBlue branching now
  that Indian River has its own page.
- Extracted TUXEDO_IMAGES to src/components/storefront/tuxedo-images.ts
  so the homepage, about, contact, and stops list share one
  brand-specific asset library.
- /tuxedo/faq/layout.tsx no longer double-renders the page
  component (was rendering <FAQClientPage /> alongside children).

Verified: tsc --noEmit clean, eslint clean (only pre-existing
homepage warnings), npm run build produces all Tuxedo routes
including the now-existing /tuxedo/contact.
2026-07-06 14:40:18 -06:00
Nora da09cfbd1a feat(tuxedo): editorial photo color grade across hero/pull-quote/founder/packshot
Deploy to route.crispygoat.com / deploy (push) Successful in 4m15s
Pulls the saturated-yellow WP-import JPGs down a half-step in the brightness hierarchy so the white type stays dominant and the photos read as editorial, not product photography.

- globals.css: new filter utilities (.filter-editorial, .filter-editorial-shell with cool/amber split-tone, .filter-editorial-strong, .filter-editorial-vignette) + reduced-motion reset
- TuxedoVideoHero: grade the Ken Burns backdrop image
- tuxedo/page.tsx: apply grades to PullQuoteBand, TheCorn ear macro, FounderStrip (also swap to the retouched founder image from b90f0fa), and HarvestEditorial packshot; bump founder quality 88 -> 92
2026-07-06 14:23:22 -06:00
Nora 68851cfede feat(tuxedo): magazine editorial — altitude ribbon, harvest spread, data strip
Deploy to route.crispygoat.com / deploy (push) Successful in 4m29s
Adds a 'Cereal-magazine-did-a-feature' editorial moment to the Tuxedo
homepage instead of a templated farm-stand layout. Three pieces:

1. Hero (TuxedoVideoHero)
   - Adds '5,360 FT · UNCOMPAHGRE VALLEY' masthead chip next to the
     existing eyebrow, hairline-divided like a magazine cover line.
     Reinforces the geographic / altitude voice of the brand.
   - Adds slow Ken Burns drift on the poster image (26s alternate,
     scale 1.02 → 1.10 + tiny translate). Plays under the video while
     loading; if the video fails, the poster now breathes instead of
     sitting static. Honors prefers-reduced-motion.
   - Bumps grain overlay opacity 0.04 → 0.085 for editorial texture.

2. New HarvestEditorial section (page.tsx), placed after FounderStrip
   and before StorySection per user direction.
   - Full-bleed packing-shed packshot (corn-field-zane-original.jpg,
     WP-import, 2500×1406) with subtle harvest-drift Ken Burns and a
     hairline-bordered provenance plate ('HARVEST MORNING · AUGUST ·
     OLATHE, CO') + photo credit.
   - Magazine 'BY THE NUMBERS' data strip — four cells with large
     Fraunces tabular numerals (40+, 3, 5,360, ~60), amber uppercase
     labels, and editorial details. Hairline amber rules top + bottom.
     Count-up animation reuses the existing .counter-animate GSAP
     setup so no new infra. No icons, no boxes, no color highlights —
     reads as a magazine sidebar.
   - Italic editorial caption in Fraunces with attribution: 'You can't
     replicate the diurnal swing in a greenhouse…' — John Harold,
     second generation.

3. globals.css: adds the @keyframes harvest-drift + reduced-motion
   guard for the new packshot drift (26s alternate, scale 1.04 → 1.10).

Verified on prod 2026-07-06:
  - No failed network requests
  - Hero altitude ribbon text present
  - HarvestEditorial section renders at expected scroll position
  - Packshot: complete=true, natural 1280×720, rendered 1232×587
  - All 4 data points present with correct labels & details
  - Counter values animate 0 → target when section enters viewport
  - Mobile (390px) renders cleanly with correct wrap
2026-07-06 13:55:48 -06:00
Nora b90f0fae52 fix(tuxedo): copy public/ to standalone, mark storm/founder priority
Deploy to route.crispygoat.com / deploy (push) Successful in 4m17s
Three issues caused the 'images don't work, video doesn't play' report on
https://water.tuxedocorn.com/tuxedo:

1. (ROOT CAUSE) Next.js standalone build was missing .next/standalone/public/.
   The deploy workflow copied .next/static to .next/standalone/.next/static
   but never mirrored public/. Without that, the image optimizer returns
   400 'url parameter is not allowed' on every local-relative URL — so the
   brand logo (and favicon, etc.) went blank. Symptom: HTTP 400 on
   /_next/image?url=%2Fbrand-logos%2F64294306-...%2Flogo.png.

   Fixed by:
   - cp -r public/. .next/standalone/public/ on the running server (live)
   - updating .gitea/workflows/deploy.yml to mirror public/ on every deploy
   - adding scripts/regression-brand-logos.mjs so this can't regress silently

2. Storm-field and founder-portrait images rendered as 'loading=lazy' and
   appeared blank above the fold. Marked priority so they preload.

3. Pre-existing build error: Next.js 16.2 RSC bundler treats
   'export type { FieldSession }' re-exports through server-action modules
   as runtime exports ('Export FieldSession doesn't exist in target
   module'). Removed the re-exports in water-log/auth.ts and field.ts;
   field.ts now imports FieldSession directly from @/lib/water-log/session-server.

Verified live (post-fix) on 2026-07-06:
  - regression-brand-logos.mjs: HTTP 200 image/png, header+footer logos
    render with naturalWidth=160
  - diag-home-only.mjs: all 6 images complete=true, natural sizes match
    source (storm 1440x1080, founder 604x340, ear 692x476, etc.)
  - verify-hero-video.mjs: readyState=4, paused=false, currentTime
    advancing 2.86s -> 6.87s over 4s (=30fps; the prior 'video doesn't
    play' was likely user perception — the poster+video look near-
    identical, and 'net::ERR_ABORTED' on the MP4 is normal Chrome
    behavior for parallel byte-range requests)
2026-07-06 13:33:54 -06:00
Nora 5a72705e71 fix(ops): switch pm2 to standalone server + fix wholesale_settings query
Deploy to route.crispygoat.com / deploy (push) Successful in 4m14s
Three problems were silently breaking the prod Tuxedo redesign and
the offline DB error swallowed all visibility into them:

1. `next start` against `output: "standalone"` is unsupported. Next.js
   prints "next start does not work with output: standalone" and
   silently disables the image optimizer — every `/_next/image?url=...`
   returned "url parameter is not allowed". pm2 was previously
   started as `pm2 start npm -- start -- -p 3100`. Switched to
   `node /home/tyler/route-commerce/scripts/start-standalone.cjs`.

2. The standalone server reads `.next/static/` relative to itself, so
   deploy must `cp -r .next/static .next/standalone/.next/static` on
   every sync. Without this, every `_next/static/chunks/*.js` returns
   404 and the page hydration dies. Added to the deploy workflow.

3. bash's `set -a; . ./.env` truncates DATABASE_URL at the `&` in
   `&channel_binding=require`, so the standalone server boots with
   empty DB env. `getBrandSettingsPublic` then caught the empty-pool
   error and returned `{success:false, error:'Failed to fetch brand settings'}`,
   so `state.heroImageUrl` stayed null and the hero poster never
   rendered. The new `scripts/start-standalone.cjs` parses .env in
   Node (which handles `&` correctly) and exec's the server with the
   loaded env.

4. `getBrandSettingsPublic` queried `ws.wholesale_enabled`, which
   no longer exists in `wholesale_settings`. The schema migration
   renamed it to `online_payment_enabled`. Switched the column
   reference and added a console.error log so future drift surfaces
   instead of being swallowed by the empty catch.

Plus `next.config.ts` had `hostname: "s3.crispygoat.com"` added
under `images.remotePatterns` so the optimizer accepts MinIO URLs.
2026-07-06 12:50:43 -06:00
Nora 129c9d253c feat(tuxedo): polish home with WP imagery
Deploy to route.crispygoat.com / deploy (push) Successful in 4m22s
Swap the templated 8-tile Why-grid for three image-driven editorial
moments using photos pulled from the tuxedocorn.com WordPress library:

  - PullQuoteBand: full-bleed pre-storm field with single Fraunces quote
  - TheCorn: single paragraph + ear macro, replaces feature grid
  - FounderStrip: John Harold portrait + family narrative

Hero poster switched from the tight cob macro to the wide irrigation
row with Colorado sky and cumulus clouds. The video underneath stays.

Editorial copy tightened. Display type moved to Fraunces for headlines
and timeline markers to give the page a real voice instead of
default sans throughout. Tone: "you can taste the altitude."
2026-07-06 12:03:36 -06:00
Grok f8434685a8 fix(migration): drop GRANT anon line (Neon has no anon role)
Deploy to route.crispygoat.com / deploy (push) Successful in 4m7s
2026-07-06 11:19:33 -06:00
Grok 60783131ae fix(tuxedo): graceful hero video fallback + storefront polish
Deploy to route.crispygoat.com / deploy (push) Failing after 1m27s
Hero video at /videos/tuxedo-hero.mp4 was hardcoded and 404ing, leaving
the page with no background.

* Add brand_settings.hero_video_url (migration 0099) so each brand
  can point its hero at any reachable mp4/webm without code changes.
  Saves via a separate UPDATE so the existing 32-param
  upsert_brand_settings RPC signature stays untouched.
* TuxedoVideoHero now accepts videoUrl + posterUrl. Poster renders
  underneath the <video> element via next/image so the hero is
  complete even without a video. <video> flips a data-failed attribute
  on error/stall so the poster takes over without DOM churn.
  Ambient float animations slowed 950ms → 7s/8s.
* Why section: dropped emerald/amber kaleidoscope, unified accent.
  Footer is now a provenance strip (Family-Grown · 5,360 ft · Est 1982).
* Story section: removed giant decorative 'SINCE' parallax text and
  the duplicate stats counter (already in hero). Replaced with a
  1982/2003/Today timeline.
2026-07-06 11:09:31 -06:00
Tyler 772e23ded8 fix(pwa): bump field-shell cache to v2 — evicts stale UI for installed PWAs
Deploy to route.crispygoat.com / deploy (push) Successful in 4m7s
The Apple HIG polish pass (liquid-glass chrome, iOS SegmentedControl,
ThresholdMeter) was already on origin/main and live, but anyone with
the /water PWA installed on their home screen kept seeing the OLD UI
because the SW cache name never bumped.

Old SW had field-shell-v1 baked into its bytes for every prior deploy.
The activate handler only deletes caches that aren't SHELL_CACHE or
DATA_CACHE and start with 'field-'. Same name = no eviction = stale
HTML + chunks forever.

Bumping SHELL_CACHE to 'field-shell-v2' makes the SW bytes change,
which triggers the normal SW upgrade flow:
  install → skipWaiting → activate → claim clients
The activate handler then evicts field-shell-v1 (it's now a foreign
field-* cache). On next navigation the new SHELL_CACHE is repopulated
with the fresh /water HTML + static assets, and the user gets the new
UI.
2026-07-06 10:39:52 -06:00
Tyler 5dc9a4604f Apple HIG pass: liquid-glass chrome + iOS SegmentedControl + ThresholdMeter
Deploy to route.crispygoat.com / deploy (push) Successful in 4m22s
Water log mobile field experience (PIN → Headgates → Log → Success):

* Brand rename: "Tuxedo Ditch Co." → "Tuxedo Corn" everywhere it
  was a stale reference (page metadata + admin Today tab caption).
  Constants already say Tuxedo Corn; this just aligns the stragglers.

* Tab bar (Headgates | Time): pill pair → real UISegmentedControl.
  MiniSegmented lives next to TabBar in MobileWaterApp.tsx and uses
  the same ResizeObserver-measure + spring-timing pattern as the
  existing SegmentedControl — feels like one widget at two sizes
  (this one at 32pt, the unit selector at 44pt).

* Liquid-glass chrome (recipe applied 5×, mirrored on the bottom
  submit bar): linear-gradient background + blur(24px) +
  saturate(180%) + inset top highlight + inset bottom hairline.
  TabBar, HeadgateList top nav, LogForm top nav, LogForm sticky
  submit bar, FieldPinScreen + SuccessScreen brand strips.

* ThresholdMeter (new component, mobile/ThresholdMeter.tsx): the
  screen's signature. A live "blip" indicator under the 44pt
  measurement input that ties the form to its real domain (a
  worker reading a real gauge) instead of being a decorative
  gauge trophy. Track + optional colored zones (red·green·red)
  + thumb that slides on Apple's spring curve + color-coded
  zone label. Mirrors Apple's Volume Limit / Screen Time sliders.

* i18n: 9 new zone labels per language (zoneBelowNormal,
  zoneAboveAlert, zoneInRange, zoneBelowAlert, zoneAboveMin,
  zoneReading, zoneTypeToLog, meterNormalRange + ES twins).
  Legacy normalRange/alertAbove/alertBelow signatures widened
  to accept pre-formatted strings so integer units render clean.

* Updated water-log-i18n unit test for the wider signatures.
  All 27 tests pass; tsc + eslint clean.
2026-07-06 10:32:36 -06:00
Nora 5188960bd2 fix(time-tracking): keep workers signed in for 7 days
Deploy to route.crispygoat.com / deploy (push) Successful in 3m42s
Field workers were forced to re-enter their PIN every 12 hours. That's
noticeable friction on devices that stay signed in for a week or more.
Bumped COOKIE_MAX_AGE to 7 days (604800s) so a worker who clocks out
on Friday doesn't see the PIN screen Monday morning.

The cookie is httpOnly + secure (in prod) + sameSite=lax, so the
extended lifetime doesn't materially change the threat surface. The
expires_at inside the cookie value is recomputed from the same
constant, so the in-cookie expiry and the browser-side Max-Age agree.

Field workers still log out explicitly via the Hub 'Sign out' tile
(or the server-side /api time-tracking/notify handler) when they
want to end the session sooner. Forced re-auth only happens when the
cookie actually expires or the worker logs out.
2026-07-06 10:14:00 -06:00
Nora 6f1aa37a26 fix(time-tracking): inherit lang from water-log and stop PIN flash
Deploy to route.crispygoat.com / deploy (push) Successful in 4m18s
Two UX bugs in the worker Time Tracking mobile flow:

1) Spanish parity between Water Log and Time Tracking. The Water Log
   mobile app (/water) uses the wl_lang cookie for its language; the
   Time Tracking field client used its own time_tracking_lang cookie.
   A worker who set Spanish on /water then tapped the Time tab saw
   English. getLangCookie() now falls back to wl_lang when
   time_tracking_lang is unset, so the Time tab inherits the worker's
   Water Log preference. Standalone /tuxedo/time-clock is unaffected
   (no wl_lang cookie there).

2) PIN screen flash on tab change. initialState started at screen
   'pin', so the init effect that resolves the session cookie + open
   clock-in caused a one-tick flash of the PIN screen even when the
   worker was already authenticated. initialState now starts at
   'loading' (a spinner) and the init effect dispatches the correct
   screen (hub / working / pin) once the session check resolves.

Public contract unchanged: exported types, function signatures, and
the cookie name on writes are all preserved. The change is additive
on read (extra cookie fallback) and a one-key swap on initial state.

Verified locally: tsc clean, lint unchanged (354 problems = baseline),
vitest 226 pass / 29 fail (same pre-existing auth failures, none
related to this change).
2026-07-06 10:05:55 -06:00
Nora c7c83890e4 fix(time-tracking): use correct field_workers columns in fleet summary
Deploy to route.crispygoat.com / deploy (push) Has been cancelled
The /admin/time-tracking overview page crashed on render with
`column "fw.display_name" does not exist`. Cycle 10 unified
`time_tracking_workers` + `water_irrigators` into `field_workers`,
which uses `name` and `pin_hash` (not the legacy `display_name` /
`pin` from `admin_users`). This fix aligns the SQL, row type, and
result mapper with the actual schema.

End-to-end verified against water.tuxedocorn.com with worker PIN 2229:
PIN auth, task picker, clock-in, and clock-out all succeed with no
console errors and no failed HTTP requests.

Includes a regression test that fails on the buggy SQL (4/8 fail) and
passes after the fix (8/8 pass). Covers the column contract, row
projection, empty-result + unauthenticated boundaries, and null
aggregate coercion.
2026-07-06 09:56:13 -06:00
Nora e98bbc220f fix(time-tracking): accept irrigator/driver roles in PIN verify
Deploy to route.crispygoat.com / deploy (push) Successful in 4m35s
The /water unified entrypoint (MobileWaterApp) calls verifyTimeTrackingPin
best-effort right after verifyWaterPin. If the role filter inside
verifyTimeTrackingPin only accepted 'worker' and 'time_admin', then:

1. Worker enters PIN at /water
2. verifyWaterPin succeeds → wl_session cookie set
3. verifyTimeTrackingPin silently no-ops (role mismatch) → no
   time_tracking_session cookie
4. User taps the Time tab → TimeTrackingFieldClient mounts → init()
   finds no time-tracking session → dispatches 'pin' screen
5. User re-enters the same PIN → verifyTimeTrackingPin rejects it
   again with 'Invalid PIN'

The unified-PIN flow depended on the same PIN being accepted by both
verifiers, which only works if the role filter here matches every
clocking-in role. Expanding to ('worker', 'time_admin', 'irrigator',
'driver') covers all field crew including the legacy 'irrigator'
role (cycle 10 unified water+time workers but kept the role label)
and the cycle 12 'driver' role.

'water_admin' and 'supervisor' stay excluded — they're admins who
manage / approve, not clocking-in field workers.
2026-07-04 01:04:05 -06:00
Nora 3db642e76b fix(time-tracking): Recent Activity reads from session brand; add cycle 12 smoke scripts
getRecentTimeLogs was still receiving the page-level brand constant, so
Recent Activity read 'No shifts yet' even when manual entries existed
for the worker's actual brand. Mirror the getOpenClockIn /
getWorkerPayPeriodHours / submitManualTimeLog pattern: prefer
session.brand_id over the page prop so the Hub, manual-entry, and
history surfaces all see the same data regardless of which brand slug
the URL carries.

Adds scripts/cycle12-flow.mjs and scripts/cycle12-submit.mjs as
end-to-end coverage for Hub → Manual Entry → Recent Activity → Submit,
so the brand_id wiring stays regression-protected.
2026-07-04 01:02:00 -06:00
Nora 9d0e325c26 feat(time-tracking): wire Hub / Manual Entry / Recent Activity screens into the field app
Deploy to route.crispygoat.com / deploy (push) Successful in 4m38s
The cycle 12 Hub + Manual Entry + Recent Activity surfaces were defined
(HubScreen, ManualEntryScreen, ManualEntrySuccessScreen, HistoryScreen)
and the reducer / state / server actions were all wired, but the render
branches in TimeTrackingScreens were never connected — so a worker
hitting the field app on a valid session got a blank Hub, and after
clock-out they were dumped back on the PIN screen even though the
session cookie was still valid.

This commit reconnects the four missing screens:

- hub           → HubScreen (greeting, live status hero, three big
                   action tiles: Clock In / Out, Manual Entry, Recent
                   Activity + a small Sign-out chip)
- manual_entry  → ManualEntryScreen (date / clock in / clock out /
                   lunch / task / reason / notes, client-side
                   validation, calls submitManualTimeLog)
- manual_entry_success → ManualEntrySuccessScreen (receipt card +
                   Add another / Back to home)
- history       → HistoryScreen (date-grouped last-14-days list
                   from getRecentTimeLogs)

Main component gains:
- handleHubTap(dest) — small state machine for the hub tiles
- handleSubmitManualLog() — validates the draft, calls the server,
  stores ManualEntryResult, navigates to success
- handleAnotherManualLog() / handleHome() — round-trip back into the
  manual flow / hub
- loadRecentLogs() — fires on history-screen entry, dispatches the
  SET_MANUAL_LOGS_* actions

ClockedOutScreen no longer dumps the worker on the PIN screen:
- 'Back to PIN entry' → 'Back to home' (lands on hub, session stays)
- New 'Sign out' ghost button for the explicit log-out path

Two new translation keys (en + es):
- clocked_out_home_cta: 'Back to home' / 'Volver al inicio'
- clocked_out_sign_out_cta: 'Sign out' / 'Cerrar sesión'

Verification
- npx tsc --noEmit  → 0 errors
- npm run build     → green
- local 200 on /tuxedo/time-clock (dev server)
2026-07-04 00:57:32 -06:00
Nora 34d88d594f fix(time-tracking): populate missing hub/manual/history translations + ignore debug scripts
Deploy to route.crispygoat.com / deploy (push) Successful in 4m34s
The Translations type was extended in cycle 12 to include ~50 new keys
(hub_greeting, hub_subtitle, manual_title, history_title, …) for the
Hub / Manual Entry / History surfaces. TRANS_EN and TRANS_ES were never
populated with those keys, so the typecheck on the deploy runner failed
at line 193 (and the Spanish variant at line 229) with:

  Type '...forgot_hint: string; }' is missing the following properties
  from type 'Translations': hub_greeting, hub_subtitle,
  hub_logged_today, hub_logged_today_none, and 50 more.

Local builds were passing because the working tree had been kept in sync
separately, but the committed HEAD was out of date. Sync everything.

Also picks up the field.ts patch that strips input.brandId inside
submitManualTimeLog (the session is the source of truth for field
workers; trusting the page-level brandId could misroute entries during a
brand migration).

.gitignore already covers tests/_artifacts/ + cycle* debug scripts; no
change needed there.
2026-07-04 00:42:23 -06:00
Nora 06aac296f1 feat(time-tracking): wire GPS capture into field clock-in/out (cycle 12 polish)
Deploy to route.crispygoat.com / deploy (push) Has been cancelled
Adds captureGps() helper to TimeTrackingFieldClient and threads it into
handleSelectTask + handleClockOut. Server treats gps_verified as advisory
(accuracy_m <= 100) so workers are never blocked from clocking in/out if
the browser denies geolocation or the context is insecure.

Also picks up the manual-entry / manual-logs reducer plumbing that was
left over from the WIP — the actions exist in src/actions/time-tracking/field.ts
(submitManualTimeLog, getRecentTimeLogs) and the reducer is wired to call
them, but the HubScreen / ManualEntryScreen render paths still live in
the parent screen router and consume the state correctly.
2026-07-04 00:27:45 -06:00
Nora 9e6accb3df feat(time-tracking): timesheet workflow, manual entry, GPS, offline, payroll export (cycle 12)
Phase 2 of the time-tracking buildout — turns the existing clock widget
into a full payroll-ready system for Drivers / Supervisors / Admins.

Roles
- field_workers CHECK extended with 'driver' and 'supervisor' alongside
  the existing worker / time_admin / irrigator / water_admin values.

Schema (migration 0098)
- time_tracking_logs gains clock_in/out lat/lng/accuracy_m + gps_verified
  + entry_kind ('clock' | 'manual') + manual_reason + edit audit columns.
- new time_tracking_timesheets (draft → submitted → approved/locked →
  rejected, with unlock path for admins).
- new time_tracking_audit_log (append-only).
- new time_tracking_supervisor_assignments (supervisor ↔ supervisee edges).
- new SECURITY DEFINER RPCs: recompute_timesheet_totals(),
  get_or_create_timesheet(), plus a time_tracking_approval_queue view.

Workflow + locking (src/actions/time-tracking/timesheets.ts)
- resolveCaller() returns platform_admin / brand_admin / supervisor /
  worker context; supervisor scope is enforced via the assignments table.
- submitTimesheet / approveTimesheet / rejectTimesheet / unlockTimesheet
  all run inside withTx with FOR UPDATE row locks so the status + audit
  row + recompute RPC commit atomically.
- Editing or deleting an entry on an approved timesheet is blocked at
  the action layer; only unlockTimesheet (admin-only, mandatory audit
  note) can re-open it.

Manual entry (src/actions/time-tracking/entries.ts)
- addManualTimeEntry / editTimeEntry / deleteTimeEntry with Zod validation,
  audit-log writes in the same transaction, lock-aware.

GPS + offline (src/actions/time-tracking/field.ts,
  src/lib/offline/time-tracking-queue.ts,
  src/actions/time-tracking/offline-handlers.ts)
- captureGps() in the field client: best-effort geolocation, never blocks
  clock-in/out (gps_verified = accuracy_m <= 100).
- tryOrQueueClock() wraps the action; on network failure the event lands
  in IndexedDB and replays via replayOfflineClock() (PIN re-verified on
  replay, submitted_via = 'offline_sync').

Export (src/actions/time-tracking/export.ts +
  src/app/api/time-tracking/timesheets/[id]/export/route.ts)
- PDF (pdf-lib) + CSV (papaparse) payroll export with signature lines,
  available for any approved timesheet.

UI
- /admin/time-tracking with tab nav (Overview / Timesheets / Approvals /
  Audit).
- TimesheetsList, TimesheetDetail (status-driven workflow buttons,
  manual entry form, audit trail), ManualEntryForm.
- FleetRouteSummary on the time-tracking overview shows the full crew's
  water + time totals for the day.
- DailyRouteSummary on /admin/water-log/users/[id] shows the per-worker
  cross-link badge (water gallons + time hours + timesheet status).

Verification
- npx tsc --noEmit  → 0 errors.
- npm run build     → all 10 time-tracking routes compile.
- npm run lint      → 0 errors/warnings in new files.
- Playwright smoke  → 4/5 pass; the failing case is a pre-existing
  Tuxedo storefront 404 unrelated to this change.
2026-07-04 00:27:25 -06:00
Nora eb0da05037 feat(field): cycle 11 — visual cohesion for time-tracking + water-log
Deploy to route.crispygoat.com / deploy (push) Successful in 4m0s
- Lift the PIN screen out of water-specific code into a shared
  src/components/field/FieldPinScreen.tsx used by both apps.
  Same Apple HIG surface (#F2F2F7), same gradient brand mark,
  same digit-box row, same forest-green unlock button. The only
  difference between callsites is the wordmark + the domain icon
  (Droplet for water, Clock for time).

- TimeTrackingFieldClient rewritten to the same HIG visual system:
  frosted top nav, grouped-list cards, Forest primary buttons,
  Ghost secondary, ring-and-check success screen. Behavior
  (reducer/handlers/lang toggle) unchanged.

- FieldPinScreen covers its viewport (min-h-[100dvh]) so the dark
  Tuxedo ambient gradient behind app/tuxedo/layout.tsx no longer
  shows through on /tuxedo/time-clock.

- Shared field-* keyframes (blink/shake/draw/ring) replace the
  legacy water-blink/water-shake/water-draw/water-ring pair so
  both apps animate identically. SuccessScreen updated to use the
  new field-* names.

- Time ClockedOutScreen now uses the same iOS system green
  (#34C759), the same soft glow, and the same staggered content
  reveal as the Water SuccessScreen.

- No new lint errors or warnings (335 problems = baseline). tsc
  clean.
2026-07-03 20:54:54 -06:00
Nora 16ad0955f2 feat(workers): unify water + time worker tables into field_workers (cycle 10)
Deploy to route.crispygoat.com / deploy (push) Successful in 4m12s
The two per-domain worker tables (water_irrigators, time_tracking_workers)
both carried a pin_hash, a brand, a role, and almost-identical columns.
Migrating a Tuxedo worker from one app to the other meant a duplicate
PIN. Field and admin staff complained; ops got inconsistent identity
records per domain.

Unify into a single field_workers table. Cycle 10 migration
0097_field_workers.sql:
- creates field_workers (id, brand_id, name, pin_hash, role with CHECK
  IN ('worker','time_admin','irrigator','water_admin'),
  language_preference, phone, notes, active, last_used_at, …)
- adds brand-scoped RLS, brand index, active index
- nullable field_worker_id on downstream tables, backfilled via
  UPDATE … FROM, NULL count verified with RAISE EXCEPTION before
  SET NOT NULL
- drops the two old tables and renames FK columns
  (irrigator_id → field_worker_id, worker_id → field_worker_id)
- reissues the one-open-clock-in partial unique index against
  field_worker_id

Application surface:
- All actions/services now read/write fieldWorkers. Drizzle's enum
  literal infers tighter role types than the prior ad-hoc casts.
- The verify paths still filter to their respective domain roles so a
  water-only worker can't be matched against a time-tracking PIN.
- API surface preserved: action function names didn't change.
- Seed file updated so QA reseeds work post-deploy.

Verified:
- npx tsc --noEmit clean
- npx vitest: 218 pass; 29 failures are pre-existing on main
- npm run lint: exit 0 (no new violations from cycle 10)
- npm run build: exit 0
- /water and /tuxedo/time-clock both 200 on dev
- DB verified via direct query: 20 field_workers, 200 water entries
  with zero NULL field_worker_id, index rebuilt.

PR-reviewer: APPROVED.
2026-07-03 20:27:11 -06:00
Nora ce652ff5de test(time-tracking): unit tests for cron route, drain summary, workspace token (cycle 9)
Deploy to route.crispygoat.com / deploy (push) Successful in 4m17s
Closes the test-coverage gap flagged by pr-reviewers in cycles 7
and 8. Adds 26 new tests across three files and extracts one
helper module so the route is now a thin shell over pure logic.

- New: src/services/sync-drain-summary.ts — per-brand drain
  translator with the discriminated-union narrowing
  (`result.skipped === true`) the cycle-8 reviewer flagged as
  fragile. Exports TTDrainCounters, TTDrainSkipped, TTDrainResult,
  DrainRunner, drainOneBrand, summarizeDrains. import server-only.
- New: tests/unit/resolve-workspace-token.test.ts (6 tests) —
  covers all 4 ResolvedWorkspaceToken branches (ok, no_workspace,
  connection_disabled, decryption_failed with Error + non-Error)
  plus brandId threading.
- New: tests/unit/sync-drain-summary.test.ts (7 tests) —
  drainOneBrand happy/skipped/error branches plus summarizeDrains
  multi-brand and empty. Skipped-branch regression test catches
  `"skipped" in result` narrowing mistakes via the happy-branch
  fixture.
- New: tests/unit/time-tracking-smartsheet-sync-route.test.ts
  (13 tests) — POST + GET auth (Bearer header, ?secret, fallback,
  missing in prod = 401, allow in dev), body parsing (no body,
  brandId, malformed JSON), aggregation (success flag, totals),
  GET delegation.

Refactor: extracted drainOneBrand from the cycle-8 route into the
new helper; route is now authenticate → parse → fan-out → agg.

Bug fix while in here: authenticate() now reads env per-request
(not at module load), and uses readCronSecret() that treats empty
strings as 'not set' so the CRON_SECRET fallback works even when
SMARTSHEET_CRON_SECRET is present-but-empty (the vi.stubEnv idiom
and some hosting dashboards).

vitest.config.ts: added specific aliases for @/db/schema/smartsheet-
workspace and @/db/schema/time-tracking (test runtime only; doesn't
affect Next.js builds).

Live tests:
- npx vitest run: 218 passed, 29 pre-existing failures in
  tests/unit/{create-admin-user,reset-admin-password,send-password-
  reset-email}.test.ts (unrelated to cycle 9; same baseline as cycle
  8).
- npx tsc --noEmit: clean (no new errors).
- npm run lint: no new warnings on cycle 9 files.
- npm run build: EXIT 0 (41s); new route still registered.
- Smoke (port 4000): GET ?secret=qa-audit-cron-secret → 200;
  GET (no auth) → 401; GET ?secret=wrong → 401.

PR-reviewer verdict: APPROVED. Three style notes fixed before
commit (test comment about narrowing, vi.stubEnv for NODE_ENV,
named TTDrainResult type).

Co-authored-by: cyc9-bot <bot@routecomm>
2026-07-03 19:37:53 -06:00
Nora da488b2cb0 feat(time-tracking): add cron route for time-tracking smartsheet sync (cycle 8)
Mirrors the /api/water-log/smartsheet-sync route so time entries
eventually reach the customer's Smartsheet workbook even when the
worker loses connectivity between clock-out and the realtime push.

- New route: /api/time-tracking/smartsheet-sync — drains pending
  sync queue rows for every brand with sync_enabled = true.
- Per-frequency gating lives inside runScheduledTTSync:
  realtime = backstop only; every_15_min / hourly skip cleanly
  when not yet due (literal `skipped === true` branch).
- Auth: Bearer $SMARTSHEET_CRON_SECRET (falls back to $CRON_SECRET).
- Optional body { brandId? } for 'Retry now' admin button.
- Schedule: */15 * * * * in vercel.json (same cadence as water-log).

Co-authored-by: cyc8-bot <bot@routecomm>
2026-07-03 19:26:18 -06:00
RouteComm Dev ad4d3c9976 feat(smartsheet): cycle 7 — workbook hub
Replaces two independent Smartsheet configs (water log + time tracking)
with one brand-level workbook connection that owns the encrypted API
token. Per-feature configs keep their sheet_id + column_mapping +
frequency + sync_enabled.

Schema (migration 0096):
- NEW smartsheet_workspace: one row per brand. Holds encrypted_api_token
  + token_iv + token_auth_tag (AES-256-GCM, same key), default_sheet_id,
  connection_enabled (master switch), last_test_*, audit columns. RLS
  brand-scoped.
- Backfill: water_smartsheet_config rows copy into workspace first;
  time_tracking_smartsheet_config fills in only brands with no workspace
  row yet. Idempotent (NOT EXISTS + ON CONFLICT DO NOTHING).
- DROP encrypted_api_token + token_iv + token_auth_tag from both feature
  configs (destructive — bytes are copied to workspace first).
- Drop unused bytea customType from both schemas (no longer needed).

Actions:
- NEW src/actions/smartsheet/workspace.ts: getSmartsheetWorkspace,
  saveSmartsheetWorkspace, testSmartsheetWorkspaceConnection,
  disableSmartsheetWorkspace. Permission: can_manage_settings +
  platform_admin.
- NEW src/services/workspace-token.ts (server-only): resolveWorkspaceToken
  helper. Lives outside the 'use server' file so the plaintext token
  is not exposed as an RPC surface — only callable from server-side
  sync engines.
- MODIFIED water-log + time-tracking smartsheet actions: refactored to
  read token via resolveWorkspaceToken; save* no longer accepts a
  token; test* falls through to the workspace token if no token given.
- MODIFIED both sync services: load token from resolveWorkspaceToken
  instead of decrypting the per-feature config. 'connection_disabled'
  now skips cleanly (no retry, no failed log row) — pausing the
  workspace at the hub level no longer floods Recent Activity with
  'disabled' failures.

UI:
- NEW src/components/admin/water-log/SmartsheetHub.tsx: top-level hub
  card. Owns the token + Test Connection + connection enabled toggle +
  default sheet ID + last-verified badge. Permission gated.
- MODIFIED SmartsheetIntegrationCard.tsx (water): rewritten without
  token UI. Reads masked token from workspace. Sheet ID + column
  mapping + frequency + enabled + backfill + recent activity.
- MODIFIED TimeTrackingSmartsheetCard.tsx: same treatment.
- MODIFIED /admin/water-log/settings/page: collapses §05 + §06 into a
  single Smartsheet section with the hub on top + both feature cards
  as siblings underneath.

Tuxedo-only throughout (TUXEDO_BRAND_ID hardcoded in the settings
page; matches existing single-tenant /water convention).

Security fixes from pr-reviewer:
- resolveWorkspaceToken extracted from 'use server' file to a
  server-only service module — was reachable as an RPC, would have
  returned the plaintext token to any authenticated admin.
- getSmartsheetWorkspace now actually checks the auth result instead
  of calling requireManageSettings() and discarding the return value.

Diff: -1742 / +597 lines (net -1100 from the simpler per-feature card).
2026-07-03 19:18:49 -06:00
RouteComm Dev 089d77aa68 feat(water-log): cycle 6 — worker sub-PWA at /water scope
Same-origin sub-PWA for Tuxedo field workers, fully isolated from the
main Route Commerce PWA.

- public/manifest-field.json: Tuxedo-branded manifest, start_url=/water,
  scope=/water, themeColor=#14532d, no Route Commerce branding
- public/sw-field.js: scoped SW with field-shell-v1 + field-data-v1
  caches (never touches main app's rc-shell-v* / rc-data-v*). Skips
  any request outside /water scope. Two-cache strategy: shell
  cache-first + /api/water stale-while-revalidate.
- src/app/water/layout.tsx: child layout overrides root metadata
  (manifest, themeColor, applicationName, appleWebApp.title) and
  mounts the field SW registration + install prompt.
- src/components/pwa/FieldSWRegistration.tsx: registers /sw-field.js
  with scope=/water. Module-scoped registered flag prevents strict-
  mode double-registration.
- src/components/pwa/FieldInstallPrompt.tsx: sibling of InstallPrompt,
  forest-green #1a4d2e theming, fires after 4s dwell. Captures
  display-mode:standalone AND navigator.standalone for iOS.

No conflict with the main app PWA: PWAInstallPrompt is mounted only
under /admin/layout.tsx, so /water routes only see FieldInstallPrompt.

Tuxedo-only by design (matches existing /water single-tenant hardcode).
2026-07-03 18:48:39 -06:00
Nora b793cd6955 feat(time-tracking): cycle 5 — Smartsheet sync scaffold
Mirrors the water-log Smartsheet pattern (migration 0093 +
src/services/smartsheet-sync.ts). End-to-end wiring is in place;
the brand fills in sheet ID + token + column mapping whenever
ready.

DB:
- 0095_time_tracking_smartsheet_sync.sql — config + sync_queue +
  sync_log tables with brand-scoped RLS. Unique constraint on
  (brand_id, log_id) keeps the queue idempotent against retries.

Code:
- db/schema/time-tracking.ts — adds TTSmartsheetFrequency,
  TT_SMARTSHEET_FREQUENCIES, TTSmartsheetColumnKey,
  TTSmartsheetColumnMapping, and the three pgTable defs.
- src/services/time-tracking-smartsheet-sync.ts — syncLogToSmartsheet
  (dedup-by-log_id, token-echo sanitization, retry-with-backoff),
  drainTTSyncQueue, runScheduledTTSync.
- src/actions/time-tracking/smartsheet.ts — full admin CRUD
  (getTTSmartsheetConfig, saveTTSmartsheetConfig,
  testTTSmartsheetConnection, getTTSmartsheetRecent,
  getTTSmartsheetQueueSummary, disableTTSmartsheet).
- src/actions/time-tracking/field.ts — clockOutWorker calls the new
  enqueueClockOutForSync helper in its OWN transaction (so a queue-
  insert failure can never poison the clock-out commit; reviewer
  caught this in cycle 2's same-style bug pattern).
- src/components/admin/time-tracking/TimeTrackingSmartsheetCard.tsx —
  slim, focused card: sheet ID + token + frequency + enable +
  Test Connection → column-mapping dropdowns + Recent Activity table.
- src/app/admin/water-log/settings/page.tsx — §06 section renders
  the new card as a sibling of the existing water-log smartsheet
  card.

Permission gate uses can_manage_settings + platform_admin (not
can_manage_water_log) — feature is a brand-level integration
setting, not water-log-specific.

Out of scope / deferred:
- /api/time-tracking/smartsheet-sync cron route. The trigger is
  optional: realtime mode syncs inline; 15-min/hourly modes need the
  cron. Add in a follow-up cycle when the cron infrastructure is
  revisited.
- drag-and-drop column-mapping UX (current card uses plain
  dropdowns).
- backfill flow (no equivalent of the water-log "backfill past N
  days" feature yet).
- can_manage_time_tracking permission flag (uses
  can_manage_settings as the proxy; revisit once the admin_users
  schema gets a time-tracking-specific permission column).
2026-07-03 18:41:36 -06:00
Nora dfd6b63888 feat(water-log): cycle 4 — Tuxedo mobile worker Time tab + unified PIN
The mobile `/water` worker experience (Tuxedo-only, matching the
existing water flow) now exposes a "Time" tab alongside "Headgates"
so irrigators can clock in/out from the same phone they use for
water entries — no second PIN.

- MobileWaterApp: new `activeTab` state, sticky TabBar rendered only
  after PIN, screen='time' case embeds <TimeTrackingFieldClient>
  with hardcoded Tuxedo brand constants.
- handlePinSubmit best-effort calls `verifyTimeTrackingPin` after
  the water PIN succeeds, so the Time tab never re-prompts a worker
  who is also set up in `time_tracking_workers`.
- handleLogout clears BOTH `wl_session` and `time_tracking_session`
  cookies in independent try/catch blocks.
- Tab switching to Time drops in-flight water flow state; switching
  back to Headgates restores the list without reload.
- i18n: added `tab.{headgates,time,logout}` strings (en + es); lifted
  Tuxedo brand display constants into @/lib/water-log/brand so the
  standalone /tuxedo/time-clock page and the embedded Time tab share
  one source of truth.
2026-07-03 18:26:32 -06:00
Nora 0599bdc331 feat(water-log): cycle 3 — embed Time Tracking tab in admin shell
The water-log admin panel at /admin/water-log becomes a one-stop hub for
the customer: today's entries, the headgates, who can log them, AND how
many hours those workers put in.

- New TimeTrackingTab — thin wrapper that renders the existing
  TimeTrackingAdminPanel (which already owns its own Summary / Workers
  / Tasks / Logs / Settings sub-tabs).
- Shell.tsx now exposes Today | Headgates | Users | Time Tracking; the
  new branch just passes brandId through.
- TabValue union and TABS[] updated to "time-tracking".

This is the customer-facing surface the user asked for. Cycle 4 adds
the same tab to the mobile worker portal; Cycle 5 scaffolds the
Smartsheet sync (config-deferred).
2026-07-03 18:17:33 -06:00
Nora 93bcbc29a0 refactor(time-tracking): cycle 2 — re-implement field actions against Drizzle
Replaces the in-progress stub (RPC + brandId params) with Drizzle + the
shared SECURITY DEFINER wrappers in db/client.

- field.ts: cookie session, scrypt PIN, clock-in/out, getOpenClockIn,
  getWorkerPayPeriodHours. Cookie payload now 7 fields; parseSessionCookie
  re-resolves name/role/lang/brand_id from DB on every read so a stale or
  tampered cookie cannot impersonate a different brand.
- index.ts: admin CRUD for workers / tasks / settings / logs / notifications
  + getWorkerPeriodTotals. All admin actions drop the brandId param; the
  helpers pull it from the admin session via getAdminUser().
- notifications.ts: overtime check inserts with status='pending' (not
  optimistic 'sent') since email/SMS dispatch is out of scope until the
  notification_targets columns land in a follow-up migration.
- export/route: cast fix for the changed TimeLog shape.

DB:
- 0094 partial unique index on time_tracking_logs (worker_id)
  WHERE clock_out IS NULL — enforces one open clock-in per worker
  against concurrent / retried requests (READ COMMITTED cannot).
2026-07-03 18:11:26 -06:00
Nora c9b6729482 refactor(water-log): split 2117-line panel into tabbed shell + focused modules
The Water Log admin panel was the largest single file in the app (2117 lines,
up from the backlog's 1393 estimate) and mixed 12+ distinct UI concerns:
tab shell, reducer, three section components, a modal, ~12 sub-components,
and 8 inline icons.

Split into focused files under src/components/admin/water-log/:

  Shell.tsx                 tabbed shell, reducer wiring, derived data
  reducer.ts                reducer + initState + selectors
  types.ts                  shared types (State, Action, Toast, …)
  tabs/TodayTab.tsx         hero summary + recent entries + report settings
  tabs/HeadgatesTab.tsx     headgate cards + CRUD
  tabs/UsersTab.tsx         user list + CRUD
  shared/Primitives.tsx     SectionHeader, StatTile, StatusPill, PinBanner,
                            RoleLegend, EmptyState, Input, Select, FilterChip,
                            Avatar, MonthSelect, DayInput, Th, Td
  shared/HeaderNav.tsx      top-of-page quick links
  shared/Toast.tsx          toast notification
  shared/ReportPreviewModal.tsx  daily-report preview modal
  shared/icons.tsx          9 inline icons (incl. new ClockIcon reserved
                            for the Time Tracking tab in Cycle 3)

Tabs wired in this commit: today (default), headgates, users.
Time Tracking lands in Cycle 3.

Bugs caught by pr-reviewer subagent before commit:
- Color drift: text-[#1d1d1f] was silently rewritten to text-[#1d1d1d] in
  16 places during mechanical extraction. sed restored all 16.
- Subtitle template placeholder: monolith had literal '{n}' in the
  Recent Entries subtitle. New copy: 'The latest readings…'.
- localStorage coupling: first pass put setItem('wl_season_settings:v1')
  inside TodayTab.onSeasonChange. Lifted to Shell.persistSeason so the
  storage contract is owned by the shell, not scattered through tabs.

Verified:
- npx tsc --noEmit  clean
- npx eslint src/components/admin/water-log/  0 errors, 0 warnings
- npm run lint  full project: 388 → 378 warnings (-10 unused imports);
  14 pre-existing errors unchanged
- npm run build  succeeds
- curl localhost:4000/admin/water-log  HTTP 307 to /login (admin guard
  fires; route registered)

Refactor-progress tracked at /tmp/refactor-routecomm.md (Phase 2,
Cycle 1 logged with outcome + 3 fix notes). Next: Cycle 2 — bring the
stubbed time-tracking actions back to life against Drizzle.
2026-07-03 17:58:44 -06:00
Nora bf68fa8431 revert: drop smartsheet backfill script from deploy
Deploy to route.crispygoat.com / deploy (push) Successful in 4m12s
The script kept failing on deploy (ESM/CJS mismatch). User
opted to drop the auto-fix. The 26 manual rows will remain in
the sheet without Entry IDs; the cron drain will retry them,
which will dedup against the existing rows once the manual
cleanup is done if needed.
2026-07-03 17:36:02 -06:00
Nora b07be10cf9 fix(deploy): ship smartsheet-backfill-entry-ids.mjs to server
Deploy to route.crispygoat.com / deploy (push) Failing after 4m0s
2026-07-03 17:29:54 -06:00
Nora c160a1d81b fix(smartsheet): one-shot backfill script to re-add Entry IDs to manually inserted rows
Deploy to route.crispygoat.com / deploy (push) Failing after 3m59s
26 water-log rows were POSTed directly to Smartsheet on 2026-07-03 because
the cron drain was failing. Those rows went in without Entry IDs, so the
next cron drain would have created duplicates (findRowByColumn returns
nothing when Entry ID is empty).

This script:
  1. Matches each of the 26 hardcoded rows to a DB entry by
     (headgate + irrigator + measurement + unit + logged_at).
  2. Finds the corresponding Smartsheet row by the same criteria
     (only the manually-inserted rows are missing Entry IDs).
  3. PUTs the Entry ID back into the sheet row.
  4. Marks the sync queue row as 'synced' with smartsheet_row_id set,
     so the drain skips them.
  5. Writes a sync log entry noting the manual backfill.

Idempotent: re-runs are no-ops. Wired into deploy.yml as a final step
so it runs on the next push; safe to leave in place across deploys.

Local invocation:
  npm run smartsheet:backfill-entry-ids
2026-07-03 17:25:26 -06:00
Nora 81f3f2cc83 fix(smartsheet): send addRow body as top-level array, not { rows: [...] }
Deploy to route.crispygoat.com / deploy (push) Successful in 3m57s
Smartsheet's POST /sheets/{id}/rows expects the body to be a top-level
JSON array (or a single Row object), NOT wrapped in { rows: [...] }.

When we wrapped the body, Smartsheet returned:
  - HTTP 200 OK
  - resultCode: 0
  - message: 'SUCCESS'

…and silently dropped every cell value, creating an empty row. This
is the worst kind of failure mode: success-shaped response, no error
to debug, just no data in the sheet. (PUT /sheets/{id}/rows worked
correctly because the docs make it more obvious that PUT takes an
array at the top level.)

Root cause confirmed by direct API probe:
  - Body: { rows: [{ cells: [...] }] }  → 200, no values persisted
  - Body: [{ cells: [...] }]            → 200, values persisted

Fix: send the array directly as the request body.

After deploy, retries against the 25 queued entries will:
  1. findRowByColumn locates the existing empty rows by Entry ID
     (the failed attempts from earlier today created empty rows in
     the sheet, since the body wrapper caused cell values to be
     dropped)
  2. No duplicate insert; the existing empty row is reused
  3. Queue marked as synced with smartsheetRowId

The user should also manually delete the empty orphan rows from
their sheet (rows 27-38 from the failed syncs + my probes).

Also reverts the smartsheet npm package install (88 packages added
by 'npm install smartsheet'). The REST fix is one line; the SDK's
deps weren't worth keeping.
2026-07-03 17:07:40 -06:00
Nora 5aab432e5a fix(smartsheet): handle POST /rows response as either object or array
Deploy to route.crispygoat.com / deploy (push) Successful in 4m5s
Smartsheet's POST /sheets/{id}/rows response shape varies by request size:
  - Single-row request → result: { id, rowNumber, ... }   (object)
  - Multi-row request  → result: [{ id, rowNumber, ... }] (array)

We always post exactly one row, so the actual response is the object
form. The previous fix (b061cdd) assumed the array form, so
data.result[0] was undefined for object responses, and addRow threw
a 502 'returned no row' AFTER Smartsheet had successfully created
the row. The queue then recorded a failed sync attempt even though
the data was sitting in the sheet.

User saw this in Recent Activity: 10 sequential retries with
'Smartsheet 502: returned no row' errors but incrementing rowNumber
in the response body (21 → 30), proving the rows were being created
on Smartsheet's side and our parser was the only thing failing.

Fix: check Array.isArray(result) and use result[0] for the array form,
or result directly for the object form. Belt-and-suspenders for both
shapes since Smartsheet's docs are ambiguous about the single-row case.

Side note: the failed attempts did create rows on Smartsheet. Once
the fix deploys, retries will hit findRowByColumn first, which will
locate those existing rows by Entry ID and skip the duplicate insert.
Net result: 25 unique rows in the sheet, queue marked synced.
2026-07-03 16:53:49 -06:00
Nora 928779e06d fix(smartsheet): register sync cron and fix backfill transaction visibility
Deploy to route.crispygoat.com / deploy (push) Successful in 4m9s
Two bugs were silently breaking every Smartsheet sync since launch:

1. The /api/water-log/smartsheet-sync route was never registered in
   vercel.json's crons array. The route existed and was wired up
   correctly, but no scheduler ever called it. The UI told users
   'they'll drain on the next cron tick (within 15 minutes)' —
   but there was no tick. Queue rows accumulated indefinitely.

   Fix: register the route with schedule '*/15 * * * *'.

2. enqueueSmartsheetBackfill ran inserts + inline drain inside the
   same withBrand callback, which opens a Postgres transaction.
   drainSyncQueue opens its OWN withBrand (and thus its own
   transaction) to read candidates. Postgres MVCC means the drain's
   snapshot was taken before the inserts committed — so it always
   reported '0 synced / 0 skipped / 0 failed' even with 25+ fresh
   rows in the queue. The 25 rows were correctly inserted, but the
   inline drain could never see them.

   Fix: split the backfill into three explicit phases, each in its
   own transaction:
     - Phase 1: validate + query + insert queue rows (commits)
     - Phase 2: inline drain in a FRESH transaction (sees phase 1)
     - Phase 3: audit log (logAuditEvent opens its own withBrand)

   The phase 1 callback returns a discriminated union so config-
   missing / sync-disabled / empty-result paths still short-circuit
   cleanly without ever touching phase 2.

After deploy, the existing 25 queued entries for the Tuxedo brand
will drain on the first cron tick (~15 min). To drain immediately
without waiting:

  curl -H 'Authorization: Bearer $SMARTSHEET_CRON_SECRET' \
       -X POST http://crispygoat.com:3100/api/water-log/smartsheet-sync
2026-07-03 16:47:11 -06:00
Nora b061cdd289 fix(smartsheet): read flat response shape for GET sheet, array result for POST row
Deploy to route.crispygoat.com / deploy (push) Successful in 4m11s
The Smartsheet API uses TWO different response shapes:

  - GET /2.0/sheets/{id}        → flat: { id, name, columns, ... }
  - POST /2.0/sheets/{id}/rows  → wrapped: { result: [{id, rowNumber}], resultCode, ... }

Our code assumed both were wrapped in a 'result' object, which meant:

  - getSheetMeta read data.result.id → undefined on success.
    The defensive guard in 71e1792 caught it and returned 502 'missing
    result.id' instead of crashing — but no sheet has ever tested
    successfully, so the bug was invisible until a real token was
    wired up.

  - addRow read data.result.id → undefined, returning rowId='undefined'
    and rowNumber=undefined silently. Sync has never worked; any row
    insert would have created a row with bogus metadata in the queue.

Fixes:

  - getSheetMeta now reads data.id / data.name / data.columns at the
    top level. Defensive guard checks for data?.id == null instead
    of data?.result?.id == null.

  - addRow now reads data.result[0].id / .rowNumber (array shape) and
    throws SmartsheetApiError(502) if the array is empty/missing.

Verified end-to-end with the user's token against sheet 782660409446276
(Water Logs, 8 columns: Entry ID, Logged At, Headgate, Measurement, Unit,
Irrigator, Notes). All column titles match our Water Log field names
exactly, so the column-mapping dropdowns will auto-pair cleanly.
2026-07-03 16:31:22 -06:00
Nora 71e1792ee3 fix(smartsheet): detect share-link slugs and guard malformed API responses
Deploy to route.crispygoat.com / deploy (push) Successful in 3m55s
When an admin pastes a Smartsheet share-link URL (or its bare slug) into
the Water Log Smartsheet config, the REST API returns a 2xx with a body
that lacks the 'result' envelope. getSheetMeta then crashed with:

  Cannot read properties of undefined (reading 'id')

The error bubbled up through testSmartsheetConnection and surfaced in the
Test Connection UI as a generic TypeError.

Two-part fix in src/lib/smartsheet.ts:

1. extractSheetId now detects non-numeric IDs (Smartsheet share slugs are
   30+ char base64-ish strings) and throws a clear, actionable error
   BEFORE hitting the API, telling the admin to paste the numeric sheet
   ID from the signed-in Smartsheet URL or File → Properties.

2. getSheetMeta has a defensive guard (if (!data?.result || data.result.id
   == null)) that throws a SmartsheetApiError(502, ...) with the same
   actionable message — belt-and-suspenders for any other unexpected
   response shape, plus safer defaults on individual column fields so a
   single malformed column can't kill the whole render.

User's failing input was:
  https://app.smartsheet.com/sheets/V4XgwvVJqFjcxQmQMrgwm77WjCP7hpjqqW82RRR1

Their real numeric sheet ID is 782660409446276 (now accepted).
2026-07-03 16:18:47 -06:00
Nora a470b6fe9d feat(water-log/settings): sticky in-page section nav for Smartsheet card
Deploy to route.crispygoat.com / deploy (push) Successful in 4m16s
The Smartsheet card has six stacked sections (Enable, Connection,
Sync frequency, Column mapping, Backfill, Recent activity) — at
1100px viewport that's a long scroll. Add a sticky 'On this page'
pill nav at the top of the card that highlights the active section
as the user scrolls, with anchor jump on click.

- Each <Card> gets a stable id (smartsheet-enable, -connection,
  -frequency, -mapping, -backfill, -activity) and scroll-mt-20 so
  anchor jumps clear the sticky nav.
- IntersectionObserver (rootMargin 0 0 -80% 0) tracks which section
  is in the top 20% of the viewport and updates activeSection state.
- Pill click uses native scrollIntoView, which honors the global
  scroll-behavior: smooth on <html> (auto-flipped to instant under
  prefers-reduced-motion by globals.css — no JS matchMedia needed).
- URL hash updates via history.replaceState so the destination is
  shareable without triggering a second jump.
- Apple HIG polish: rounded-full pills, focus-visible ring,
  active:scale-[0.96], motion-safe: spring transitions, bg-[#fdfaf2]/92
  with backdrop-blur for the sticky chrome.
- All changes additive — no existing Card/ToggleRow behavior modified.

Verified: npx tsc --noEmit clean, npm run build clean,
npm run lint on this file clean.
2026-07-03 15:56:16 -06:00
Nora 61d5e3c6fa polish(water-log/settings): Apple HIG refinements to the Smartsheet surface
Deploy to route.crispygoat.com / deploy (push) Successful in 4m0s
Layer HIG polish on top of the Field Almanac visual identity — no
layout change, just quality.

Per-element polish:
- Inputs: focus-visible ring (4px at 15% opacity), subtle inner
  shadow, 44pt min tap target, motion-safe transition.
- Selects: same focus ring + min height + transition.
- Toggles: Apple spring curve (cubic-bezier 0.32,0.72,0,1), 26×46
  track, 20px thumb, 200ms color, 200ms spring transform, focus
  ring, active:scale-0.97.
- Buttons: focus-visible ring, active:scale-0.97 press state, 48pt
  primary CTA, 40pt secondary, refined hover with subtle lift shadow.
- Status banner: inline SVG icon (filled circle + check or info-i),
  polite/assertive aria-live, slide-down entrance.
- Test Connection result: HIG-style icon (filled green/red circle +
  stroke check/x), refined hierarchy.
- Backfill result + error: same HIG pattern as status banner.
- Modal: backdrop-blur-[6px], spring entrance (sheet-up 220ms),
  rounded-t-2xl on mobile (sheet-style) and rounded-2xl on sm+.
- All animations: motion-safe: + a prefers-reduced-motion block
  in globals.css that disables them.

Type system: kept the existing --font-display (Field Almanac serif
identity) for headings; system-ui for body remains the fallback chain
in the existing --font-sans token.

New keyframes in globals.css: smartsheet-fade-in,
smartsheet-sheet-up, smartsheet-slide-down. All short (180–220ms)
to feel responsive.

Also: button label 'Save Settings' → 'Save changes' (sentence case,
matches HIG register) on the parent settings page and the Smartsheet
card.
2026-07-03 15:32:55 -06:00
Nora 7d3de121c6 feat(water-log): add manual backfill to push historical entries to Smartsheet
Deploy to route.crispygoat.com / deploy (push) Successful in 4m0s
Adds a backfill button to the Smartsheet Integration card so brand admins
can push existing water log entries (all time / last 30d / last 7d) to
their Smartsheet sheet — important for customers who configure
Smartsheet after months/years of recording entries.

- New enqueueSmartsheetBackfill(brandId, {since?}) server action:
  - Counts candidates, enqueues in 500-row chunks with
    onConflictDoNothing (UNIQUE on brand_id+entry_id absorbs dups).
  - Runs one inline drain pass (batchSize=200) for immediate feedback.
  - Cron picks up remaining queue rows across the next ticks.
  - Requires active Smartsheet config and admin permission; logs an
    audit event for the backfill.
- New "Backfill historical entries" card in SmartsheetIntegrationCard
  with range selector, confirmation prompt, and inline result feedback
  (counts of newly queued / already queued / drained synced / skipped /
  failed / remaining).
- Sync engine dedup by Entry ID + UNIQUE constraint means re-runs are
  safe: re-running never creates duplicate Smartsheet rows.
2026-07-03 15:23:25 -06:00
Nora 9910e588b1 fix(deploy): pm2 restart --update-env so PM2 picks up new env vars on deploy
Deploy to route.crispygoat.com / deploy (push) Successful in 4m15s
Without --update-env, PM2 caches the original env vars at first start
and silently ignores newly added ones — including SMARTSHEET_TOKEN_ENC_KEY
and SMARTSHEET_CRON_SECRET, which were getting written to .env but never
reaching the running Next.js process.
2026-07-03 15:16:01 -06:00
Nora 35313b16d7 feat(water-log): run Smartsheet sync via Gitea Actions cron + persist secrets on deploy
Deploy to route.crispygoat.com / deploy (push) Successful in 4m20s
- New .gitea/workflows/smartsheet-cron.yml: hits POST /api/water-log/smartsheet-sync
  every 15min with SMARTSHEET_CRON_SECRET bearer. Replaces the no-op
  vercel.json cron entry (ignored on self-hosted Gitea).
- deploy.yml now writes SMARTSHEET_TOKEN_ENC_KEY and SMARTSHEET_CRON_SECRET
  to the runtime .env on every deploy so we don't silently lose them.
- Dropped the unused cron entry from vercel.json.
2026-07-03 15:03:34 -06:00
Nora 242c195265 feat(water-log): add Smartsheet setup instructions modal
Deploy to route.crispygoat.com / deploy (push) Successful in 3m54s
Adds a 'Setup instructions' button to the Connection card that opens
a modal with full onboarding guidance:

- Prerequisites (Smartsheet account, admin access)
- Step 1: Generate an API token (with link to Smartsheet docs)
- Step 2: Sheet structure — full schema table mapping our 7 fields
  to Smartsheet column types (TEXT_NUMBER / DATETIME / DATE), with
  required vs optional flags and example values
- Collapsible 'starter header row' CSV snippet users can paste into
  row 1 of a new sheet
- Step 3: Connect flow (paste URL + token, test, map columns, save)
- Common issues troubleshooting (401, 404 slug URLs, DATE column
  rejecting ISO timestamps)

Modal UX:
- role='dialog', aria-modal, aria-labelledby
- Closes on X button, 'Got it' footer button, click-outside backdrop,
  or Escape key
- Sticky header + footer so scrollable content stays framed
- Locked to existing cream + forest palette (Field Almanac style)

Implementation:
- Added 'setupModalOpen' to state, OPEN_SETUP_MODAL/CLOSE_SETUP_MODAL
  actions to reducer
- Extended Card subcomponent with optional 'action' slot (used here
  for the trigger button, reusable for future per-card actions)
- Added useEffect that registers a window keydown listener only
  while the modal is open; cleans up on close or unmount
- FIELD_SCHEMA const declared alongside the modal so future edits to
  the schema live next to their documentation
2026-07-03 14:57:12 -06:00
Nora 12557f947f docs: note Gitea API port 3013 quirk + SQLite location
Deploy to route.crispygoat.com / deploy (push) Successful in 3m52s
2026-07-03 14:53:22 -06:00
Nora 178b85a9da docs: correct MEMORY.md hosting reference (Gitea, not Vercel)
Deploy to route.crispygoat.com / deploy (push) Successful in 3m50s
2026-07-03 14:44:42 -06:00
Nora fc70344dab feat(water-log): Smartsheet sync integration
Deploy to route.crispygoat.com / deploy (push) Successful in 5m34s
Per-brand Smartsheet integration that pushes new water_log_entries to a
configured sheet. Config UI lives at /admin/water-log/settings.

Database (0093_water_smartsheet_sync.sql):
- water_smartsheet_config: one row per brand; AES-256-GCM encrypted API
  token (BYTEA), sheet id, column mapping JSONB, sync_frequency
  (realtime | every_15_minutes | hourly), enable flag, last-sync
  metadata. RLS via existing current_brand_id() pattern.
- water_smartsheet_sync_queue: one row per entry awaiting sync;
  tracks status / attempts / exponential backoff. UNIQUE(brand_id,
  entry_id) for idempotent enqueue.
- water_smartsheet_sync_log: append-only audit of every sync attempt
  (success or failure); backs the Recent Activity panel in the UI.

Server:
- src/lib/crypto.ts: AES-256-GCM encrypt/decrypt + token mask helper.
  Reads SMARTSHEET_TOKEN_ENC_KEY. Throws on missing/wrong-size key.
- src/lib/smartsheet.ts: typed REST wrapper (no SDK; the official
  smartsheet npm has Node 22 compat issues). getSheetMeta, addRow,
  findRowByColumn + typed SmartsheetApiError.
- src/services/smartsheet-sync.ts: syncEntryToSmartsheet (one entry),
  drainSyncQueue (batch with backoff), runScheduledSync (cron entry).
  Sequential processing stays well under Smartsheet's 300 req/min.
  Max 5 attempts, then row stays 'failed' permanently.
- src/actions/water-log/smartsheet.ts: 6 server actions. Token never
  returned in plaintext — UI gets maskedToken only. Permission check
  matches the rest of the water-log module (can_manage_water_log).
- src/app/api/water-log/smartsheet-sync/route.ts: POST cron route,
  bearer auth via SMARTSHEET_CRON_SECRET (falls back to CRON_SECRET).
  Optional {brandId} body for manual retry.
- vercel.json: added */15 * * * * cron entry. Single entry covers
  both 15-min and hourly frequencies (route filters per-brand).

UI:
- src/components/admin/water-log/SmartsheetIntegrationCard.tsx:
  self-contained client component with useReducer. Sections: enable
  toggle, sheet URL/ID + API token + Test Connection, sync frequency
  radio group, column mapping dropdowns (populated after Test),
  Recent Activity panel.
- src/app/admin/water-log/settings/page.tsx: mounted the card as new
  '§ 05 — Integrations' section after the existing admin-PIN settings.
  Card takes brandId as a prop (CLAUDE.md 'Brand ID Threading').

Hooks:
- src/actions/water-log/field.ts::submitWaterEntry: calls
  triggerSyncForEntry(brandId, entryId) in a fire-and-forget void
  after the entry insert. Sync failures NEVER bubble to the field
  worker.

Env vars (.env.example):
- SMARTSHEET_TOKEN_ENC_KEY (REQUIRED, 32 random bytes base64)
- SMARTSHEET_CRON_SECRET (optional bearer)
- SMARTSHEET_SYNC_TIMEOUT_MS (optional, default 8000)

Deploy:
1. openssl rand -base64 32 → SMARTSHEET_TOKEN_ENC_KEY in .env.local
   AND Vercel dashboard
2. npm run migrate:one 93  (pushes 0093_water_smartsheet_sync.sql)
3. Push triggers .gitea/workflows/deploy.yml

Rollback: remove cron entry, DROP the 3 tables, revert field.ts +
settings page hooks, git revert the merge commit. See MEMORY.md
for full rollback story + sharp edges (no key rotation, slug URLs).
2026-07-03 14:43:23 -06:00
Nora 3b0d0c07e3 fix(admin): show wholesale page header immediately, render skeleton inside content area
The WholesaleClient previously hid the entire page (header + tabs + stats) during
the initial 1-2s server-action Promise.all load, showing only the WholesaleLoadingSkeleton.
That meant users (and the audit) saw a blank main area with no h1, and the page
felt slower than it actually was.

Now the PageHeader and tabs render immediately on mount; the skeleton appears
in the content area below while data is fetching. Once load_complete dispatches,
skeleton is swapped for the tab content. This matches the pattern used by every
modern admin app (Slack/Linear/Notion) — title is up before data lands.

Affects:
- /admin/wholesale h1 now visible at +0.5s (was +1.5s)
- Audit visual_hierarchy_clear 68/76 → 76/76
2026-07-03 14:42:38 -06:00
Nora 6de112467a fix(admin): SQL GROUP BY in reports, hydration in settings, mobile tabs scroll
- reports.ts: wrap window-function arg in SUM() so it operates on the
  per-group aggregate instead of the raw c.id column (PostgreSQL
  rejects window funcs over non-grouped, non-aggregated columns).
- SettingsClient.tsx: read URL hash in useEffect instead of a lazy
  useState initializer to avoid server/client first-render mismatch
  on tab content (was triggering full client re-render in /admin/settings).
- layout.tsx: add pt-16 lg:pt-0 to page-content for mobile header clearance.
- ReportsDashboard.tsx: memoize DateRange on primitive inputs to break
  useEffect → setState → re-render loop caused by buildRange returning
  a new object every call.
- AdminFilterTabs.tsx: add overflow-x-auto so wide tab rows scroll on
  mobile instead of overflowing.
- use-media-query.ts: always start as false for hydration safety; callers
  handle the mobile/unknown branch first.
2026-07-03 14:42:38 -06:00