Commit Graph

73 Commits

Author SHA1 Message Date
groombook-cto[bot] c438f5772c feat(GRO-607): Stripe Elements payment UI replacing mock flow
* GRO-605: Stripe SDK integration + payment service

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* GRO-606: Add payment API endpoints (pay invoice, payment methods, refunds)

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(GRO-597): Stripe payment backend — schema, service, API, webhooks

Consolidates GRO-605, GRO-606, GRO-608 into a single clean PR:
- GRO-605: Stripe SDK integration + payment service
- GRO-606: Payment API endpoints (pay invoice, payment methods, refunds)
- GRO-608: Stripe webhook handler

Migration consolidation:
- Single 0026_stripe_payment.sql migration adds stripeCustomerId to clients
  and stripe_payment_intent_id, stripe_refund_id, payment_failure_reason to invoices
- Removed duplicate 0027_stripe_identifiers.sql

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* GRO-607: Install Stripe frontend packages

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* GRO-607: Add /portal/config endpoint + rename date field

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* GRO-607: Replace mock payment flow with real Stripe Elements

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(GRO-607): Stripe Elements payment UI - lint/type fixes

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(GRO-607): remove unused eslint-disable directive in CustomerPortal

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(GRO-607): CTO review fixes — payment security and correctness

- Fix multi-invoice total calculation: use inArray() instead of eq()
  on single ID, sum all invoices not just first
- Add ownership check to payment method deletion: verify the payment
  method belongs to the authenticated Stripe customer before detaching
- Remove duplicate /config endpoint in portal.ts
- Fix webhook Stripe client: use getStripeClient() from payment service
  instead of constructing with WEBHOOK_SECRET
- Remove unnecessary body validator on /invoices/:id/pay route
- Export getStripeClient() for use by stripe-webhooks.ts
- Add inArray import to payment.ts

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-14 08:27:03 +00:00
groombook-cto[bot] 15131b72f0 fix(GRO-574): add rate_limit table migration for Better Auth
Adds the missing rate_limit table that Better Auth v1.5.6 requires when rateLimit.storage is set to 'database'. Without this table, all auth endpoints return HTTP 500.

Also includes GRO-566: SKIP_OOBE env var to bypass setup wizard in dev/test.

cc @cpfarhood
2026-04-12 03:30:45 +00:00
Paperclip c919632aea fix(GRO-395): adjust Puggle image array to 4 available images
Removed reference to tricolor-outdoor image that experienced API timeout.
Seed now uses 4 successfully generated Puggle-specific images for the
first 250 seeded pets, ensuring all referenced images exist in demo-pets.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-04-11 02:22:05 +00:00
Paperclip 522e5dbf63 feat(GRO-395): ensure at least 250 seeded pets are Puggles with photos
Add Puggle breed to dogBreeds array and modify seed logic to guarantee first 250 pets are assigned Puggle breed. This ensures demo data includes a significant population of Puggle dogs (Pug-Beagle mix) with images for testing grooming workflows with diverse pet breeds.

- Add Puggle to available dog breeds list
- Track pet creation index across all clients
- Assign Puggle breed to first 250 pets regardless of randomization
- Assign Puggle-specific images to first 250 pets
- Remaining pets use general demo image pool

This satisfies requirement: "at least 250 of the 2500 pets are first or second generation puggles with photos"

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-04-10 21:45:16 +00:00
Paperclip 39f603589b feat(GRO-395): expand demo pet image library with 13 AI-generated diverse dog images
- Generated 13 new diverse dog images using MiniMax (Afghan Hound, Basset Hound, Bichon Frise variants, Boxer, Cavalier, Cocker Spaniel variants, Corgi, Dachshund variants, Pomeranian variants, Schnauzer variants, Setter, Sheepdog)
- Updated seed script to include all 28 dog images in demoPetImages array
- Ensures wider variety of dog breeds and grooming styles in demo seed data
- All images are photorealistic and suitable for pet grooming demo site

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-10 21:40:09 +00:00
Paperclip 2ab06853e6 fix(GRO-395): add demo pet images to seed data for all profiles
- Add demoPetImages array with 15 available dog images
- Assign random pet images during seed for regular, UAT, and demo profiles
- Ensures demo site displays pet images instead of missing images

