Commit Graph
17 Commits
Author SHA1 Message Date
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 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 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 d2fcae9824 feat(shop): branded category art — no product ever renders as a placeholder box (#24)
New ProductArt component: uploaded photo when present, otherwise a per-category
line illustration in the brand palette (CSS-var driven, re-themes with
globals.css). Wired into every product surface: portal shop grid + cart drawer,
public shop grid + product detail, buyer/seller/admin order items, seller
product list. Order APIs now expose productCategory for the fallback.

Also: public shop hero title was invisible — .ed-title is platinum-on-dark
marketing typography and PR #22 placed it on the light cream hero; now matches
the adopt page's ink title (surfaces stay unmixed per AGENTS.md).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 12:27:10 +00: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 dced92979e refactor(ssot): consolidate price formatting to lib/utils/format.ts
Add formatAdoptionFee(feeCents: number | null): string — returns "Free"
for null/0, whole-dollar amount ("$25") otherwise. Eliminates 7 copies
of the same null-check + division + toFixed pattern scattered across
adoption pages and the admin panel.

Also wire formatPrice() in orders/route.ts and orders/[orderId]/route.ts
(5 instances) instead of inlining the dollar/cent division idiom.

No behavior change; all 534 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 14:05:49 +02:00
g-butandClaude Opus 4.7 dd0599bdec feat(i18n): translate all email templates into 9 locales
- lib/email/i18n.ts: new SSOT with locale-keyed strings for every email
  template (ownerWelcome/AddPet/HealthTracking/WeekOne, passwordReset,
  petHealthAlert, vaccinationReminder, medicationEndingReminder,
  bookingReminder, bookingRequestReceived, bookingStatusChanged,
  orderConfirmation, orderStatusUpdate, sellerOrderNotification,
  adoptionApplicationReceived, adoptionApplicationStatusChanged) in all
  9 locales (en de fr es ja zh ko tr ar). Arabic sets dir=rtl; base()
  injects lang/dir on <html> and rtl inline styles for Arabic.
- lib/email/templates.ts: all template functions accept locale? and
  delegate to getEmailStrings(); t() handles {{key}} interpolation.
- Cron routes: cron/emails now fetches users.locale; cron/health-alerts
  adds locale to owner query; vaccination/medication/booking reminders
  pass ownerLocale to template calls (was only used for date formatting).
- API routes: all transactional email sends (bookings, orders, adoptions,
  forgot-password) add locale to their user selects and pass to templates.
- lib/email/i18n.test.ts: 12 tests covering locale resolution, RTL flag,
  translation completeness for all 9 locales, bullet count, and t().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 09:51:18 +02:00
g-butandClaude Opus 4.7 a5941be818 test: cover three recently-shipped routes that lacked tests
Backfilled tests for endpoints added during the marketplace + i18n
work where rapid iteration outpaced test coverage:

- PATCH /api/account/locale: auth gate, missing-locale 400, invalid-
  locale 400, valid-locale success, parametric coverage of every
  locale in routing.locales (so a new locale added to routing won't
  silently break this endpoint).
- GET /api/orders/seller: auth gate, empty-state, multi-order grouping
  with per-seller subtotal computation, and the load-bearing assertion
  that sellerSubtotalCents covers ONLY the seller's items even when
  the buyer's order spans other sellers.
- GET /api/admin/products: admin gate, empty state, LEFT JOIN payload
  shape (platform product → null seller fields; user-listed product →
  populated sellerName/sellerEmail).

12 new tests, suite at 426 pass · 0 fail. No behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:15:37 +02:00
g-butandClaude Opus 4.7 15d7d8911e feat(marketplace): email sellers when their products are ordered
Adds sellerOrderNotification template + wires it into POST /api/orders.
On checkout, group order items by sellerId, look up sellers in one
query, send each one a notification with their items and subtotal,
linking to /portal/my-products/orders.

Sellers no longer have to poll the fulfillment page — they get
notified the moment a buyer orders. Hoisted the buyer lookup out
of the buyer-confirmation try block since it's now reused for the
buyerName in seller emails (one DB query instead of two).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:46:53 +02:00
g-butandClaude Opus 4.7 aeca2b770d feat(marketplace): seller fulfillment view at /portal/my-products/orders
Closes the loop for marketplace sellers — they can now see orders
containing products they listed, with items filtered to only theirs,
buyer name + email for fulfillment, and their subtotal per order.

- GET /api/orders/seller — orders joined to seller's order_items only
- New page lists orders with status badge + pending-count callout
- "Orders" button added to my-products page header

Order status remains admin-managed (status is order-level, can span
sellers). Sellers see read-only what to ship and to whom.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:28:50 +02:00
g-butandClaude Sonnet 4.6 736a738953 test(api): add integration tests for orders PATCH (status transitions + admin bypass)
8 tests: auth guard, invalid status, user-owns-order scope, owner-cancel-only
enforcement (403), cancel-pending-only guard (400), 200 cancel, admin
confirm + admin ship flows.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 21:49:26 +02:00
g-butandClaude Sonnet 4.6 4e10ea9569 test(api): add integration tests for orders and adoptions routes
Tests cover the critical business rules with a mocked Drizzle chain:
- Orders POST: validation, product not found/inactive, stock check,
  total calculation (2×$10 + 1×$25 = $45), 201 on success
- Adoptions POST: validation, pet ownership guard (404), duplicate
  listing guard (409), 201 on success
- Adoptions PATCH/DELETE: 401 unauthenticated, 403 non-owner,
  200 owner, 200 admin bypass, 400 invalid status

Also adds lib/test-helpers/db-mock.ts — thenable Drizzle chain factory
that resolves via a queue so sequential selects return different data.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 21:33:33 +02:00
g-butandClaude Sonnet 4.6 dc7c08abe9 feat(email): wire transactional emails for orders + adoptions
- orderConfirmation: sent to customer on POST /api/orders
- orderStatusUpdate: sent to customer on PATCH /api/orders/[orderId]
  (confirmed / shipped / delivered / cancelled only — not pending)
- adoptionApplicationReceived: sent to listing owner on application submit
- adoptionApplicationStatusChanged: sent to applicant on approve/reject
- register page: honour ?returnTo param so adopt → register → apply flow works
- All emails fire-and-forget; never block the API response; gracefully
  skip when RESEND_API_KEY is not set

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 10:05:25 +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