Commit Graph
30 Commits
Author SHA1 Message Date
CatoandClaude 2d3609c13e feat(auth): stage AccountKit beside Auth.js, switch off (#156)
Petvity moves from Auth.js to @bitbaum/accountkit one reversible step at a
time, as evig and kivvi do. Nothing changes while AUTH_RUNTIME is unset.

- Migration 0008: AccountKit's tables under an `auth_` prefix, plus the
  users <-> auth_users mirror functions, inert until attached.
- scripts/db/accountkit-import.sql: accounts under their own ids, bcrypt
  hashes byte for byte, verification kept, orangecat_sub as an `orangecat`
  account row; refuses collisions, drift or a live shared runtime, then
  attaches the triggers. The rehearsal CLI always rolls back.
- lib/auth/shared/: the runtime (ids: 'uuid', legacy bcrypt, AccountKit
  0.16.0), a session reader re-read from `users` on every request, a bridge
  that answers next-auth/react including "Sign in with OrangeCat", and a
  Petvity row for a person AccountKit creates itself. AccountKit's own
  credential endpoints stay closed; Petvity's writers stay the only ones.
- lib/auth/claims.ts: the ADMIN_EMAILS promotion rule, written once.
- The proxy has one routing function and two session sources.
- browser-smoke.yml runs the account journey once per runtime; the
  AccountKit leg first runs the rehearsal and the real-database journeys.

docs/ACCOUNTKIT-MIGRATION.md records what is left before switching.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 08:31:55 +01:00
CatoandClaude Opus 5.5 2b7a71cb4f feat(auth): sign in with OrangeCat (#104)
"Sign in with OrangeCat" (OIDC) is now the primary action on /login and
/register; email + password stays behind a disclosure so existing accounts
are not locked out. OrangeCat's own page carries Google, GitHub, email and
open registration.

- Provider: client_secret_post + PKCE + state, scope "openid profile email",
  issuer https://orangecat.ch (ORANGECAT_OAUTH_ISSUER overrides). Absent,
  not broken, until ORANGECAT_OAUTH_CLIENT_ID/SECRET are set.
- Users are keyed ONLY on the new users.orangecat_sub (additive migration
  0007). The provider profile carries no email, so Auth.js never looks a
  user up by email; a new sub always creates a new user. A taken email gets
  an undeliverable @users.invalid placeholder.
- An OrangeCat login never earns ADMIN_EMAILS promotion (email unverified).
- Identity only: no OrangeCat token refresh, tokens not stored.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 05:01:17 -07: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 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 c2b5f392c1 fix(blog): a taken URL is a 409 the author can fix, not a 500 (#49)
Caught by exercising the live endpoint as an admin rather than trusting the
unit test: creating a second post with an existing slug answered 500.

Drizzle wraps driver errors, so the pg error carrying `code: 23505` is the
`cause` of what the route catches, not the error itself. Reading only the
top-level `code` looks correct in a test — where the error is hand-built with
the code right on it — and is wrong against a real database. The test passed
and production returned 500 for a mistake the author can fix in two seconds.

isUniqueViolation now walks the cause chain, bounded, with a guard against a
self-referencing chain hanging the request.

Both tests now use the wrapped shape production actually throws, which is the
point: the old test asserted the shape I assumed, not the shape reality
produces.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 13:13:11 +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 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 2a46bced71 fix(orders): cancelled orders restore stock; sellers can delete their account (#29)
Found by an exhaustive 129-check production walkthrough of every user path:

1. Cancelling an order never released the stock it reserved at creation —
   every cancellation permanently destroyed inventory. Cancellation (user
   or admin) now restores stock for finite-stock items, guarded against
   double-restore.

2. A seller who had ever sold anything could not delete their account
   (GDPR erasure 500'd): order_items.product_id was ON DELETE RESTRICT.
   Order items now snapshot the product NAME at purchase time (they
   already snapshot price), product_id is nullable ON DELETE SET NULL,
   and all order reads use the snapshot — the buyer's order history
   survives the seller's erasure intact. Migration backfills existing
   rows from the products table.

verify + build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 17:37:14 +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 Opus 4.8 f79ae9772d chore(infra): remove Vercel references — self-hosted now (#8)
Vercel is decommissioned; petvity runs self-hosted on the Hetzner box
behind Caddy at petvity.orangecat.ch. Repoint every current-setup Vercel
reference to that reality:

- Remove vercel.json (Vercel Cron is gone; CLAUDE.md cron table is the
  schedule SSOT, driven by host cron/systemd timers).
- Privacy page: Vercel hosting -> Hetzner; drop "Vercel Blob" vendor
  (avatars now on local disk, not a third party).
- Cookies page: drop the Vercel Analytics claim (no analytics package is
  installed) -> state no third-party analytics.
- FAQ (de/en/es/fr): "Vercel's global edge infrastructure" -> self-hosted
  European infrastructure.
- schema.ts / avatar route / forgot-password: comments no longer say
  "Vercel Blob"/"Vercel logs".
- .gitignore: drop the .vercel ignore.

Kept: lib/storage.ts "replaces @vercel/blob" narrative and the CLAUDE.md
"there is no Vercel Cron" guardrail. Lockfile transitive deps untouched.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 21:51:16 +02:00
Mao NakamotoandClaude Fable 5 94882211f2 feat(selfhost): migrate to self-hosted Hetzner (Vercel/Neon/Supabase exit 2026-06-12)
Standalone output, portable Postgres driver, proxy-aware fixes as needed.
Runbook: fleetcrown/docs/infrastructure/hetzner-migration.md

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 19:48:13 +02:00
g-butandClaude Sonnet 4.6 2ff092aaaf feat(seller): seller profile CRUD + i18n in 9 locales + improved registration onboarding
- lib/db/schema.ts: add sellerProfiles table (displayName, bio, city, country, phone, website, isActive)
- app/api/sellers/me: GET / POST / PATCH handler with requireSession() guard
- proxy.ts: add /api/sellers to PRIVATE_API_PREFIXES
- app/(portal)/layout.tsx: query sellerProfiles, pass hasSeller to SidebarNav
- app/(portal)/portal/seller-profile/: page.tsx (server) + SellerProfileForm.tsx (client, full i18n)
- messages/*.json: add 17 seller i18n keys to all 9 locales (EN DE FR ES JA ZH KO TR AR)
- register/page.tsx: redirect pet owners to /portal/pets/new?from=registration after sign-up
- portal/pets/new/page.tsx: show welcome banner + redirect to health log on first pet creation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 12:39:20 +02:00
g-butandClaude Sonnet 4.6 0709b56879 fix(security): eliminate race conditions in orders and adoption applications
orders/route.ts — stock decrement was read-modify-write using a stale snapshot,
two concurrent requests could both pass the stock check and oversell the last unit.
Fix: atomically decrement each product using
  UPDATE products SET stock = stock - qty WHERE id = ? AND stock >= qty
before inserting the order record. If any decrement returns 0 rows (stock gone),
we compensate by re-incrementing the products that already decremented and return 409.

schema.ts — adoptionApplications had no DB-level uniqueness for (listingId, applicantId);
the API-only check-then-insert was vulnerable to concurrent duplicate submissions.
Fix: add UNIQUE INDEX on (listing_id, applicant_id). Migration applied via pnpm db:push.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 18:32:01 +02: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 Opus 4.7 0034da48fc feat(account): GDPR Article 15 — data export + fix loggedBy cascade
Pairs with yesterday's account-deletion (0ce5192) to complete the
core GDPR data-rights story (right of access + right to erasure).

- GET /api/account/export: bundles every row the current user owns or
  authored into a downloadable JSON file (Content-Disposition:
  attachment, no-store cache). Sections: account profile (sanitized —
  no password hash), pets, health metrics/records/vaccinations/
  medications, signal history, bookings, reviews written, orders +
  items, products listed, adoption listings + applications submitted.
  Schema-versioned so future format changes don't break old downloads.
- Settings page: "Your data" card with a Download button above the
  Danger zone — the natural pairing (back up, then delete).
- 4 tests cover auth gate, missing-account 404, full payload shape +
  filename + cache headers, and the load-bearing assertion that the
  password hash is NEVER included in the account section.

Also: healthMetrics.loggedBy now SET NULL on user delete instead of
the previous (unset) NO ACTION default. The metric belongs to the
pet (owner cascade handles its lifecycle) — deleting the *logger*
(e.g. a vet who entered it on the owner's behalf) must not erase
the owner's history. Latent under single-actor flows; a footgun the
moment multi-user logging ships. Fixed proactively.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:13:24 +02:00
g-butandClaude Opus 4.7 00627fbce4 feat(email): wire end-to-end welcome-email opt-out
users.digestOptOut existed in the schema (on the never-used
ownerProfiles table) but had no UI, no API, and no cron enforcement —
fully dead. Closing the loop:

- Schema: moved digestOptOut from ownerProfiles → users (where every
  user already has a row, no parallel-table juggling). pnpm db:push
  applied; ownerProfiles is still dead but tidier.
- API: extended PATCH /api/account to accept digestOptOut: boolean.
  New GET /api/account returns { name, email, locale, digestOptOut }
  so the settings page can hydrate without session-token changes.
- Cron: /api/cron/emails now reads users.digestOptOut and DELETEs
  pending welcome items for opted-out users instead of sending them.
  Returns { sent, failed, skipped } for visibility.
- Settings UI: new "Email preferences" card between Profile and
  Password with a clear checkbox; copy makes explicit that
  transactional emails (vaccination reminders, health alerts, order
  confirmations) are not affected.

Users who don't want the day-1/3/7 onboarding series can finally
turn it off without losing transactional notifications.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:47:56 +02:00
g-butandClaude Opus 4.7 14fdb9a847 feat(i18n): persist users.locale so cron emails match the user's choice
The LocaleSwitcher set a cookie but cron jobs (running outside any
session) had no way to know what language each recipient wanted —
so vaccination/medication/booking reminders were always English.

- Schema: add users.locale (varchar(5), nullable; null = default).
  pnpm db:push applied to Neon.
- New PATCH /api/account/locale: requireSession-guarded, validates
  against routing.locales, updates the user row.
- LocaleSwitcher: best-effort PATCH the new endpoint when picking a
  language (anonymous 401 is fine — cookie still drives portal/marketing).
- Reminder crons (vaccination, medication, booking): include
  ownerLocale in the join projection and pass it to formatDateShort
  / toLocaleDateString. Booking reminder also stops hardcoding "en-US".

Side-effects in LocaleSwitcher extracted to module-scope persistLocale()
so React Compiler's immutability rule doesn't flag the cookie write.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:27:59 +02:00
g-butandClaude Opus 4.7 6233f84dc1 feat(marketplace): let any user list products via /portal/my-products
- Schema: products.sellerId FK to users (null = platform product) + index
- API: GET ?mine=true scoped to seller; POST defaults sellerId=self,
  admin-only ?platform=true creates sellerId=null; PATCH/DELETE allow
  owner OR admin
- New /api/admin/products returns full list with seller name/email join
- Admin products page now POSTs to /api/products?platform=true
- Portal: /portal/my-products with list, form modal, hide/show toggle,
  soft-delete; sidebar entry under Orders
- i18n: myProducts key in all 9 locales (EN DE FR ES JA ZH KO TR AR)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 15:55:14 +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 f66314b271 perf(db): add missing FK indexes on hot query columns
PostgreSQL does not auto-index FK columns (unlike MySQL). Every portal
page load was hitting full table scans on pets.ownerId, healthMetrics.petId,
vaccinations.petId, medications.petId, orders.userId, etc.

Added 12 indexes across 11 tables:
- pets: ownerId
- healthRecords: petId
- vaccinations: petId
- medications: petId
- orders: userId
- orderItems: orderId
- adoptionListings: ownerId, status
- adoptionApplications: listingId, applicantId
- bookings: ownerId, professionalId
- emailQueue: (status, sendAt) composite
- reviews: professionalId

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 06:54:19 +02:00
g-butandClaude Sonnet 4.6 2d14fd42d6 feat(phase4): add adoption listings — browse, apply, manage + schema
Schema: adoptionListings + adoptionApplications tables (pushed to Neon)

API routes:
- GET/POST /api/adoptions (public browse + owner create)
- GET/PATCH/DELETE /api/adoptions/[listingId]
- POST /api/adoptions/[listingId]/apply (one application per user)
- GET/PATCH /api/adoptions/[listingId]/applications (owner manages applications)

Portal pages:
- /portal/adopt — browse available listings with species + location filters
- /portal/adopt/[listingId] — listing detail + application form
- /portal/adoptions — owner manages their listings + approves/rejects applications
- /portal/pets/[petId]/list-for-adoption — create listing for a specific pet

Pet profile page: "List for adoption" shortcut link added
SidebarNav: Adopt nav item added

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 08:56:29 +02:00
g-butandClaude Sonnet 4.6 7a9dc1ae97 feat(phase3): add marketplace — products, shop, orders
Schema:
- Add productCategoryEnum, orderStatusEnum, products, orders, orderItems tables
- products: name, description, priceCents (integer), imageUrl, category, stock, isActive
- orders: userId, status, totalCents, notes
- orderItems: orderId, productId, quantity, priceCents snapshot

APIs:
- GET/POST /api/products (public list; admin create)
- PATCH/DELETE /api/products/[productId] (admin only; DELETE = soft deactivate)
- GET/POST /api/orders (user's orders; place order with stock validation)
- PATCH /api/orders/[orderId] (user can cancel pending; admin can advance status)
- Add /api/orders to PRIVATE_API_PREFIXES in proxy.ts

UI:
- /portal/shop — product grid with category filter, inline qty controls, cart drawer, order placement
- /portal/orders — order history with expandable line items, cancel pending orders
- /admin/products — admin product catalogue (add, edit, activate/deactivate)
- SidebarNav: add Shop + Orders links
- Admin layout: add Products link

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 20:29:48 +02:00
g-butandClaude Sonnet 4.6 a96313acf7 feat(phase2): add reviews — post-booking star ratings + find-page aggregates
- Add reviews table to schema with unique bookingId constraint (pushed to Neon)
- Add /api/reviews GET (list with avg/count) + POST (owner, completed booking only)
- Bookings page: Review button on completed unreviewed bookings, StarPicker modal
- Find page: star rating + review count shown on vet/sitter cards
- Vet/sitter list APIs now include avgRating + reviewCount via single aggregation query
- Bookings API GET now LEFT JOINs reviews to return reviewId
- Add /api/reviews to PRIVATE_API_PREFIXES in middleware

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 15:06:55 +02:00
g-butandClaude Sonnet 4.6 9dd1a539e5 feat(phase2): add bookings — schema, API, portal page, find-page Book button
- Add booking_status enum + bookings table to schema (pushed to Neon)
- Add /api/bookings GET (list own) + POST (create, owner-only) endpoints
- Add /api/bookings/[bookingId] PATCH (confirm/cancel/complete) + DELETE
- Add /portal/bookings page with upcoming/past sections and status actions
- Add Book button + modal to /portal/find page (pet selector, dates, notes)
- Show phone numbers on vet/sitter cards in find page
- Add Bookings nav item to SidebarNav
- Add /api/bookings to PRIVATE_API_PREFIXES in middleware

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 14:52:23 +02:00
g-butandClaude Sonnet 4.6 f01b36a395 feat(phase2): add vet/sitter profiles + find-a-pro discovery
- Add vetProfiles + sitterProfiles tables to schema (pushed to Neon)
- Add /api/vets and /api/sitters list endpoints with city/accepting filters
- Add /api/vets/me and /api/sitters/me upsert endpoints (role-scoped)
- Add /portal/professional-profile page (server-rendered, role-checked)
- Add /portal/find discovery page (tabs: vets/sitters, city filter)
- Update SidebarNav: Find a Pro for all users, My Profile for professionals
- Add /api/vets + /api/sitters to PRIVATE_API_PREFIXES in middleware

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 14:27:24 +02:00
g-butandClaude Sonnet 4.6 c75a4820e4 feat(species): expand from 4 to 10 species + SSOT enum fixes
New species: bird, rabbit, guinea_pig, hamster, reptile, fish — each
with breeds, lifespan, and species-specific health metric normal ranges
(weight, temperature, heart rate) in both species.ts and health-metrics.ts

- lib/db/schema.ts: extend speciesEnum with 6 new values (db:push applied)
- lib/config/species.ts: full SpeciesDef for all 10 species including
  clinically accurate normal ranges and breed lists
- lib/config/health-metrics.ts: per-species normalRange entries for all
  new species so wellness scoring and signal detection are accurate
- app/api/pets/route.ts: derive species/sex Zod enums from schema (SSOT)
- app/api/pets/[petId]/route.ts: same sex enum fix

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 14:11:11 +02:00
g-butandClaude Sonnet 4.6 53ba8eadb6 feat(species): reduce to dog, cat, horse, other for MVP focus
Remove bird, rabbit, guinea_pig, hamster, reptile, fish from both
the SSOT config and the Postgres enum. Schema pushed to Neon.
Keeping 'other' as a fallback for uncategorised pets.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 20:22:50 +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