The seed script previously only added images for seedKnownUsers mode.
Now all seeded pets get assigned a random demo pet image.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-10 21:18:10 +00:00
Flea Flicker fafb717e5a feat(GRO-537): add UAT Super User and Staff Groomer to seed script
In seedKnownUsers(), add staff records for UAT Super User
(manager, superuser) and UAT Staff Groomer (groomer) with oidcSub
read from SEED_UAT_SUPER_OIDC_SUB and SEED_UAT_STAFF_OIDC_SUB
env vars. Only creates records when the env vars are present.
Idempotent: skips if email already exists.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-10 10:48:11 +00:00
groombook-engineer[bot] 1255fd91cd feat: parameterize seed script with SEED_PROFILE env var (GRO-526)
Adds SEED_PROFILE env var accepting 'dev', 'uat', or 'demo' values:

- dev: 4 staff (1 manager, 1 receptionist, 2 groomers), 100 clients,
  7d/30d appointment window, ~1000 invoices, no UAT clients
- uat: 8 staff (1 manager, 1 receptionist, 3 groomers, 3 bathers),
  500 clients, 30d/90d window, ~4000 invoices, includes UAT clients
- demo: same volume as uat

Unset SEED_PROFILE defaults to 'uat' for backwards compatibility.
SEED_KNOWN_USERS_ONLY=true path unchanged.
All appointment dates computed relative to NOW() at seed time.
Supplemental completed appointments generated when profile invoice
target exceeds organic appointment count.

Closes groombook/groombook#247

Co-authored-by: Flea Flicker <flea-flicker@groombook.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-10 04:00:37 +00:00
Flea Flicker 63256b8bc0 feat: implement SEED_ADMIN_EMAIL support in seedKnownUsers and full seed
- Add admin upsert to seedKnownUsers() for prod path
- Add admin upsert to seed() for UAT path
- Idempotent: skips if SEED_ADMIN_EMAIL not set

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-09 22:33:15 +00:00
Paperclip a84d5e7b9a fix: set isSuperUser=false for Jordan Lee in full seed
Jordan Lee was being created with isSuperUser=true in the full seed path,
causing GET /api/setup/status to return needsSetup=false after UAT reset.
2026-04-08 02:56:31 +00:00
Flea Flicker 9be6a87105 chore: implement hourly reset CronJob for prod and UAT
- Add ALLOW_RESET env var override to reset.ts safety guard
- Add reset Docker build target to Dockerfile
- Add reset image build step to CI docker job
- Add reset image tag update to CD job dev overlay update

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-07 20:01:56 +00:00
Flea Flicker 0fe10434e1 feat(invoices): add indexes, pagination, and client name enrichment
- Add database migration 0024 with indexes on invoices, invoice_line_items, and invoice_tip_splits
- Update Drizzle schema with index definitions for sync
- Add pagination (limit/offset) to GET /api/invoices with max 200 limit
- Add LEFT JOIN to include clientName in invoice list response
- Return { data: [...], total: N } response shape for pagination

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-07 19:23:03 +00:00
groombook-qa[bot] 9a3d8d1516 Merge branch 'main' into fix/gro-478-auto-link-staff-user 2026-04-05 14:59:21 +00:00
Flea Flicker e39924b236 fix(api): import isNull from @groombook/db instead of drizzle-orm directly
drizzle-orm is not a direct dependency of @groombook/api, causing
TS2307 at typecheck time. Re-export isNull from @groombook/db and
update the import in rbac.ts.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-05 14:39:22 +00:00
Paperclip 78a6758349 fix(db): generate unique random salt per encryptSecret call (GRO-453)
Use a 16-byte random salt per encryption instead of the fixed
"groombook-auth-provider-config" salt. This prevents identical
plaintexts from producing identical ciphertexts, closing the
timing/anagram security gap identified in GRO-452.

New format: salt:iv:ciphertext:authTag (all base64).
Legacy format (iv:ciphertext:authTag) is still accepted for
backward-compatible decryption of existing stored values.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-04 21:37:30 +00:00
Paperclip 1c7628459f fix(db): use random per-encryption salt in crypto.ts (GRO-453)
Generate a unique 16-byte random salt for each encryptSecret() call
and store it as a prefix in the ciphertext. Format changed from
  iv:ciphertext:authTag → salt:iv:ciphertext:authTag

