Commit Graph
31 Commits
Author SHA1 Message Date
Cato b9c4899ee7 feat(auth): one password rule from accountkit (non-empty, up to 128); no local minimum or hint text (#123) 2026-10-28 03:53:21 +01:00
CatoandClaude Fable 5 daa029e81f refactor(blog): replace the homegrown three-block parser with bip-kit (#79)
The DB blog rendered through lib/domain/blog-markup.ts — a deliberately tiny
p|h2|ul parser whose no-raw-HTML security rationale is exactly bip-kit's
typed-block model, making this a pure upgrade: parse + ArticleBody from
bip-kit v0.2.1 now render the public post page and the admin editor's live
preview (parse + readingTime), and authors instantly gain the full long-form
vocabulary (h3/h4, ol, quotes, callouts, images, tables, code, math,
footnotes, charts, embeds).

- app/longform.css maps the editorial-luxury tokens onto the --bp-* theming
  contract, class-scoped (.pv-longform dark public reader, .pv-preview light
  admin) so nothing leaks into the rest of the app
- parseLongform() degrades malformed chart/stats fences to code blocks —
  bodies are DB-authored, so a half-typed fence must never 500 a page or
  crash the editor (bip-kit's throw-on-parse targets committed content)
- JSON-LD, i18n alternates and reading time preserved; blog-markup.ts and
  its test deleted, the legacy-subset assertions ported to longform.test.ts
- word-level parity verified old-vs-new across all published post bodies


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-07 12:14:50 +00: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 Opus 5 02d847a016 feat(commerce): extract commercekit, and adopt it here (#53)
* feat(health): track what actually matters, per species

The seven metrics in health-metrics.ts are applied uniformly to all ten
species. That is tidy and, for several of them, wrong in ways that matter.

Body temperature is not a property a fish or a reptile has in the sense the
field implies. They are ectotherms: a fish's body temperature IS the water
temperature, and a reptile's depends on where it is sitting in a thermal
gradient. Heart rate is not measurable at home for a bird, a fish or a hamster.
Asking for either produces an empty field, and empty fields teach owners to
skip — a habit that generalises to the field that mattered.

Worse, none of the seven capture what actually kills these animals. A rabbit
that has not eaten and produced no droppings for twelve hours is a medical
emergency; gut stasis is the leading cause of death in pet rabbits. A male cat
straining without producing urine is fatal in 24-48 hours. A horse whose manure
output drops is the earliest practical warning of colic. A UVB bulb keeps
emitting visible light long after its UVB output has decayed, so the enclosure
looks fine while the animal develops metabolic bone disease.

lib/config/observations.ts is the SSOT for what is worth observing and for
which species. Each observation declares its species, cadence, whether an owner
can actually produce the answer, why it earns a tap, and what answer means
"call a vet" — with the reason, because an alert nobody believes is an alert
everybody dismisses. Records (microchip, parasite schedule, diet, farrier,
water changes) are modelled separately, since they are durable facts rather
than things that changed today.

The daily set is capped at five and the cap is a test that FAILS rather than a
slice that truncates. Printing the sets caught three real design faults that
the first round of tests passed: fish had an empty daily check-in because water
temperature is device-sourced and I was filtering device readings out; dogs and
cats had seven candidates silently cut to five by array order; and reptiles were
being asked about mood while the enclosure gradient that actually kills them was
excluded. Priority is now explicit and cadence can be overridden per species —
a snake fed weekly should not be asked daily whether it ate.

Clinical values are typical published ranges compiled for product design, NOT
clinically reviewed. REVIEW_STATUS records that, so it cannot quietly be
presented to an owner as authority.

Also adds docs/pet-health-science.md (the reasoning, species by species),
docs/digital-twin-and-legacy.md (twin staging, memorialisation, gamification
and revenue, including an explicit list of what not to build), and a first blog
draft. Nothing is published — that is a deliberate decision, not a side effect.

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

* feat(commerce): extract commercekit, and adopt it here

Three shops in the fleet: evig, petvity and fitfoot. Before proposing anything
shared I checked what is actually duplicated rather than assuming — revampit
turned out to be a second clone of evig, so it is three codebases, not four,
which is exactly the rule of three.

They have three incompatible foundations, so a single shared "webshop" adopted
by all of them would be a rewrite of two. What IS shared is narrower and is the
part every shop rewrites and gets subtly wrong. That is what this extracts.

packages/commercekit — zero runtime dependencies, framework-free core, React
bindings behind a separate entry point.

  money      Integer minor units. `12.55 * 100` is 1254.9999999999998, so
             fromDecimal works on digits. The currency carries its own exponent,
             so JPY has no decimals and KWD has three without a special case.
             allocate() is largest-remainder: splitting 100 three ways gives
             [34,33,33] and never loses or invents a unit — asserted across 200
             amounts x 5 weight patterns. percent() takes an explicit rounding
             mode, because a marketplace computing its own commission should
             round down rather than over-charge a seller.

  cart       A line is an id and a quantity. Never a price — a cart open for a
             week would otherwise show one number and charge another. Cross-tab
             sync, clamping, and corrupt storage yielding an empty cart rather
             than a crashed shop. Stable snapshot reference, which is what
             useSyncExternalStore needs to avoid an infinite render loop.

  inventory  Conditional decrement, all-or-nothing, with compensation on partial
             failure and sorted lock order so opposite carts cannot deadlock.
             Duplicate lines are merged, or the availability check for the
             second is made against stock the first already took. The test
             suite demonstrates the bug it prevents: a read-then-write adapter
             tells 50 buyers "yes" against 10 units while recorded stock falls
             by one.

  buyer      Account XOR guest as a discriminated union rather than two nullable
             columns, so an order belonging to nobody cannot be represented. A
             type is a claim, so the matching Postgres CHECK ships beside it.
             Receipt tokens use the platform CSPRNG and refuse to run without
             one.

  address    ISO-3166 codes with names from Intl.DisplayNames — every locale the
             runtime supports, no translation files, no way for the German list
             to drift from the English one.

Petvity adopts all of it, which is the proof: lib/shop/cart.ts and
lib/config/countries.ts become thin bindings, and placeOrder's hand-rolled
reservation is replaced by reserveAll over a Drizzle adapter that is the only
Petvity-specific part. Cancellation goes through releaseAll, so there is now one
implementation of giving stock back instead of two.

One behaviour change worth naming: the old code skipped the UPDATE entirely for
unlimited-stock products, so the shared db mock's default empty return was never
exercised on that path. The new adapter always issues the conditional update
(`stock IS NULL OR stock >= n`, and NULL - n stays NULL), which is correct
against a real database but made the mock read as "sold out". The mock was
modelling an UPDATE that matches nothing; two tests now say what a matching
UPDATE returns.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 13:24:41 +00:00
GandClaude Opus 5 37b1f59ed7 feat(shop): sell to visitors who don't have an account (#50)
The public storefront was a brochure. It shipped a Product/Offer JSON-LD so
search engines treat it as purchasable, then the only buy path was
"Sign up to buy" -> /register?returnTo=/portal/shop, which both forced
registration before a first purchase and dropped the product the visitor came
for. Cold traffic could not buy anything.

A visitor can now add to cart on the catalogue and the product page, check out
in one page with an email and an address, and read their order back from a
receipt link. No account anywhere in that path.

orders.userId becomes nullable, alongside guestEmail and an unguessable
publicToken. A CHECK constraint enforces exactly one of userId / guestEmail,
because an order with no reachable buyer cannot be repaired after the fact.
The token is the guest's only handle on their order: it is emailed, never
listed, and authorises resuming payment and cancelling while pending.

Order placement moves to placeOrder() in lib/domain/orders.ts so the authed
cart and the guest checkout share one implementation -- the stock reservation
and its compensation must not exist twice. setOrderStatus() joins it for the
same reason: a cancellation that forgot to restore stock destroys inventory,
and that happens when one route remembers and another does not.

Two joins were fixed before any UI existed. app/api/orders/seller and
app/api/admin/orders inner-joined users on orders.userId; with a nullable
column that drops every guest order from the views of the people who have to
ship them -- real revenue, invisible, nothing appearing broken. Both are now
leftJoin + COALESCE onto the address the buyer typed.

Also fixed while reviewing:
- toLocale() used `value in LOCALE_CONFIG`, true for inherited keys like
  "constructor", and the result goes straight into a URL path.
- orderShippingSchema accepted any two letters as a country, so "XX" could be
  stored and printed on an undeliverable label. Checked against a new ISO-3166
  SSOT whose names come from Intl.DisplayNames, so all nine locales are
  translated with no message files to maintain.
- Guest input (shippingName, notes) reaches a seller's inbox unauthenticated;
  email templates now escape it.

Guards, not just fixes: locale parity across all nine message files is now a
test rather than a convention, and the prod walkthrough places a real guest
order and asserts the seller can see the buyer's email -- the check that goes
red if anyone reintroduces an inner join there.

The public endpoints are deliberately outside PRIVATE_API_PREFIXES; a session
guard there would silently delete the feature. They are rate limited per
client, and the payment and cancel routes require the order token.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 08:56:48 +00:00
GandClaude Opus 5 cd591aef27 feat(blog): publish posts from the admin instead of editing code (#48)
Publishing meant editing a TypeScript array in lib/content/blog.ts, opening a
PR, and waiting for a deploy. That is not a blog anyone will actually write in —
and it made every post a developer task. There was exactly one post.

Posts now live in the database, written and published at /admin/blog. A post
goes live the moment it is published; nothing is rebuilt or redeployed.

Authoring markup is a deliberately tiny subset of Markdown:

    ## Subheading
    - bullet
    anything else is a paragraph

No Markdown dependency. A full parser would buy inline HTML we would then have
to sanitise — an XSS surface in exchange for syntax nobody asked for. Parsing
to the closed block set the post page already styles means untrusted text can
never become markup, which a test pins with a <script> tag rendering as literal
text. The editor previews the parsed blocks live, so a mistyped bullet is
visible before publishing rather than after.

Body is stored as written and parsed at render, so the author's source stays
the single truth and the renderer can improve without a data migration.

Publish dates are stamped once, on the first publish, and preserved after that.
Unpublishing to fix a typo and publishing again must not silently re-date the
post and reshuffle the index — tested in both directions.

Drafts 404 publicly rather than merely being unlisted, so guessing a slug does
not reveal unpublished writing.

The migration carries the existing post across. Its URL
(/[locale]/blog/a-platform-for-both-sides-of-pet-care) is already public, so
losing the row would 404 an indexed page; the insert is dollar-quoted for the
apostrophes and ON CONFLICT DO NOTHING so it is safe to re-run.

Deleting is a two-step inline confirm rather than a confirm() dialog: deleting a
published post breaks its URL, and a browser dialog is both easy to click
through and impossible to drive from a test.

Both public pages are force-dynamic — content that an editor changes must not be
frozen into the build.

The walkthrough now fetches a real post and asserts its prose, which exercises
the table, the content migration and the renderer together. It fetches the body
itself rather than reading $LAST_BODY, which page() never sets — asserting on it
would have grepped whatever the previous request happened to leave behind.

27 new tests; pnpm verify green (678 tests / 75 files).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 14:59:57 +02:00
GandClaude Opus 5 dadbe7e4a5 fix(readiness): a full profile is live even while not accepting clients (#35)
The readiness checklist required `isAcceptingClients` before calling a profile
live, but the directory queries treat it as an optional filter — a professional
who was temporarily full appeared in search results while their own dashboard
told them they were invisible. The directory behaviour is the correct one: a
full pro is worth showing, badged as not accepting, so owners can find them and
come back. The checklist now matches, and the dead `readyStep_accepting` string
is removed from all nine locales.

The production walkthrough caught this: it created professionals with partial
profiles and asserted they were browsable, which the gate correctly refused.
It now completes each profile before expecting a listing, and — more usefully —
asserts the negative first: an incomplete vet must NOT appear in browse. That
turns the readiness gate itself into a permanent regression check rather than
something only asserted in unit tests.

135/135 checks pass against production.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 12:24:46 +02:00
GandClaude Opus 5 42bcc47ff4 feat(marketplace): real onboarding replaces fake profiles; orders become shippable (#33)
Three things made the marketplace a demo rather than a business.

1. Orders had no delivery address. A seller could receive an order and have
   nowhere to send it. Orders now carry a required address (migration 0004,
   additive); the API rejects an order without one, and both the seller and
   admin order views expose it so fulfilment is actually possible.

2. The directory was populated by five invented businesses. Dr. Brunner,
   Sam Keller, Nadia Roth, Pfoten & Co. and Tierheim Sonnenhof do not exist —
   a customer in Zurich searching for a groomer would have found a fiction.
   They are removed from lib/config/resident-pet.ts, and ensureCommunity is
   gone from the resident-checkin cron so nothing recreates them.

3. Nothing replaced them. lib/domain/profile-readiness.ts is now the single
   rule for when a professional or seller is real enough to be listed:
   identity, services, price, location, a 40-character intro, contact, and
   the pro's own "accepting clients" switch. The same predicate drives the
   ProfileReadiness checklist the pro sees and the SQL conditions the public
   directory queries use — so the listing is earned, never hand-curated.

Selling was already open to any account (products.sellerId = userId) but was
undiscoverable; /portal/become-a-pro now says so and links to the store setup,
which shows the seller's own readiness checklist including "list your first
product".

Also: deleting a pet was reachable only by guessing it lived inside the edit
form — the pet profile now links straight to the danger zone. Professionals
could not accept a booking from /portal/bookings, and groomers were missing
from the booking role union entirely.

E2E gains two checks: an order without an address must be rejected, and the
seller must be able to see where to ship.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 01:10:42 +00:00
GandClaude Fable 5 300fe1cdc2 feat(groomers): grooming as a first-class professional vertical (#27)
Groomer joins vet and sitter everywhere a professional exists:
- user_role enum + groomer_profiles (salon, services, from-price) + migration
- /api/groomers browse + /api/groomers/me CRUD; role plumbed through
  registration (?role=groomer), become-a-pro, availability, bookings,
  conflict guard, admin verification, dashboards, sidebar
- Find a Pro gains a Groomers tab; booking modal books grooming as a
  one-hour session with the salon's from-price in the header
- Public pro profile renders groomers (salon, services, starting price)
- Resident groomer Nadia Roth / Salon Pfotenschick seeds via the daily
  cron with a completed booking + 5-star review, so the tab ships alive
- 6 grooming services in the professionals SSOT; role badge tokens in
  globals.css; ~25 strings x 9 locales

Verified end-to-end locally: register groomer -> profile -> visible in
browse -> booked 201 -> overlap 409. verify + build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 15:36:56 +00:00
GandClaude Fable 5 bb5615c0fa feat(bookings,shop): calendar conflict blocking + Stripe payment integration (#25)
* feat(bookings,shop): calendar conflict blocking + Stripe payment integration

Tier-1 scheduling: the booking API now rejects (409) any request that
overlaps a professional's active bookings or their self-declared blocked
dates; vets/sitters manage blocked ranges at /portal/professional-profile
(new professional_blocked_dates table + /api/availability CRUD).

Payments: full Stripe Checkout flow, env-gated like Resend — without
STRIPE_SECRET_KEY nothing changes; with it, checkout redirects to Stripe,
the signed webhook (/api/payments/webhook) marks orders paid, and unpaid
orders stay payable from /portal/orders (Pay now + paid/awaiting badges).
orders gains paid_at + checkout_session_id.

Critical bug found by the smoke test: the login JWT callback wrote
resolveRole(email) back to the DB, silently DEMOTING every vet/sitter to
pet_owner at their next sign-in (residents were safe only because they
never log in). ADMIN_EMAILS now only promotes; professional roles survive.

Verified end-to-end locally: sitter registers → blocks dates → owner
booking overlap 409, blocked-dates 409, disjoint 201; checkout w/o keys
falls back to recorded orders. verify green (1209 tests incl. 12 new).

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

* chore: nudge CI (pull_request event was never delivered)

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 13:49:47 +00:00
GandClaude Fable 5 acabbdf4f4 feat(resident): full resident ecosystem — every user type represented with living data (#21)
Rosie the Beagle joins Milo as a second daily-tracked resident pet (28-day
deterministic backfill on bootstrap so charts start alive), and the same
cron now idempotently seeds one of every user type: a verified vet and
sitter (Find-a-Pro), a seller with a stocked 7-product shop, a rescue with
an adoption listing, and completed bookings with 5-star reviews so ratings
render on pro profiles. Check-in generation is parametrized per pet
(CheckinProfile) with Milo's series continuing unchanged (salt 0).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 16:38:06 +00:00
GandClaude Fable 5 226a775196 feat(resident): Milo — a real pet tracked for real, one day at a time (#19)
The demo account is wiped and reseeded daily, so nothing on it ever
truly ages. Milo is the opposite: a persistent resident cat whose
morning check-in is logged by a daily cron exactly the way a real
owner would — one row per day, accumulating genuine history. Charts
lengthen, trends emerge, vaccination due-dates actually approach,
and roughly every eleventh day is an anxious one (vacuum day), so
the wellness signal earns the occasional honest 'watch'.

Values are date-seeded and deterministic (re-running a day yields the
same row; the year-long series stays inside cat normal ranges — tested
across 365 generated days). The route bootstraps the account (no
password: machine-only), pet, vaccinations, and first vet record on
first run, then is a one-row-per-day idempotent logger.

Publicly watchable at /pets/milo.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 22:31:50 +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 effd62ce17 feat(i18n): translate pet wellness signal reasons across 9 locales
Add SignalReasonData structured type to computePetSignal return value;
create lib/i18n/signal-reason.ts helper; replace hardcoded English reason
strings with translateSignalReason() calls in dashboard, check-in, pet
profile, health page, and public pet profile; add 13 signal namespace
keys (reasonNoMetrics, reasonStale, reasonOutOfRange,
reasonOverdueVaccinations, metric_*) across all 9 locale files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 12:49:21 +02:00
g-butandClaude Sonnet 4.6 72e407c1d2 feat(i18n): translate digital twin metric labels, scale values, and summaries across 9 locales
- TwinMetricDisplay: removed English-only label/valueLabel fields; components now resolve via i18n
- TwinState: summary field renamed to summaryKey (translation key); summaryText() returns a twin namespace key
- DigitalTwinCard + public pet profile: metric labels, scale value labels, and summary now translated
- HealthLogForm: emotional metric labels and 1-5 scale options now use portal/twin namespaces
- health/page.tsx: metric grid labels and emotional chart legend now use portal namespace
- 38 new twin namespace keys + 4 new portal keys added to all 9 locale JSON files
- EMOTIONAL_SCALE_LABELS duplication removed from HealthLogForm (was also in digital-twin.ts)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 18:47:48 +02:00
g-butandClaude Opus 4.7 a88ec1a835 test: cover three security/i18n helpers that lacked unit tests
Backfill for three helpers used by every protected route or every
new-user flow — the kind of code where a silent regression cascades.

- lib/auth/guards.ts (8 tests): requireSession authed vs not, the
  exact 401 body shape, requireRole for matching/non-matching/no
  session including the load-bearing assertion that pet_owner asking
  for "admin" gets blocked, requireAdmin parametric over every
  non-admin role, and that all failure shapes return identical bodies
  so client UIs can handle uniformly.
- lib/i18n/portal-locale.ts (5 tests): cookie value supported / unset
  / unknown / empty string, plus parametric coverage of every locale
  in routing.locales (so a new locale added to routing won't silently
  break portal cookie reads).
- lib/domain/email-queue.ts (4 tests): single batch insert (not 4
  separate inserts), canonical templateKey order, scheduling delays
  match WELCOME_SEQUENCE values within a slack window, payload +
  userId propagated to every row.

Suite at 491 pass (+18). No behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 11:49:10 +02:00
g-butandClaude Sonnet 4.6 fcf4e81e64 feat(auth): professional self-registration — vets and sitters can declare role at sign-up
Removes the admin bottleneck for the pro network. Previously vets/sitters had
no way to self-register — an admin had to change their role manually. Now any
user can select "Veterinarian" or "Pet sitter" during registration and receive
the correct role immediately (trust-first). After sign-up, pros are redirected
straight to /portal/professional-profile to complete their listing.

Also fixes getAdminEmails() to normalize to lowercase, preventing ADMIN_EMAILS
case mismatches. Adds lib/domain/auth.test.ts (8 tests) and 4 new registration
tests covering intendedRole paths.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 14:07:53 +02:00
g-butandClaude Sonnet 4.6 0bda6b2651 fix(wellness): score 100% for metrics at normal range boundary
Old algorithm used midpoint-distance for physical metrics and raw 1–5
normalisation for emotional metrics, causing healthy pets to show amber
"fair" badges (e.g. temp at 39°C scored 66.7%, energy=3 scored 50%).

Replace both branches with unified range-based scoring: 100% within
normalRange, decreasing linearly to 0 at exactly 1 range-width outside.
Adds 2 explicit boundary tests to lock in the behaviour.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 11:26:09 +02:00
g-butandClaude Sonnet 4.6 2608ee3d97 test(pet-signal): lock in weight-displays-in-kg behaviour
Regression test: weight reason shows '0.5kg' (display units) not '500'
(raw grams). Prevents future changes to toDisplay/unit from silently
breaking the reason string.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 11:00:37 +02:00
g-butandClaude Sonnet 4.6 1c327d3c37 test(pet-signal): add reason string format tests
6 new tests verifying the enriched signal reason introduced in the previous
session: value+range formatting, singular/plural vaccination count, ' · '
joining, and the healthy baseline reason.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 10:55:51 +02:00
g-butandClaude Sonnet 4.6 3ef0fdb7d8 feat(signal): surface signal reason across check-in, health page + richer reason text
- Check-in: compute live signal (metrics + vaccinations) instead of using stale
  lastKnownSignal; show reason line under pet name for watch/concern pets
- Health page: add signal reason banner at top for watch/concern, with link to
  update vaccinations when overdueCount > 0
- pet-signal: enrich reason string to include actual values and normal ranges
  e.g. "Temperature 40.5°C (normal 38–39°C) · 1 overdue vaccination"
  instead of "Temperature outside normal range"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 10:36:41 +02:00
g-butandClaude Sonnet 4.6 8aa95c300e test: add format utils tests + fix formatRelativeDate timezone bug
formatRelativeDate used local midnight for the target date but all other
date operations in the codebase use UTC. For users in non-UTC timezones,
"today" could show as "yesterday". Fixed by using UTC midnight on both
sides of the comparison.

Also adds 11 unit tests for formatDateShort, formatWeight,
formatTemperature, and formatRelativeDate; and 2 missing pet-signal
cases (no metrics + overdue vaccinations → concern; high anxiety →
out-of-range watch).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 09:18:56 +02:00
g-butandClaude Sonnet 4.6 9355bbd589 fix(pet-signal): use friendly metric labels in reason string; fix grammar
Before: "2 metric(s) outside normal range: weight, heart_rate"
After:  "Weight, Heart rate outside normal range"

Also handles the combined case (out-of-range + overdue vaccinations)
and fixes "vaccination(s)" → correct plural.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 03:09:34 +02:00
g-butandClaude Sonnet 4.6 4c56080b2a fix(ssot): move TwinTrend config and wellness thresholds to lib/config
Dashboard was duplicating trend icon/color ternaries that DigitalTwinCard
already defined in a local TREND_CONFIG constant — and that constant lived
in a component instead of a config file, violating SSOT. The wellness score
badge in health/page.tsx used magic numbers 80/60 with no named meaning.

- Add TwinTrend type + TWIN_TREND_CONFIG (color + label) to lib/config/digital-twin.ts
- Re-export TwinTrend from lib/domain/digital-twin.ts for existing consumers
- DigitalTwinCard: import TWIN_TREND_CONFIG from config; keep icon map locally (React refs are UI)
- Dashboard: replace inline ternaries with TWIN_TREND_CONFIG.color lookup
- Add WELLNESS_SCORE_THRESHOLDS = { good: 80, fair: 60 } to lib/domain/health.ts
- health/page.tsx: use WELLNESS_SCORE_THRESHOLDS instead of magic numbers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 01:05:15 +02:00
g-butandClaude Sonnet 4.6 74d74a54fc fix(pets): guarantee unique pet handles + add domain tests
Bug: createPetHandle("Max") always returned "max" — if two users had
pets named "Max", the second insert would fail with a DB unique
constraint violation and surface as a generic 500 error.

Fix: insert pet without a handle, then set handle = baseHandle-<id[:6]>
using the returned UUID. This is collision-free since pet IDs are unique.
Empty baseHandles (all-special-char names) get null handle.

Tests: add lib/domain/pets.test.ts — 17 tests covering createPetHandle
(lowercasing, hyphenation, special char stripping, truncation, edge cases)
and validateSpeciesBreed (empty/Other/valid/invalid breeds, case sensitivity).

Tests: 51 pass · 0 fail (was 34)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 10:35:20 +02:00
g-butandClaude Sonnet 4.6 06c260ef10 fix(quality): resolve all lint errors and activate edit/delete on health pages
- Add edit/delete action buttons to health records page (were wired but not rendered)
- Fix vaccinations table: add `group` class to <tr> so hover buttons are visible
- Fix bookings page: replace raw <a> with Link, restructure useEffect to avoid
  synchronous setState, add Link import
- Fix find page: replace raw <a href="/portal/pets/new"> with Link
- Suppress react-hooks/purity false-positive on server component Date.now() call
- Fix 7 unescaped entity errors across about, pricing, public pet, and homepage
- Remove 8 unused imports/vars: admins, gte, FileText, bookingStatusEnum,
  vaccinations (cron route), Pill (MarketingNav), DAY4 (test), VACCINATION_DUE_SOON_DAYS (pet-signal domain)
- Remove unused NextRequest param from GET /api/bookings

Result: 0 errors · 0 warnings · 34/34 tests · clean build

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 20:02:34 +02:00
g-butandClaude Sonnet 4.6 85f73354fe feat(health): wire computeWellnessScore into health page + add tests
- Health page now shows a color-coded "Wellness N%" badge in the Latest
  reading header (green ≥80, amber ≥60, red <60), computed from all
  available metrics in the latest log entry
- Add lib/domain/health.test.ts with 11 unit tests covering
  computeWellnessScore (null cases, range scoring, inverted anxiety,
  species-specific ranges) and getMetricDisplay (unit conversions,
  in-range detection)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 14:01:53 +02:00
g-butandClaude Sonnet 4.6 c5ce8f4914 feat(digital-twin): add trend analysis + enrich dashboard with twin mini-bar
- computeDigitalTwin now accepts full recentMetrics[] array instead of single row
- Trend: split metrics into recent/prior halves, compare group averages (threshold ±5)
- TwinState gains trend and trendDelta fields
- DigitalTwinCard header shows color-coded trend badge with TrendingUp/Down/Minus icon
- Dashboard pet cards show compact twin mini-bar: state label + trend icon + score + bar
- Dashboard subtitle shows checked-in count based on twin.daysAgo
- 13 unit tests covering all states, anxiety inversion, trend detection

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 11:18:03 +02:00
g-but 5ec41677c9 feat(digital-twin): add pet digital twin — emotional state visualization on pet profile 2026-04-22 10:50:43 +02:00
g-but 3b35d8edcd feat: frictionless registration + improved auth UX + comprehensive CLAUDE.md
Registration:
- Remove name field — just email + password (2 fields only)
- Name auto-derived from email prefix on backend
- Show/hide password toggle on both forms
- Auto-focus email field
- Benefit-driven CTA copy ("Begin your pet's wellness journey")
- "Your pets missed you" greeting on login

Auth layout:
- Feature list replaces emoji grid (health tracking, emotional wellbeing, etc.)
- Cleaner hierarchy with overline label + large headline

CLAUDE.md:
- Add deployed URLs, Vercel team, Neon project ID
- Document all env vars: set vs missing + impact
- Full directory structure with descriptions
- Middleware routing rules with CRITICAL notes
- Complete schema reference table
- Design system (all CSS variables + utility classes)
- Phase status (complete vs todo)
- Known gotchas (8 documented edge cases)
2026-04-20 20:33:12 +02:00
g-butandClaude Sonnet 4.6 ddfb647149 feat: scaffold Petvity — global pet care platform
Full Phase 1 scaffold:
- Next.js 16 + TypeScript strict + Tailwind 4 + Neon/Drizzle + NextAuth 5
- 9-language i18n (EN DE FR ES JA ZH KO TR AR) with RTL support for Arabic
- SSOT config: species (10 types), health metrics (7 KPIs), pet signal system
- DB schema: pets, healthMetrics (unique per pet+day), vaccinations, medications,
  healthRecords, emailQueue
- Numeric storage: weight=grams, temperature=centidegrees (no float drift)
- computePetSignal() — pure domain function, 9 unit tests passing
- API routes: auth, account, pets CRUD, health metrics (upsert), records,
  vaccinations, medications, public pet profiles (no auth)
- Cron: health-alerts, vaccination-reminders, email queue (all Bearer-protected)
- Portal UI: dashboard, pet list, add pet, health tracking, log page, vaccinations
- Public influencer pet profiles at /[locale]/pets/[handle]
- Email templates: welcome sequence, health alert, vaccination reminder

pnpm build ✓  pnpm test ✓ (9/9)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 19:19:52 +02:00