docs: update README to reflect Phases 1-5 complete

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Sonnet 4.6 committed 2026-06-14 08:44:48 +02:00
1 parent da0f9f2bb7
commit 1fc69add4d
1 file changed
+110 -43
+110 -43
View File
@@ -20,14 +20,16 @@ A social platform where pets are the stars. Dogs, cats, and birds get their own
| Media Storage | Supabase Storage (S3-compatible) | — |
| Cache / Feed | Upstash Redis (serverless) | — |
| Client Fetching | TanStack Query | 5.x |
| Video | Mux (upload, transcoding, HLS streaming) | — |
| Tests | Vitest | 4.x |
| Hosting | Vercel (target) | — |
**Design decisions:**
- All data access goes through **Prisma → direct Postgres connection**, never through Supabase PostgREST. RLS is enabled on all tables with no policies, which closes the PostgREST surface entirely.
- Media (photos, avatars, stories) is stored in **Supabase Storage** via presigned PUT URLs — file bytes never pass through the Next.js API server.
- The social feed uses a **Redis fan-out-on-write** pattern: on each new post, a sorted set entry is written into every follower's feed inbox. `feed.getFeed` reads from Redis and hydrates with Prisma.
- The social feed uses a **Redis fan-out-on-write** pattern: on each new post, a sorted set entry is written into every follower's feed inbox. `feed.getFeed` reads from Redis and hydrates with Prisma. Falls back to Postgres when Redis is unavailable.
- Authentication is handled by **Clerk** (owner accounts). Pet profiles are app-domain entities in Postgres, not Clerk users.
- Short-form video is handled by **Mux**: client uploads directly to a signed Mux URL → Mux transcodes and serves HLS via `mux-player-react`. The `getByPostId` query self-heals in dev by polling the Mux API directly, so webhooks are not required during local development.
---
@@ -38,34 +40,44 @@ src/
app/
(app)/ # Protected app shell (Clerk middleware)
feed/ # Home feed page + StoryTray
notifications/ # Notification center page
pets/[petId]/ # Pet profile page + ProfileTabs
pets/[petId]/edit/
pets/[petId]/followers/
pets/[petId]/following/
search/ # Pet + People + Hashtag search
onboarding/ # Pet creation onboarding
(auth)/ # Clerk-rendered sign-in / sign-up
api/
trpc/ # tRPC HTTP handler
webhooks/
mux/ # Mux webhook handler (video.asset.ready etc.)
components/
feed/ # PostCard, MilestoneCard, FeedList, SkeletonCard
layout/ # Sidebar, MobileNav
feed/ # PostCard, MilestoneCard, RepostCard, FeedList, SkeletonCard
# PawButton (🐾 reaction), PawBackButton (repost), CommentSheet
layout/ # Sidebar (with NotificationBell), MobileNav
notifications/ # NotificationBell (badge + count)
pet/ # AvatarUpload, PetForm, PetListItem
post-creation/ # PostTypeSheet, PhotoPostForm, StoryForm, MilestoneForm, MultiImageUpload
post-creation/ # PostTypeSheet, PhotoPostForm, StoryForm, MilestoneForm,
# MultiImageUpload, VideoUploadForm (+ Mux direct upload)
profile/ # ProfileTabs (Posts grid + Milestones list)
safety/ # BlockDialog, ReportSheet
social/ # FollowButton
stories/ # PawRing, StoryViewer, StoryTray, StoryForm
ui/ # shadcn component copies (button, dialog, sheet, etc.)
video/ # VideoCard (polls PROCESSING → plays READY via MuxPlayer)
context/
ActivePetContext.tsx # Global active pet state (pet switcher)
hooks/
useActivePet.ts
lib/
auth.ts # Clerk server helper
avatar-url.ts # CDN URL construction for avatars
feed-helpers.ts # fanOutPost, backfillOnFollow (Redis)
hashtag-helpers.ts # extractHashtags, saveHashtags
media-url.ts # CDN URL construction for post/story media
milestone-meta.ts # MilestoneType → Lucide icon + label map
milestone-thresholds.ts # Follower count thresholds for auto-milestones
mux.ts # Mux Node SDK singleton + MUX_WEBHOOK_SECRET
parse-caption.ts # Tokenises captions into text + #hashtag segments
prisma.ts # Prisma singleton with PgBouncer adapter
r2.ts # AWS SDK S3 client for Cloudflare R2 (Phase 5+)
redis.ts # Upstash Redis client
supabase-storage.ts # Supabase Storage presigned URL helpers (server-only)
utils.ts # cn() helper
@@ -81,6 +93,13 @@ src/
milestones.ts # Milestone posts (create, listByPet)
feed.ts # Home feed (getFeed via Redis + Prisma hydration)
follows.ts # Pet-to-pet follow graph
reactions.ts # 🐾 paw reactions (toggle, count per post)
comments.ts # Flat comments (create, delete, listByPost)
reposts.ts # Paw-Back repost with attribution
explore.ts # Explore page (species/breed filter)
search.ts # Pet name/breed search + owner username search + hashtag search
notifications.ts # In-app notifications (list, unreadCount, markRead, markAllRead)
videos.ts # Mux video (createUpload, getByPostId with Mux self-heal, updateCaption)
blocks.ts # Block a pet
reports.ts # Report a post or pet
media.ts # Avatar presigned upload (getPresignedUrl, confirmUpload)
@@ -95,9 +114,10 @@ src/
posts.test.ts
stories.test.ts
milestones.test.ts
proxy.ts # Next.js middleware (Clerk auth guard)
middleware.ts # Next.js middleware (Clerk auth guard)
prisma/
schema.prisma # Full DB schema
schema.prisma # Full DB schema (Owner, Pet, Post, Story, Follow, Block, Report,
# Reaction, Comment, Repost, Hashtag, Notification, VideoPost)
seed.ts # Species + breed seed (Dog/Cat/Bird)
supabase/
migrations/
@@ -115,6 +135,7 @@ supabase/
- A [Supabase](https://supabase.com) project (PostgreSQL + Storage)
- A [Clerk](https://clerk.com) application
- An [Upstash](https://upstash.com) Redis database
- A [Mux](https://mux.com) account (for video posts)
### 1. Clone and install
@@ -142,8 +163,11 @@ cp .env.example .env.local
| `SUPABASE_SERVICE_ROLE_KEY` | Supabase → Project Settings → API → service_role key |
| `UPSTASH_REDIS_REST_URL` | Upstash Console → Redis database → REST URL |
| `UPSTASH_REDIS_REST_TOKEN` | Upstash Console → Redis database → REST Token |
| `MUX_TOKEN_ID` | Mux Dashboard → Settings → API Access Tokens |
| `MUX_TOKEN_SECRET` | Mux Dashboard → Settings → API Access Tokens |
| `MUX_WEBHOOK_SECRET` | Mux Dashboard → Settings → Webhooks → Signing secret |
> `SUPABASE_SERVICE_ROLE_KEY` is a server-only secret. It is imported exclusively in `server-only` modules and never exposed to the client.
> `SUPABASE_SERVICE_ROLE_KEY` and `MUX_TOKEN_SECRET` are server-only secrets. They are imported exclusively in `server-only` modules and never exposed to the client.
### 3. Database setup
@@ -151,6 +175,7 @@ Push the Prisma schema to Supabase:
```bash
npx prisma db push
npx prisma generate
```
Seed species and breeds:
@@ -172,7 +197,16 @@ Enable Row Level Security on all tables (run once in Supabase SQL Editor):
Create a public bucket named `pet-avatars` in Supabase Storage (Dashboard → Storage → New bucket).
### 5. Run the dev server
### 5. Mux webhook (production only)
In Mux Dashboard → Settings → Webhooks, add an endpoint pointing to `https://your-domain.com/api/webhooks/mux`. Subscribe to:
- `video.upload.asset_created`
- `video.asset.ready`
- `video.asset.errored`
> In local development, the webhook is not needed. `videos.getByPostId` polls the Mux API directly when the video is still `PROCESSING`, so the status self-heals without a tunnel.
### 6. Run the dev server
```bash
npm run dev
@@ -193,9 +227,9 @@ Open [http://localhost:3000](http://localhost:3000). The app redirects unauthent
| `npx vitest run src/__tests__/posts.test.ts` | Run a single test file |
| `npx tsc --noEmit` | Type check without emitting |
| `npx prisma db push` | Sync schema to DB (no migration files) |
| `npx prisma generate` | Regenerate Prisma client after schema change |
| `npx prisma studio` | Open Prisma Studio (DB browser) |
| `npx prisma db seed` | Re-seed species + breeds |
| `npx prisma generate` | Regenerate Prisma client after schema change |
---
@@ -206,20 +240,32 @@ Open [http://localhost:3000](http://localhost:3000). The app redirects unauthent
```
Clerk User (owner)
└── owns 1..n Pet profiles (Postgres)
└── Pet is the social identity (posts, follows, stories, milestones)
└── Pet is the social identity (posts, follows, stories, milestones,
reactions, comments, reposts, notifications, videos)
```
An owner can switch between their pets via `ActivePetContext`. All tRPC mutations assert `pet.ownerId === ctx.userId` before writing.
### Media pipeline
### Media pipeline — Photos
```
Client → tRPC getPresignedUrl → Supabase Storage signed URL
Client → XHR PUT directly to signed URL (file bytes never hit Next.js server)
Client → XHR PUT directly to signed URL (bytes never hit Next.js server)
Client → tRPC create/confirmUpload (writes storage key to DB)
Feed → getMediaUrl(storageKey) → Supabase public CDN URL
```
### Media pipeline — Video (Mux)
```
Client → tRPC videos.createUpload → Mux direct upload URL + PROCESSING Post row
Client → XHR PUT directly to Mux URL (bytes never hit Next.js server)
Mux → transcodes → fires webhook → /api/webhooks/mux → updates VideoPost (READY + playbackId)
VideoCard polls videos.getByPostId every 5s → transitions from spinner to MuxPlayer
```
> In dev (no webhook): `getByPostId` checks the Mux API directly when the status is `PROCESSING` and updates the DB on the fly. No ngrok required.
### Feed architecture
```
@@ -230,21 +276,38 @@ Post created
feed.getFeed({ petId, cursor })
└── ZRANGE feed:{petId} → postIds
└── prisma.post.findMany({ where: { id: { in: postIds } } }) → hydrated posts
└── Fallback (Redis unavailable): Postgres query on follows + own posts
```
### Notification triggers (fire-and-forget)
```
follows.follow → FOLLOW notification to followeePet
reactions.toggle → REACTION notification to post owner (skip if own post)
comments.create → COMMENT notification to post owner (skip if own post)
```
All triggers are wrapped in `.catch(() => {})` — they never crash the parent mutation.
### Story expiry (lazy-delete)
Stories are never deleted in real time. All queries filter `expiresAt > NOW()`. A weekly cleanup job purges expired rows. Story views are retained 30 days for analytics.
### PawRing (story indicator)
Instead of a standard circular ring (Instagram-style), active stories are indicated by a paw-print SVG outline around the avatar: a circular main pad ring with four toe-bean circles above it, all in orange-500.
Instead of a standard circular ring (Instagram-style), active stories are indicated by a paw-print SVG outline around the avatar: a circular main pad ring with four toe-bean circles above it.
- **Orange** — pet has unseen stories
- **Gray** — pet has stories but viewer has seen them all
- **No ring** — no active stories
The viewer identity comes from `ActivePetContext` inside `PawRing` itself — callers don't need to pass it.
---
## Development Progress
### Phase 1 — Foundation (complete)
### Phase 1 — Foundation ✅
- Next.js 16 + Tailwind v4 + shadcn/ui (base-nova) scaffold
- Clerk auth with middleware, protected app shell, onboarding flow
@@ -256,37 +319,42 @@ Instead of a standard circular ring (Instagram-style), active stories are indica
- ActivePetContext (pet switcher)
- Responsive layout (Sidebar + MobileNav)
### Phase 2 — Content Core (complete)
### Phase 2 — Content Core ✅
- **Social graph:** pet-to-pet follow/unfollow, followers/following pages
- **Safety:** block a pet, report a post or profile
- **Feed:** Redis fan-out-on-write, infinite scroll FeedList, PostCard
- **Photo posts:** 1–10 image carousel (Embla), caption edit/delete, presigned upload
- **Stories:** 24h photo stories, paw-print ring indicator, StoryTray, StoryViewer with progress bar + viewer list
- **Stories:** 24h photo stories, paw-print ring indicator (orange/gray), StoryTray, StoryViewer with progress bar + viewer list
- **Milestones:** 5 structured milestone types (Birthday, Adoption Day, First Outing, Vet Visit, New Litter), distinct orange card, PostTypeSheet fully wired for all 3 post types
- **Profile:** Posts 3-col grid + Milestones tab
- **Profile:** Posts 3-col grid (opens full PostCard in sheet with original-format image) + Milestones tab
### Phase 3 — Engagement and Discovery (in progress — plan 1/6 done)
### Phase 3 — Engagement & Discovery ✅
Schema foundation complete (2026-06-13):
- **DB schema:** `Reaction`, `Comment`, `Repost`, `Hashtag`, `PostHashtag` models; `PostType.REPOST` enum
- **tRPC stubs:** `reactions`, `comments`, `reposts`, `explore`, `search` routers registered
- **Test scaffolds:** 5 files, 14 failing RED tests covering ENGM-01–04, EXPL-01, SRCH-01–02
- **🐾 Paw reactions:** single reaction per post, toggle on/off, live count on PostCard
- **Comments:** flat thread, create/delete own, CommentSheet drawer
- **Paw-Back (Repost):** repost with attribution header in feed (PostType.REPOST)
- **Explore page:** species tabs + breed filter, random fresh content
- **Search:** pet name/breed search, owner username search (via Clerk), hashtag search with 3-col grid
- **Hashtags:** extracted on post create, clickable `#tags` in captions navigate to hashtag feed
Remaining plans:
- **03-02:** Paw reactions (single 🐾 per post, toggle on/off, count on PostCard)
- **03-03:** Flat comments (create/delete own, CommentSheet drawer)
- **03-04:** Paw-Back / repost with attribution header (PostType.REPOST in feed)
- **03-05:** Explore page (species tabs + breed filter) + pet name/breed search
- **03-06:** Hashtag extraction on post create, hashtag search, clickable `#tags` in captions
### Phase 4 — Notifications ✅
### Phase 4 — Notifications (planned)
- `Notification` model with `FOLLOW | REACTION | COMMENT | MESSAGE` types
- Fire-and-forget triggers in follows, reactions, and comments routers
- `NotificationBell` in Sidebar + MobileNav (orange badge, 30s polling, "99+" cap)
- `/notifications` page: list with actor avatar, type icon, relative time, post thumbnail
- Clicking a notification navigates to the actor's profile (FOLLOW) or the relevant pet's profile (REACTION/COMMENT)
- Auto-marks all read on page visit
In-app notification center: follows, paw reactions, comments, DMs.
### Phase 5 — Video ✅
### Phase 5 — Video (planned)
Short-form video posts via Mux (signed upload → HLS adaptive streaming).
- `VideoPost` model + `VideoStatus` enum (`PROCESSING | READY | ERROR`)
- Mux direct upload: client PUTs directly to Mux, bytes never pass through Next.js server
- `VideoCard` component polls `getByPostId` every 5s while PROCESSING; transitions to `MuxPlayer` when READY
- `getByPostId` self-heals in dev by calling Mux API directly (no webhook tunnel required)
- Mux webhook handler at `/api/webhooks/mux` for production (`video.upload.asset_created`, `video.asset.ready`, `video.asset.errored`)
- Video posts appear in feed, profile grid, and notifications alongside photo posts
### Phase 6 — Messaging (planned)
@@ -303,14 +371,10 @@ Vet records, vaccination logs, weight tracking, shareable health card.
Tests are unit tests only (no DB, no network). Prisma and Redis are mocked per file using `createMockPrisma()` from `src/__tests__/helpers/prisma-mock.ts`.
```bash
npx vitest run # full suite (~4s)
npx vitest run # full suite
npx vitest # watch mode
```
**Current state:** 53 passing (Phase 1+2), 14 failing RED (Phase 3 — NOT_IMPLEMENTED stubs, intentional), 1 pre-existing failure.
> `src/__tests__/media-upload.test.ts` currently fails due to a missing Supabase URL in the test environment. This is a pre-existing issue from Phase 1 and does not affect Phase 2 or Phase 3 tests.
---
## Known Issues / Debugging Notes
@@ -319,7 +383,10 @@ npx vitest # watch mode
|---|---|
| `DATABASE_URL` must use the **pooled** connection (port 6543, `?pgbouncer=true`) | Prisma uses this at runtime. `DIRECT_URL` (port 5432) is only for `prisma db push` / migrations. |
| Prisma on Windows requires `DIRECT_URL` set in `.env.local` | The Prisma CLI reads `.env.local` via a custom `prisma.config.ts`. If `npx prisma db push` hangs, check `DIRECT_URL` is set. |
| After a Prisma schema change, **always restart the dev server** | The Next.js dev server caches the Prisma client in memory. A running server started before `prisma generate` will not see new enum values (e.g. `PostType.VIDEO`). |
| Supabase service_role key is never client-facing | All files that import `supabase-storage.ts` must be `server-only`. The client only ever receives signed URLs. |
| `asChild` prop is not available in the base-nova shadcn preset | Do not use `asChild` on any shadcn component. This affects `PopoverTrigger`, `DropdownMenuItem`, etc. Style the trigger element directly. |
| StoryView records are NOT cascade-deleted when a story expires | This is intentional (D-08): view analytics are retained 30 days. A separate cleanup job will purge old views. |
| Feed cleanup on post delete is best-effort in Phase 2 | When a post is deleted, its ID is not removed from Redis sorted sets. `feed.getFeed` silently skips IDs that Prisma doesn't return. Full cleanup (ZREM) is scheduled for Phase 4. |
| Feed cleanup on post delete is best-effort | When a post is deleted, its ID is not removed from Redis sorted sets. `feed.getFeed` silently skips IDs that Prisma doesn't return. |
| Mux webhook not required in local dev | `videos.getByPostId` polls Mux directly when status is `PROCESSING`. The DB is updated on the next poll cycle. In production, the webhook updates the DB faster (within seconds of transcode completion). |
| People search requires Clerk username to be set | `search.byOwner` queries Clerk's `getUserList`. Users who signed up without a username will match by first/last name instead. |