decryptSecret() detects legacy 3-part format and uses the fixed
package salt for backward compatibility with existing encrypted rows.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-04 13:14:18 +00:00
Flea Flicker 2453e3a0ae fix(db): remove duplicate encryptSecret/decryptSecret exports
Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-04 00:03:48 +00:00
Flea Flicker 1c502bb165 fix(api): wrap encryptSecret in try/catch to return proper JSON error
PUT /api/admin/auth-provider was returning HTTP 500 with an HTML error page
when BETTER_AUTH_SECRET was missing, because encryptSecret() throws an
unhandled error. This change wraps both the encryption step and the DB
transaction in try/catch blocks to return a proper JSON error response.

Also adds the missing authProviderConfig schema and encryptSecret crypto
helpers from the feat/gro-392-oobe-auth-provider-bootstrap branch.

Fixes: GRO-441

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-04 00:02:11 +00:00
groombook-engineer[bot] 02bc0d2c1b fix(db): add missing image and logoKey schema fields to match migrations
Adds `image: text("image")` to pets table and `logoKey: text("logo_key")`
to businessSettings table to resolve typecheck failures. These fields
were added by migrations 0021 and 0022 but the schema definitions were
missing, causing TypeScript errors in seed.ts and settings.ts.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-02 17:38:29 +00:00
groombook-engineer[bot] f4acf5be23 feat(db): auth_provider_config table + AES-256-GCM encryption helpers
Renumbered migration 0021 → 0023 to resolve conflict with pet_image and
logo_key migrations that landed on main after this branch was created.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-02 17:16:35 +00:00
groombook-engineer[bot] 71a6623da2 fix(db): add image: null to Pet factory
Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-02 12:35:05 +00:00
groombook-engineer[bot] 74571d9f2b feat(demo): expand demo pet images and seed data with diverse breed showcase
Generated 16 diverse pet images for demo site using MiniMax image generation:
- Multiple dog breeds (Golden Retriever, Poodle, Labrador, Shih Tzu, Cocker Spaniel, Schnauzer, Maltese, Dachshund, Pomeranian)
- Professional grooming styles and poses
- Studio lighting for quality showcase

Updated seed.ts to create 9 demo pets with image references:
- Expands from single demo pet to diverse pet portfolio
- Images deployed to apps/web/public/demo-pets/
- Each pet has breed-accurate styling and professional grooming

This completes GRO-395 demo assets expansion using allocated MiniMax credits.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-02 12:15:21 +00:00
groombook-engineer[bot] a867be7d55 fix(db): add image column to pets table for demo pet images
Adds `image` field to pets table schema and creates migration to support storing demo pet image URLs. Resolves TypeScript error in seed.ts where image property was being referenced on insert.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-02 11:56:49 +00:00
groombook-engineer[bot] 3d9021913d feat(branding): add GroomBook logo and demo pet images for demo site
- Generated professional GroomBook logo using brand colors (sage green & warm brown)
- Created 4 realistic test pet images (Golden Retriever, Labrador, Poodle, Mixed Breed)
- Updated demo seed to reference pet image in demo database
- Assets are reloaded with demo data going forward

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-02 11:49:43 +00:00
groombook-engineer[bot] 5a09290d9f fix(db): move impersonation TRUNCATE before staff upsert to avoid FK violation
The TRUNCATE of impersonation_sessions/audit_logs was running after the
staff upsert. When a prior seed left impersonation_sessions rows
referencing staff records, ON CONFLICT DO UPDATE on staff violated the
FK constraint on impersonation_sessions.staff_id.

Moving the TRUNCATE before the staff block ensures all impersonation rows
are cleared before any staff insert/update attempt.

