14 Commits
Author SHA1 Message Date
CatoandClaude Fable 5.1 18776a4251 refactor: one definition per concern — shared forms, one directory handler, limitkit, zero lint noise (#95)
* fix(lint): anchor the ignore patterns so eslint stops linting build output

`eslint` reported 18 unparseable files and 2 `no-explicit-any` errors that
exist in no source file. They came from `.claude/worktrees/*/.next/**` —
generated, minified code inside the repo. The default ignores of
eslint-config-next are unanchored (`.next/**`), which only matches at the
config root, so nested build output was walked.

Every pattern is now `**/`-prefixed, and `.claude/**` is ignored outright:
a worktree's files are linted on its own branch, never as a copy of this one.

Before: 2 errors, 36 warnings. After: 0 errors, 16 warnings — and the same
result whether you run it from the checkout or from a worktree.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(pets): one set of pet fields for both add and edit

"Add a pet" and "edit a pet" rendered the same ~120 lines twice — name,
species, breed, birth date, sex, bio, public toggle — so a new field or a
fixed label had to be applied in two places, and the two only stayed
identical by luck.

The fields now live in `components/portal/PetFormFields.tsx`. Each takes the
whole form plus a patch callback rather than a value and a setter, because
the pages hold one `useState` object (the edit page's also carries `handle`)
and a patch is what they can actually apply. The pages keep what genuinely
differs: one creates and can send you on to the first health log, the other
uploads an avatar, owns a handle and a delete zone.

Two primitives came out with it: `ToggleSwitch` (the peer-checkbox switch is
easy to get subtly wrong in a copy — the knob detaches from the track and
nobody sees it until they toggle) and `UploadedImage` (the plain `<img>` for
user-uploaded files, with the reason `next/image` is wrong for them written
down once instead of thirteen bare `eslint-disable` lines).

Render output is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(api): one handler behind /api/vets, /api/sitters and /api/groomers

The three directory routes differed in a role string, a table and a list of
columns — and agreed, character for character, on everything that decides
what a caller sees: the session guard, the completeness rule, the city
filter, the 50-row page, the review aggregate and the response envelope.
Three copies of a paging rule is three chances for one directory to quietly
start answering a different question from its siblings.

`createProfessionalDirectoryRoute` in `lib/api/professional-directory.ts`
now owns that shared half. Each route file declares only what it publishes:
its role, its table, the extra columns a profile must have filled to be
listed at all, and its SELECT list — because that list IS the contract the
directory offers (a sitter has a day rate, a vet has a clinic).

Responses are byte-identical: 106 + 103 + 106 lines became three ~35-line
declarations over one handler.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(products): the add/edit-a-product state machine, once

`/admin/products` and `/portal/my-products` look nothing alike — a table with
an inline panel versus a grid with a modal, and only one of them is
translated — but underneath they ran the same 55 lines: the same form shape,
the same "blank stock means unlimited", the same dollars-to-cents rounding,
the same POST-or-PATCH decision, the same optimistic list update.

The arithmetic is the part worth having in one place. `parseFloat * 100` is
where a product silently goes on sale for the wrong money, and it was
written twice.

`useProductEditor` takes the create URL (the admin page appends
`?platform=true` — the one behavioural difference), the two messages it may
need to show, and a callback for the saved row. The pages keep their markup,
their copy, and ownership of their list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(portal): one labelled input and one contact block for the profile forms

`ProfessionalProfileForm` carried the same four-field grid twice — once for a
vet's practice, once for a sitter's or groomer's services — which jscpd
reported as a 40-line clone of the file against itself. Two copies inside ONE
file is the worst kind: a reviewer reads the first, recognises it, and skims
the second, which is exactly where "city" kept its label and lost its
placeholder.

`ProfileTextField` is that labelled input; `ContactFields` is the
city/country/phone trio as a fragment, so the caller still owns the grid the
cells sit in. `country` is passed through as typed — the route takes the
first two characters and upper-cases them on submit, and normalising here
would be a second opinion about the same value. `SellerProfileForm` uses
both, and its on/off row is now the shared `ToggleSwitch`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* fix(security): key the guest rate limits on the hop Caddy wrote, via limitkit

The hand-rolled limiter in `lib/utils/rate-limit.ts` keyed on the FIRST entry
of `X-Forwarded-For`, with a comment asserting that was the original client
and a test pinning it. Both were wrong in the same direction: a reverse proxy
APPENDS to that header, so the first entry is a string the caller typed. Any
client could send a different `X-Forwarded-For` with each request, mint a
fresh bucket every time and never trip the limit at all — the guest checkout,
which reserves stock without a session, was effectively unlimited. A limiter
that cannot be tripped is not a limiter.

The same bug was found in three sibling repos during this migration, and in
limitkit itself before v0.2.0 (bitbaum/orangecat#563, finding 2). It is
exactly the kind of thing one shared implementation exists to fix once.

So the mechanism is now `limitkit` (fleet/SHARED.md; it replaces 12 copies of
this across 9 repos) and the local copy is deleted: window arithmetic, the
bounded store, the refusal shape and the client-IP dance all come from the
package. What stays local is what is genuinely ours — the limit VALUES, still
declared at each route next to the reason for them, and the proxy depth,
stated once in `rate-limit.ts` because it is a fact about our deployment
(Caddy on the box is the single proxy, so `trustedProxies: 1`).

Behaviour otherwise unchanged: same 429s, same copy, same `Retry-After`, same
per-key allowances. `slidingWindow` (not `fixedWindow`) because the local
implementation started its window at the first hit, which is what sliding
means — the old test expecting 45s of wait after 15s still describes it.

The window-arithmetic tests moved with the code they tested; what this repo
keeps is a test of the part that was broken, including one that a caller
cannot split its bucket by varying the hops it sends.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* fix(portal): give the page loaders a stable identity instead of muting the rule

Eight portal pages declared a `loadX()` that fetches the page's list, then ran
it from a `useEffect` with an empty dependency array and an
`eslint-disable-next-line react-hooks/exhaustive-deps` above the `useEffect(`
line. The directive did nothing: the rule reports on the dependency array two
lines down, so every one of these files produced BOTH an "unused
eslint-disable" warning and the exhaustive-deps warning it was meant to
silence. Sixteen warnings from eight disables that never applied.

The cause is that `loadX` was redefined on every render, so listing it as a
dependency would have refetched forever. `useCallback` fixes that at the
source: each loader is now stable over the translation function (plus the
route param where there is one), the effect depends on the loader like the
rule asks, and the disables are gone. The retry buttons already called these
same loaders and keep working.

Lint: 16 warnings → 0. `pnpm run lint` now passes with nothing to say, so the
next real warning will be visible instead of arriving in a crowd.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(ui): one uploaded-image component, and a no-console rule so it stays that way

Thirteen components carried their own `<img>` for user-uploaded files, each
with its own `// eslint-disable-next-line @next/next/no-img-element` above it
and none with the reason written down. Thirteen places for that reasoning to
rot and thirteen exemptions a reviewer has to re-audit independently.

They now all render `<UploadedImage>`, which holds the exemption once and
explains it: these URLs are written by the upload routes at request time
(`/uploads/…` on the box, or an `object:` URL while a preview is in flight),
so `next/image` would need the path known at build time or matched by a
configured pattern — and a missing pattern fails the whole render, not just
the picture. The optimizer has nothing to add either; the upload route already
resized the file.

The last `any` went with them: `TSignal` in `lib/i18n/signal-reason.ts` now
says `Record<string, string | number>`, which is what a reason actually
interpolates — counts, days, formatted measurements, nested translations. The
loose shape is still structural rather than next-intl's own type, because the
key is composed at runtime (`metric_${id}`) and the real literal-keyed type
rejects that by design; that reason is now in the file.

eslint-disable directives: 25 → 1 (the one inside `UploadedImage`).

And `no-console` is on, allowing `warn` and `error`. There were no stray
`console.log`s to remove — `error` is how these routes report a failure they
swallowed, and it is what `journalctl -u petvity-app` shows at 2am — so this
is the ratchet rather than a cleanup: a forgotten debug line on a server
writes a stranger's data into the journal forever. `scripts/**` is exempt,
where stdout IS the output. Verified by mutation: a planted `console.log`
fails the lint.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* style: wrap the two UploadedImage calls prettier wanted on four lines

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* fix(deps): install limitkit from npm, not from git

CI refused the git-hosted form: a package fetched from a tarball has no
`dist/`, so pnpm must run its `prepare` build, and pnpm 11 will not run a
git dependency's build scripts unless the exact resolved URL is listed in
`allowBuilds`. The local install had it cached from before that rule, which is
why this was green on the laptop and red the moment CI installed from scratch.

limitkit has been published to npm since, so the fix is the npm form rather
than an allowlist entry pinned to a commit sha that has to be re-edited every
time the version moves. fleet/SHARED.md still shows the github install line;
the published tarball ships `dist/` and needs no build here.

Same version, same resolution: 0.2.0.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 02:09:23 -07:00
GandClaude Opus 5 c65ac4b7d7 chore: add a formatter (#71)
* chore: add a formatter, matching the style this repo already writes

singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (252 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 10:05:01 +00:00
GandClaude Fable 5 9ed916af14 feat(system): healthz, one-click /demo funnel, public demo profile, new-pet grace, score labeling (#17)
- /api/healthz: public DB-pinging healthcheck. /api/health is the auth-gated
  pet-data API, so deploys and uptime monitors had nothing honest to probe.
- /demo: signs a visitor into the shared demo account in one click; linked
  from the marketing hero ('Try the live demo') and nav across all locales.
  Also fixes two hardcoded English strings in HeroCTA.
- Demo seed claims the public handle /pets/luna (when free), so the
  public-influencer-profile feature has a live showcase.
- New-pet grace: a profile younger than the 7-day alert window with no data
  and nothing overdue reads healthy/'new profile' instead of an alarming
  Watch badge seconds after creation. Overdue vaccinations still escalate.
- Digital-twin score is labeled 'Emotional wellness' (9 locales) so it stops
  reading as a contradiction of the all-metric wellness % on the health page.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 21:00:07 +00:00
g-butandClaude Sonnet 4.6 c5085874bd feat(i18n): persist SignalReasonData in DB and translate signal history
Add reason_data jsonb column to pet_signal_history; write reasonData in
signal-cache.ts and health-alerts cron; update SignalHistoryTimeline to
call translateSignalReason() for new rows, falling back to stored English
text for legacy rows (graceful degradation).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:30:28 +02:00
g-butandClaude Sonnet 4.6 ccc894cb8f feat(health): add signal history timeline to pet health page
Owners can now see why their pet's signal changed and when, directly on
the health page. Fetches last 20 petSignalHistory rows (already written
on every health-log mutation and cron run) in the existing Promise.all;
renders a signal-badged timeline with reason text and date.

Also fixes a pre-existing TS2322 in signal-cache.test.ts (null passed
to string|undefined param — changed to makePet() which defaults to null).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 16:18:20 +02:00
g-butandClaude Sonnet 4.6 1ff3ce8830 test(signal-cache): add 7 tests for refreshSignalCache
Previously zero coverage on the function that runs on every health log
and vaccination mutation — the primary daily action in the app.

Tests cover: early return on missing pet, cache update when signal is
unchanged (no history insert), history insert on signal transition
(null→watch, healthy→watch, watch→healthy), no history insert when
signal holds steady at healthy, and graceful degradation when the
history insert throws (cache update still runs).

Suite grows 546 → 553.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 14:36:10 +02:00
g-butandClaude Sonnet 4.6 7380808d7a fix(types): resolve pre-existing TS errors in two test files
- ownership.test.ts: remove stale @ts-expect-error that was unused
  after type narrowing made the assertion unnecessary
- unsubscribe-token.test.ts: non-null assert makeUnsubscribeToken()
  return value in tests where NEXTAUTH_SECRET is set in beforeEach,
  so callers accept string instead of string | undefined

pnpm build now passes TypeScript check cleanly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:34:10 +02:00
g-butandClaude Opus 4.7 011ec6ae58 test: cover ownership helpers and health-metric converters
9 tests for getHealthRecordForOwner/getVaccinationForOwner/getMedicationForOwner
(empty JOIN → null guards cross-user access); 19 tests for getNormalRange,
isMetricInRange, signalFromOutOfRangeCount, toDisplay/toStorage round-trips,
PHYSICAL/EMOTIONAL partition, and anxiety inversion.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 08:42:23 +02:00
g-butandClaude Opus 4.7 0835835fd5 chore(signal-history): drop stale 'table not yet created' fallbacks
pnpm db:push reports 'No changes detected' — pet_signal_history is
present in production. Cleaning up the migration-era defensive code:

- Pet profile page: merge the SELECT into the existing Promise.all;
  drop the try/catch (any DB failure here would already break the
  surrounding queries, so isolating this one was dead defense).
- signal-cache + health-alerts cron: keep the insert try/catches
  (history is auxiliary; a transient failure must not block the
  signal cache update) but rewrite comments to reflect resilience
  intent rather than the long-since-resolved migration concern.

No behavior change; removes ~10 lines of code that lied to readers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 17:20:58 +02:00
g-butandClaude Sonnet 4.6 6655651ede fix(signal-history): graceful degradation for writes before pnpm db:push
The pet_signal_history table requires pnpm db:push to exist in Neon.
Before db:push, refreshSignalCache and health-alerts cron would throw
on INSERT, breaking every health-metric and vaccination mutation.

Wraps history INSERT in try/catch (mirrors the read-side degradation
already on the pet profile page).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 08:57:17 +02:00
g-butandClaude Sonnet 4.6 e7477e7dc4 refactor(ssot): extract countOverdueVaccinations — eliminate 4 duplicates
Overdue vaccination count logic was repeated inline in signal-cache,
dashboard, and health-alerts cron (×2). Now sourced from a single
function in lib/config/vaccinations.ts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 08:49:45 +02:00
g-butandClaude Sonnet 4.6 ca9100bc27 feat(signal-history): record and display wellness signal transitions
Adds append-only pet_signal_history table (petId, signal enum, reason,
source, recordedAt). History rows are written only when the signal
CHANGES from its previous cached value — no noise on unchanged refreshes.

Two write paths:
- refreshSignalCache (user_action): fires after health metric / vaccination
  mutations; single INSERT per transition
- health-alerts cron (cron): bulk INSERT at the end of the daily loop

Pet profile page queries the last 5 history rows and renders them via
SignalHistoryTimeline — a compact left-border timeline that shows the
signal badge, date, and reason text. The section is hidden until the
first transition exists (new pets see nothing extra).

Requires: pnpm db:push to create the new table + enum in Neon.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 07:58:50 +02:00
g-butandClaude Sonnet 4.6 7479ab0b13 fix(signal): refresh signal cache after vaccination mutations
The signal cache was only updated on health metric logs, so adding an
overdue vaccination or marking one as up-to-date had no immediate effect
on the dashboard signal badge.

- Extract refreshSignalCache() helper to lib/api/signal-cache.ts
  (fetches pet species internally; callers only pass petId)
- Wire into vaccination POST, PATCH, DELETE routes
- Refactor health metrics POST to use the shared helper

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 07:10:30 +02:00
g-butandClaude Sonnet 4.6 63c67cdb9c refactor(api): enforce SSOT for enums + extract ownership helpers
- Derive Zod enum validation from schema pgEnum.enumValues instead of
  hardcoded arrays (SSOT: schema is the single source of truth)
- Extract verifyOwnership into lib/api/ownership.ts with one JOIN query
  per entity — eliminates N+1 two-query pattern and removes 3× duplication
- Fix medications POST missing status field (form sent it, API silently
  dropped it, defaulting all new meds to "active" regardless of input)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 13:43:53 +02:00