Co-authored-by: groombook-engineer[bot] <3141748+groombook-engineer[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-02 01:03:36 +00:00
groombook-engineer[bot] ee803b4376 fix(db): add impersonation_sessions and audit_logs to seed TRUNCATE chain (#200)
Truncate these tables before staff upsert to avoid FK constraint violations
when the dev DB already has impersonation sessions referencing staff rows.

Co-authored-by: groombook-engineer[bot] <3141748+groombook-engineer[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: groombook-ceo[bot] <269735724+groombook-ceo[bot]@users.noreply.github.com>
2026-04-01 21:24:58 +00:00
groombook-ceo[bot] 361567dc3b Merge branch 'main' into fix/gro-360-yq-compound-assignment 2026-04-01 19:56:01 +00:00
groombook-engineer[bot] dff11d02be fix(db): seed staff_id FK fix (GRO-369)
Fixes staff_id FK violation on re-seed: move TRUNCATE before staff upsert and add id to onConflictDoUpdate set clause.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-01 14:19:49 +00:00
groombook-engineer[bot] cfa28c64b6 fix(db): add migration 0020 for UNIQUE(name) + align admin seed ON CONFLICT
Problem:
- Schema change in eacf8ab added .unique() to services.name
- No migration existed to apply this constraint to the database
- Admin seed and seedKnownUsers still used ON CONFLICT (id) with
  a0000001-... IDs, inconsistent with main seed's b0000001-... IDs
  and ON CONFLICT (name)

Fix:
- Migration 0020: clean up existing duplicate services (keep lowest
  id per name), then add UNIQUE constraint on services.name
- Admin seed (apps/api): switch to ON CONFLICT (name) and b0000001
  IDs to match main seed's servicesDef
- seedKnownUsers (packages/db): same alignment — b0000001 IDs and
  ON CONFLICT (name)

GRO-364: ON CONFLICT (name) eliminates the duplicate-row problem
that the old dedup+ON CONFLICT(id) approach could not solve when
existing rows had non-deterministic IDs.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-01 13:54:54 +00:00
groombook-engineer[bot] 7033cd1d5c fix(db): remove dedup DELETE and use ON CONFLICT (name) for idempotent services seed
The dedup DELETE was causing two problems:
1. FK violation (GRO-365) — deleting services referenced by appointments
2. Duplicate services (GRO-301) — MIN(id) per name could delete the wrong row,
   causing ON CONFLICT (id) to create duplicates on re-run

Fix:
- Remove the dedup DELETE entirely
- Keep TRUNCATE of downstream tables (appointments, invoices, etc.) to clear
  stale data from prior runs
- Change ON CONFLICT target from `id` to `name` with a unique constraint on
  name column — deterministic IDs in servicesDef ensure idempotency

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-01 13:54:54 +00:00
groombook-engineer[bot] 07263a89fe fix(db): truncate downstream tables before services dedup to avoid FK violation (#197)
TRUNCATE appointments, invoices, invoice_line_items, invoice_tip_splits,
and grooming_visit_logs CASCADE before the services dedup DELETE to prevent
FK violations from appointments created by previous seed runs.

Fixes: GRO-365

Co-authored-by: groombook-engineer[bot] <3141748+groombook-engineer[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-01 13:21:31 +00:00
groombook-engineer[bot] 034b733f74 fix(db): cast uuid to text for MIN() in services dedup query (GRO-364)
Postgres has no built-in MIN() aggregate for UUID type.
Cast to text before aggregating, then cast back to uuid.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-01 12:25:43 +00:00
Barkley Trimsworth 6277b1c427 Merge remote-tracking branch 'origin/main' into fix/gro-309-landing-page-redirect 2026-04-01 03:43:40 +00:00
groombook-engineer[bot] 2fd86d0636 fix(api): use UTC in reports date helpers — reports show no data (GRO-302)
Fixes GRO-302. Reports page showed no data because date range helpers used local time instead of UTC for boundary calculations.
2026-03-31 19:47:30 +00:00
Barkley Trimsworth d4bdca5616 fix(db): restore serviceIds array used in appointment seed lookups
The serviceIds array is referenced by later appointment creation code.
Restore it inside the services loop.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-31 18:43:35 +00:00
Barkley Trimsworth 6974ca88a8 fix(db): use deterministic service IDs and add deduplication step
Replace random uuid() for service IDs with pre-assigned deterministic
UUIDs (b0000001-0000-0000-0000-...) so that ON CONFLICT DO UPDATE
correctly targets the id column and prevents duplicate inserts.

Also add a one-time deduplication query before inserting that removes
any existing duplicate service rows (keeps lowest id per name), which
cleans up the current deployed database that already has duplicates.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-31 18:38:33 +00:00
groombook-engineer[bot] 40143c4efa fix(db): seed ON CONFLICT target uses clients.id instead of non-unique clients.email
Fixes seed script crash — both onConflictDoUpdate calls on clients table now use schema.clients.id (PK) as conflict target instead of non-unique schema.clients.email. Email added to set clause for both call sites.

Resolves GRO-298. Unblocks GRO-290, GRO-295, GRO-297.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-30 14:44:38 +00:00
groombook-ci[bot] b06314efe2 fix(db): guarantee 5 UAT test clients with pending invoices (GRO-290)
Before: ~5% probabilistic pending invoices meant UAT couldn't reliably
find billing test data. Shedward was blocked from testing Pay Now flows.

After: deterministic 5 UAT clients (uat-alpha through uat-echo) each get
a completed appointment + pending invoice on every seed run. Client
names and emails documented in Shedward AGENTS.md for direct access.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-30 13:33:53 +00:00
groombook-ceo[bot] 0506385157 Merge branch 'main' into fix/make-seed-idempotent-gro-179 2026-03-29 08:05:14 +00:00
groombook-engineer[bot] 4746a63292 feat(portal): replace mock data with real session-driven API calls (#152)
Closes GRO-205. Reviewed and approved by CTO (The Dogfather) and QA (Lint Roller). cc @cpfarhood
2026-03-29 07:08:35 +00:00
groombook-ci[bot] eb48d97ee3 fix(db): make seed script idempotent using upserts
Convert raw inserts to upserts (ON CONFLICT DO UPDATE) for:
- staff: upsert on email (unique constraint)
- services: upsert on id (deterministic UUID)
- clients: upsert on email (unique constraint)
- pets: upsert on id (deterministic UUID)

This fixes the duplicate key violation when re-running the seed
script against an existing database (e.g., after schema migrations
or test restarts).

Note: appointments, invoices, visit logs still use raw inserts
and would need DELETE-before-insert for full idempotency. Those
tables use deterministic UUIDs so a second seed run without
prior DELETE would still fail. This is scoped to the immediate
staff email constraint violation reported.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-29 02:23:02 +00:00
groombook-engineer[bot] 3a31ad71c2 feat(schema): add is_super_user to staff table (GRO-201)
Add boolean is_super_user column (default false) to staff table.
Update Staff interface in shared types.
Mark first manager as super user in both seed modes.
Update test fixtures to include isSuperUser field.

Co-authored-by: groombook-ci[bot] <ci@groombook.bot>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 20:39:46 +00:00
groombook-engineer[bot] ad1f32eb8f feat(auth): replace OIDC/jose with Better-Auth (#136)
* feat(db): add Better-Auth schema tables (GRO-118)

Add user, session, account, and verification tables required by
Better-Auth's Drizzle adapter. Add nullable userId FK on staff to
link business identity to auth identity. Fix test fixtures and
factory to include the new column.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(api): mount Better-Auth handler at /api/auth/** (GRO-118)

- Import toNodeHandler from better-auth/node and auth from ./lib/auth.js
- Mount Better-Auth HTTP handler before auth middleware block
- Handles OAuth callbacks, sign-in/sign-out, session management
- Supports GET/POST/PUT/PATCH/DELETE/OPTIONS methods

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(api): replace JWT auth with Better-Auth session validation (GRO-118)

- Replace jose/jwtVerify with auth.api.getSession()
- Session token validated via cookie/header, DB-backed
- jwtPayload.sub now = Better-Auth user ID (not OIDC sub)
- Dev mode bypass preserved; production guard against AUTH_DISABLED preserved
- rbac.ts and tests updated in subsequent tasks

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(api): update resolveStaffMiddleware for Better-Auth userId (GRO-118)

- Remove JwtPayload import; use inline type in AppEnv
- Production and dev mode lookups now use staff.userId (not oidcSub)
- Backward compat: jwtPayload.sub now = Better-Auth user ID

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* chore(api): remove jose and openid-client deps (GRO-118)

- Remove unused jose and openid-client packages
- Regenerate pnpm lockfile
- Pre-existing Zod type errors resolved (1 remaining: JwtPayload in test)

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(api): remove stale JwtPayload import from impersonation test (GRO-118)

auth.ts no longer exports JwtPayload — replace with inline type.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* test(api): update RBAC tests for Better-Auth userId (GRO-128)

- Add userId field to mock staff records (MANAGER, RECEPTIONIST, GROOMER)
- Update jwtPayload.sub to use userId instead of oidcSub in test helpers
- Update dev mode X-Dev-User-Id header to use userId

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* chore(api): upgrade zod to v4 with v3 compat layer (GRO-131)

- Bump zod from ^3.24.1 to ^4.3.6
- Bump @hono/zod-validator from ^0.4.3 to ^0.7.6
- Update all 12 route files to import from "zod/v3" compat layer

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(api): add Better-Auth configuration (GRO-118)

Exports the better-auth() instance configured with:
- Drizzle PG adapter
- genericOAuth plugin for Authentik OIDC
- 7-day session with 5-min cookie cache

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(web): install Better-Auth client and create config (GRO-118)

- Add better-auth to apps/web/package.json dependencies
- Create apps/web/src/lib/auth-client.ts with createAuthClient config
- Export signIn, signOut, useSession from the client
- Add vite-env.d.ts for Vite client types

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(web): use Better-Auth session state in App.tsx (GRO-126)

Add useSession hook to check Better-Auth session for production auth.
Redirect to Authentik sign-in when no session in production mode.
Dev mode flow (DevLoginSelector) preserved.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(web): scope devFetch interceptor to dev mode only (GRO-127)

* fix(api): validate BETTER_AUTH_SECRET and fix lockfile specifier (GRO-118)

- Add startup validation for BETTER_AUTH_SECRET when auth is enabled
- Fix pnpm-lock.yaml typescript specifier mismatch (^5.9.3 → ^5.7.3)

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(web): mock authDisabled=true in App.test.tsx to fix CI failures

App.test.tsx "App navigation" tests were failing because the beforeEach
set authDisabled=false (production mode), which triggers the Better Auth
useSession() path. Since useSession() was not mocked in tests, the
component rendered null instead of the admin nav.

Now uses authDisabled=true + dev user in localStorage for those tests,
bypassing the Better Auth dependency while still testing the nav render.

Also removes duplicate App.test.js (compiled artifact).

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): set authDisabled=true in fixtures to bypass Better Auth

The App.tsx production auth path calls signIn.social() when
authDisabled=false, causing E2E tests to render blank. The fixtures
must mock authDisabled=true so the dev login selector is used instead.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): add dev/config, dev/users, and branding mocks to navigation.spec.ts

Playwright matches routes in last-registered-first-served order, so the
catch-all /api/** handler was overwriting the authDisabled: true fixture.
Added specific handlers before the catch-all to ensure auth config,
user list, and branding responses are properly shaped.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(web): gate DevLoginSelector on API authDisabled, not import.meta.env.DEV

Move the DevLoginSelector rendering check from import.meta.env.DEV to the
API-driven authDisabled state, after the loading guard. Simplify the redirect
condition to remove the now-redundant pathname exception.

Fixes E2E login tests that were failing because DevLoginSelector was never
rendered in Docker production builds where import.meta.env.DEV is false.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(db): add missing migration journal entries 0012-0017

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(web): import App.tsx (not App.js) in App.test.tsx (#137)

* fix(web): mock /api/auth/get-session in Dev login selector test

The "redirects to /login when auth is disabled and no user selected" test
fails because useSession() from better-auth/react calls /api/auth/get-session
which wasn't mocked, causing sessionLoading to stay true indefinitely.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(web): import App.tsx (not App.js) in test to get authDisabled bypass

The Dev login selector test was importing the compiled App.js instead of
the source App.tsx. App.js has different logic (uses import.meta.env.DEV
instead of API-based authDisabled) and doesn't implement the
sessionLoading bypass needed for tests to pass.

Also applied the rawSession/rawSessionLoading refactor in App.tsx that
bypasses useSession result when authDisabled=true.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(web): use extensionless import for App in test

The `.tsx` extension in the import path is not allowed without
`allowImportingTsExtensions` (TS5097). Use extensionless `../App`
which resolves correctly via moduleResolution: "bundler".

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>

* fix(auth): dev login resolve staff by id, not userId

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(rbac): fallback lookup for staff records predating Better-Auth userId (#140)

GRO-153: /api/staff returned 403 for all staff because resolveStaffMiddleware
looked up by staff.userId (Better-Auth ID) but dev login sent staff.id (PK),
and existing staff records had userId=NULL.

Changes:
- resolveStaffMiddleware: try userId first, fall back to staff.id (dev mode)
- resolveStaffMiddleware: try userId first, fall back to oidcSub (production)
- GET /api/dev/users: include userId field for DevLoginSelector
- DevLoginSelector: send userId (not staff.id) as X-Dev-User-Id
- Migration 0018: backfill userId for known demo staff

Co-authored-by: groombook-engineer[bot] <groombook-engineer@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Barkley Trimsworth <barkley@groombook.farh.net>

* fix(rbac): allow all staff roles to READ /api/staff

GRO-156 follow-up: RBAC middleware was blocking groomer/receptionist
from GET /api/staff. The QA review found 403 with "role groomer is not
permitted" after PR #140 deployment.

Fix: split the /staff/* guard — GET requests allow all roles
(groomer, receptionist, manager); write operations remain manager-only.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: groombook-engineer[bot] <269742240+groombook-engineer[bot]@users.noreply.github.com>
Co-authored-by: Flea Flicker <flea-flicker@paperclip.ing>
Co-authored-by: groombook-engineer[bot] <groombook-engineer@users.noreply.github.com>
Co-authored-by: Barkley Trimsworth <barkley@groombook.farh.net>
2026-03-28 03:50:45 +00:00
groombook-engineer[bot] ce621a29b1 chore: add AGPL-3.0 license and update package.json license fields
Co-authored-by: Flea Flicker <flea-flicker@paperclip.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-27 18:22:19 +00:00
groombook-engineer[bot] 9eb0c3d151 fix(gro66): E2E selector fix + groomer isolation + portal confirm/cancel
* Implement confirm/cancel in customer portal (GRO-50)

Backend:
- Add POST /api/portal/appointments/:id/confirm endpoint
  - Validates impersonation session auth and ownership
  - Rejects past/in-progress, non-pending, or already-cancelled/completed
  - Sets confirmationStatus="confirmed", confirmedAt, updatedAt
- Add POST /api/portal/appointments/:id/cancel endpoint
  - Same auth/ownership pattern
  - Rejects past/in-progress or already-cancelled/completed
  - Sets status="cancelled", confirmationStatus="cancelled", cancelledAt, updatedAt

Frontend (Appointments.tsx):
- Add confirmationStatus field to Appointment type and mock data
- Add ConfirmationSection component: shows status badge + confirm button
- Add CancelAppointmentButton: wires to cancel API with loading/error state
- Wire existing Cancel button to CancelAppointmentButton
- Show confirmation status badge in expanded view for upcoming appointments

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat(gro-48): row-level data scoping for groomer role (RBAC Phase 2)

Filter query results at the route handler level when staff role is groomer:

- GET /api/appointments: WHERE staffId = groomer OR batherStaffId = groomer
- GET /api/appointments/🆔 403 if not assigned to groomer (as staff or bather)
- GET /api/clients: Clients with ≥1 appointment for this groomer (via exists subquery)
- GET /api/clients/🆔 403 if no appointment linkage
- GET /api/pets: Pets owned by groomer-linked clients (via exists subquery)
- GET /api/pets/:petId: 403 if no appointment linkage

Managers and receptionists: no change.

Added exists to @groombook/db exports (was missing from re-export).
Added groomerIsolation unit tests for role guard and filter logic.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(gro-50): add portal confirm/cancel tests and fix ConfirmationSection state

- Add test coverage for POST /portal/appointments/:id/confirm endpoint
- Add test coverage for POST /portal/appointments/:id/cancel endpoint
- Fix ConfirmationSection not updating local status after successful confirm
- Remove unused onCancel prop from ConfirmationSection call site
- Fix Appointments.test.tsx missing confirmationStatus field

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

* test(gro-50): add ConfirmationSection UI component tests

Add tests for the ConfirmationSection component:
- Renders correct badge for each confirmationStatus state
- Shows/hides Confirm button based on status
- Calls confirm API with correct headers
- Handles sessionId null case
- Shows error messages for 401/403/422 responses
- Shows loading state while confirming
- Shows success message briefly after confirm
- Does not call API if user cancels confirm dialog

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(gro-48): address QA review feedback — staffRow?.role and portal TS guards

- appointments.ts: use staffRow?.role (consistent with clients.ts/pets.ts)
  to handle undefined staff context safely
- portal.ts: add null guards on .returning() results for confirm and cancel
  endpoints (TS18048: 'updated' is possibly undefined)
- All 188 tests passing; TypeScript typecheck clean

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(gro66): use specific selector for banner visibility assertion

Replace ambiguous `getByText("STAFF VIEW")` that matched both the
ImpersonationBanner and the CustomerPortal watermark with a precise
`getByTestId("impersonation-banner")` selector to eliminate strict
mode violations.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(gro-66): add missing afterEach to vitest import

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(gro-48): add icalToken to MANAGER mock after rebase

After rebasing onto origin/main (which added icalToken to the staff
schema via GRO-107), the MANAGER mock in groomerIsolation.test.ts was
missing the new required field. Added icalToken: null to the MANAGER
constant. factories.ts is clean (no duplicate icalToken after rebase).

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(gro-47): add non-null assertions on Drizzle RETURNING results

Drizzle's update().returning() types the array element as T | undefined.
After the if (!appt) guard, updated is still typed as possibly undefined
because RETURNING can succeed with no rows. Add ! assertions since
we already guard with the existence check.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Flea Flicker <fleaflicker@groombook.ai>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Flea Flicker <flea-flicker@paperclip.ing>
2026-03-27 14:23:19 +00:00
groombook-engineer[bot] 6539eb4554 feat: iCal calendar feed (GRO-107)
feat: iCal calendar feed (GRO-107)

Closes GRO-107
2026-03-27 02:37:06 +00:00
groombook-engineer[bot] e3220af9ce fix(gro-38): prod/demo auth and API-based seed (#117)
Closes GRO-38. Adds POST /api/admin/seed (manager-only, gated by SEED_KNOWN_USERS_ONLY) and separates dev vs prod seeding paths. Reviewed and approved by CTO and QA.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-26 20:51:08 +00:00
groombook-engineer[bot] d0b4baf5aa feat: customer-facing appointment notes (GRO-106) (#109)
* feat: add customer-facing appointment notes (GRO-106)

- Migration 0014: add customer_notes column to appointments
- Schema update: add customerNotes field to appointments table
- Factory update: include customerNotes in buildAppointment
- Portal route: PATCH /api/portal/appointments/:id/notes
  - Ownership validation via impersonation session
  - Future-only validation (no edits after start)
  - 500 character limit
- Register portal router in index.ts

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* Fix confirmationToken leak and add unit tests for portal notes endpoint

- Return only id, customerNotes, updatedAt instead of full appointment row
- Add comprehensive unit tests covering auth, ownership, time-gating, and validation
- Fix: confirmationToken no longer returned to portal session

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* feat: add customer notes UI to portal and staff views (GRO-178)

- Add customerNotes field to Appointment type
- Add read-only customer notes display in staff appointment detail modal
- Add customer notes textarea with save, char counter (500 max), and disabled state
- Wire up PATCH /api/portal/appointments/:id/notes in portal UI
- Update mockData with customerNotes field

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: address QA review feedback - null check and portal route auth

- Add null check after db.update().returning() in portal notes endpoint
- Move portal router registration before auth middleware so clients can access it
- Remove unused ENDED_SESSION variable from test file

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(portal): address QA review - isUpcoming time parsing and session header

- Fixed parseTimeTo24Hour to handle 12-hour AM/PM format correctly
- Added X-Impersonation-Session-Id header to CustomerNotesSection fetch
- Added comprehensive tests for CustomerNotesSection and time parsing
- Fixed TypeScript strict null checks for parseTimeTo24Hour

Fixes QA review issues:
- isUpcoming() now correctly parses 12-hour time format
- CustomerNotesSection sends session ID header for auth
- Added unit tests for new UI component

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: thread sessionId as prop instead of sessionStorage

CustomerNotesSection was reading sessionStorage for the impersonation
session ID, but CustomerPortal stores it in React state. Pass sessionId
as a prop through AppointmentsSection and AppointmentCard instead.

Also update tests to pass sessionId prop and add test for null sessionId
case.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Scrubs McBarkley <scrubs@groombook.app>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: groombook-cto[bot] <269737991+groombook-cto[bot]@users.noreply.github.com>
2026-03-26 08:24:21 +00:00
Scrubs McBarkley d1ab91adfa feat: appointment confirmation and cancellation (GH #98, GRO-153)
Add customer confirmation/cancellation flow for appointments:

- DB migration (0013): add confirmation_status, confirmed_at, cancelled_at,
  confirmation_token to appointments table with index on token column
- schema.ts + factories.ts + types: expose new columns and ConfirmationStatus type
- GET /api/book/confirm/:token — tokenized confirm via email link (redirects)
- GET /api/book/cancel/:token — tokenized cancel via email link, single-use token
- POST /api/appointments/:id/confirm — portal/staff confirm endpoint
- POST /api/appointments/:id/cancel — portal/staff cancel endpoint
- Reminder emails now include Confirm/Cancel CTA buttons with tokenized links
- Reminder service generates confirmation token if missing before sending
- Staff calendar shows confirmation status indicator on appointment cards
  and in the detail modal (confirmed ✓ / customer cancelled ✗)
- /booking/confirmed, /booking/cancelled, /booking/error redirect pages
- 23 new unit tests covering all new endpoints and edge cases

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-24 16:02:58 +00:00
groombook-ceo[bot] 020e758916 Merge branch 'main' into feat/pet-photo-upload-gh93 2026-03-22 19:45:35 +00:00