Compare commits
240 Commits
84d6cfeb07
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f871f4f588 | |||
| 8d5787e56e | |||
| eb99faf655 | |||
| f0632cce95 | |||
| 592c86f8d4 | |||
| 35d4f3d055 | |||
| c8ee743458 | |||
| 4c3880e07f | |||
| e3f2cf6834 | |||
| 513e4a904a | |||
| 83a1381052 | |||
| e78e24e40d | |||
| 3aaa12910a | |||
| 9ba2996022 | |||
| 5f270dee08 | |||
| b17984fbef | |||
| 274c50c2f6 | |||
| c5e1643d39 | |||
| cced962bff | |||
| 7626f1b496 | |||
| 623e5bcd34 | |||
| f6975e98a9 | |||
| f6214e60df | |||
| 6ec9b65c24 | |||
| 1ee3ec70ba | |||
| 2f18462548 | |||
| 37739699f9 | |||
| 6eb759dd43 | |||
| a6e3dc999b | |||
| cf7cc6c885 | |||
| 44df734f1c | |||
| 9da57dd1d0 | |||
| b1f745da66 | |||
| e8c687e53a | |||
| 5403a06348 | |||
| 8f83a1eaae | |||
| 1b72135958 | |||
| 43088759cf | |||
| 6502307340 | |||
| e6a5e1e6ab | |||
| b4dd29893d | |||
| 1bfd03c42e | |||
| 520d992de4 | |||
| 51e6722f4c | |||
| 955c4bd9dd | |||
| edcde8b34a | |||
| 2f3ba14093 | |||
| 12c2ec213a | |||
| 811d4cad42 | |||
| 9ea1f90ec4 | |||
| 8dccd8898b | |||
| e71c978e52 | |||
| 2a256a8943 | |||
| e4ad092751 | |||
| 634f8245e1 | |||
| f2d423c8d7 | |||
| ef18712ced | |||
| 4e9e23c080 | |||
| c8f4b50ef3 | |||
| 21a3622e6c | |||
| 458b5f2b07 | |||
| 9eecdbac3c | |||
| 982d4e3264 | |||
| 7d290c5b1f | |||
| c31ab8771a | |||
| c5a8f94b26 | |||
| 25e624f618 | |||
| 77c739960d | |||
| 23babd4ee9 | |||
| d8dc0aa465 | |||
| 31ff7b9ac0 | |||
| f0340859fa | |||
| 5763bd3318 | |||
| 1577b8de01 | |||
| bd3d8c88f0 | |||
| b330583dd3 | |||
| af92b8cc71 | |||
| 3042d289a0 | |||
| 6f11dc07fd | |||
| 894784afda | |||
| affa6f5c3d | |||
| d8bc077f47 | |||
| 21c541e115 | |||
| b730dfac41 | |||
| 6ad2731751 | |||
| 45adb023b9 | |||
| 1237330a0c | |||
| 8ef97da2c2 | |||
| 3e71bd29a2 | |||
| 6c4fc93aab | |||
| 6096e49008 | |||
| a08588cf85 | |||
| 38516bff63 | |||
| c16342a9b9 | |||
| acc93de708 | |||
| 4e5f45a7e5 | |||
| c21157fc93 | |||
| 95a4dccce8 | |||
| 6513bfa6ee | |||
| 00ca8b9d68 | |||
| aa67868b96 | |||
| a144052e46 | |||
| 6efabeab8a | |||
| f0397740d7 | |||
| 2ee99ea463 | |||
| 79cdb8cd04 | |||
| 6dd48b5c25 | |||
| 2beb23b360 | |||
| b1f4bba6dd | |||
| 70eb565eec | |||
| 4960dfc7c6 | |||
| 6818f10fc4 | |||
| 7c63388618 | |||
| 36e707b934 | |||
| 13b8de0e0c | |||
| 257908da7f | |||
| e117533f6f | |||
| d107bce92e | |||
| 5d351f88b0 | |||
| b1995522ee | |||
| da48d0ecef | |||
| adaa837564 | |||
| 9549684254 | |||
| 96ef5b8379 | |||
| 0062220d8e | |||
| b2f2274673 | |||
| adc88e63b0 | |||
| 8ec11e9463 | |||
| 2ffa05e4cf | |||
| 9a448ef34d | |||
| eed57cd10b | |||
| b69f5845c3 | |||
| e678e21ee8 | |||
| 4d5269aced | |||
| e78c959c49 | |||
| 5a9e306357 | |||
| 4f36ce24b2 | |||
| aa6bd03c5e | |||
| 9566e19cd0 | |||
| a9dc1b63c1 | |||
| 1bcea2f273 | |||
| a1a11ff5e5 | |||
| e98a9c3bb7 | |||
| d7e0d7eada | |||
| c54c554374 | |||
| b627dda5bf | |||
| a42fd497b0 | |||
| 13128df19f | |||
| 5b8c50dd1e | |||
| 61014a3224 | |||
| 20e4ce3597 | |||
| 8df292dfee | |||
| b160fdc338 | |||
| 546ba98d2f | |||
| 77f43ee673 | |||
| ccc41a2018 | |||
| 321507b570 | |||
| 83d18f5ad4 | |||
| 2682eba2be | |||
| 1baf5ce20e | |||
| 002f14ced0 | |||
| 646c97128d | |||
| f29fa531a1 | |||
| ba1614073b | |||
| 8e83cc0dc7 | |||
| 78d0599ffc | |||
| 68f0f490b9 | |||
| 8b749f432e | |||
| e0d39c86ef | |||
| 0cb926bd26 | |||
| 580d5bbf2f | |||
| a5661ef882 | |||
| 1a40eccad5 | |||
| 521ecce68f | |||
| 5d2cad255c | |||
| 0022d807d0 | |||
| 70ad1bec9c | |||
| d951587d31 | |||
| 51a323b054 | |||
| 5afc7cd182 | |||
| d62e2a6383 | |||
| 9c545a5bb3 | |||
| 36e7698096 | |||
| b0849c3989 | |||
| 913410dbf3 | |||
| 45b886e398 | |||
| d035378520 | |||
| 362f65656b | |||
| b4b964aafb | |||
| cd444d4d23 | |||
| f2a0c20f07 | |||
| a8406e9963 | |||
| 212d6f7335 | |||
| 64f45ed74d | |||
| 1614da38cd | |||
| 10233b3ef9 | |||
| 292c7d6722 | |||
| 08ab9ac71f | |||
| e67145493e | |||
| 1677e40668 | |||
| 68cbd5b4e4 | |||
| c453cb395e | |||
| 67246c69e5 | |||
| ee7946316c | |||
| c3776238c7 | |||
| a51ba85253 | |||
| 73a71d28cd | |||
| 57c29f62b4 | |||
| a3f387fa2a | |||
| 1abab17ca8 | |||
| e0e1ac49d9 | |||
| c5bc2e1470 | |||
| 9412529120 | |||
| 487e7755be | |||
| ac9f5c87e9 | |||
| cbba1ec2ff | |||
| 737d011c1b | |||
| eb424d8c04 | |||
| b07bada291 | |||
| 524310433c | |||
| e5d1080fb9 | |||
| d2faf98ac1 | |||
| 2154512e54 | |||
| 01fdbb880b | |||
| afff6cf9eb | |||
| 5ff8ef5547 | |||
| fbae04f824 | |||
| 7e93c332ce | |||
| a4fb62c86c | |||
| 4a90ad910c | |||
| 8b57a3fd87 | |||
| 9d9dfb46c6 | |||
| 3f96d1ea41 | |||
| d6032edc00 | |||
| cba5d9c3ac | |||
| b2d592afe8 | |||
| e179692adf | |||
| 3636ab27ae | |||
| 9d02a69250 | |||
| d9d58fd01a |
@@ -0,0 +1,8 @@
|
||||
**/node_modules
|
||||
**/.next
|
||||
**/coverage
|
||||
**/.turbo
|
||||
.git
|
||||
.env*
|
||||
!.env.example
|
||||
*.md
|
||||
@@ -0,0 +1,92 @@
|
||||
# Database
|
||||
DATABASE_URL=postgresql://epicure:epicure@localhost:5432/epicure
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://localhost:6379
|
||||
|
||||
# Storage (MinIO / S3-compatible)
|
||||
STORAGE_ENDPOINT=http://localhost:9000
|
||||
STORAGE_ACCESS_KEY=minioadmin
|
||||
STORAGE_SECRET_KEY=minioadmin
|
||||
STORAGE_BUCKET=epicure-uploads
|
||||
STORAGE_REGION=us-east-1
|
||||
|
||||
# Auth (generate with: openssl rand -base64 32)
|
||||
BETTER_AUTH_SECRET=
|
||||
BETTER_AUTH_URL=http://localhost:3000
|
||||
|
||||
# Encryption key for BYOK AI keys stored in DB (generate with: openssl rand -base64 32)
|
||||
# Separate from BETTER_AUTH_SECRET for key separation. Falls back to BETTER_AUTH_SECRET if unset.
|
||||
ENCRYPTION_SECRET=
|
||||
|
||||
# OAuth — Google (always available)
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
|
||||
# OAuth — GitHub (optional; set NEXT_PUBLIC_GITHUB_ENABLED=true to show button in UI)
|
||||
GITHUB_CLIENT_ID=
|
||||
GITHUB_CLIENT_SECRET=
|
||||
NEXT_PUBLIC_GITHUB_ENABLED=
|
||||
|
||||
# OAuth — Discord (optional; set NEXT_PUBLIC_DISCORD_ENABLED=true to show button in UI)
|
||||
DISCORD_CLIENT_ID=
|
||||
DISCORD_CLIENT_SECRET=
|
||||
NEXT_PUBLIC_DISCORD_ENABLED=
|
||||
|
||||
# OIDC — Authentik (or any OIDC provider)
|
||||
# AUTHENTIK_BASE_URL: base URL including application slug, e.g.
|
||||
# https://auth.example.com/application/o/epicure
|
||||
# The discovery document is fetched from $AUTHENTIK_BASE_URL/.well-known/openid-configuration
|
||||
# In authentik: create an OAuth2/OpenID provider, set redirect URI to
|
||||
# $BETTER_AUTH_URL/api/auth/callback/authentik
|
||||
AUTHENTIK_CLIENT_ID=
|
||||
AUTHENTIK_CLIENT_SECRET=
|
||||
AUTHENTIK_BASE_URL=
|
||||
# Set to true to show Authentik login button in UI
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED=
|
||||
|
||||
# SMTP (leave blank to log emails to console in dev)
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=
|
||||
SMTP_PASS=
|
||||
SMTP_FROM=Epicure <noreply@epicure.app>
|
||||
|
||||
# Web push (generate with: npx web-push generate-vapid-keys)
|
||||
NEXT_PUBLIC_VAPID_PUBLIC_KEY=
|
||||
VAPID_PRIVATE_KEY=
|
||||
|
||||
# Gitea (optional — in-app support tickets open an issue here if all three are set)
|
||||
GITEA_URL=
|
||||
GITEA_TOKEN=
|
||||
GITEA_REPO=owner/repo
|
||||
# Set as the webhook secret on the Gitea repo's webhook config (issues + issue_comment
|
||||
# events) to sync issue close/reopen/comments back into Epicure support tickets.
|
||||
GITEA_WEBHOOK_SECRET=
|
||||
|
||||
# USDA FoodData Central (optional, free — get a key at https://fdc.nal.usda.gov/api-key-signup)
|
||||
# Improves recipe nutrition estimates with real per-ingredient data instead of AI-only guesses.
|
||||
USDA_API_KEY=
|
||||
|
||||
# Stripe (optional — billing for Pro/Family tiers). Only needed as a
|
||||
# bootstrap fallback for self-hosters without the admin settings UI set up
|
||||
# yet — a value stored via Admin > Settings takes precedence.
|
||||
STRIPE_SECRET_KEY=
|
||||
STRIPE_PUBLISHABLE_KEY=
|
||||
STRIPE_WEBHOOK_SECRET=
|
||||
|
||||
# Shared secret for internal cron-triggered endpoints (e.g. weekly digest email).
|
||||
# Generate with: openssl rand -base64 32
|
||||
CRON_SECRET=
|
||||
|
||||
# AI Providers (configure at least one)
|
||||
OPENROUTER_API_KEY=
|
||||
OPENROUTER_DEFAULT_MODEL=google/gemini-flash-1.5
|
||||
OPENAI_API_KEY=
|
||||
ANTHROPIC_API_KEY=
|
||||
OLLAMA_BASE_URL=http://localhost:11434
|
||||
|
||||
# Grocery delivery handoff (optional — without these, shopping lists only offer "copy as text")
|
||||
NEXT_PUBLIC_GROCERY_PROVIDER=
|
||||
INSTACART_API_KEY=
|
||||
+1
-1
@@ -44,4 +44,4 @@ coverage/
|
||||
# Misc
|
||||
.claude/
|
||||
project_epicure.md
|
||||
PLAN.md
|
||||
plans/
|
||||
|
||||
+726
@@ -0,0 +1,726 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to Epicure are documented here. This file is mirrored in-app at `/changelog` (and in the admin dashboard) via `apps/web/lib/changelog.ts` — update both together.
|
||||
|
||||
## 0.73.0 — 2026-07-23 14:00
|
||||
|
||||
### Added
|
||||
- Real Stripe billing for Pro/Family: subscribe and manage your plan yourself at Settings → Billing (Checkout + Stripe's hosted Customer Portal for cancel/upgrade/card updates), instead of only an admin being able to change your tier. Cancel takes effect at the end of the paid period.
|
||||
- Admin → Billing: connection status, subscriber counts, past-due payments needing attention, recent billing events. Admin → Tier Limits gained Stripe Product/Price ID fields per tier.
|
||||
|
||||
Family tier is purchasable solo but doesn't yet support inviting other accounts into a shared subscription — that's a separate, larger piece tracked in `plans/STRIPE_PLAN.md`, deliberately shipped after solo billing.
|
||||
|
||||
## 0.72.0 — 2026-07-23 09:30
|
||||
|
||||
### Added
|
||||
- Developer access (webhooks + API keys) is now self-serve for any paid-tier user, free of charge — enable it yourself in Settings instead of waiting on an admin. Free tier still needs an admin grant. BYOK is now a fully separate permission, admin-only, unaffected by the self-serve change.
|
||||
|
||||
## 0.71.0 — 2026-07-22 10:00
|
||||
|
||||
### Added
|
||||
- New "developer access" permission, admin-toggled per user (Admin → Users), gates webhooks, self-serve API keys, and BYOK AI provider keys — previously available to every logged-in user with no gating at all. Anyone who already had a webhook, API key, or BYOK key configured keeps access automatically.
|
||||
|
||||
## 0.70.0 — 2026-07-22 09:30
|
||||
|
||||
### Added
|
||||
- Recipe nutrition estimation now looks up real per-ingredient data from USDA FoodData Central (for ingredients whose quantity/unit converts to grams — e.g. "200g flour", "2 tbsp oil") and only asks AI to estimate whatever's left (count-based units like "2 cloves", or ingredients with no USDA match). Configure `USDA_API_KEY` in Admin → Settings (free, no partnership needed) — unset, it falls back to the previous fully-AI-estimated behavior exactly as before.
|
||||
|
||||
## 0.69.0 — 2026-07-22 09:00
|
||||
|
||||
### Added
|
||||
- Nutrition page gets a Trend tab alongside the daily Diary: a 7/30/90-day calorie chart plus daily protein/carbs/fat averages, computed from the same cooking history the diary already tracks.
|
||||
|
||||
## 0.68.0 — 2026-07-21 10:00
|
||||
|
||||
### Added
|
||||
- Meal plans can now be shared with a read-only anonymous public link (Share → Public link), same idea as shopping lists' public link but view-only, plus a QR code you can screenshot or print to hand someone the week's plan.
|
||||
|
||||
## 0.67.0 — 2026-07-21 09:30
|
||||
|
||||
### Added
|
||||
- Epicure now registers as an OS share target (Chromium/Android, once installed): share a recipe link from another app's share sheet and it opens straight into the URL-import flow, pre-filled and auto-imported. Safari has no equivalent API — Chromium/Android only, same restriction as the install-prompt banner.
|
||||
|
||||
## 0.66.0 — 2026-07-21 09:00
|
||||
|
||||
### Added
|
||||
- Moderator role is now wired up: moderators get access to Admin → Reports (view/resolve) and Admin → Recipes (view + unpublish a public recipe as a takedown action). Every other admin section stays admin-only, enforced server-side on each page, not just hidden from the nav.
|
||||
- Push notifications now actually display. The service worker had no `push` event listener at all, so incoming push messages never showed anything — fixed, plus a `notificationclick` handler that focuses an existing tab or opens one at the notification's target URL.
|
||||
|
||||
## 0.65.3 — 2026-07-21 01:20
|
||||
|
||||
### Fixed
|
||||
- Removed a stale `app/favicon.ico` left over from the original create-next-app scaffold (the default Next.js/Vercel triangle logo) — Next's file-based routing served it as `/favicon.ico` regardless of the app icon configured via `icon.svg`, so some browsers showed the placeholder logo instead of Epicure's icon no matter what cache state you were in. The SVG icon is now the only favicon source.
|
||||
|
||||
## 0.65.2 — 2026-07-21 01:10
|
||||
|
||||
### Fixed
|
||||
- The "Save offline" button on the recipe page was a labeled outline button, inconsistent with the icon-only ghost + tooltip style every other recipe action button (print, share, export) uses. Now matches.
|
||||
|
||||
## 0.65.1 — 2026-07-21 01:00
|
||||
|
||||
### Added
|
||||
- The install banner now shows an iOS Safari-specific instructional variant ("Tap Share, then Add to Home Screen") instead of silently doing nothing — Safari never fires the event the regular Install button depends on, so it had no install guidance at all before this.
|
||||
|
||||
## 0.65.0 — 2026-07-21 00:45
|
||||
|
||||
### Added
|
||||
- Save recipes for offline use: a "Save offline" button on any recipe pins it in the service worker cache so it opens with no connection. The offline fallback page now lists your saved (and recently visited) recipes instead of being a dead end.
|
||||
- Marking a batch-cook dish as cooked while offline no longer just fails — it's queued and synced automatically once you're back online (via Background Sync where supported, otherwise as soon as the app detects a connection).
|
||||
|
||||
### Fixed
|
||||
- The service worker's network-first pages never actually populated its cache on success, so the offline page's claim that "recently visited recipes are available" wasn't true. It does now.
|
||||
|
||||
## 0.64.0 — 2026-07-21 00:30
|
||||
|
||||
### Fixed
|
||||
- The web app manifest was never actually linked into the page (pointed at `/manifest.json`, but the real route is `/manifest.webmanifest`) and its icons referenced PNGs that don't exist in the repo — both silently broke install eligibility on Chrome/Android. Manifest now links correctly and icons point at the existing SVGs.
|
||||
|
||||
### Added
|
||||
- Added apple-mobile-web-app meta tags and a `viewport-fit=cover` safe-area setting for iOS home-screen installs.
|
||||
- Added an install-app banner (Chrome/Edge/Android only, via the standard `beforeinstallprompt` event) so the PWA install prompt is a first-class, dismissible UI element instead of relying on the browser's own icon.
|
||||
|
||||
## 0.63.0 — 2026-07-21 00:15
|
||||
|
||||
### Added
|
||||
- Support tickets now sync two-way with their linked Gitea issue: closing/reopening the issue in Gitea updates the ticket's status, and comments on either side (Epicure or Gitea) show up in both places. Configure a webhook secret (`GITEA_WEBHOOK_SECRET`) on the Gitea repo's webhook, subscribed to Issues and Issue Comment events, pointed at `/api/webhooks/gitea`.
|
||||
|
||||
## 0.62.0 — 2026-07-20 23:45
|
||||
|
||||
### Added
|
||||
- Settings → Features: new Chatbots toggle — hides both the recipe cooking-chat panel and the recipe-list cooking assistant when off.
|
||||
|
||||
### Fixed
|
||||
- Feature toggles (Settings → Features) were only respected by the mobile hamburger menu — the desktop horizontal nav still showed every item regardless of your saved preferences. Both now read the same visibility list.
|
||||
|
||||
## 0.61.0 — 2026-07-20 23:15
|
||||
|
||||
### Added
|
||||
- Settings → Notifications now has an email toggle for every category alongside the existing push toggle, plus a Weekly Digest toggle to opt out of the weekly email summary entirely.
|
||||
- Admin → Webhooks: site-wide ops webhooks (new signups, support tickets, reports filed) — separate from the existing per-user webhooks, for Slack/Discord-style ops alerting.
|
||||
- Settings → Features: hide Nutrition, Pantry, Meal Plan, Shopping Lists, Collections, or Messages from your own navigation. Cosmetic only — hidden pages stay reachable by direct link.
|
||||
|
||||
## 0.60.0 — 2026-07-20 22:15
|
||||
|
||||
### Security
|
||||
- Closed a race in recipe/storage tier-limit checks — two concurrent requests near the cap could both pass a live count check and both write, exceeding the lifetime limit. Now locked per-user inside the same transaction as the write.
|
||||
- Fixed four AI recipe-creation routes (photo import, idea generation, batch-cook, translate-to-new-draft) that had no recipe-limit check at all, letting any tier create unlimited recipes through them.
|
||||
- Added missing per-user rate limits to 5 AI endpoints (adapt, drinks, pairings, translate, variations).
|
||||
- Search page now checks for a session server-side, matching every other page (defense-in-depth — the underlying API was already public by design and the edge proxy already blocked unauthenticated access).
|
||||
- Upgraded drizzle-orm to fix a SQL-identifier-escaping vulnerability, and overrode two transitive dependencies (esbuild, postcss) with known CVEs — `pnpm audit` is now clean.
|
||||
|
||||
### Fixed
|
||||
- Admin settings endpoint now uses the shared admin-auth check instead of a local duplicate.
|
||||
- Documented two admin support-ticket endpoints that were missing from the OpenAPI spec.
|
||||
|
||||
## 0.59.0 — 2026-07-20 21:15
|
||||
|
||||
### Added
|
||||
- Admin: chatbot now has its own default-model setting, separate from generic text generation — the general assistant and per-recipe Q&A chat can be pointed at a different model than recipe generation.
|
||||
- Admin: tool calling (the chatbot's inline recipe/shopping-list drafting) can be toggled off — useful for a local/Ollama model that doesn't reliably support it, so the bot falls back to plain text answers instead.
|
||||
|
||||
### Fixed
|
||||
- Simplified the admin AI Configuration page — it showed the same provider keys and routing settings twice (once read-only, once as an edit form). Merged into one section.
|
||||
|
||||
## 0.58.0 — 2026-07-20 21:00
|
||||
|
||||
### Fixed
|
||||
- Recipe count and storage usage were incorrectly reset every month, same as AI calls — a user near their recipe/storage cap got fresh room on the 1st even though nothing was deleted. Only AI calls are meant to be monthly; recipes and storage are now lifetime totals derived live from actual data (recipes, photos, avatar), so deleting something is itself what frees up quota.
|
||||
- Removing your avatar from Settings silently did nothing — the client sent a field the API didn't recognize, so the update was a no-op.
|
||||
|
||||
## 0.57.2 — 2026-07-20 20:15
|
||||
|
||||
### Fixed
|
||||
- The previous chatbot fix only caught the model spelling a recipe out as prose. The more common case: a short reply that claims a draft exists ("here's a draft, check below") without ever calling the tool, so nothing renders. Now also detects recipe-creation intent from the user's own message and forces the tool call in that case too.
|
||||
|
||||
## 0.57.1 — 2026-07-20 20:00
|
||||
|
||||
### Fixed
|
||||
- Chatbot sometimes answered "create a recipe" requests with the recipe spelled out as prose instead of the actual draft card (weaker/free-tier models occasionally ignore the tool-calling instruction). Now detects that shape and forces one retry with the tool call required, so the draft card still appears.
|
||||
|
||||
## 0.57.0 — 2026-07-20 09:20
|
||||
|
||||
### Added
|
||||
- Cooking assistant, fullscreen on desktop, now has a persistent conversation sidebar on the left (like ChatGPT/Claude) instead of a dropdown menu. Mobile and the normal drawer view keep the dropdown.
|
||||
|
||||
## 0.56.0 — 2026-07-20 09:10
|
||||
|
||||
### Added
|
||||
- Step timers in the recipe editor now take a unit (seconds/minutes/hours) instead of forcing everyone to do the math into seconds. Editing an existing recipe shows the timer in whichever unit divides evenly into what's stored.
|
||||
|
||||
### Fixed
|
||||
- Ingredient list on the recipe page didn't line up — the quantity column only had a minimum width, so a longer value pushed that row's ingredient name further right than the others. Switched to a shared grid column so every row's name starts at the same spot.
|
||||
|
||||
## 0.55.3 — 2026-07-19 19:00
|
||||
|
||||
### Fixed
|
||||
- Admin Insights page's actual crash, found from server logs: the page (a server component) was passing plain formatter functions as props into its chart components (client components) — React can't serialize functions across that boundary. Replaced with a plain string prop ("day" vs "month") formatted inside the client component instead.
|
||||
|
||||
## 0.55.2 — 2026-07-19 18:20
|
||||
|
||||
### Fixed
|
||||
- Admin Insights page could 500 the whole panel if any one of its six aggregate queries failed — replaced a non-standard positional GROUP BY with the expression-repeat pattern used everywhere else in the codebase, and made the six queries independent (Promise.allSettled) so one failing degrades that one chart instead of crashing the page.
|
||||
|
||||
## 0.55.1 — 2026-07-19 18:05
|
||||
|
||||
### Fixed
|
||||
- Chatbot's rename/delete buttons for a conversation were hover-only, so they never appeared on mobile (no hover state on touch). Now always visible.
|
||||
|
||||
## 0.55.0 — 2026-07-19 17:50
|
||||
|
||||
### Added
|
||||
- New Admin > Insights page — signups and recipes-created over the last 30 days, users by tier, recipes by visibility, monthly AI usage, and support tickets by status. Charts are hand-built (hover tooltips, table-view fallback, colorblind-safe palette), no new dependency.
|
||||
|
||||
## 0.54.1 — 2026-07-19 17:25
|
||||
|
||||
### Added
|
||||
- Public collections are now viewable by logged-out visitors at /c/{id} (no account needed), same as public recipes at /r/{id} — the collection's QR code/print link and the new "view publicly" icon on the collection page both point here. Followers-only collections check the visitor's follow status the same way followers-only recipes do.
|
||||
|
||||
## 0.54.0 — 2026-07-19 17:05
|
||||
|
||||
### Added
|
||||
- Collections now have the same visibility options as recipes — private, followers-only, unlisted, or public — replacing the old public/private toggle. Fork, favorite, and viewing a collection all respect the new followers-only option the same way recipes do.
|
||||
- Collection PDF exports now include a QR code linking back to the collection, same as recipe PDFs.
|
||||
|
||||
## 0.53.1 — 2026-07-19 16:10
|
||||
|
||||
### Fixed
|
||||
- Drag-reorder in a collection now animates live as you drag instead of only updating on drop, and the grip handle is now visible instead of an invisible hover target.
|
||||
- "Edit" was untranslated everywhere it's used (missing from both languages, not just French).
|
||||
- Recipes generated via "Generate meal", weekly meal plan, or "Adapt recipe" never had their language recorded — this made the Translate button appear even though the recipe was already in your language. Fixed at the source for all three.
|
||||
- The Translate dialog itself was hardcoded in English regardless of app language — now fully translated.
|
||||
|
||||
### Added
|
||||
- Recipe tags now show on the recipe detail page.
|
||||
- Collection header actions are now icon-only with tooltips, matching the recipe page.
|
||||
- Searching collections now also matches recipes inside them.
|
||||
- Explore links to "Discover collections" next to its tabs.
|
||||
|
||||
## 0.53.0 — 2026-07-19 15:20
|
||||
|
||||
### Added
|
||||
- Collections got a big upgrade: drag-and-drop reorder recipes, search collections and search within a collection, edit name/description/tags/private notes, delete with a choice to also delete the recipes (only ones you own), and tags/labels on collections themselves.
|
||||
|
||||
### Fixed
|
||||
- Collection cards showed the wrong recipe count (capped at 1) — now a real count. Cards also got a visual refresh (photo collage preview) and collection detail pages now use the same recipe card as the main Recipes page.
|
||||
|
||||
## 0.52.1 — 2026-07-19 14:10
|
||||
|
||||
### Fixed
|
||||
- Steps with no timer sometimes showed a stray "0" on the recipe page, cook mode, and print views — a step whose timer happened to be stored as 0 (rather than empty) hit a JS truthiness quirk where `0 && ...` renders the literal 0 instead of nothing.
|
||||
|
||||
## 0.52.0 — 2026-07-19 13:55
|
||||
|
||||
### Added
|
||||
- Generate a complete meal from a collection — pick a theme and 2+ courses (starter, main, side, dessert, drink), AI generates one coherent, matching recipe per course and adds them all to that collection in one go.
|
||||
|
||||
## 0.51.7 — 2026-07-19 13:35
|
||||
|
||||
### Fixed
|
||||
- Account dropdown menu: "View profile" and "Settings" now have icons like every other item in the menu, and there's a new separator grouping the account/support links apart from the theme switcher.
|
||||
|
||||
## 0.51.6 — 2026-07-19 13:20
|
||||
|
||||
### Fixed
|
||||
- Image attachments on support tickets now embed inline in the Gitea issue (rendered preview) instead of just a plain link. Also fixed the admin "Create Gitea issue" retry action, which was dropping attachments entirely and only ever sent the ticket description.
|
||||
|
||||
## 0.51.5 — 2026-07-19 13:05
|
||||
|
||||
### Fixed
|
||||
- Gitea issue creation was sending label names ("bug", "enhancement") where Gitea's API expects numeric label IDs, failing with a 422 on every attempt. Now looks up the repo's actual label IDs by name first — issues still get created (just unlabeled) if the repo doesn't have matching labels yet.
|
||||
|
||||
## 0.51.4 — 2026-07-19 12:50
|
||||
|
||||
### Fixed
|
||||
- Gitea issue creation failures now log the real network-level cause server-side (DNS/connection/timeout, not just "fetch failed") and surface a more specific message in the admin support view's tooltip.
|
||||
|
||||
## 0.51.3 — 2026-07-19 12:35
|
||||
|
||||
### Fixed
|
||||
- Admin Settings' Gitea Integration section now spells out exactly what each field expects and what token scope to grant, instead of a one-line hint.
|
||||
|
||||
## 0.51.2 — 2026-07-19 12:20
|
||||
|
||||
### Fixed
|
||||
- Recipe cover placeholder icons now use a solid color instead of a transparent one — the transparency darkened wherever an icon's own strokes overlapped, showing up as an uneven blotch on icons like the chef's hat or croissant.
|
||||
|
||||
## 0.51.1 — 2026-07-19 12:05
|
||||
|
||||
### Added
|
||||
- More icon choices for custom recipe covers — dish icons went from 16 to 29 (banana, grape, citrus, hamburger, popcorn, bean, vegan, utensils, leaf, shrimp, cooking pot, candy, nut), drinks got milk.
|
||||
|
||||
## 0.51.0 — 2026-07-19 11:40
|
||||
|
||||
### Added
|
||||
- Pick your own recipe cover color + icon in the recipe editor (below Photos) — used whenever that recipe has no photo. Also toned down the auto-generated placeholder colors from the previous release, which were too saturated next to real cover photos.
|
||||
|
||||
## 0.50.2 — 2026-07-19 10:15
|
||||
|
||||
### Fixed
|
||||
- Recipes without a cover photo now get a varied gradient + food/drink icon instead of the same flat emoji everywhere — deterministic per recipe, so it stays stable across reloads. Applied to the Recipes grid/list, Explore/collections cards, and public profile pages.
|
||||
|
||||
## 0.50.1 — 2026-07-19 09:30
|
||||
|
||||
### Fixed
|
||||
- Password sign-in for 2FA-enabled accounts could silently bounce back to the login page with no error shown — the app was pushing straight to /recipes on any non-error sign-in response, racing the SDK's own redirect to the 2FA code screen and sometimes losing. Now waits for that case explicitly.
|
||||
|
||||
## 0.50.0 — 2026-07-18 14:20
|
||||
|
||||
### Added
|
||||
- Per-tier feature toggles, managed from Admin > Tier Limits. Recipe variations, drink pairing, and meal pairing can each be disabled for a tier (e.g. Free) — the buttons stay visible but show an upgrade prompt instead of running, and the API rejects the call server-side either way.
|
||||
|
||||
## 0.49.1 — 2026-07-18 13:10
|
||||
|
||||
### Added
|
||||
- Support form now accepts attachments — screenshots or files (images, PDF, text, JSON, zip; up to 5 files, 10MB each). They're linked in the confirmation email's Gitea issue and shown as thumbnails on your ticket history and in the admin support view.
|
||||
|
||||
## 0.49.0 — 2026-07-18 12:30
|
||||
|
||||
### Added
|
||||
- New Support page — report a bug, share a suggestion, or ask a question right from the app. Submissions email you a confirmation and (if an admin has configured a Gitea repo in Settings) automatically open a tracked issue. Admins get a Support section in the admin panel to triage tickets and retry issue creation.
|
||||
|
||||
## 0.48.2 — 2026-07-18 11:15
|
||||
|
||||
### Fixed
|
||||
- Marketing site's language switcher no longer uses emoji flags (inconsistent rendering across OS/browsers) — now inline SVG flags in a proper dropdown menu. Home page's feature grid also got a 9th highlight (personalized recommendations) so the last row isn't left half-empty.
|
||||
|
||||
## 0.48.1 — 2026-07-18 11:00
|
||||
|
||||
### Added
|
||||
- Marketing site: language switcher (flag toggle, EN/FR) and a dark-mode toggle in the header — both work for logged-out visitors, no account needed. Features/Home now also cover cook mode, recipe variations, personalized recommendations, and ingredient substitution. Signup CTAs now say "Signups closed" instead of "Get started free" when signups are disabled.
|
||||
|
||||
## 0.48.0 — 2026-07-18 09:45
|
||||
|
||||
### Added
|
||||
- Public marketing pages — Home, Features, About, Privacy, Terms, Contact — visible to logged-out visitors at the root domain, plus a sitemap and robots.txt. Logged-in users hitting "/" still land straight in the app, unchanged.
|
||||
|
||||
Note: Privacy and Terms are structural drafts, not lawyer-reviewed (see `VITRINE_PLAN.md` §4). Pricing page intentionally not included yet (waiting on Stripe Checkout per `STRIPE_PLAN.md`).
|
||||
|
||||
## 0.47.0 — 2026-07-18 00:30
|
||||
|
||||
Renamed the "Team" billing tier to "Family" (free/pro/family) — same limits, same admin editing, just the name. Existing Team users keep their tier/limits unaffected; the DB enum value itself was renamed in place (no data migration needed).
|
||||
|
||||
## 0.46.2 — 2026-07-17 19:20
|
||||
|
||||
### Fixed
|
||||
- Recipe editor's ingredient and step rows were cramped on mobile — 4 inline fields plus a timer/delete button squeezed into one row with no real wrap plan. Both now stack sanely on narrow screens (name/quantity/unit on one line, note/timer + delete on the next) and stay a single row on larger screens.
|
||||
|
||||
## 0.46.1 — 2026-07-17 19:05
|
||||
|
||||
### Fixed
|
||||
- Asking the cooking assistant to create a recipe would often just get you the recipe typed out in the chat instead of the createRecipe draft card — the instruction telling the model to use the tool was a soft suggestion, not a hard rule. Made it explicit: full recipes must go through the tool, never as plain-text ingredients/steps in the reply.
|
||||
|
||||
## 0.46.0 — 2026-07-17 18:00
|
||||
|
||||
### Added
|
||||
- The cooking assistant can now also propose adding items to a shopping list ("add that to my shopping list") — pick an existing list or name a new one, then confirm. Same no-action-without-confirmation pattern as recipe creation, going through the same endpoints the manual "Add to shopping list" button already uses.
|
||||
|
||||
Note: generateMealPlan is still not built as a chat tool — the existing meal-plan-generation endpoint generates and saves in one step with its own input shape (week/preferences, not a specific plan to save), so it doesn't fit the draft-then-confirm pattern the other two tools use without a larger change to that endpoint.
|
||||
|
||||
## 0.45.0 — 2026-07-17 17:30
|
||||
|
||||
### Added
|
||||
- The cooking assistant can now propose creating a recipe when you explicitly ask it to ("make me a recipe for X", "write that down") — it drafts one right in the chat with a Create/Discard choice. Nothing is saved until you confirm; confirming goes through the same recipe-creation endpoint (and the same per-tier recipe limit) as the manual editor.
|
||||
|
||||
Note: this is the first step of chatbot-driven actions — only recipe creation for now. Adding to a shopping list or generating a meal plan from chat are tracked as follow-ups, not yet built.
|
||||
|
||||
## 0.44.1 — 2026-07-17 17:00
|
||||
|
||||
### Fixed
|
||||
- Every recipe page was broken (server error) since 0.41.0 — the new followers-visibility check referenced the user_follows table incorrectly inside a query the ORM rewrites in a way that silently produces invalid SQL for cross-table references. Fixed by using a literal table reference instead.
|
||||
|
||||
## 0.44.0 — 2026-07-17 16:15
|
||||
|
||||
### Added
|
||||
- New "Team" billing tier, above Pro — higher AI-call, recipe, and storage limits, editable from Admin > Tiers like the existing tiers. (Moderator/admin remain separate account roles, unrelated to billing tier — unchanged by this.)
|
||||
|
||||
## 0.43.0 — 2026-07-17 15:45
|
||||
|
||||
### Added
|
||||
- The cooking assistant now supports multiple named conversations — start a new one, rename, or delete from the conversations menu in the chat header. Auto-titled from your first question; older single-thread history stays as-is but isn't shown in the new list.
|
||||
|
||||
## 0.42.0 — 2026-07-17 15:15
|
||||
|
||||
### Added
|
||||
- Recipe editor now has "Regenerate with AI" — describe what to change (e.g. "make it spicier", "swap in chicken") and the draft you're editing updates in place, no new recipe created. You still need to save.
|
||||
|
||||
## 0.41.0 — 2026-07-17 14:45
|
||||
|
||||
### Added
|
||||
- New recipe visibility option: "Followers only" — visible to people who follow you, hidden from public browsing, search, and anonymous share links. Available in the recipe editor, bulk visibility actions, and the Recipes filter.
|
||||
|
||||
Note: public profile pages and search results don't yet surface a viewer's followers-only recipes from that author — those remain reachable only via the recipe's direct link or the Following feed.
|
||||
|
||||
## 0.40.0 — 2026-07-17 14:00
|
||||
|
||||
### Added
|
||||
- AI Settings now shows a usage panel — AI calls, recipes created, and storage used this month against your tier's limits, with progress bars.
|
||||
|
||||
## 0.39.0 — 2026-07-17 13:30
|
||||
|
||||
### Fixed
|
||||
- Adapting/varying a recipe with AI could fail silently (no error shown) on a network hiccup, and could save a byte-for-byte duplicate recipe when the AI's output didn't actually differ from the original — both flows now surface real errors and skip saving when nothing changed. AI-adapted recipes also now show up in recipe history (Forked from…) like forks always have.
|
||||
|
||||
## 0.38.0 — 2026-07-17 13:00
|
||||
|
||||
### Added
|
||||
- The cooking assistant and per-recipe chat can now expand to fullscreen — a new toggle in the chat header.
|
||||
|
||||
## 0.37.0 — 2026-07-17 12:30
|
||||
|
||||
### Fixed
|
||||
- Generating a recipe from a photo now uses two separate AI steps — a vision model recognizes what's in the picture, then a text model writes the recipe from that — instead of one model doing both, so each step can use the model actually suited to it.
|
||||
|
||||
## 0.36.0 — 2026-07-17 12:00
|
||||
|
||||
### Added
|
||||
- Explore and the Activity Feed are now one page — Explore has Discover/Following/For You tabs, so browsing and following recipes no longer live in two separate places.
|
||||
- Explore's recipe cards (search results, trending, recently added, following, for you) now use the same cover-photo card as the Recipes page, instead of the old text-only search card.
|
||||
|
||||
## 0.35.0 — 2026-07-14 18:20
|
||||
|
||||
### Added
|
||||
- Recipe editor now lets you enter nutrition values by hand (calories, protein, carbs, fat, fiber, sodium per serving) instead of relying only on the AI estimate — the nutrition panel shows a "Manually entered" badge and swaps to "Estimate with AI instead" when manual data is present.
|
||||
|
||||
## 0.34.0 — 2026-07-14 18:05
|
||||
|
||||
### Added
|
||||
- Admin overview now shows growth (new users/recipes this week), engagement (recipes cooked this week), a moderation queue count, storage used, and platform-integration counts (webhooks, API keys) — not just totals.
|
||||
|
||||
### Fixed
|
||||
- The admin Signups toggle was inverted — switching it "on" used to disable signups. It now reads naturally: on means open.
|
||||
- AI provider keys and default-model settings have moved from Site Settings to AI Config, alongside the rest of the AI setup.
|
||||
|
||||
## 0.33.1 — 2026-07-14 17:45
|
||||
|
||||
### Fixed
|
||||
- URL-imported recipes never recorded what language they were actually written in, so the Translate button couldn't tell whether translation was needed — the importer now detects the source page's language, and photo import records the language it always writes in.
|
||||
|
||||
## 0.33.0 — 2026-07-14 17:35
|
||||
|
||||
### Added
|
||||
- **AI recipe generation/import now auto-detects drinks vs dishes** — generate, generate-from-idea, URL import, and photo import all classify the result and skip cook time for drinks, defaulting to dish whenever it's ambiguous.
|
||||
- **Drink recipes get their own default icon** (🍹 instead of 🍽️) wherever a recipe has no cover photo.
|
||||
- **Explore now has a Type filter** (dish/drink), alongside My Recipes' existing one.
|
||||
|
||||
## 0.32.0 — 2026-07-14 17:10
|
||||
|
||||
### Security
|
||||
- Fixed a stored-XSS hole in public recipe pages' embedded structured data, and tightened the production Content-Security-Policy so script injection like it can't execute even if a similar bug slips in again.
|
||||
- Avatar photos now require proof you actually own the upload — previously any URL was accepted, including another user's uploaded photo key.
|
||||
- Changing your password now signs out every other active session, and so does resetting a forgotten password.
|
||||
- Fixed a rate-limit bypass on public share-link throttling caused by trusting a spoofable header.
|
||||
- Webhook signing secrets are now encrypted at rest, matching how API keys and other secrets are already stored.
|
||||
- Login/2FA/password-reset rate limiting now shares Redis instead of quietly resetting per server instance.
|
||||
- Photo/avatar uploads are now size-capped by the storage server itself, not just a number the client could lie about.
|
||||
- A private recipe's title could leak via its page's browser-tab title to any signed-in user who had the link — fixed to respect the same visibility rules as the page itself.
|
||||
- Blocking/unblocking a user is now rate-limited, matching follow/unfollow.
|
||||
- AI calls made with your own API key (Settings → AI Keys) no longer count against your monthly AI-call limit.
|
||||
|
||||
## 0.31.0 — 2026-07-14 16:35
|
||||
|
||||
### Added
|
||||
- **Recipes can now be marked as a Drink/cocktail** instead of a dish — the recipe form hides irrelevant food-only fields (prep/cook time, difficulty, batch cooking) for drinks, and you can filter your recipe list by type. Drink recipes also no longer show the food/drink pairing suggestion buttons on their own page.
|
||||
|
||||
## 0.30.1 — 2026-07-14 16:20
|
||||
|
||||
Internal: fixed test mocks left stale by the earlier API-key auth-widening pass (recipes/meal-plans/shopping-lists route tests) — no user-facing change.
|
||||
|
||||
## 0.30.0 — 2026-07-14 16:05
|
||||
|
||||
### Added
|
||||
- **Admins can now set the site-wide default AI provider/model** per use case (text generation, photo/vision, meal-plan generation) from Settings → Admin, applied whenever a user hasn't picked their own model preference or brought their own API key.
|
||||
|
||||
## 0.29.0 — 2026-07-14 15:20
|
||||
|
||||
### Added
|
||||
- **Photo recipe import now respects your app language** — previously it defaulted to English (or whatever language was in the photo) instead of matching your locale like other AI generation features.
|
||||
|
||||
### Fixed
|
||||
- Importing a photo with no recognizable recipe used to open the recipe editor anyway with empty/garbage fields — it now shows a clear error instead.
|
||||
|
||||
## 0.28.3 — 2026-07-14 14:55
|
||||
|
||||
### Fixed
|
||||
- Copying an unlisted recipe's share link wrongly warned "this link won't work until the recipe is Public" — unlisted links work fine (that's the point of unlisted); the warning now only shows for actually-private recipes.
|
||||
|
||||
## 0.28.2 — 2026-07-14 14:45
|
||||
|
||||
### Fixed
|
||||
- Recipe cards on Explore and Search cramped the title next to the difficulty badge, cutting titles off early — the title now gets its own full-width line, and the grid gains a medium-viewport column step matching the Recipes page.
|
||||
|
||||
## 0.28.1 — 2026-07-14 14:25
|
||||
|
||||
### Fixed
|
||||
- Cooking mode's keyboard/voice shortcuts panel could overflow and overlap the surrounding screen in French (longer translated labels) — now scrolls internally and wraps instead of overflowing.
|
||||
|
||||
## 0.28.0 — 2026-07-14 14:05
|
||||
|
||||
### Added
|
||||
- **Meal plan and shopping list header buttons now match the recipe page's icon+tooltip style** — Share, Generate shopping list, Shopping lists, Print, Export to calendar, Send to grocery delivery all collapsed to icon-only with a tooltip, instead of crowding the header with text labels.
|
||||
- **Week-switch arrows on the meal plan now sit right next to the week date**, instead of at the far end of the button row.
|
||||
|
||||
## 0.27.2 — 2026-07-14 13:20
|
||||
|
||||
### Fixed
|
||||
- Dietary tag chips, the recipe tag-adding form, the "Edit recipe" title, and the meal-plan nutrition-goals bar were all hardcoded in English regardless of app language — now translated.
|
||||
|
||||
## 0.27.1 — 2026-07-14 12:05
|
||||
|
||||
### Fixed
|
||||
- API Reference (`/docs`) schemas corrected against the actual code across the whole API — recipes (batch-cook fields, tags, photos were undocumented), comments, ratings, meal plans, shopping lists, pantry, feed, and several missing error responses. A webhook-redelivery route also returned a malformed error body — now matches the rest of the API's `{ error: string }` convention.
|
||||
|
||||
## 0.27.0 — 2026-07-14 11:15
|
||||
|
||||
### Added
|
||||
- **API keys now work on recipes, collections, meal plans, shopping lists, pantry, feed, and AI generation** — previously most of the API only accepted a session cookie, so keys couldn't actually be used for most endpoints. Account/credential-adjacent routes (profile, AI provider keys, webhooks, notifications, messages, admin) intentionally stay session-only.
|
||||
|
||||
## 0.26.0 — 2026-07-14 10:20
|
||||
|
||||
### Added
|
||||
- **API Reference (`/docs`) now covers the full API**: went from 14 documented endpoints to all ~100 — pantry, meal plans, shopping lists, collections, users/social, AI generation, webhooks, conversations, notifications, and admin routes are now all documented with request/response schemas.
|
||||
|
||||
## 0.25.1 — 2026-07-14 09:40
|
||||
|
||||
### Fixed
|
||||
- API key "Last used" only showed a date — now shows date and time.
|
||||
|
||||
## 0.25.0 — 2026-07-14 09:36
|
||||
|
||||
### Added
|
||||
- **Gravatar is now opt-in, off by default** — previously every account without a custom photo automatically had its email hashed and sent to gravatar.com. Turn it on in Settings → Profile if you want it.
|
||||
|
||||
## 0.24.1 — 2026-07-14 09:24
|
||||
|
||||
### Fixed
|
||||
- My Recipes search result count showed a literal "{count}" instead of the number, in every locale.
|
||||
|
||||
## 0.24.0 — 2026-07-14 08:08
|
||||
|
||||
### Added
|
||||
- **My Recipes search now matches ingredients and tags too**, not just title/description — same improvement shipped for Explore/Search earlier.
|
||||
- **QR code on printed recipes**: a public or unlisted recipe's printout now includes a scannable code linking back to the online version.
|
||||
|
||||
## 0.23.0 — 2026-07-13 23:06
|
||||
|
||||
### Added
|
||||
- **Two-factor authentication**: turn it on in Settings → Security to require a code from an authenticator app when signing in, with backup codes in case you lose access to it.
|
||||
|
||||
## 0.22.0 — 2026-07-13 22:49
|
||||
|
||||
### Added
|
||||
- **QR code on printed shopping lists**: a public list's printout now includes a scannable code linking back to the live version — pairs with public-editable links, so someone at the store can scan and check items off in real time.
|
||||
|
||||
## 0.21.0 — 2026-07-13 22:34
|
||||
|
||||
### Added
|
||||
- **Rating stars on recipe cards** — average rating and review count now show on Search and Explore results, not just the recipe detail page.
|
||||
|
||||
## 0.20.0 — 2026-07-13 22:26
|
||||
|
||||
### Added
|
||||
- **Duplicate your own recipe** — same one-click copy used for forking others' recipes, now also on your own, for making variations without touching version history.
|
||||
|
||||
## 0.19.0 — 2026-07-13 22:21
|
||||
|
||||
### Added
|
||||
- **Export your meal plan to a calendar file** — download a week's meals as a .ics file to import into Google/Apple/Outlook calendar.
|
||||
|
||||
## 0.18.0 — 2026-07-13 22:16
|
||||
|
||||
### Added
|
||||
- **Live updates on shared meal plans**: entries added, removed, or cleared by a collaborator now appear automatically, both on the owner's own week view and everyone else's shared view.
|
||||
|
||||
## 0.17.0 — 2026-07-13 22:06
|
||||
|
||||
### Added
|
||||
- **Clear a day or the whole meal-plan week** in one click instead of removing each meal individually.
|
||||
|
||||
## 0.16.0 — 2026-07-13 21:59
|
||||
|
||||
### Added
|
||||
- **@mention autocomplete in comments**: type "@" and a name to search and insert a mention, instead of typing the exact username blind.
|
||||
|
||||
## 0.15.0 — 2026-07-13 21:54
|
||||
|
||||
### Added
|
||||
- **Search now matches ingredients and tags**, not just title/description — "zaatar" now finds a recipe that uses it even if the title doesn't mention it.
|
||||
- **Tag filter chips on Explore**: click a popular tag to narrow results instead of typing it.
|
||||
|
||||
## 0.14.0 — 2026-07-13 21:47
|
||||
|
||||
### Added
|
||||
- **Change your username** in Settings — previously auto-assigned at signup with no way to change it.
|
||||
|
||||
## 0.13.1 — 2026-07-13 17:25
|
||||
|
||||
### Fixed
|
||||
- People search never found anyone, for anyone — there was no signup or settings flow that ever set a username, and search (along with profiles and follow) requires one. Every account now gets one automatically on signup; existing accounts were backfilled.
|
||||
|
||||
## 0.13.0 — 2026-07-13 15:37
|
||||
|
||||
### Added
|
||||
- **Explore search now finds people and recipes together**: one search bar, one query — no more separate, hard-to-find people tab.
|
||||
|
||||
## 0.12.1 — 2026-07-13 13:25
|
||||
|
||||
### Fixed
|
||||
- Changelog entries showed literal `**bold**` markup instead of rendering it.
|
||||
|
||||
## 0.12.0 — 2026-07-13 12:52
|
||||
|
||||
### Added
|
||||
- **Public shopping list links can now allow editing**: turn on "Allow editing" alongside the public link so anyone who has it can check off, add, and reorder items — no account needed. Off by default, and turning off the public link revokes editing too.
|
||||
|
||||
## 0.11.0 — 2026-07-13 12:27
|
||||
|
||||
### Added
|
||||
- **Live updates on shared shopping lists**: items checked, added, recategorized, or reordered by a collaborator now appear automatically, without a manual refresh.
|
||||
|
||||
## 0.10.0 — 2026-07-13 11:55
|
||||
|
||||
### Added
|
||||
- **Bulk tag editing**: add or remove tags across several selected recipes at once.
|
||||
- **Bulk export**: export several selected recipes to a single Markdown file.
|
||||
- **Move recipes between collections**: select recipes inside a collection to move them to another collection or remove them from this one.
|
||||
|
||||
## 0.9.6 — 2026-07-13 09:31
|
||||
|
||||
### Added
|
||||
- **Rate limiting on public routes**: sign-in/sign-up now throttle after 3 attempts per 10s per IP; public recipe/shopping-list share links (`/r/`, `/s/`) throttle after 60 requests/min per IP.
|
||||
|
||||
## 0.9.5 — 2026-07-13 09:20
|
||||
|
||||
### Fixed
|
||||
- Explore page's "Recipe ideas" input got squeezed to a couple of visible characters on mobile — buttons now stay icon-only below `sm:`.
|
||||
- The per-recipe chat button could overlap the private-notes save button on short recipe pages.
|
||||
|
||||
## 0.9.4 — 2026-07-13 09:03
|
||||
|
||||
### Fixed
|
||||
- "New recipe" wrapped to its own line on mobile (especially French) instead of sharing a row with Generate/Import — icon-only below that breakpoint now.
|
||||
- The view-toggle/Select row floated flush right with a large dead gap on the left — now left-aligned outside select mode.
|
||||
|
||||
## 0.9.3 — 2026-07-13 08:38
|
||||
|
||||
### Fixed
|
||||
- Recipes page wasted a lot of vertical space above the recipe list on mobile — Sort/Filter now sit alongside Search on one row instead of forcing an extra one.
|
||||
|
||||
## 0.9.2 — 2026-07-13 07:14
|
||||
|
||||
### Fixed
|
||||
- Explore page's "Recipe ideas" banner buttons clashed with its violet gradient background — restyled to match.
|
||||
|
||||
## 0.9.1 — 2026-07-13 06:59
|
||||
|
||||
### Fixed
|
||||
- Destructive confirm buttons (clear chat history, discard recipe changes) had unreadable black text on a red background — a missing CSS variable.
|
||||
|
||||
## 0.9.0 — 2026-07-12 23:28
|
||||
|
||||
### Added
|
||||
- **Clear chat history**: a trash-icon button in both chatbots clears that conversation's saved history.
|
||||
- Chat history now auto-expires after 90 days (daily cleanup job).
|
||||
|
||||
## 0.8.0 — 2026-07-12 22:38
|
||||
|
||||
### Added
|
||||
- **Read-only API key scoping**: create keys that can only read (GET), not create/edit/delete anything.
|
||||
- **AI chat history**: both chatbots now remember past conversations across sessions, and let you search across everything you've ever asked.
|
||||
|
||||
## 0.7.1 — 2026-07-12 21:36
|
||||
|
||||
### Fixed
|
||||
- Cooking-assistant button on the homepage sat too high.
|
||||
- The chatbots would answer honestly if asked what AI model they run on — now always identify as Epicure.
|
||||
|
||||
## 0.7.0 — 2026-07-12 19:36
|
||||
|
||||
### Added
|
||||
- **General cooking-question chatbot** on the recipes homepage — ask technique/substitution/timing questions not tied to a specific recipe.
|
||||
|
||||
### Fixed
|
||||
- API keys always showed "never used" — middleware was blocking every Bearer-key request before it ever reached the code that verifies the key and records usage.
|
||||
- The webhooks documentation page had no way back to webhooks settings.
|
||||
|
||||
## 0.6.0 — 2026-07-12 19:09
|
||||
|
||||
### Added
|
||||
- **Granular push-notification settings**: turn individual categories on/off (follows, comments, replies, reactions, ratings, mentions, leftover reminders, shared shopping list updates) instead of all-or-nothing.
|
||||
|
||||
### Fixed
|
||||
- The push-notification toggle in Settings always showed as off, even when notifications were genuinely still enabled — it never checked the actual browser subscription state.
|
||||
- The API Reference page (`/docs`) was blank — Content-Security-Policy blocked the script it needs to render.
|
||||
|
||||
## 0.5.1 — 2026-07-12 19:05
|
||||
|
||||
### Security
|
||||
- Recipe/review photo uploads: a stolen storage key from another user's public recipe or review could be submitted as your own, causing that user's photo to be deleted from storage when the recipe was later edited or deleted. Both routes now check the key was actually issued to you for that recipe.
|
||||
- AI URL-import could be redirected to internal/private network addresses via a crafted 3xx response, and was separately vulnerable to DNS-rebinding between validation and fetch. Both the import and outgoing webhook delivery now resolve the host once and pin the connection to that address, re-validating on every redirect hop.
|
||||
- Comment moderation and monthly AI/recipe/storage quota checks trusted a session field that can lag up to 5 minutes behind a role or tier change — both now re-check the current value in the database.
|
||||
|
||||
## 0.5.0 — 2026-07-12 18:37
|
||||
|
||||
### Added
|
||||
- **Push notifications for shared shopping lists** — get pinged when someone else checks off or adds items.
|
||||
|
||||
### Fixed
|
||||
- Batch-cook dishes never deducted pantry when marked cooked — now deducts once, on the first dish cooked per batch session.
|
||||
- Weekly meal-plan nutrition coverage compared a week's total intake against a daily goal (reading ~7x too high) — now compares a proper daily average, with a per-day breakdown and a flag for meals missing nutrition data.
|
||||
- Meal-plan week navigation could resolve the wrong Monday depending on server timezone.
|
||||
|
||||
## 0.4.0 — 2026-07-12 16:13
|
||||
|
||||
### Added
|
||||
- **Profile pictures**: upload a custom photo, or get a Gravatar-backed avatar automatically — no more generic initials by default.
|
||||
- **"Imported from" badge** on recipe cards for recipes brought in from a URL.
|
||||
- **Share shopping lists via a public link** — anyone with the link can view, no account required, alongside the existing private collaborator invites.
|
||||
|
||||
### Fixed
|
||||
- Batch-cook recipes shifted left in compact view when they had no time set or a longer dish/time label.
|
||||
|
||||
## 0.3.1 — 2026-07-12 15:08
|
||||
|
||||
### Added
|
||||
- A free-text "describe what you're after" field for batch-cooking generation, matching the standard recipe generator.
|
||||
|
||||
### Fixed
|
||||
- AI recipe generation used a separate language picker instead of following the app's own language — removed, generation now always matches your app language.
|
||||
- The bulk-select action bar on the recipe list could show a horizontal scrollbar on desktop even though there was room to grow.
|
||||
- Recipes imported from a URL never actually saved their source URL — the "Source: ..." link on the recipe page was dead code until now.
|
||||
|
||||
## 0.3.0 — 2026-07-12 14:46
|
||||
|
||||
### Added
|
||||
- **Manually create and edit batch-cook recipes**: the recipe form now has a batch-cook toggle, an editable dish list (storage/reheat guidance per dish), and per-step dish tagging — not just AI-generated ones anymore. Editing an existing batch-cook recipe no longer silently strips its dish data.
|
||||
|
||||
## 0.2.2 — 2026-07-12 13:54
|
||||
|
||||
### Fixed
|
||||
- Recipe photo thumbnails always tried to load from `localhost:9000` in production, tripping CSP/mixed-content blocks in every browser — the public storage URL wasn't reaching client-side code.
|
||||
|
||||
## 0.2.1 — 2026-07-12 13:21
|
||||
|
||||
### Fixed
|
||||
- Recipe photos were lost after saving, and multi-file uploads only kept the last file selected.
|
||||
- Photo thumbnails failed to load (blocked by Next.js's image optimizer refusing local-storage hosts).
|
||||
|
||||
## 0.2.0 — 2026-07-12
|
||||
|
||||
### Added
|
||||
- **Batch cooking**: generate a single "mega recipe" covering several meals at once — merged shopping list, steps tagged per dish (including steps that advance several dishes at once), and per-dish storage/reheat guidance. Available from the recipe list's Generate dialog and from the meal planner.
|
||||
- **Leftover expiry reminders**: mark a batch-cook dish as cooked, track its fridge life, see it surfaced on the Pantry page, and get a daily reminder before it goes bad.
|
||||
- **"Cooked it" photo reviews**: attach a photo and written review when rating a recipe.
|
||||
- **Pantry-expiry recipe suggestions**: the Pantry page now surfaces recipes that use up ingredients about to expire.
|
||||
- **Trending collections**: star public collections; browse trending and recently-added ones under Collections → Discover.
|
||||
- **Add to collection from the recipe list**: select recipes and add them to a new or existing collection without leaving the page.
|
||||
- List and compact view modes for the recipe list, alongside the existing grid view.
|
||||
|
||||
### Fixed
|
||||
- Recipe version-comparison diff was unreadable and partially untranslated.
|
||||
- Print/export pages always render light, regardless of the app's dark/light setting.
|
||||
- Presigned photo-upload URLs were signed against an internal-only address in production, breaking uploads.
|
||||
- Several recipe-list and recipe-form UI issues: filter menu closing on every click, tag filter not accepting keystrokes, inconsistent card badge styling, missing tooltips, a floating save button on long recipe forms.
|
||||
|
||||
## 0.1.0 — earlier
|
||||
|
||||
Initial feature set: recipes (create, edit, AI-generate, import from URL/photo), meal planning, shopping lists, pantry tracking, collections, social features (follow, comment, rate, notifications), nutrition tracking, admin dashboard, and account/billing basics.
|
||||
@@ -7,7 +7,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
```bash
|
||||
cp .env.example .env.local # fill in secrets (lives at repo root)
|
||||
ln -s ../../.env.local apps/web/.env.local # Next.js reads from apps/web/, not root
|
||||
docker compose -f docker/compose.yml up -d # start postgres, redis, minio
|
||||
docker compose -f compose.yml up -d # start postgres, redis, minio
|
||||
pnpm install
|
||||
pnpm db:generate # generate migrations from schema (first time)
|
||||
pnpm db:migrate # apply migrations
|
||||
@@ -36,7 +36,6 @@ pnpm db:studio # open Drizzle Studio
|
||||
**Monorepo** (pnpm workspaces):
|
||||
- `apps/web` — Next.js 15 App Router app (`@epicure/web`)
|
||||
- `packages/db` — Drizzle ORM schema + client (`@epicure/db`)
|
||||
- `packages/api-types` — Zod schemas, single source of truth for API types + OpenAPI (`@epicure/api-types`)
|
||||
|
||||
**Route groups in `apps/web/app/`**:
|
||||
- `(auth)/` — login, signup, verify-email (no auth required)
|
||||
@@ -45,7 +44,7 @@ pnpm db:studio # open Drizzle Studio
|
||||
- `api/v1/` — REST API endpoints
|
||||
- `api/auth/[...all]/` — Better Auth handler
|
||||
|
||||
**Auth**: Better Auth with Drizzle adapter. Server: `lib/auth/server.ts`. Client: `lib/auth/client.ts`. Middleware at `middleware.ts` guards all routes.
|
||||
**Auth**: Better Auth with Drizzle adapter. Server: `lib/auth/server.ts`. Client: `lib/auth/client.ts`. Edge-level guard is `proxy.ts` (not `middleware.ts`, which was removed) — it checks for a session cookie and redirects to `/login` for non-public paths, and additionally gates `/admin` paths. Per-route/per-page checks (`auth.api.getSession` in server components, `requireSession`/`requireSessionOrApiKey`/`requireAdmin` in API routes) are still required as defense-in-depth — don't rely on `proxy.ts` alone when adding a page or route under `(app)/` or `admin/`.
|
||||
|
||||
**DB**: Drizzle ORM on Postgres. Schema in `packages/db/src/schema/` split by domain: `users`, `recipes`, `social`, `meal-planning`, `tiers`. Import from `@epicure/db`.
|
||||
|
||||
@@ -66,7 +65,7 @@ cd apps/web && pnpm dlx shadcn@latest add <component-name>
|
||||
1. Edit `packages/db/src/schema/*.ts`
|
||||
2. `pnpm db:generate` — creates migration file
|
||||
3. `pnpm db:migrate` — applies it
|
||||
4. Update corresponding Zod schemas in `packages/api-types/src/`
|
||||
4. Update the corresponding inline Zod schemas in the affected `apps/web/app/api/v1/**/route.ts` files (and `apps/web/lib/openapi.ts` if documented there)
|
||||
|
||||
## Environment Variables
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Deploy: Portainer (git stack) + external Traefik LXC
|
||||
|
||||
## Portainer
|
||||
|
||||
1. Stacks → Add stack → **Repository**
|
||||
2. Repository URL: this repo. Reference: branch to track (e.g. `main`)
|
||||
3. Compose path: `compose.prod.yml`
|
||||
4. Environment variables (Portainer stack env, not committed):
|
||||
|
||||
```
|
||||
POSTGRES_DB=epicure
|
||||
POSTGRES_USER=epicure
|
||||
POSTGRES_PASSWORD=<generate>
|
||||
REDIS_PASSWORD=<generate>
|
||||
MINIO_ROOT_USER=<generate>
|
||||
MINIO_ROOT_PASSWORD=<generate>
|
||||
BETTER_AUTH_SECRET=<openssl rand -base64 32>
|
||||
BETTER_AUTH_URL=https://HOST_DOMAIN
|
||||
ENCRYPTION_SECRET=<openssl rand -base64 32>
|
||||
NEXT_PUBLIC_VAPID_PUBLIC_KEY=<npx web-push generate-vapid-keys>
|
||||
VAPID_PRIVATE_KEY=<from same command>
|
||||
WEB_PORT=3000
|
||||
# optional
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
GITHUB_CLIENT_ID=
|
||||
GITHUB_CLIENT_SECRET=
|
||||
NEXT_PUBLIC_GITHUB_ENABLED=
|
||||
DISCORD_CLIENT_ID=
|
||||
DISCORD_CLIENT_SECRET=
|
||||
NEXT_PUBLIC_DISCORD_ENABLED=
|
||||
AUTHENTIK_CLIENT_ID=
|
||||
AUTHENTIK_CLIENT_SECRET=
|
||||
AUTHENTIK_BASE_URL=
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED=
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=
|
||||
SMTP_PASS=
|
||||
SMTP_FROM=Epicure <noreply@epicure.app>
|
||||
STRIPE_WEBHOOK_SECRET=
|
||||
OPENROUTER_API_KEY=
|
||||
OPENROUTER_DEFAULT_MODEL=
|
||||
OPENAI_API_KEY=
|
||||
ANTHROPIC_API_KEY=
|
||||
OLLAMA_BASE_URL=
|
||||
```
|
||||
|
||||
Every var listed here must exist in `compose.prod.yml`'s `web.environment` block to actually
|
||||
reach the container — Portainer stack env alone isn't enough, it only fills in `${...}` refs the
|
||||
compose file declares.
|
||||
|
||||
`NEXT_PUBLIC_*` vars (`NEXT_PUBLIC_VAPID_PUBLIC_KEY`, `NEXT_PUBLIC_GITHUB_ENABLED`,
|
||||
`NEXT_PUBLIC_DISCORD_ENABLED`, `NEXT_PUBLIC_AUTHENTIK_ENABLED`) are baked into the client JS
|
||||
bundle at **build time**, not read at container startup — they're wired as Docker `build.args`
|
||||
in compose.prod.yml, not just `environment`. Changing one of these requires Portainer to
|
||||
actually rebuild the image (redeploy with "re-pull image and rebuild"), a plain container
|
||||
restart won't pick up the new value.
|
||||
|
||||
5. Deploy the stack. Portainer builds `web` from the repo's root `Dockerfile` (see `build:` in compose.prod.yml) — no separate image push needed.
|
||||
6. Enable GitOps updates (webhook or polling) on the stack if you want redeploy-on-push.
|
||||
|
||||
## Migrations + seed
|
||||
|
||||
Handled automatically. The `migrate` service builds from the `migrator` Dockerfile target,
|
||||
runs `drizzle-kit migrate` then the tier-definitions seed, and exits; `web` waits for it to
|
||||
complete successfully before starting (`depends_on: migrate: condition: service_completed_successfully`).
|
||||
Both are idempotent — safe to re-run on every stack redeploy, not just the first one.
|
||||
|
||||
## Traefik (separate LXC, file provider)
|
||||
|
||||
1. Copy `traefik/epicure.yml` into the traefik LXC's dynamic config directory.
|
||||
2. Replace `HOST_DOMAIN` with the public hostname and `PORTAINER_LXC_IP` with the portainer LXC's network IP (must match `WEB_PORT` published in compose.prod.yml).
|
||||
3. Confirm `certResolver` name matches what's set in traefik's static config.
|
||||
4. Traefik picks it up automatically (file provider watches for changes) — no restart needed.
|
||||
|
||||
## Notes
|
||||
|
||||
- `web` connects to `postgres`/`redis`/`minio` over the compose-internal network; only `web`'s port is published to the LXC host for traefik to reach.
|
||||
- `apps/web/next.config.ts` has `output: "standalone"` — required for the Dockerfile's slim runtime stage.
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM node:22-alpine AS base
|
||||
RUN corepack enable
|
||||
|
||||
# ---- deps: install full workspace deps ----
|
||||
FROM base AS deps
|
||||
WORKDIR /repo
|
||||
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/db/package.json packages/db/package.json
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# ---- migrator: applies drizzle migrations + seeds tier definitions ----
|
||||
FROM deps AS migrator
|
||||
WORKDIR /repo/packages/db
|
||||
COPY packages/db .
|
||||
CMD ["sh", "-c", "pnpm migrate && pnpm seed"]
|
||||
|
||||
# ---- build ----
|
||||
FROM base AS build
|
||||
WORKDIR /repo
|
||||
COPY --from=deps /repo/node_modules ./node_modules
|
||||
COPY --from=deps /repo/apps/web/node_modules ./apps/web/node_modules
|
||||
COPY --from=deps /repo/packages/db/node_modules ./packages/db/node_modules
|
||||
COPY . .
|
||||
# apps/web/.env.local is normally a symlink to repo-root .env.local (gitignored);
|
||||
# it doesn't exist in the build context, so Next's env loader chokes on the dangling
|
||||
# link. No secrets are needed at build time — they're injected at container runtime.
|
||||
RUN rm -f apps/web/.env.local && touch apps/web/.env.local
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
# NEXT_PUBLIC_* vars are inlined into the client bundle at build time, not read at
|
||||
# container runtime — must be passed as build args (compose.prod.yml wires these
|
||||
# from the same stack env vars used at runtime, so they stay in sync).
|
||||
ARG NEXT_PUBLIC_VAPID_PUBLIC_KEY
|
||||
ARG NEXT_PUBLIC_GITHUB_ENABLED
|
||||
ARG NEXT_PUBLIC_DISCORD_ENABLED
|
||||
ARG NEXT_PUBLIC_AUTHENTIK_ENABLED
|
||||
ENV NEXT_PUBLIC_VAPID_PUBLIC_KEY=$NEXT_PUBLIC_VAPID_PUBLIC_KEY
|
||||
ENV NEXT_PUBLIC_GITHUB_ENABLED=$NEXT_PUBLIC_GITHUB_ENABLED
|
||||
ENV NEXT_PUBLIC_DISCORD_ENABLED=$NEXT_PUBLIC_DISCORD_ENABLED
|
||||
ENV NEXT_PUBLIC_AUTHENTIK_ENABLED=$NEXT_PUBLIC_AUTHENTIK_ENABLED
|
||||
# next.config.ts reads STORAGE_PUBLIC_URL to compute the CSP connect-src/img-src
|
||||
# allowlist, and next.config.ts's headers() are evaluated at build time — so this
|
||||
# also needs to be a build arg, not just a runtime env var (unlike STORAGE_ENDPOINT).
|
||||
ARG STORAGE_PUBLIC_URL
|
||||
ENV STORAGE_PUBLIC_URL=$STORAGE_PUBLIC_URL
|
||||
# lib/storage.ts's getPublicUrl() is called from client components to render photo
|
||||
# <img> tags — a plain (non-NEXT_PUBLIC_) env var is never inlined into the browser
|
||||
# bundle, so it must be duplicated under a NEXT_PUBLIC_ name to reach the client.
|
||||
ARG NEXT_PUBLIC_STORAGE_PUBLIC_URL
|
||||
ENV NEXT_PUBLIC_STORAGE_PUBLIC_URL=$NEXT_PUBLIC_STORAGE_PUBLIC_URL
|
||||
RUN pnpm --filter web build
|
||||
|
||||
# ---- runtime ----
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
ENV PORT=3000
|
||||
RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001
|
||||
|
||||
COPY --from=build /repo/apps/web/public ./public
|
||||
COPY --from=build --chown=nextjs:nodejs /repo/apps/web/.next/standalone ./
|
||||
COPY --from=build --chown=nextjs:nodejs /repo/apps/web/.next/static ./apps/web/.next/static
|
||||
|
||||
USER nextjs
|
||||
EXPOSE 3000
|
||||
CMD ["node", "apps/web/server.js"]
|
||||
|
||||
# ---- cron: periodically triggers internal cron endpoints (e.g. weekly digest) ----
|
||||
# Minimal alpine + busybox crond image — just curls the running `web` service on a
|
||||
# schedule. Doesn't need the app build output at all, so it's based on `base`
|
||||
# rather than `runner`, keeping the image tiny and independent of the Next build.
|
||||
FROM base AS cron
|
||||
RUN apk add --no-cache curl
|
||||
COPY cron/crontab /etc/crontabs/root
|
||||
COPY cron/run-digest.sh /usr/local/bin/run-digest.sh
|
||||
COPY cron/run-leftover-reminders.sh /usr/local/bin/run-leftover-reminders.sh
|
||||
COPY cron/run-chat-cleanup.sh /usr/local/bin/run-chat-cleanup.sh
|
||||
RUN chmod +x /usr/local/bin/run-digest.sh /usr/local/bin/run-leftover-reminders.sh /usr/local/bin/run-chat-cleanup.sh
|
||||
CMD ["crond", "-f", "-l", "2"]
|
||||
@@ -0,0 +1,163 @@
|
||||
# Epicure Feature Audit
|
||||
|
||||
Code-verified inventory of what exists in the app today, by domain. Written 2026-07-21 after a full read of the routes/schema/components listed under "key files" for each entry — not guessed from names. **Keep this file updated whenever a feature is added or changes what it does** (see standing rule below).
|
||||
|
||||
Status legend: **Exists** (fully working) · **Partial** (works but with a real limitation, noted) · **Missing** (confirmed absent by grep/read, not just "didn't find it").
|
||||
|
||||
---
|
||||
|
||||
## 1. Recipes & AI
|
||||
|
||||
**AI stack**: Vercel AI SDK, provider-agnostic (`apps/web/lib/ai/factory.ts`) — OpenAI, Anthropic, OpenRouter, Ollama (local). Key resolution order: user's own BYOK key → admin default per use-case → admin's raw provider key → env var. Structured outputs always `generateObject` + Zod; chat features use `generateText` with optional tool-calling.
|
||||
|
||||
| Feature | Status | Description | Key files |
|
||||
|---|---|---|---|
|
||||
| Recipe CRUD | Exists | Create/get/list/update/delete; update snapshots the prior version first (`recipeSnapshots`) | `apps/web/app/api/v1/recipes/**` |
|
||||
| Fork / duplicate | Exists | Same backend action for both — UI just swaps the label based on ownership | `apps/web/app/api/v1/recipes/[id]/fork/route.ts` |
|
||||
| Version history | Exists | `GET /recipes/[id]/versions`, diff-able snapshots | `apps/web/app/api/v1/recipes/[id]/versions/**` |
|
||||
| **Import from URL** | **Exists** | Fetches a page (SSRF-checked), strips markup, extracts a structured recipe via AI. Returns the extraction to the client — doesn't self-persist, caller POSTs it to create | `apps/web/app/api/v1/ai/import-url` |
|
||||
| Import from photo | Exists | Two-stage vision→text; recognizes a photographed page/handwritten recipe, self-persists as a private recipe | `apps/web/app/api/v1/ai/import-photo`, `lib/ai/features/{recognize-photo,generate-recipe-from-recognition}.ts` |
|
||||
| Generate from idea/title | Exists | Text-only generation from just a title | `apps/web/app/api/v1/ai/generate-from-idea` |
|
||||
| Recipe ideas (browsing) | Exists | 6 idea cards from an optional prompt, not persisted | `apps/web/app/api/v1/ai/recipe-ideas` |
|
||||
| Adapt (exclude ingredients / constraints) | Exists | Persists as new recipe + variation link, unless AI reports unchanged | `apps/web/app/api/v1/ai/adapt/[id]` |
|
||||
| Suggest variations | Exists | Ideas only, not persisted; gated by tier feature flag `recipe_variations` | `apps/web/app/api/v1/ai/variations/[id]` |
|
||||
| Meal / drink pairings | Exists | Gated by tier feature flags `meal_pairing` / `drink_pairing` | `apps/web/app/api/v1/ai/{pairings,drinks}/[id]` |
|
||||
| Translate recipe | Exists | Saves as a new private recipe, keeps original quantities/units/timers | `apps/web/app/api/v1/ai/translate/[id]` |
|
||||
| Batch-cook generator | Exists | One recipe, multiple dishes, per-dish fridge/freezer guidance | `apps/web/app/api/v1/ai/batch-cook/generate` |
|
||||
| Nutrition estimation | Exists | AI-estimated, cached on the recipe row; author-triggered | `apps/web/app/api/v1/recipes/[id]/nutrition` |
|
||||
| Scale servings | Exists | Model-driven, not naive linear math (handles "1 egg" etc.) | `apps/web/app/api/v1/ai/scale` |
|
||||
| Substitute ingredient | Exists | | `apps/web/app/api/v1/ai/substitute` |
|
||||
| Recipe chat / cooking chat | Exists | Recipe-grounded Q&A, and a general assistant with tool-calling (`createRecipe`, `addToShoppingList`) | `apps/web/app/api/v1/ai/{recipe-chat,cooking-chat}` |
|
||||
| Themed meal generator | Exists | Multi-course meal into a collection | `apps/web/app/api/v1/ai/generate-meal` |
|
||||
| Recipe media: photos | Exists | S3-compatible storage, counts against tier storage limit | `packages/db/src/schema/recipes.ts` (`recipePhotos`) |
|
||||
| **Recipe video** | **Missing** | No video field/upload path anywhere in schema or components | — |
|
||||
| Collections | Exists | Shared/collaborative (`collection_members`, viewer/editor roles), fork-a-collection, explore page, reorder | `apps/web/app/api/v1/collections/**` |
|
||||
| Tags, difficulty, dietary labels | Exists | Dietary schema has 7 tags; search only exposes 4 of them as filters (`vegan/vegetarian/glutenFree/dairyFree`) | `packages/db/src/schema/recipes.ts` |
|
||||
| Visibility (private/unlisted/public/followers) | Exists, one flagged gap | Enforced almost everywhere as public-vs-not-private; the `/r/[id]` anonymous share route's own code comment flags that `followers`-only recipes may be reachable without a follow-relationship check | `apps/web/app/r/[id]/page.tsx` |
|
||||
| Print views | Exists | Recipe, collection, meal plan, shopping list, pantry all have print routes | `apps/web/app/print/**` |
|
||||
| Markdown export | Exists | Single recipe, bulk (up to 100), meal plan | `apps/web/lib/markdown/**` |
|
||||
| Cooking mode | Exists | Step timers (multiple parallel), **voice control** (Web Speech API, EN/FR commands), wake-lock, batch-cook step grouping | `apps/web/components/cooking-mode/cooking-mode.tsx` |
|
||||
| Search | Exists | Title/description/ingredient/tag substring match + filters (difficulty, type, max time, dietary, exact tags) | `apps/web/app/api/v1/search` |
|
||||
| "What can I cook" (pantry-matched) | Exists | Deterministic ingredient-overlap scorer against the user's own recipes, not AI | `apps/web/lib/pantry-match.ts`, `/recipes/can-cook` |
|
||||
| Explore / trending | Exists | Purely favorite-count-driven (7-day window) + recency — no editorial curation | `apps/web/app/(app)/explore` |
|
||||
|
||||
---
|
||||
|
||||
## 2. Meal planning, pantry, shopping, nutrition
|
||||
|
||||
| Feature | Status | Description | Key files |
|
||||
|---|---|---|---|
|
||||
| Weekly calendar meal plan | Exists | Mon–Sun grid, manual CRUD + bulk-set-week | `apps/web/app/(app)/meal-plan`, `apps/web/app/api/v1/meal-plans/[weekStart]/**` |
|
||||
| AI weekly meal-plan generator | Exists | Pantry-aware, dietary-aware, nudged by nutrition goals; one real recipe per entry | `apps/web/app/api/v1/ai/meal-plan/generate` |
|
||||
| Meal plan sharing | Exists | `meal_plan_members` viewer/editor roles for collaborators, plus an anonymous read-only public link (`isPublic` flag, mirrors shopping lists' but view-only — no public-editable mode) at `/m/[id]`, with a QR code generated client-side for the link | `apps/web/lib/meal-plan-access.ts`, `apps/web/app/m/[id]/page.tsx`, `apps/web/components/meal-plan/share-meal-plan-button.tsx` |
|
||||
| **Calendar export (.ics)** | **Exists** | Real ICS builder with per-meal-type wall-clock times | `apps/web/app/api/v1/meal-plans/[weekStart]/export/ics` |
|
||||
| Weekly nutrition rollup | Exists | | `apps/web/app/api/v1/meal-plans/[weekStart]/nutrition` |
|
||||
| Multiple shopping lists | Exists | | `apps/web/app/api/v1/shopping-lists/**` |
|
||||
| Generate list from meal-plan week | Exists | Merges duplicate ingredients, flags items already covered by pantry (never silently drops) | `apps/web/lib/pantry-shopping-match.ts` |
|
||||
| Shared/collaborative lists | Exists | Member roles **and** an anonymous public link mode (`isPublic`/`publicEditable`) | `packages/db/src/schema/meal-planning.ts` |
|
||||
| List collaboration | Partial | Short-polling, not websocket/push — explicitly documented as such in code | `apps/web/components/meal-plan/shopping-list-view.tsx` |
|
||||
| Aisle categorization | Exists | Heuristic auto-assign + bulk re-categorize | `apps/web/lib/grocery-categories.ts` |
|
||||
| Grocery delivery integration | **Partial / stub** | Generic export payload works; Instacart adapter is an explicit stub (requires a partnership agreement Epicure doesn't have — returns 501 if unconfigured, throws if "configured") | `apps/web/lib/grocery-providers/instacart.ts` |
|
||||
| Other delivery/price integrations (DoorDash, Kroger, Walmart, live pricing) | **Missing** | Confirmed absent by repo-wide search | — |
|
||||
| Pantry manual CRUD | Exists | | `apps/web/app/api/v1/pantry/**` |
|
||||
| Auto-deduct pantry on cook | Exists, one nuance | Name+unit matching; for batch-cook recipes, deduction fires once (not re-scaled) on the first dish marked cooked | `apps/web/app/api/v1/recipes/[id]/cooked/route.ts` |
|
||||
| Expiring-soon tracking | Exists | With "use it up" recipe suggestions | `apps/web/components/pantry/expiring-soon-suggestions.tsx` |
|
||||
| **Barcode scan (pantry)** | **Exists** | Real Open Food Facts API lookup by UPC/EAN | `apps/web/app/api/v1/pantry/scan/barcode` |
|
||||
| Photo scan (pantry) | Exists | Vision-model based | `apps/web/app/api/v1/pantry/scan/photo` |
|
||||
| Nutrition goals | Exists | | `apps/web/app/api/v1/users/me/nutrition-goals` |
|
||||
| Nutrition diary | Exists | Single-day diary view, plus a Trend tab (7/30/90-day calorie line chart + daily macro averages) — the same endpoint switches modes via a `range` query param | `apps/web/app/api/v1/users/me/nutrition-diary`, `apps/web/components/nutrition/nutrition-trend.tsx` |
|
||||
| USDA nutrition-facts database | Exists | `estimateNutrition` now looks up each ingredient in USDA FoodData Central (SR Legacy + Survey (FNDDS) datasets) after converting its quantity/unit to grams, sums the matches, and only falls back to AI estimation for ingredients that couldn't be converted (count-based units like "2 cloves") or had no USDA match — including every ingredient, transparently, when `USDA_API_KEY` isn't configured. Barcode scan (pantry) still only IDs product names via Open Food Facts, unrelated to this. | `apps/web/lib/usda.ts`, `apps/web/lib/ingredient-grams.ts`, `apps/web/lib/ai/features/estimate-nutrition.ts` |
|
||||
| Batch cooking | Exists | Shared prep steps grouped by which dish they serve, per-dish fridge/freezer countdown independent of the whole-batch pantry deduction | `apps/web/components/recipe/batch-cook-*.tsx` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Social, messaging, notifications
|
||||
|
||||
| Feature | Status | Description | Key files |
|
||||
|---|---|---|---|
|
||||
| Follow / unfollow | Exists | One-way, no approval step | `apps/web/app/api/v1/users/[username]/follow` |
|
||||
| Block | Exists | Hides comments, blocks messaging both ways | `apps/web/lib/blocks.ts` |
|
||||
| Private accounts | Exists | Hides recipe grid from non-followers; excluded from "for you" unless already followed | `apps/web/app/(app)/u/[username]/page.tsx` |
|
||||
| Profile page | Exists | Cooking-history streak stats, "cooked it" photo gallery (owner-visible) | `apps/web/app/(app)/u/[username]` |
|
||||
| Ratings/reviews, comments (1-level threaded), reactions, @mentions | Exists | | `packages/db/src/schema/social.ts` |
|
||||
| Favorites | Exists | Drives "for you" ranking and trending | `apps/web/app/api/v1/recipes/[id]/favorite` |
|
||||
| Direct messaging | Exists, 1:1 by design | No group messaging (deliberate — unique-pair constraint at schema level) | `packages/db/src/schema/messaging.ts` |
|
||||
| Read receipts | Partial | Thread-level `lastReadAt` only — no per-message delivery/seen state | `packages/db/src/schema/messaging.ts` |
|
||||
| Following feed | Exists | | `apps/web/app/api/v1/feed` |
|
||||
| "For You" personalized feed | Exists | Tag/dietary preference profile from favorites + high ratings | `apps/web/lib/for-you-ranking.ts` |
|
||||
| Trending feed / explore | Exists | Favorite-count driven, no editorial curation, **no separate "featured" surface** | `apps/web/app/api/v1/feed/trending` |
|
||||
| Notification categories | Exists | 8 categories, independent push + email toggle each, plus email-only weekly digest | `packages/db/src/schema/users.ts` (`userNotificationPrefs`) |
|
||||
| Push notifications | Exists | Web Push + VAPID, end-to-end, real trigger call sites (not just plumbing) | `apps/web/lib/push.ts` |
|
||||
| Push display + click-through | Exists | `sw.js` previously had no `push` listener at all — push messages never displayed. Now has both `push` (calls `showNotification`) and `notificationclick` (focuses an existing tab on the payload's `url`, or opens one) | `apps/web/public/sw.js` |
|
||||
| Email notifications + weekly digest cron | Exists | | `apps/web/lib/notifications.ts`, `apps/web/app/api/internal/cron/weekly-digest` |
|
||||
| Reports/moderation | Exists | Report → admin webhook → admin queue → resolve (reviewed/dismissed) + audit log | `apps/web/app/api/v1/reports`, `apps/web/app/api/v1/admin/reports` |
|
||||
| Moderator role | Exists | Moderators get `/admin/reports` (view/resolve) and `/admin/recipes` (view + unpublish takedown); every other `/admin/*` page redirects them out via `requireFullAdminPage()`. Comment deletion already allowed moderator before this. | `apps/web/lib/require-admin-page.ts`, `apps/web/app/admin/layout.tsx`, `apps/web/app/api/v1/admin/recipes/[id]/route.ts` |
|
||||
|
||||
---
|
||||
|
||||
## 4. Admin, billing, ops, integrations
|
||||
|
||||
| Feature | Status | Description | Key files |
|
||||
|---|---|---|---|
|
||||
| Tiers (free/pro/family) + limits | Exists | Recipe count, AI calls/month, storage, public-recipe count; TOCTOU-safe via advisory lock + transaction | `apps/web/lib/tiers.ts` |
|
||||
| Stripe webhook (checkout/cancel) | Exists | Signature-verified, replay-protected, event-deduped — production quality | `apps/web/app/api/webhooks/stripe/route.ts` |
|
||||
| Stripe checkout + self-serve billing portal (2026-07-23) | Exists | `POST /api/v1/billing/checkout` creates a subscription Checkout Session (promotion codes enabled); `POST /api/v1/billing/portal` opens Stripe's hosted Customer Portal for self-serve cancel/upgrade/card-update. Webhook route rewritten with the real `stripe` SDK (`stripe.webhooks.constructEvent`, replacing the hand-rolled HMAC verifier) and now handles the full event set: `checkout.session.completed`, `customer.subscription.{updated,deleted}`, `invoice.{payment_failed,paid}` — `past_due` deliberately doesn't downgrade tier (Stripe retries the card first). `/settings/billing` shows plan cards, usage, and a "Manage billing" button; `/admin/billing` shows connection status, subscriber counts, past-due list, recent billing audit events. Cancel/downgrade is at period end (Stripe Portal default); no trial period. **Not yet built:** family-group multi-user sharing (Family tier is purchasable solo, but the plan's per-account member invite/join/tier-resolution piece is deliberately deferred — see `plans/STRIPE_PLAN.md` §1a, flagged there as the most novel/error-prone piece, intentionally shipped after solo billing is proven). | `apps/web/lib/stripe.ts`, `apps/web/app/api/webhooks/stripe/route.ts`, `apps/web/app/api/v1/billing/**`, `apps/web/app/(app)/settings/billing/page.tsx`, `apps/web/app/admin/billing/page.tsx` |
|
||||
| Admin dashboard | Exists | 13 sections: overview, insights/analytics, users, invites, recipe moderation, reports, support, tiers, webhooks, audit logs, storage, AI config, site settings, changelog | `apps/web/app/admin/**` |
|
||||
| Feature flags (per-tier) vs feature prefs (per-user cosmetic) | Exists, two distinct systems | Flags gate 3 AI capabilities by tier; prefs let users hide 7 nav sections, no billing implication | `apps/web/lib/{feature-flags,feature-prefs}.ts` |
|
||||
| **Developer permission** (2026-07-22, split 2026-07-23) | Exists | Two separate, orthogonal permissions — not one. `users.isDeveloper` gates webhooks + self-serve API keys: admin-toggled always, *and* self-serve toggleable by the user themselves once on a paid tier (no added fee) via `PATCH /api/v1/users/me/developer-access`; free-tier users still need an admin grant. `users.isByokEnabled` gates BYOK separately, admin-only, no self-serve — routing real AI spend through Epicure on the user's own key warrants a manual check-in. Previously all three (webhooks/API keys/BYOK) shared one flag with zero self-serve path. Existing users with a webhook/API key were already grandfathered for `isDeveloper`; a second migration grandfathered existing BYOK users into `isByokEnabled` specifically. | `apps/web/lib/permissions.ts` (`hasDeveloperAccess`, `hasByokAccess`, `canSelfServeDeveloperAccess`), `apps/web/lib/api-auth.ts` (`requireDeveloper`, `requireByok`) |
|
||||
| User webhooks (personal automation) | Exists | 7 events, Zapier-style, requires developer access | `apps/web/lib/webhooks.ts` |
|
||||
| Admin ops webhooks (site-wide) | Exists | 3 events (signup, ticket, report) — admin-only, unrelated to developer access | `apps/web/lib/admin-webhooks.ts` |
|
||||
| Support tickets ↔ Gitea two-way sync | Exists, verified real | Outbound (create/comment/close mirror to Gitea issue) + inbound (signed webhook receiver, dedup, loop-safe) | `apps/web/lib/gitea.ts`, `apps/web/app/api/webhooks/gitea/route.ts` |
|
||||
| Self-serve API keys | Exists | Up to 10 per user, scoped full/read, SHA-256 hashed at rest, requires developer access | `apps/web/app/api/v1/api-keys` |
|
||||
| Public OpenAPI spec + docs page | Exists | Scalar-rendered at `/docs`, spec at `/api/v1/openapi.json` | `apps/web/lib/openapi.ts` |
|
||||
| i18n | Partial | Only `en` and `fr` — no other locales | `apps/web/messages/*.json` |
|
||||
| 2FA | Exists | TOTP + backup codes + OTP, passwordless-account-compatible | Better Auth `twoFactor` plugin |
|
||||
| Social login | Exists | Google always, GitHub/Discord/generic OIDC if configured | `apps/web/lib/auth/server.ts` |
|
||||
| Rate limiting | Exists | Two layers: Better Auth's Redis-backed built-in limiter (tighter on 2FA verify endpoints) + a general sliding-window limiter for AI/API routes | `apps/web/lib/rate-limit.ts` |
|
||||
| Invite-gated signup | Exists | Signups can be globally disabled, invite-only fallback; first-ever user auto-promoted to admin | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. PWA, offline, mobile
|
||||
|
||||
| Feature | Status | Description | Key files |
|
||||
|---|---|---|---|
|
||||
| Installability | Exists | Manifest + SVG icons (no raster/PNG fallback), Chromium `beforeinstallprompt` button, **iOS Safari gets a static "tap Share" instructional banner** (no programmatic install API exists on Safari — Apple restriction, not fixable) | `apps/web/app/manifest.ts`, `apps/web/components/pwa/install-prompt.tsx` |
|
||||
| Service worker | Exists | Cache-first for `/cook` pages, network-first-with-cache-populate elsewhere, `/api/*` bypassed | `apps/web/public/sw.js` |
|
||||
| Background Sync | Exists | Chromium via native Background Sync API; Safari/Firefox (no support at all) via an `online`-event fallback reading the same IndexedDB queue | `apps/web/lib/offline-queue.ts`, `apps/web/public/sw.js` |
|
||||
| Offline save-for-later | Exists | Per-recipe explicit pin + IndexedDB-tracked list shown on the `/offline` fallback page | `apps/web/lib/offline-db.ts`, `apps/web/components/recipe/save-offline-button.tsx` |
|
||||
| Offline scope | Partial | Recipe viewing + one write path (mark-cooked). **Shopping lists and meal plan have no offline/queue coverage** | — |
|
||||
| Push (client + server) | Exists end-to-end | Real subscribe/unsubscribe with correct state sync, VAPID, multiple triggers wired | `apps/web/lib/push.ts` |
|
||||
| Voice control | **Exists** | Web Speech API in cooking mode (this was previously assumed missing — it isn't) | `apps/web/components/cooking-mode/cooking-mode.tsx` |
|
||||
| Barcode scanning | **Exists** (pantry only) | `BarcodeDetector` isn't used, but a manual-entry-triggered Open Food Facts API lookup covers the same use case | `apps/web/app/api/v1/pantry/scan/barcode` |
|
||||
| OS Share Target (share a URL into Epicure from another app) | Exists (Chromium/Android only) | Manifest `share_target` → `/recipes?title&text&url`; extracts the shared link from either `url` or a URL substring in `text` (senders vary), auto-opens the existing import-from-URL dialog pre-filled and auto-imports. Safari has no Share Target API at all — same Apple-restriction story as install prompts. | `apps/web/app/manifest.ts`, `apps/web/app/(app)/recipes/page.tsx`, `apps/web/components/recipe/url-import-dialog.tsx` |
|
||||
| Home-screen widgets, Siri/Assistant shortcuts | **Missing**, expected — N/A for a pure PWA without a native shell | — |
|
||||
| Native mobile app (React Native/Capacitor/Expo) | **Missing** | Confirmed PWA-only, no native project anywhere in the monorepo | — |
|
||||
|
||||
---
|
||||
|
||||
## Real gaps (confirmed absent, worth considering)
|
||||
|
||||
Ranked roughly by likely value:
|
||||
|
||||
1. ~~Stripe checkout + billing portal~~ — closed 2026-07-23 (solo Pro/Family subscribe/cancel/manage; family multi-user sharing still deferred, see the note in the table above).
|
||||
2. **Recipe video** — no support at all.
|
||||
3. ~~Nutrition trend/history view~~ — closed 2026-07-22 (7/30/90-day calorie chart + macro averages).
|
||||
4. ~~USDA/nutrition-database lookup~~ — closed 2026-07-22 (per-ingredient, gram-convertible ingredients only; AI fills the rest).
|
||||
5. ~~OS Share Target~~ — closed 2026-07-21 (Chromium/Android only, no Safari equivalent exists).
|
||||
6. ~~Push click-through handling~~ — closed 2026-07-21 (`push`/`notificationclick` listeners added to `sw.js`).
|
||||
7. ~~Anonymous public link for meal plans~~ — closed 2026-07-21 (read-only, with a QR code).
|
||||
8. **Grocery delivery/live pricing** beyond the Instacart stub (which needs a partnership agreement to go live).
|
||||
9. **Offline coverage for shopping lists / meal plan** — currently recipe-viewing + mark-cooked only.
|
||||
10. ~~Moderator-scoped admin routes~~ — closed 2026-07-21 (reports + recipe-unpublish).
|
||||
|
||||
## Deliberate design choices (not gaps)
|
||||
- Direct messaging is 1:1 only — enforced at the schema level, not a missing feature.
|
||||
- Feature toggles (`userFeaturePrefs`) are cosmetic nav-hiding only, never access control — separate from tier-based feature flags.
|
||||
- No native app — PWA-only is the stated architecture, covered well by the offline/install/push work already shipped.
|
||||
|
||||
---
|
||||
|
||||
## Standing rule
|
||||
|
||||
**Every time a feature ships, update this file in the same change** — add/update its row, move it out of "Real gaps" if it closes one. Bug fixes to existing features don't need an entry unless they change what the feature does.
|
||||
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Printer, UtensilsCrossed, StickyNote, ExternalLink } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, collections, eq, and } from "@epicure/db";
|
||||
import { collectionVisibleToViewer } from "@/lib/visibility";
|
||||
import { RecipeGridCard } from "@/components/recipe/recipe-grid-card";
|
||||
import { CollectionRecipesGrid } from "@/components/collections/collection-recipes-grid";
|
||||
import { ForkCollectionButton } from "@/components/collections/fork-collection-button";
|
||||
import { ShareCollectionButton } from "@/components/collections/share-collection-button";
|
||||
import { GenerateMealDialog } from "@/components/collections/generate-meal-dialog";
|
||||
import { EditCollectionDialog } from "@/components/collections/edit-collection-dialog";
|
||||
import { DeleteCollectionDialog } from "@/components/collections/delete-collection-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
|
||||
import { EmptyState } from "@/components/shared/empty-state";
|
||||
import { collectionToMarkdown } from "@/lib/markdown/collection";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function CollectionPage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const col = await db.query.collections.findFirst({
|
||||
where: and(eq(collections.id, id), collectionVisibleToViewer(session.user.id)),
|
||||
with: {
|
||||
recipes: {
|
||||
orderBy: (t, { asc }) => asc(t.position),
|
||||
with: { recipe: { with: { photos: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!col) notFound();
|
||||
|
||||
const isOwner = col.userId === session.user.id;
|
||||
const recipeList = col.recipes.flatMap((r) => (r.recipe ? [r.recipe] : []));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{col.name}</h1>
|
||||
{col.description && <p className="text-muted-foreground mt-1">{col.description}</p>}
|
||||
{col.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 mt-2">
|
||||
{col.tags.map((tag) => (
|
||||
<Badge key={tag} variant="outline" className="text-xs">{tag}</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{recipeList.length} recipe{recipeList.length !== 1 ? "s" : ""} · {m.recipe.visibility[col.visibility]}
|
||||
</p>
|
||||
{isOwner && col.notes && (
|
||||
<div className="mt-2 flex items-start gap-2 rounded-lg border bg-muted/30 px-3 py-2 text-sm text-muted-foreground max-w-2xl">
|
||||
<StickyNote className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<p className="whitespace-pre-wrap">{col.notes}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<TooltipProvider>
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{recipeList.length > 0 && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/print/collection/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}>
|
||||
<Printer className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{m.collections.exportPdf}</TooltipContent>
|
||||
</Tooltip>
|
||||
<ExportMarkdownButton
|
||||
markdown={collectionToMarkdown({
|
||||
name: col.name,
|
||||
description: col.description,
|
||||
recipes: recipeList,
|
||||
})}
|
||||
filename={col.name}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{isOwner && <GenerateMealDialog collectionId={id} />}
|
||||
{isOwner && <ShareCollectionButton collectionId={id} />}
|
||||
{isOwner && (
|
||||
<EditCollectionDialog
|
||||
collectionId={id}
|
||||
initialName={col.name}
|
||||
initialDescription={col.description}
|
||||
initialNotes={col.notes}
|
||||
initialTags={col.tags}
|
||||
initialVisibility={col.visibility}
|
||||
/>
|
||||
)}
|
||||
{isOwner && <DeleteCollectionDialog collectionId={id} />}
|
||||
{col.visibility === "public" && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/c/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{m.recipe.viewPublicly}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{!isOwner && (col.visibility === "public" || col.visibility === "unlisted") && (
|
||||
<ForkCollectionButton collectionId={id} />
|
||||
)}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
|
||||
{recipeList.length === 0 ? (
|
||||
<EmptyState icon={UtensilsCrossed} title={m.collections.emptyCollection} compact />
|
||||
) : isOwner ? (
|
||||
<CollectionRecipesGrid collectionId={id} recipes={recipeList} />
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{recipeList.map((recipe) => (
|
||||
<Link key={recipe.id} href={`/recipes/${recipe.id}`}>
|
||||
<RecipeGridCard recipe={recipe} />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import {
|
||||
db,
|
||||
collections,
|
||||
users,
|
||||
collectionFavorites,
|
||||
collectionRecipes,
|
||||
eq,
|
||||
desc,
|
||||
sql,
|
||||
and,
|
||||
gte,
|
||||
count,
|
||||
inArray,
|
||||
} from "@epicure/db";
|
||||
import { ExploreCollectionsContent } from "@/components/collections/explore-collections-content";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export type CollectionResult = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
authorName: string | null;
|
||||
recipeCount: number;
|
||||
starCount: number;
|
||||
starred: boolean;
|
||||
};
|
||||
|
||||
export default async function ExploreCollectionsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const trendingRows = await db
|
||||
.select({
|
||||
id: collections.id,
|
||||
name: collections.name,
|
||||
description: collections.description,
|
||||
authorName: users.name,
|
||||
recentStars: count(collectionFavorites.collectionId),
|
||||
})
|
||||
.from(collections)
|
||||
.innerJoin(users, eq(collections.userId, users.id))
|
||||
.leftJoin(
|
||||
collectionFavorites,
|
||||
and(eq(collectionFavorites.collectionId, collections.id), gte(collectionFavorites.createdAt, sevenDaysAgo))
|
||||
)
|
||||
.where(eq(collections.visibility, "public"))
|
||||
.groupBy(collections.id, users.id)
|
||||
.orderBy(desc(sql`count(${collectionFavorites.collectionId})`))
|
||||
.limit(12);
|
||||
|
||||
const recentRows = await db
|
||||
.select({
|
||||
id: collections.id,
|
||||
name: collections.name,
|
||||
description: collections.description,
|
||||
authorName: users.name,
|
||||
})
|
||||
.from(collections)
|
||||
.innerJoin(users, eq(collections.userId, users.id))
|
||||
.where(eq(collections.visibility, "public"))
|
||||
.orderBy(desc(collections.createdAt))
|
||||
.limit(12);
|
||||
|
||||
const allIds = [...new Set([...trendingRows.map((r) => r.id), ...recentRows.map((r) => r.id)])];
|
||||
|
||||
const [recipeCounts, totalStars, myStars] = await Promise.all([
|
||||
allIds.length > 0
|
||||
? db.select({ collectionId: collectionRecipes.collectionId, n: count() })
|
||||
.from(collectionRecipes)
|
||||
.where(inArray(collectionRecipes.collectionId, allIds))
|
||||
.groupBy(collectionRecipes.collectionId)
|
||||
: [],
|
||||
allIds.length > 0
|
||||
? db.select({ collectionId: collectionFavorites.collectionId, n: count() })
|
||||
.from(collectionFavorites)
|
||||
.where(inArray(collectionFavorites.collectionId, allIds))
|
||||
.groupBy(collectionFavorites.collectionId)
|
||||
: [],
|
||||
allIds.length > 0
|
||||
? db.query.collectionFavorites.findMany({
|
||||
where: and(eq(collectionFavorites.userId, session.user.id), inArray(collectionFavorites.collectionId, allIds)),
|
||||
columns: { collectionId: true },
|
||||
})
|
||||
: [],
|
||||
]);
|
||||
|
||||
const recipeCountMap = new Map(recipeCounts.map((r) => [r.collectionId, r.n]));
|
||||
const starCountMap = new Map(totalStars.map((r) => [r.collectionId, r.n]));
|
||||
const starredSet = new Set(myStars.map((s) => s.collectionId));
|
||||
|
||||
function toResult(row: { id: string; name: string; description: string | null; authorName: string | null }): CollectionResult {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
authorName: row.authorName,
|
||||
recipeCount: recipeCountMap.get(row.id) ?? 0,
|
||||
starCount: starCountMap.get(row.id) ?? 0,
|
||||
starred: starredSet.has(row.id),
|
||||
};
|
||||
}
|
||||
|
||||
const trending = trendingRows.map(toResult);
|
||||
const recent = recentRows.map(toResult);
|
||||
|
||||
return <ExploreCollectionsContent trending={trending} recent={recent} />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { PageHeaderSkeleton, InfoCardSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function CollectionsLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeaderSkeleton actions={1} />
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<InfoCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, collections, collectionRecipes, eq, and, or, ilike, sql } from "@epicure/db";
|
||||
import { CollectionsPageContent } from "@/components/collections/collections-page-content";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function CollectionsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ q?: string }>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const { q } = await searchParams;
|
||||
const query = q?.trim();
|
||||
|
||||
const where = query
|
||||
? and(
|
||||
eq(collections.userId, session.user.id),
|
||||
or(
|
||||
ilike(collections.name, `%${query}%`),
|
||||
ilike(collections.description, `%${query}%`),
|
||||
sql`exists (
|
||||
select 1 from collection_recipes cr
|
||||
inner join recipes r on r.id = cr.recipe_id
|
||||
where cr.collection_id = ${collections.id} and r.title ilike ${`%${query}%`}
|
||||
)`
|
||||
)
|
||||
)
|
||||
: eq(collections.userId, session.user.id);
|
||||
|
||||
const [userCollections, countRows] = await Promise.all([
|
||||
db.query.collections.findMany({
|
||||
where,
|
||||
orderBy: (t, { desc }) => desc(t.updatedAt),
|
||||
with: {
|
||||
recipes: {
|
||||
limit: 4,
|
||||
orderBy: (t, { asc }) => asc(t.position),
|
||||
with: { recipe: { with: { photos: true } } },
|
||||
},
|
||||
},
|
||||
}),
|
||||
// Separate grouped count — the `with: { recipes: { limit: 4 } }` above is
|
||||
// capped for thumbnail previews, so `.recipes.length` off that relation
|
||||
// would only ever report up to 4, never the real total.
|
||||
db
|
||||
.select({ collectionId: collectionRecipes.collectionId, count: sql<number>`count(*)::int` })
|
||||
.from(collectionRecipes)
|
||||
.innerJoin(collections, eq(collectionRecipes.collectionId, collections.id))
|
||||
.where(eq(collections.userId, session.user.id))
|
||||
.groupBy(collectionRecipes.collectionId),
|
||||
]);
|
||||
|
||||
const countByCollection = new Map(countRows.map((r) => [r.collectionId, r.count]));
|
||||
|
||||
return (
|
||||
<CollectionsPageContent
|
||||
query={query ?? ""}
|
||||
collections={userCollections.map((col) => ({
|
||||
id: col.id,
|
||||
name: col.name,
|
||||
description: col.description,
|
||||
tags: col.tags,
|
||||
visibility: col.visibility,
|
||||
recipeCount: countByCollection.get(col.id) ?? 0,
|
||||
thumbnails: col.recipes.flatMap((r) => {
|
||||
if (!r.recipe) return [];
|
||||
const cover = r.recipe.photos.find((p) => p.isCover) ?? r.recipe.photos[0];
|
||||
return [{
|
||||
recipeId: r.recipe.id,
|
||||
recipeType: r.recipe.recipeType,
|
||||
coverIcon: r.recipe.coverIcon,
|
||||
coverColor: r.recipe.coverColor,
|
||||
photoUrl: cover ? getPublicUrl(cover.storageKey) : null,
|
||||
}];
|
||||
}),
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function AppError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
console.error(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
|
||||
<h2 className="text-xl font-semibold">Something went wrong</h2>
|
||||
<p className="text-muted-foreground max-w-md">
|
||||
An unexpected error occurred while loading this page. You can try again, or head back
|
||||
later.
|
||||
</p>
|
||||
<Button onClick={() => reset()}>Try again</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { InfoCardSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
function ExploreSection() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-6 w-32" />
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<InfoCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ExploreLoading() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<Skeleton className="h-12 w-full max-w-xl rounded-md" />
|
||||
<ExploreSection />
|
||||
<ExploreSection />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import {
|
||||
db,
|
||||
recipes,
|
||||
users,
|
||||
favorites,
|
||||
userFollows,
|
||||
eq,
|
||||
desc,
|
||||
sql,
|
||||
and,
|
||||
gte,
|
||||
count,
|
||||
} from "@epicure/db";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { ExplorePageContent } from "@/components/search/explore-page-content";
|
||||
import { attachCardExtras } from "@/lib/recipe-card-extras";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export type RecipeResult = {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
authorName: string | null;
|
||||
difficulty: "easy" | "medium" | "hard" | null;
|
||||
baseServings: number;
|
||||
prepMins: number | null;
|
||||
cookMins: number | null;
|
||||
visibility: "private" | "unlisted" | "public" | "followers";
|
||||
tags: string[];
|
||||
isBatchCook: boolean;
|
||||
sourceUrl: string | null;
|
||||
recipeType: "dish" | "drink";
|
||||
photos: { storageKey: string; isCover: boolean }[];
|
||||
dishCount: number;
|
||||
isFavorited: boolean;
|
||||
};
|
||||
|
||||
export default async function ExplorePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ q?: string }>;
|
||||
}) {
|
||||
const { q } = await searchParams;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const columns = {
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
description: recipes.description,
|
||||
authorName: users.name,
|
||||
difficulty: recipes.difficulty,
|
||||
baseServings: recipes.baseServings,
|
||||
prepMins: recipes.prepMins,
|
||||
cookMins: recipes.cookMins,
|
||||
visibility: recipes.visibility,
|
||||
tags: recipes.tags,
|
||||
isBatchCook: recipes.isBatchCook,
|
||||
sourceUrl: recipes.sourceUrl,
|
||||
recipeType: recipes.recipeType,
|
||||
coverIcon: recipes.coverIcon,
|
||||
coverColor: recipes.coverColor,
|
||||
};
|
||||
|
||||
// Trending: public recipes ordered by favorite count in last 7 days
|
||||
const trendingRows = await db
|
||||
.select({ ...columns, favoriteCount: count(favorites.recipeId) })
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.leftJoin(
|
||||
favorites,
|
||||
and(
|
||||
eq(favorites.recipeId, recipes.id),
|
||||
gte(favorites.createdAt, sevenDaysAgo)
|
||||
)
|
||||
)
|
||||
.where(and(eq(recipes.visibility, "public"), eq(users.isPrivate, false)))
|
||||
.groupBy(recipes.id, users.id)
|
||||
.orderBy(desc(sql`count(${favorites.recipeId})`))
|
||||
.limit(12);
|
||||
|
||||
// Recent: public recipes ordered by createdAt desc
|
||||
const recentRows = await db
|
||||
.select(columns)
|
||||
.from(recipes)
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.where(and(eq(recipes.visibility, "public"), eq(users.isPrivate, false)))
|
||||
.orderBy(desc(recipes.createdAt))
|
||||
.limit(12);
|
||||
|
||||
const [trending, recent] = await Promise.all([
|
||||
attachCardExtras(trendingRows.map(({ favoriteCount: _fc, ...r }) => r), session?.user.id),
|
||||
attachCardExtras(recentRows, session?.user.id),
|
||||
]);
|
||||
|
||||
// Most-used tags across public recipes — shown as filter chips on the
|
||||
// search bar so browsing by tag doesn't require typing the exact word.
|
||||
const popularTagsResult = await db.execute<{ tag: string }>(sql`
|
||||
select tag, count(*) as usage_count
|
||||
from recipes r
|
||||
inner join users u on r.author_id = u.id
|
||||
cross join lateral unnest(r.tags) as tag
|
||||
where r.visibility = 'public' and u.is_private = false
|
||||
group by tag
|
||||
order by usage_count desc
|
||||
limit 12
|
||||
`);
|
||||
const popularTags = popularTagsResult.map((r) => r.tag);
|
||||
|
||||
const followedCount = session
|
||||
? (
|
||||
await db
|
||||
.select({ followingId: userFollows.followingId })
|
||||
.from(userFollows)
|
||||
.where(eq(userFollows.followerId, session.user.id))
|
||||
).length
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<ExplorePageContent
|
||||
trending={trending}
|
||||
recent={recent}
|
||||
initialQuery={q ?? ""}
|
||||
popularTags={popularTags}
|
||||
followedCount={followedCount}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { FeedItemSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function FeedLoading() {
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto space-y-8">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<FeedItemSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function FeedPage() {
|
||||
redirect("/explore");
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { PageHeaderSkeleton, RecipeCardGridSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function AppLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeaderSkeleton actions={1} />
|
||||
<RecipeCardGridSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { PageHeaderSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function MealPlanLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeaderSkeleton actions={4} subtitle />
|
||||
<Skeleton className="h-16 w-full rounded-xl" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-7 gap-3">
|
||||
{Array.from({ length: 7 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-64 w-full rounded-xl" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { ChevronLeft, ChevronRight, ShoppingCart, Printer, CalendarDays } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, mealPlans, mealPlanMembers, recipes, userNutritionGoals, eq, and, desc } from "@epicure/db";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { MealPlanner } from "@/components/meal-plan/meal-planner";
|
||||
import { ShareMealPlanButton } from "@/components/meal-plan/share-meal-plan-button";
|
||||
import { NewShoppingListButton } from "@/components/meal-plan/new-shopping-list-button";
|
||||
import { WeeklyNutritionBar } from "@/components/nutrition/weekly-nutrition-bar";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
|
||||
import { mealPlanToMarkdown } from "@/lib/markdown/meal-plan";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
function getMonday(dateStr?: string): Date {
|
||||
// new Date("YYYY-MM-DD") parses as UTC midnight, but getDay() below reads
|
||||
// local time — in negative UTC-offset zones that's still "yesterday",
|
||||
// shifting the resolved Monday back by a full week. Parse the y/m/d parts
|
||||
// directly into local time instead.
|
||||
const d = dateStr
|
||||
? (() => {
|
||||
const [y, m, day] = dateStr.split("-").map(Number);
|
||||
return new Date(y!, m! - 1, day!);
|
||||
})()
|
||||
: new Date();
|
||||
const dow = d.getDay();
|
||||
const diff = (dow === 0 ? -6 : 1 - dow);
|
||||
d.setDate(d.getDate() + diff);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d;
|
||||
}
|
||||
|
||||
function toDateStr(d: Date): string {
|
||||
// Read local y/m/d, not toISOString() (which converts to UTC and can
|
||||
// shift the date by a day depending on the server's timezone offset).
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function addWeeks(d: Date, n: number): Date {
|
||||
const copy = new Date(d);
|
||||
copy.setDate(copy.getDate() + n * 7);
|
||||
return copy;
|
||||
}
|
||||
|
||||
export default async function MealPlanPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ week?: string }>;
|
||||
}) {
|
||||
const { week } = await searchParams;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const msgs = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const monday = getMonday(week);
|
||||
const weekStart = toDateStr(monday);
|
||||
const prevWeek = toDateStr(addWeeks(monday, -1));
|
||||
const nextWeek = toDateStr(addWeeks(monday, 1));
|
||||
|
||||
const sunday = addWeeks(monday, 1);
|
||||
sunday.setDate(sunday.getDate() - 1);
|
||||
|
||||
const [plan, userRecipes, sharedMemberships, nutritionGoals] = await Promise.all([
|
||||
db.query.mealPlans.findFirst({
|
||||
where: and(eq(mealPlans.userId, session.user.id), eq(mealPlans.weekStart, weekStart)),
|
||||
with: {
|
||||
entries: {
|
||||
with: { recipe: { with: { photos: true } }, batchDish: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.query.recipes.findMany({
|
||||
where: eq(recipes.authorId, session.user.id),
|
||||
orderBy: desc(recipes.updatedAt),
|
||||
columns: { id: true, title: true, isBatchCook: true },
|
||||
with: { batchDishes: { columns: { id: true, name: true }, orderBy: (t, { asc }) => asc(t.order) } },
|
||||
}),
|
||||
db.query.mealPlanMembers.findMany({
|
||||
where: eq(mealPlanMembers.userId, session.user.id),
|
||||
with: { mealPlan: { with: { user: true } } },
|
||||
}),
|
||||
db.query.userNutritionGoals.findFirst({
|
||||
where: eq(userNutritionGoals.userId, session.user.id),
|
||||
}),
|
||||
]);
|
||||
|
||||
const hasNutritionGoals = !!(
|
||||
nutritionGoals &&
|
||||
(nutritionGoals.caloriesKcal || nutritionGoals.proteinG || nutritionGoals.carbsG || nutritionGoals.fatG)
|
||||
);
|
||||
|
||||
const entries = (plan?.entries ?? []).map((e) => ({
|
||||
id: e.id,
|
||||
day: e.day,
|
||||
mealType: e.mealType,
|
||||
servings: e.servings,
|
||||
note: e.note,
|
||||
recipe: e.recipe ? { id: e.recipe.id, title: e.recipe.title } : null,
|
||||
batchDish: e.batchDish ? { id: e.batchDish.id, name: e.batchDish.name } : null,
|
||||
}));
|
||||
|
||||
const label = `${monday.toLocaleDateString("en-US", { month: "short", day: "numeric" })} – ${sunday.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<TooltipProvider>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{msgs.mealPlan.title}</h1>
|
||||
<div className="flex items-center gap-1 mt-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/meal-plan?week=${prevWeek}`} className={cn(buttonVariants({ variant: "ghost", size: "icon" }), "h-7 w-7")} aria-label={msgs.mealPlan.previousWeek}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{msgs.mealPlan.previousWeek}</TooltipContent>
|
||||
</Tooltip>
|
||||
<p className="text-muted-foreground">{label}</p>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/meal-plan?week=${nextWeek}`} className={cn(buttonVariants({ variant: "ghost", size: "icon" }), "h-7 w-7")} aria-label={msgs.mealPlan.nextWeek}>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{msgs.mealPlan.nextWeek}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<ShareMealPlanButton weekStart={weekStart} mealPlanId={plan?.id} initialIsPublic={plan?.isPublic ?? false} />
|
||||
<NewShoppingListButton
|
||||
defaultWeekStart={weekStart}
|
||||
defaultName={formatMessage(msgs.mealPlan.shoppingListWeekName, { week: label })}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href="/shopping-lists" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))} aria-label={msgs.mealPlan.shoppingLists}>
|
||||
<ShoppingCart className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{msgs.mealPlan.shoppingLists}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/print/meal-plan?week=${weekStart}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))} aria-label={msgs.common.print}>
|
||||
<Printer className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{msgs.common.print}</TooltipContent>
|
||||
</Tooltip>
|
||||
<ExportMarkdownButton
|
||||
markdown={mealPlanToMarkdown({ label, entries })}
|
||||
filename={`meal-plan-${weekStart}`}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<a href={`/api/v1/meal-plans/${weekStart}/export/ics`} className={cn(buttonVariants({ variant: "ghost", size: "icon" }))} aria-label={msgs.mealPlan.exportCalendar}>
|
||||
<CalendarDays className="h-4 w-4" />
|
||||
</a>
|
||||
} />
|
||||
<TooltipContent>{msgs.mealPlan.exportCalendar}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
<WeeklyNutritionBar weekStart={weekStart} />
|
||||
<MealPlanner weekStart={weekStart} initialEntries={entries} userRecipes={userRecipes} hasNutritionGoals={hasNutritionGoals} />
|
||||
|
||||
{sharedMemberships.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground">{msgs.mealPlan.sharedWithYou}</h2>
|
||||
<div className="space-y-2 max-w-lg">
|
||||
{sharedMemberships.map((membership) => (
|
||||
<Link
|
||||
key={membership.id}
|
||||
href={`/meal-plan/shared/${membership.mealPlan.id}`}
|
||||
className="flex items-center justify-between rounded-xl border p-4 hover:shadow-sm transition-shadow"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{formatMessage(msgs.mealPlan.sharedPlanOf, { name: membership.mealPlan.user?.name ?? "?" })}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{formatMessage(msgs.mealPlan.weekOf, { date: membership.mealPlan.weekStart })} · {msgs.shareDialog[membership.role]}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, mealPlans, recipes, eq, desc } from "@epicure/db";
|
||||
import { getMealPlanAccessById, canWriteMealPlan } from "@/lib/meal-plan-access";
|
||||
import { SharedMealPlanView } from "@/components/meal-plan/shared-meal-plan-view";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
type Params = { params: Promise<{ mealPlanId: string }> };
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function SharedMealPlanPage({ params }: Params) {
|
||||
const { mealPlanId } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const access = await getMealPlanAccessById(mealPlanId, session.user.id);
|
||||
if (!access) notFound();
|
||||
|
||||
const plan = await db.query.mealPlans.findFirst({
|
||||
where: eq(mealPlans.id, mealPlanId),
|
||||
with: { entries: { with: { recipe: true } }, user: true },
|
||||
});
|
||||
if (!plan) notFound();
|
||||
|
||||
const userRecipes = await db.query.recipes.findMany({
|
||||
where: eq(recipes.authorId, session.user.id),
|
||||
orderBy: desc(recipes.updatedAt),
|
||||
columns: { id: true, title: true },
|
||||
});
|
||||
|
||||
const canEdit = canWriteMealPlan(access.role);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{formatMessage(m.mealPlan.sharedMealPlanTitle, { name: plan.user?.name ?? "?" })}</h1>
|
||||
<p className="text-muted-foreground mt-1">{formatMessage(m.mealPlan.weekOf, { date: plan.weekStart })} · {m.shareDialog[access.role]}</p>
|
||||
</div>
|
||||
<SharedMealPlanView
|
||||
mealPlanId={mealPlanId}
|
||||
canEdit={canEdit}
|
||||
userRecipes={userRecipes}
|
||||
initialEntries={plan.entries.map((e) => ({
|
||||
id: e.id,
|
||||
day: e.day,
|
||||
mealType: e.mealType,
|
||||
servings: e.servings,
|
||||
recipe: e.recipe ? { id: e.recipe.id, title: e.recipe.title } : null,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, conversations, users, eq } from "@epicure/db";
|
||||
import { ConversationsList } from "@/components/social/conversations-list";
|
||||
import { MessageThread } from "@/components/social/message-thread";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { isParticipant, otherParticipantId } from "@/lib/messaging";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export default async function ConversationPage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const conversation = await db.query.conversations.findFirst({ where: eq(conversations.id, id) });
|
||||
if (!conversation || !isParticipant(conversation, session.user.id)) notFound();
|
||||
|
||||
const otherId = otherParticipantId(conversation, session.user.id);
|
||||
const other = await db.query.users.findFirst({ where: eq(users.id, otherId) });
|
||||
if (!other) notFound();
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto h-[calc(100vh-8rem)] border rounded-xl overflow-hidden flex">
|
||||
<div className="hidden sm:block w-80 border-r shrink-0 overflow-y-auto">
|
||||
<ConversationsList />
|
||||
</div>
|
||||
<div className="flex-1 flex flex-col min-w-0">
|
||||
<div className="border-b p-3 flex items-center gap-3">
|
||||
<Link href={`/u/${other.username}`} className="flex items-center gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
{other.avatarUrl && <AvatarImage src={other.avatarUrl} alt={other.name} />}
|
||||
<AvatarFallback className="text-xs">{other.name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="font-medium text-sm hover:underline">{other.name}</span>
|
||||
</Link>
|
||||
</div>
|
||||
<MessageThread conversationId={id} currentUserId={session.user.id} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { MessageCircle } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { ConversationsList } from "@/components/social/conversations-list";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function MessagesPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto h-[calc(100vh-8rem)] border rounded-xl overflow-hidden flex">
|
||||
<div className="w-full sm:w-80 border-r shrink-0 overflow-y-auto">
|
||||
<ConversationsList />
|
||||
</div>
|
||||
<div className="hidden sm:flex flex-1 items-center justify-center text-muted-foreground">
|
||||
<div className="text-center space-y-2">
|
||||
<MessageCircle className="h-10 w-10 mx-auto opacity-50" />
|
||||
<p className="text-sm">{m.messages.selectConversation}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import Link from "next/link";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
|
||||
export default function AppNotFound() {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Page not found</h1>
|
||||
<p className="text-muted-foreground max-w-md">
|
||||
The page you're looking for doesn't exist or may have been moved.
|
||||
</p>
|
||||
<Link href="/recipes" className={buttonVariants({ variant: "default" })}>
|
||||
Back home
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function NotificationsLoading() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<PageHeaderSkeleton actions={1} />
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<ListRowSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { NotificationsPageContent } from "@/components/notifications/notifications-page-content";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function NotificationsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
return <NotificationsPageContent />;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { NutritionDiary } from "@/components/nutrition/nutrition-diary";
|
||||
import { NutritionTrend } from "@/components/nutrition/nutrition-trend";
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function NutritionDiaryPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">{m.nutritionDiary.title}</h1>
|
||||
<p className="text-muted-foreground mt-1">{m.nutritionDiary.subtitle}</p>
|
||||
</div>
|
||||
<Tabs defaultValue="diary" className="gap-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="diary">{m.nutritionDiary.tabDiary}</TabsTrigger>
|
||||
<TabsTrigger value="trend">{m.nutritionDiary.tabTrend}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="diary">
|
||||
<NutritionDiary />
|
||||
</TabsContent>
|
||||
<TabsContent value="trend">
|
||||
<NutritionTrend />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function PantryLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeaderSkeleton actions={1} />
|
||||
<Skeleton className="h-20 w-full rounded-xl" />
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<ListRowSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, pantryItems, recipes, cookingHistory, eq, and, or, inArray, isNotNull } from "@epicure/db";
|
||||
import { asc } from "@epicure/db";
|
||||
import { PantryManager } from "@/components/meal-plan/pantry-manager";
|
||||
import { PantryPageHeader } from "@/components/pantry/pantry-page-header";
|
||||
import { ExpiringSoonSuggestions } from "@/components/pantry/expiring-soon-suggestions";
|
||||
import { ExpiringLeftovers } from "@/components/pantry/expiring-leftovers";
|
||||
import { scoreRecipesAgainstPantry } from "@/lib/pantry-match";
|
||||
import { dishExpiresAt, daysUntil, isLeftoverExpiringSoon } from "@/lib/leftover-match";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function PantryPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const [items, candidateRecipes, cookedDishes] = await Promise.all([
|
||||
db.query.pantryItems.findMany({
|
||||
where: eq(pantryItems.userId, session.user.id),
|
||||
orderBy: asc(pantryItems.rawName),
|
||||
}),
|
||||
db.query.recipes.findMany({
|
||||
where: or(eq(recipes.authorId, session.user.id), inArray(recipes.visibility, ["public", "unlisted"])),
|
||||
with: { ingredients: true, photos: true },
|
||||
}),
|
||||
db.query.cookingHistory.findMany({
|
||||
where: and(eq(cookingHistory.userId, session.user.id), isNotNull(cookingHistory.batchDishId)),
|
||||
with: {
|
||||
batchDish: { columns: { id: true, name: true, fridgeDays: true } },
|
||||
recipe: { columns: { id: true, title: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const mappedItems = items.map((i) => ({
|
||||
id: i.id,
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
expiresAt: i.expiresAt?.toISOString() ?? null,
|
||||
}));
|
||||
|
||||
const suggestions = scoreRecipesAgainstPantry(candidateRecipes, items)
|
||||
.filter((s) => s.usesExpiring.length > 0)
|
||||
.slice(0, 3)
|
||||
.map((s) => {
|
||||
const cover = s.recipe.photos?.find((p) => p.isCover) ?? s.recipe.photos?.[0];
|
||||
return {
|
||||
id: s.recipe.id,
|
||||
title: s.recipe.title,
|
||||
photoUrl: cover ? getPublicUrl(cover.storageKey) : null,
|
||||
usesExpiring: s.usesExpiring,
|
||||
};
|
||||
});
|
||||
|
||||
const latestByDish = new Map<string, (typeof cookedDishes)[number]>();
|
||||
for (const log of cookedDishes) {
|
||||
if (!log.batchDish) continue;
|
||||
const existing = latestByDish.get(log.batchDish.id);
|
||||
if (!existing || log.cookedAt > existing.cookedAt) latestByDish.set(log.batchDish.id, log);
|
||||
}
|
||||
const leftovers = [...latestByDish.values()]
|
||||
.filter((log) => log.batchDish && isLeftoverExpiringSoon(log.cookedAt, log.batchDish.fridgeDays))
|
||||
.map((log) => ({
|
||||
recipeId: log.recipe.id,
|
||||
dishName: log.batchDish!.name,
|
||||
recipeTitle: log.recipe.title,
|
||||
expiresAt: dishExpiresAt(log.cookedAt, log.batchDish!.fridgeDays).toISOString(),
|
||||
daysLeft: daysUntil(dishExpiresAt(log.cookedAt, log.batchDish!.fridgeDays)),
|
||||
}))
|
||||
.sort((a, b) => a.daysLeft - b.daysLeft);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PantryPageHeader items={mappedItems} />
|
||||
<ExpiringLeftovers leftovers={leftovers} />
|
||||
<ExpiringSoonSuggestions suggestions={suggestions} />
|
||||
<PantryManager key={mappedItems.map((i) => i.id).join(",")} initialItems={mappedItems} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function PeoplePage() {
|
||||
redirect("/explore?tab=people");
|
||||
}
|
||||
@@ -3,13 +3,16 @@ import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, recipes, eq, and } from "@epicure/db";
|
||||
import { CookingMode } from "@/components/cooking-mode/cooking-mode";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function generateMetadata({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
|
||||
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
|
||||
return { title: recipe ? `Cooking: ${recipe.title}` : "Cooking Mode" };
|
||||
return { title: recipe ? formatMessage(m.cookingMode.pageTitle, { title: recipe.title }) : m.cookingMode.pageTitleFallback };
|
||||
}
|
||||
|
||||
export default async function CookPage({ params }: Params) {
|
||||
@@ -27,14 +30,18 @@ export default async function CookPage({ params }: Params) {
|
||||
|
||||
if (!recipe || recipe.steps.length === 0) notFound();
|
||||
|
||||
const unitPref = (session.user as { unitPref?: string }).unitPref === "imperial" ? "imperial" : "metric";
|
||||
|
||||
return (
|
||||
<CookingMode
|
||||
recipeId={id}
|
||||
recipeTitle={recipe.title}
|
||||
unitPref={unitPref}
|
||||
steps={recipe.steps.map((s) => ({
|
||||
id: s.id,
|
||||
instruction: s.instruction,
|
||||
timerSeconds: s.timerSeconds,
|
||||
appliesTo: recipe.isBatchCook ? s.appliesTo : undefined,
|
||||
}))}
|
||||
ingredients={recipe.ingredients.map((i) => ({
|
||||
rawName: i.rawName,
|
||||
|
||||
@@ -6,10 +6,11 @@ import { db, recipes } from "@epicure/db";
|
||||
import { and, eq } from "@epicure/db";
|
||||
import { RecipeForm } from "@/components/recipe/recipe-form";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export const metadata: Metadata = { title: "Edit Recipe" };
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function EditRecipePage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
@@ -22,19 +23,24 @@ export default async function EditRecipePage({ params }: Params) {
|
||||
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
steps: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
photos: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
batchDishes: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
},
|
||||
});
|
||||
|
||||
if (!recipe) notFound();
|
||||
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const defaultValues = {
|
||||
title: recipe.title,
|
||||
description: recipe.description ?? undefined,
|
||||
baseServings: recipe.baseServings,
|
||||
recipeType: recipe.recipeType,
|
||||
visibility: recipe.visibility,
|
||||
difficulty: recipe.difficulty,
|
||||
prepMins: recipe.prepMins,
|
||||
cookMins: recipe.cookMins,
|
||||
tags: recipe.tags ?? [],
|
||||
dietaryTags: (recipe.dietaryTags as Record<string, boolean | undefined>) ?? {},
|
||||
ingredients: recipe.ingredients.map((ing) => ({
|
||||
id: ing.id,
|
||||
@@ -43,22 +49,52 @@ export default async function EditRecipePage({ params }: Params) {
|
||||
unit: ing.unit ?? "",
|
||||
note: ing.note ?? "",
|
||||
})),
|
||||
steps: recipe.steps.map((step) => ({
|
||||
id: step.id,
|
||||
instruction: step.instruction,
|
||||
timerSeconds: step.timerSeconds ? String(step.timerSeconds) : "",
|
||||
})),
|
||||
steps: recipe.steps.map((step) => {
|
||||
// Show the largest unit that divides evenly into the stored seconds,
|
||||
// so editing a 90-minute braise shows "90 min" rather than "5400 sec".
|
||||
const seconds = step.timerSeconds ?? 0;
|
||||
const timer = seconds > 0 && seconds % 3600 === 0
|
||||
? { value: String(seconds / 3600), unit: "hours" as const }
|
||||
: seconds > 0 && seconds % 60 === 0
|
||||
? { value: String(seconds / 60), unit: "minutes" as const }
|
||||
: { value: seconds > 0 ? String(seconds) : "", unit: "seconds" as const };
|
||||
return {
|
||||
id: step.id,
|
||||
instruction: step.instruction,
|
||||
timerSeconds: timer.value,
|
||||
timerUnit: timer.unit,
|
||||
appliesTo: step.appliesTo ?? [],
|
||||
};
|
||||
}),
|
||||
photos: recipe.photos.map((photo) => ({
|
||||
key: photo.storageKey,
|
||||
isCover: photo.isCover,
|
||||
preview: getPublicUrl(photo.storageKey),
|
||||
sizeMb: photo.sizeMb,
|
||||
})),
|
||||
coverIcon: recipe.coverIcon,
|
||||
coverColor: recipe.coverColor,
|
||||
isBatchCook: recipe.isBatchCook,
|
||||
// Only pre-fill the manual-nutrition editor with existing values when
|
||||
// they were actually manually entered — AI-estimated data shouldn't
|
||||
// silently become "manual" just because the recipe happened to have
|
||||
// an estimate on file when it was opened for editing.
|
||||
nutrition: recipe.nutritionManual ? recipe.nutritionData?.perServing ?? null : null,
|
||||
dishes: recipe.batchDishes.map((dish) => ({
|
||||
id: dish.id,
|
||||
name: dish.name,
|
||||
description: dish.description ?? "",
|
||||
fridgeDays: String(dish.fridgeDays),
|
||||
freezerFriendly: dish.freezerFriendly,
|
||||
freezerNote: dish.freezerNote ?? "",
|
||||
dayOfInstructions: dish.dayOfInstructions,
|
||||
})),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Edit recipe</h1>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{m.recipes.editTitle}</h1>
|
||||
<p className="text-muted-foreground mt-1">{recipe.title}</p>
|
||||
</div>
|
||||
<RecipeForm recipeId={id} defaultValues={defaultValues} />
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ListRowSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function RecipeDetailLoading() {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto space-y-8">
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-9 w-2/3" />
|
||||
<div className="flex items-center gap-2">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-8 w-8 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
<Skeleton className="h-4 w-full max-w-lg" />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="aspect-video w-full rounded-xl" />
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-6 w-32" />
|
||||
<ListRowSkeleton />
|
||||
<ListRowSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { Metadata } from "next";
|
||||
import Image from "next/image";
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Clock, Users, Globe, Lock, Link2, Pencil, ChefHat, ExternalLink, Play } from "lucide-react";
|
||||
import { Clock, Users, Globe, Lock, Link2, Pencil, ChefHat, ExternalLink, Play, UserCheck } from "lucide-react";
|
||||
import { VariationsButton } from "@/components/recipe/variations-button";
|
||||
import { TranslateButton } from "@/components/recipe/translate-button";
|
||||
import { AddToShoppingListButton } from "@/components/recipe/add-to-shopping-list-button";
|
||||
@@ -10,90 +11,196 @@ import { MealPairingButton } from "@/components/recipe/meal-pairing-button";
|
||||
import { DrinkPairingButton } from "@/components/recipe/drink-pairing-button";
|
||||
import { AdaptRecipeButton } from "@/components/recipe/adapt-recipe-button";
|
||||
import { PrintButton } from "@/components/recipe/print-button";
|
||||
import { ShareRecipeButton } from "@/components/recipe/share-recipe-button";
|
||||
import { SaveOfflineButton } from "@/components/recipe/save-offline-button";
|
||||
import { VersionHistoryButton } from "@/components/recipe/version-history-button";
|
||||
import { DeleteRecipeButton } from "@/components/recipe/delete-recipe-button";
|
||||
import { ForkRecipeButton } from "@/components/recipe/fork-recipe-button";
|
||||
import { NutritionPanel } from "@/components/recipe/nutrition-panel";
|
||||
import { GenerateContentButton } from "@/components/recipe/generate-content-button";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, recipes, ratings, favorites, avg } from "@epicure/db";
|
||||
import { and, eq, count } from "@epicure/db";
|
||||
import { db, recipes, ratings, favorites, recipeVariations, recipeNotes, cookingHistory, avg } from "@epicure/db";
|
||||
import { and, eq, count, desc } from "@epicure/db";
|
||||
import { visibleToViewer } from "@/lib/visibility";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { ServingScaler } from "@/components/recipe/serving-scaler";
|
||||
import { FavoriteButton } from "@/components/social/favorite-button";
|
||||
import { RatingStars } from "@/components/social/rating-stars";
|
||||
import { CookedItReview } from "@/components/social/cooked-it-review";
|
||||
import { RecipeNotes } from "@/components/recipe/recipe-notes";
|
||||
import { CommentsSection } from "@/components/social/comments-section";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn, stripMarkdown } from "@/lib/utils";
|
||||
import { RecipeChatPanel } from "@/components/recipe/recipe-chat-panel";
|
||||
import { getFeaturePrefs } from "@/lib/feature-prefs";
|
||||
import { BatchCookSteps } from "@/components/recipe/batch-cook-steps";
|
||||
import { BatchCookDishes } from "@/components/recipe/batch-cook-dishes";
|
||||
import { KeepScreenAwake } from "@/components/recipe/keep-screen-awake";
|
||||
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
|
||||
import { recipeToMarkdown } from "@/lib/markdown/recipe";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
import { getFeatureFlagMatrix, type Tier } from "@/lib/feature-flags";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return { title: "Recipe" };
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, id),
|
||||
visibleToViewer(session.user.id)
|
||||
),
|
||||
});
|
||||
return { title: recipe?.title ?? "Recipe" };
|
||||
}
|
||||
|
||||
const VISIBILITY_LABEL = { private: "Private", unlisted: "Unlisted", public: "Public" };
|
||||
const VISIBILITY_ICON = { private: Lock, unlisted: Link2, public: Globe };
|
||||
const VISIBILITY_ICON = { private: Lock, unlisted: Link2, public: Globe, followers: UserCheck };
|
||||
const DIFFICULTY_COLOR = { easy: "default", medium: "secondary", hard: "destructive" } as const;
|
||||
|
||||
const DIETARY_LABELS: Record<string, string> = {
|
||||
vegan: "Vegan",
|
||||
vegetarian: "Vegetarian",
|
||||
glutenFree: "Gluten-free",
|
||||
dairyFree: "Dairy-free",
|
||||
nutFree: "Nut-free",
|
||||
halal: "Halal",
|
||||
kosher: "Kosher",
|
||||
};
|
||||
|
||||
export default async function RecipePage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const [recipe, ratingData, favoriteData] = await Promise.all([
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
const VISIBILITY_LABEL = m.recipe.visibility;
|
||||
const DIETARY_LABELS = m.recipe.dietary;
|
||||
const unitPref = (session.user as { unitPref?: string }).unitPref === "imperial" ? "imperial" : "metric";
|
||||
|
||||
const [recipe, ratingData, favoriteData, myRating, forkedFrom, myNote, dishCookLog, featureFlags, featurePrefs] = await Promise.all([
|
||||
db.query.recipes.findFirst({
|
||||
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
|
||||
where: and(
|
||||
eq(recipes.id, id),
|
||||
visibleToViewer(session.user.id)
|
||||
),
|
||||
with: {
|
||||
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
steps: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
photos: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
author: { columns: { id: true, name: true, username: true, avatarUrl: true } },
|
||||
batchDishes: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
},
|
||||
}),
|
||||
db.select({ avgScore: avg(ratings.score), total: count() }).from(ratings).where(eq(ratings.recipeId, id)),
|
||||
db.query.favorites.findFirst({ where: and(eq(favorites.userId, session.user.id), eq(favorites.recipeId, id)) }),
|
||||
db.query.ratings.findFirst({ where: and(eq(ratings.recipeId, id), eq(ratings.userId, session.user.id)) }),
|
||||
db.query.recipeVariations.findFirst({
|
||||
where: eq(recipeVariations.childRecipeId, id),
|
||||
with: { parent: { columns: { id: true, title: true } } },
|
||||
}),
|
||||
db.query.recipeNotes.findFirst({
|
||||
where: and(eq(recipeNotes.recipeId, id), eq(recipeNotes.userId, session.user.id)),
|
||||
columns: { content: true },
|
||||
}),
|
||||
db.query.cookingHistory.findMany({
|
||||
where: and(eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, session.user.id)),
|
||||
orderBy: desc(cookingHistory.cookedAt),
|
||||
columns: { batchDishId: true, cookedAt: true },
|
||||
}),
|
||||
getFeatureFlagMatrix(),
|
||||
getFeaturePrefs(session.user.id),
|
||||
]);
|
||||
|
||||
if (!recipe) notFound();
|
||||
|
||||
const viewerTier = (session.user as { tier?: string }).tier as Tier | undefined ?? "free";
|
||||
const locked = {
|
||||
variations: !featureFlags.recipe_variations[viewerTier],
|
||||
drinkPairing: !featureFlags.drink_pairing[viewerTier],
|
||||
mealPairing: !featureFlags.meal_pairing[viewerTier],
|
||||
};
|
||||
|
||||
const isOwner = recipe.authorId === session.user.id;
|
||||
|
||||
const dishCookedAtMap = new Map<string, string>();
|
||||
for (const log of dishCookLog) {
|
||||
if (log.batchDishId && !dishCookedAtMap.has(log.batchDishId)) {
|
||||
dishCookedAtMap.set(log.batchDishId, log.cookedAt.toISOString());
|
||||
}
|
||||
}
|
||||
|
||||
const avgScore = ratingData[0]?.avgScore ? parseFloat(ratingData[0].avgScore) : null;
|
||||
const ratingCount = ratingData[0]?.total ?? 0;
|
||||
const isFavorited = !!favoriteData;
|
||||
const myScore = myRating?.score ?? 0;
|
||||
|
||||
const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0];
|
||||
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
|
||||
const activeDietaryTags = Object.entries(recipe.dietaryTags ?? {})
|
||||
.filter(([, v]) => v)
|
||||
.map(([k]) => DIETARY_LABELS[k])
|
||||
.map(([k]) => DIETARY_LABELS[k as keyof typeof DIETARY_LABELS])
|
||||
.filter(Boolean);
|
||||
|
||||
const VisibilityIcon = VISIBILITY_ICON[recipe.visibility];
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto space-y-8">
|
||||
<div className="max-w-4xl mx-auto space-y-8 pb-20">
|
||||
{/* pb-20 keeps the last section (private notes' Save button) clear of
|
||||
the fixed recipe-chat button, which otherwise overlaps it on short
|
||||
pages — same fix as recipe-form.tsx's floating save bar. */}
|
||||
<KeepScreenAwake />
|
||||
{/* Header */}
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{recipe.title}</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{recipe.title}</h1>
|
||||
{recipe.isBatchCook && (
|
||||
<Badge variant="secondary" className="shrink-0">{m.recipe.batchCookBadge}</Badge>
|
||||
)}
|
||||
</div>
|
||||
{!isOwner && recipe.author.username && (
|
||||
<Link
|
||||
href={`/u/${recipe.author.username}`}
|
||||
className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Avatar className="h-6 w-6">
|
||||
{recipe.author.avatarUrl && <AvatarImage src={recipe.author.avatarUrl} alt={recipe.author.name} />}
|
||||
<AvatarFallback className="text-[10px]">{recipe.author.name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
{formatMessage(m.recipe.byAuthor, { name: recipe.author.name })}
|
||||
</Link>
|
||||
)}
|
||||
{forkedFrom && (
|
||||
<Link
|
||||
href={`/recipes/${forkedFrom.parent.id}`}
|
||||
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{formatMessage(m.recipe.forkedFrom, { title: forkedFrom.parent.title })}
|
||||
</Link>
|
||||
)}
|
||||
<TooltipProvider>
|
||||
<div className="flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
|
||||
{recipe.steps.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/recipes/${id}/cook`} className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}>
|
||||
<Play className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{m.recipe.cookAction}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<FavoriteButton recipeId={id} initialFavorited={isFavorited} />
|
||||
<MealPairingButton recipeId={id} />
|
||||
<DrinkPairingButton recipeId={id} />
|
||||
{!recipe.isBatchCook && recipe.recipeType !== "drink" && (
|
||||
<>
|
||||
<MealPairingButton recipeId={id} locked={locked.mealPairing} />
|
||||
<DrinkPairingButton recipeId={id} locked={locked.drinkPairing} />
|
||||
</>
|
||||
)}
|
||||
{recipe.visibility === "public" && (
|
||||
<Link href={`/r/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "sm" }))}>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Link>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/r/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{m.recipe.viewPublicly}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{recipe.ingredients.length > 0 && (
|
||||
<AddToShoppingListButton
|
||||
@@ -107,7 +214,9 @@ export default async function RecipePage({ params }: Params) {
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
<TranslateButton recipeId={id} />
|
||||
{isOwner && (!recipe.language || recipe.language !== (session.user as { locale?: string }).locale) && (
|
||||
<TranslateButton recipeId={id} />
|
||||
)}
|
||||
{recipe.ingredients.length > 0 && (
|
||||
<AdaptRecipeButton
|
||||
recipeId={id}
|
||||
@@ -132,21 +241,60 @@ export default async function RecipePage({ params }: Params) {
|
||||
timerSeconds: s.timerSeconds,
|
||||
order: s.order,
|
||||
}))}
|
||||
locked={locked.variations}
|
||||
/>
|
||||
{recipe.steps.length > 0 && (
|
||||
<Link href={`/recipes/${id}/cook`} className={cn(buttonVariants({ variant: "default", size: "sm" }))}>
|
||||
<Play className="h-4 w-4" />
|
||||
Cook
|
||||
</Link>
|
||||
)}
|
||||
<ForkRecipeButton recipeId={id} variant={isOwner ? "duplicate" : "fork"} />
|
||||
<ShareRecipeButton recipeId={id} visibility={recipe.visibility} />
|
||||
<SaveOfflineButton recipeId={id} recipeTitle={recipe.title} />
|
||||
<PrintButton recipeId={id} />
|
||||
<VersionHistoryButton recipeId={id} />
|
||||
<Link href={`/recipes/${id}/edit`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
Edit
|
||||
</Link>
|
||||
<DeleteRecipeButton recipeId={id} />
|
||||
<ExportMarkdownButton
|
||||
markdown={recipeToMarkdown({
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
baseServings: recipe.baseServings,
|
||||
prepMins: recipe.prepMins,
|
||||
cookMins: recipe.cookMins,
|
||||
difficulty: recipe.difficulty,
|
||||
sourceUrl: recipe.sourceUrl,
|
||||
ingredients: recipe.ingredients,
|
||||
steps: recipe.steps,
|
||||
isBatchCook: recipe.isBatchCook,
|
||||
batchDishes: recipe.batchDishes,
|
||||
})}
|
||||
filename={recipe.title}
|
||||
/>
|
||||
{isOwner && (
|
||||
<>
|
||||
<VersionHistoryButton
|
||||
recipeId={id}
|
||||
currentSnapshot={{
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
ingredients: recipe.ingredients.map((ing) => ({
|
||||
rawName: ing.rawName,
|
||||
quantity: ing.quantity,
|
||||
unit: ing.unit,
|
||||
note: ing.note,
|
||||
})),
|
||||
steps: recipe.steps.map((s) => ({
|
||||
instruction: s.instruction,
|
||||
timerSeconds: s.timerSeconds,
|
||||
})),
|
||||
}}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/recipes/${id}/edit`} className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{m.recipe.edit}</TooltipContent>
|
||||
</Tooltip>
|
||||
<DeleteRecipeButton recipeId={id} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
{avgScore !== null && (
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -156,31 +304,45 @@ export default async function RecipePage({ params }: Params) {
|
||||
)}
|
||||
|
||||
{recipe.description && (
|
||||
<p className="text-muted-foreground leading-relaxed">{recipe.description}</p>
|
||||
<p className="text-muted-foreground leading-relaxed">
|
||||
{recipe.isBatchCook ? stripMarkdown(recipe.description) : recipe.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{recipe.sourceUrl && (
|
||||
<a
|
||||
href={recipe.sourceUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground underline underline-offset-4"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
{m.recipe.source}: {new URL(recipe.sourceUrl).hostname.replace(/^www\./, "")}
|
||||
</a>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
{recipe.difficulty && (
|
||||
<Badge variant={DIFFICULTY_COLOR[recipe.difficulty]}>{recipe.difficulty}</Badge>
|
||||
<Badge variant={DIFFICULTY_COLOR[recipe.difficulty]}>{m.recipe.difficulty[recipe.difficulty]}</Badge>
|
||||
)}
|
||||
<span className="flex items-center gap-1 text-muted-foreground">
|
||||
<Users className="h-4 w-4" />
|
||||
{recipe.baseServings} servings
|
||||
{formatMessage(m.recipe.servings, { count: recipe.baseServings })}
|
||||
</span>
|
||||
{recipe.prepMins && (
|
||||
<span className="flex items-center gap-1 text-muted-foreground">
|
||||
<Clock className="h-4 w-4" />
|
||||
{recipe.prepMins}m prep
|
||||
{formatMessage(m.recipe.prep, { mins: recipe.prepMins })}
|
||||
</span>
|
||||
)}
|
||||
{recipe.cookMins && (
|
||||
<span className="flex items-center gap-1 text-muted-foreground">
|
||||
<ChefHat className="h-4 w-4" />
|
||||
{recipe.cookMins}m cook
|
||||
{formatMessage(m.recipe.cook, { mins: recipe.cookMins })}
|
||||
</span>
|
||||
)}
|
||||
{totalMins > 0 && recipe.prepMins && recipe.cookMins && (
|
||||
<span className="text-muted-foreground">({totalMins}m total)</span>
|
||||
<span className="text-muted-foreground">({formatMessage(m.recipe.total, { mins: totalMins })})</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1 text-muted-foreground ml-auto">
|
||||
<VisibilityIcon className="h-4 w-4" />
|
||||
@@ -195,28 +357,59 @@ export default async function RecipePage({ params }: Params) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recipe.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{recipe.tags.map((tag) => (
|
||||
<Badge key={tag} variant="outline" className="text-xs">{tag}</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Cover photo */}
|
||||
{cover && (
|
||||
<div className="aspect-video overflow-hidden rounded-xl bg-muted">
|
||||
<img
|
||||
<div className="relative aspect-video overflow-hidden rounded-xl bg-muted">
|
||||
<Image
|
||||
src={getPublicUrl(cover.storageKey)}
|
||||
unoptimized
|
||||
alt={recipe.title}
|
||||
className="w-full h-full object-cover"
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Empty state */}
|
||||
{recipe.ingredients.length === 0 && recipe.steps.length === 0 && (
|
||||
<div className="flex flex-col items-center gap-4 py-12 text-center">
|
||||
<p className="text-muted-foreground">No ingredients or steps yet.</p>
|
||||
{isOwner && (
|
||||
<div className="flex items-center gap-2">
|
||||
<GenerateContentButton
|
||||
recipeId={id}
|
||||
title={recipe.title}
|
||||
description={recipe.description}
|
||||
/>
|
||||
<Link href={`/recipes/${id}/edit`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
Edit manually
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Serving scaler + ingredients */}
|
||||
{recipe.ingredients.length > 0 && (
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-xl font-semibold">Ingredients</h2>
|
||||
<h2 className="text-xl font-semibold">{m.recipe.ingredients}</h2>
|
||||
<ServingScaler
|
||||
baseServings={recipe.baseServings}
|
||||
recipeTitle={recipe.title}
|
||||
unitPref={unitPref}
|
||||
ingredients={recipe.ingredients.map((ing) => ({
|
||||
id: ing.id,
|
||||
rawName: ing.rawName,
|
||||
@@ -226,7 +419,7 @@ export default async function RecipePage({ params }: Params) {
|
||||
order: ing.order,
|
||||
}))}
|
||||
/>
|
||||
<NutritionPanel recipeId={id} initialData={recipe.nutritionData} />
|
||||
<NutritionPanel recipeId={id} initialData={recipe.nutritionData} initialManual={recipe.nutritionManual} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -234,40 +427,60 @@ export default async function RecipePage({ params }: Params) {
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-6">
|
||||
<h2 className="text-xl font-semibold">Instructions</h2>
|
||||
<ol className="space-y-6">
|
||||
{recipe.steps.map((step, i) => (
|
||||
<li key={step.id} className="flex gap-4">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">
|
||||
{i + 1}
|
||||
</div>
|
||||
<div className="flex-1 space-y-1 pt-1">
|
||||
<p className="leading-relaxed">{step.instruction}</p>
|
||||
{step.timerSeconds && (
|
||||
<p className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{step.timerSeconds >= 60
|
||||
? `${Math.floor(step.timerSeconds / 60)}m ${step.timerSeconds % 60 > 0 ? `${step.timerSeconds % 60}s` : ""}`
|
||||
: `${step.timerSeconds}s`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<h2 className="text-xl font-semibold">{m.recipe.instructions}</h2>
|
||||
{recipe.isBatchCook ? (
|
||||
<BatchCookSteps steps={recipe.steps} />
|
||||
) : (
|
||||
<ol className="space-y-6">
|
||||
{recipe.steps.map((step, i) => (
|
||||
<li key={step.id} className="flex gap-4">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">
|
||||
{i + 1}
|
||||
</div>
|
||||
<div className="flex-1 space-y-1 pt-1">
|
||||
<p className="leading-relaxed">{step.instruction}</p>
|
||||
{!!step.timerSeconds && (
|
||||
<p className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{step.timerSeconds >= 60
|
||||
? `${Math.floor(step.timerSeconds / 60)}m ${step.timerSeconds % 60 > 0 ? `${step.timerSeconds % 60}s` : ""}`
|
||||
: `${step.timerSeconds}s`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{recipe.isBatchCook && recipe.batchDishes.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<BatchCookDishes
|
||||
recipeId={id}
|
||||
dishes={recipe.batchDishes.map((d) => ({ ...d, cookedAt: dishCookedAtMap.get(d.id) ?? null }))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{recipe.photos.length > 1 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">Photos</h2>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{recipe.photos.map((photo) => (
|
||||
<div key={photo.id} className="aspect-square rounded-lg overflow-hidden bg-muted">
|
||||
<img src={getPublicUrl(photo.storageKey)} alt="" className="w-full h-full object-cover" />
|
||||
{recipe.photos.map((photo, i) => (
|
||||
<div key={photo.id} className="relative aspect-square rounded-lg overflow-hidden bg-muted">
|
||||
<Image
|
||||
src={getPublicUrl(photo.storageKey)}
|
||||
unoptimized
|
||||
alt={`${recipe.title} photo ${i + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -279,12 +492,26 @@ export default async function RecipePage({ params }: Params) {
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-4">
|
||||
<RatingStars recipeId={id} initialScore={0} />
|
||||
{isOwner ? (
|
||||
<RatingStars recipeId={id} initialScore={myScore} readonly />
|
||||
) : (
|
||||
<CookedItReview
|
||||
recipeId={id}
|
||||
initialScore={myScore}
|
||||
initialText={myRating?.reviewText ?? ""}
|
||||
initialPhotoKey={myRating?.photoKey ?? null}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
<CommentsSection recipeId={id} currentUserId={session.user.id} />
|
||||
</>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
<RecipeNotes recipeId={id} initialContent={myNote?.content ?? ""} />
|
||||
|
||||
{featurePrefs.chatbots && <RecipeChatPanel recipeId={id} recipeTitle={recipe.title} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, recipes, eq, and } from "@epicure/db";
|
||||
import { PrintTrigger } from "@/components/recipe/print-trigger";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export default async function RecipePrintPage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
|
||||
with: {
|
||||
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
steps: { orderBy: (t, { asc }) => asc(t.order) },
|
||||
},
|
||||
});
|
||||
|
||||
if (!recipe) notFound();
|
||||
|
||||
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
|
||||
|
||||
const DIETARY_LABELS: Record<string, string> = {
|
||||
vegan: "Vegan",
|
||||
vegetarian: "Vegetarian",
|
||||
glutenFree: "Gluten-free",
|
||||
dairyFree: "Dairy-free",
|
||||
nutFree: "Nut-free",
|
||||
halal: "Halal",
|
||||
kosher: "Kosher",
|
||||
};
|
||||
|
||||
const activeTags = Object.entries(recipe.dietaryTags ?? {})
|
||||
.filter(([, v]) => v)
|
||||
.map(([k]) => DIETARY_LABELS[k])
|
||||
.filter(Boolean);
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
@media print {
|
||||
body { margin: 0; }
|
||||
.no-print { display: none !important; }
|
||||
}
|
||||
body {
|
||||
font-family: Georgia, 'Times New Roman', serif;
|
||||
color: #1a1a1a;
|
||||
max-width: 680px;
|
||||
margin: 40px auto;
|
||||
padding: 0 24px;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
h1 { font-size: 2em; margin: 0 0 8px; line-height: 1.2; }
|
||||
h2 { font-size: 1.1em; text-transform: uppercase; letter-spacing: 0.08em; border-bottom: 1px solid #ccc; padding-bottom: 4px; margin: 24px 0 12px; }
|
||||
.meta { display: flex; gap: 24px; font-size: 0.85em; color: #555; margin: 12px 0 16px; flex-wrap: wrap; }
|
||||
.meta span { display: flex; align-items: center; gap: 4px; }
|
||||
.tags { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 16px; }
|
||||
.tag { border: 1px solid #ccc; border-radius: 4px; padding: 1px 8px; font-size: 0.8em; font-family: system-ui, sans-serif; }
|
||||
.description { color: #444; font-style: italic; margin-bottom: 16px; }
|
||||
ul.ingredients { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 4px 24px; }
|
||||
ul.ingredients li { padding: 4px 0; border-bottom: 1px dotted #e0e0e0; font-family: system-ui, sans-serif; font-size: 0.9em; }
|
||||
ul.ingredients li .qty { color: #666; min-width: 60px; display: inline-block; }
|
||||
ol.steps { padding-left: 20px; margin: 0; }
|
||||
ol.steps li { padding: 6px 0 6px 4px; border-bottom: 1px dotted #e0e0e0; font-size: 0.95em; }
|
||||
ol.steps li:last-child { border-bottom: none; }
|
||||
.timer { font-size: 0.85em; color: #666; font-family: system-ui, sans-serif; margin-left: 8px; }
|
||||
footer { margin-top: 40px; font-size: 0.75em; color: #aaa; text-align: center; font-family: system-ui, sans-serif; }
|
||||
.print-btn {
|
||||
position: fixed; top: 16px; right: 16px; padding: 8px 16px;
|
||||
background: #18181b; color: white; border: none; border-radius: 6px;
|
||||
cursor: pointer; font-size: 13px; font-family: system-ui, sans-serif;
|
||||
}
|
||||
.print-btn:hover { background: #3f3f46; }
|
||||
`}</style>
|
||||
|
||||
<PrintTrigger />
|
||||
|
||||
<article>
|
||||
<h1>{recipe.title}</h1>
|
||||
|
||||
{recipe.description && (
|
||||
<p className="description">{recipe.description}</p>
|
||||
)}
|
||||
|
||||
<div className="meta">
|
||||
{recipe.baseServings && <span>Serves {recipe.baseServings}</span>}
|
||||
{recipe.prepMins && <span>Prep {recipe.prepMins} min</span>}
|
||||
{recipe.cookMins && <span>Cook {recipe.cookMins} min</span>}
|
||||
{totalMins > 0 && <span>Total {totalMins} min</span>}
|
||||
{recipe.difficulty && <span>{recipe.difficulty.charAt(0).toUpperCase() + recipe.difficulty.slice(1)}</span>}
|
||||
</div>
|
||||
|
||||
{activeTags.length > 0 && (
|
||||
<div className="tags">
|
||||
{activeTags.map((tag) => (
|
||||
<span key={tag} className="tag">{tag}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recipe.ingredients.length > 0 && (
|
||||
<>
|
||||
<h2>Ingredients</h2>
|
||||
<ul className="ingredients">
|
||||
{recipe.ingredients.map((ing) => (
|
||||
<li key={ing.id}>
|
||||
<span className="qty">
|
||||
{[ing.quantity, ing.unit].filter(Boolean).join(" ")}
|
||||
</span>
|
||||
{ing.rawName}
|
||||
{ing.note && <span style={{ color: "#888" }}> ({ing.note})</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
|
||||
{recipe.steps.length > 0 && (
|
||||
<>
|
||||
<h2>Instructions</h2>
|
||||
<ol className="steps">
|
||||
{recipe.steps.map((step) => (
|
||||
<li key={step.id}>
|
||||
{step.instruction}
|
||||
{step.timerSeconds && (
|
||||
<span className="timer">⏱ {Math.floor(step.timerSeconds / 60)} min</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
|
||||
<footer>Printed from Epicure</footer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -5,8 +5,9 @@ import { db, recipes, pantryItems } from "@epicure/db";
|
||||
import { eq } from "@epicure/db";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { CanCookContent } from "@/components/recipe/can-cook-content";
|
||||
import { scoreRecipesAgainstPantry } from "@/lib/pantry-match";
|
||||
|
||||
export const metadata: Metadata = { title: "What can I cook?" };
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function CanCookPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
@@ -25,34 +26,18 @@ export default async function CanCookPage() {
|
||||
}),
|
||||
]);
|
||||
|
||||
const pantryKeys = new Set(pantry.map((p) => p.rawName.toLowerCase()));
|
||||
|
||||
const scored = userRecipes
|
||||
.filter((r) => r.ingredients.length > 0)
|
||||
.map((recipe) => {
|
||||
const matched = recipe.ingredients.filter((ing) =>
|
||||
pantryKeys.has(ing.rawName.toLowerCase())
|
||||
).length;
|
||||
const missing = recipe.ingredients
|
||||
.filter((ing) => !pantryKeys.has(ing.rawName.toLowerCase()))
|
||||
.map((ing) => ing.rawName)
|
||||
.slice(0, 5);
|
||||
const total = recipe.ingredients.length;
|
||||
const cover = recipe.photos?.find((p) => p.isCover) ?? recipe.photos?.[0];
|
||||
return {
|
||||
recipe: {
|
||||
id: recipe.id,
|
||||
title: recipe.title,
|
||||
description: recipe.description,
|
||||
photos: cover ? [{ url: getPublicUrl(cover.storageKey) }] : [],
|
||||
},
|
||||
matched,
|
||||
total,
|
||||
pct: Math.round((matched / total) * 100),
|
||||
missing,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.pct - a.pct);
|
||||
const scored = scoreRecipesAgainstPantry(userRecipes, pantry).map((s) => {
|
||||
const cover = s.recipe.photos?.find((p) => p.isCover) ?? s.recipe.photos?.[0];
|
||||
return {
|
||||
...s,
|
||||
recipe: {
|
||||
id: s.recipe.id,
|
||||
title: s.recipe.title,
|
||||
description: s.recipe.description,
|
||||
photos: cover ? [{ url: getPublicUrl(cover.storageKey) }] : [],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return <CanCookContent pantryCount={pantry.length} scored={scored} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, favorites, recipes, recipePhotos, users, eq, and, or, ne, desc, inArray, count } from "@epicure/db";
|
||||
import { FavoritesGrid } from "@/components/recipe/favorites-grid";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
export default async function FavoriteRecipesPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const { page: pageParam } = await searchParams;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
|
||||
// A previously-favorited recipe stays visible to the person who favorited it even if
|
||||
// the author later makes their account/recipe private — same "existing access isn't
|
||||
// revoked, only new discovery is" rule as the private-accounts feature.
|
||||
const where = and(
|
||||
eq(favorites.userId, session.user.id),
|
||||
or(ne(recipes.visibility, "private"), eq(recipes.authorId, session.user.id))
|
||||
);
|
||||
|
||||
const [rows, totalRow] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
difficulty: recipes.difficulty,
|
||||
prepMins: recipes.prepMins,
|
||||
cookMins: recipes.cookMins,
|
||||
authorId: recipes.authorId,
|
||||
authorName: users.name,
|
||||
})
|
||||
.from(favorites)
|
||||
.innerJoin(recipes, eq(favorites.recipeId, recipes.id))
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.where(where)
|
||||
.orderBy(desc(favorites.createdAt))
|
||||
.limit(PAGE_SIZE)
|
||||
.offset(offset),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(favorites)
|
||||
.innerJoin(recipes, eq(favorites.recipeId, recipes.id))
|
||||
.where(where),
|
||||
]);
|
||||
|
||||
const recipeIds = rows.map((r) => r.id);
|
||||
const photos = recipeIds.length > 0
|
||||
? await db
|
||||
.select({ recipeId: recipePhotos.recipeId, storageKey: recipePhotos.storageKey, isCover: recipePhotos.isCover })
|
||||
.from(recipePhotos)
|
||||
.where(inArray(recipePhotos.recipeId, recipeIds))
|
||||
: [];
|
||||
const coverByRecipe = new Map<string, string>();
|
||||
for (const p of photos) {
|
||||
if (!coverByRecipe.has(p.recipeId) || p.isCover) coverByRecipe.set(p.recipeId, p.storageKey);
|
||||
}
|
||||
|
||||
const total = totalRow[0]?.total ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
|
||||
const favoriteRecipes = rows.map((r) => ({
|
||||
id: r.id,
|
||||
title: r.title,
|
||||
difficulty: r.difficulty,
|
||||
prepMins: r.prepMins,
|
||||
cookMins: r.cookMins,
|
||||
authorName: r.authorId === session.user.id ? null : r.authorName,
|
||||
coverPhotoKey: coverByRecipe.get(r.id) ?? null,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Link href="/recipes" className="rounded-full px-3 py-1 text-muted-foreground hover:bg-accent">
|
||||
{m.recipes.tabMine}
|
||||
</Link>
|
||||
<span className="rounded-full bg-accent px-3 py-1 font-medium">{m.recipes.tabFavorites}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{m.recipes.tabFavorites}</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{formatMessage(total === 1 ? m.recipes.favoritesCount : m.recipes.favoritesCountPlural, { count: total })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FavoritesGrid initialRecipes={favoriteRecipes} emptyTitle={m.recipes.favoritesEmptyTitle} emptyDescription={m.recipes.favoritesEmpty} />
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2">
|
||||
{page > 1 && (
|
||||
<Link href={`/recipes/favorites?page=${page - 1}`} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
|
||||
Previous
|
||||
</Link>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground px-2">
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
{page < totalPages && (
|
||||
<Link href={`/recipes/favorites?page=${page + 1}`} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
|
||||
Next
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { PageHeaderSkeleton, RecipeCardGridSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function RecipesLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeaderSkeleton actions={2} subtitle />
|
||||
<RecipeCardGridSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { RecipeForm } from "@/components/recipe/recipe-form";
|
||||
import { NewRecipeHeader } from "@/components/recipe/new-recipe-header";
|
||||
import { PhotoImportButton } from "@/components/recipe/photo-import-button";
|
||||
|
||||
export const metadata: Metadata = { title: "New Recipe" };
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default function NewRecipePage() {
|
||||
return (
|
||||
|
||||
@@ -1,48 +1,187 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, recipes, recipeIngredients } from "@epicure/db";
|
||||
import { eq, desc, and, ilike, or, sql } from "@epicure/db";
|
||||
import { db, recipes, favorites, sql, count } from "@epicure/db";
|
||||
import { eq, desc, asc, and, ilike, or, inArray } from "@epicure/db";
|
||||
import { RecipesHeader } from "@/components/recipe/recipes-header";
|
||||
import { RecipesEmptyState } from "@/components/recipe/recipes-empty-state";
|
||||
import { RecipesGrid } from "@/components/recipe/recipes-grid";
|
||||
import { CookingAssistantPanel } from "@/components/recipe/cooking-assistant-panel";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { getFeaturePrefs } from "@/lib/feature-prefs";
|
||||
|
||||
export const metadata: Metadata = { title: "Recipes" };
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
type SearchParams = Promise<{ q?: string }>;
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
type SearchParams = Promise<{
|
||||
q?: string;
|
||||
sort?: string;
|
||||
visibility?: string;
|
||||
difficulty?: string;
|
||||
tag?: string;
|
||||
page?: string;
|
||||
batchCook?: string;
|
||||
recipeType?: string;
|
||||
// OS Share Target params (manifest.ts's share_target) — a browser share
|
||||
// sheet navigates here with these appended.
|
||||
url?: string;
|
||||
text?: string;
|
||||
title?: string;
|
||||
}>;
|
||||
|
||||
const URL_PATTERN = /https?:\/\/\S+/;
|
||||
|
||||
/** Web Share Target's GET params vary by sender: some apps put the shared
|
||||
* link in `url`, others (notably many Android apps) put it inside `text`
|
||||
* alongside other text. Prefer `url`, fall back to extracting the first
|
||||
* http(s) URL out of `text`. */
|
||||
function extractSharedUrl(params: { url?: string; text?: string }): string | undefined {
|
||||
if (params.url && URL_PATTERN.test(params.url)) return params.url;
|
||||
const match = params.text?.match(URL_PATTERN);
|
||||
return match?.[0];
|
||||
}
|
||||
|
||||
const SORT_MAP = {
|
||||
updated_desc: desc(recipes.updatedAt),
|
||||
updated_asc: asc(recipes.updatedAt),
|
||||
created_desc: desc(recipes.createdAt),
|
||||
created_asc: asc(recipes.createdAt),
|
||||
title_asc: asc(recipes.title),
|
||||
title_desc: desc(recipes.title),
|
||||
} as const;
|
||||
|
||||
type SortKey = keyof typeof SORT_MAP;
|
||||
|
||||
export default async function RecipesPage({ searchParams }: { searchParams: SearchParams }) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
const featurePrefs = await getFeaturePrefs(session.user.id);
|
||||
|
||||
const { q } = await searchParams;
|
||||
const query = q?.trim() ?? "";
|
||||
const { q, sort, visibility, difficulty, tag, page: pageParam, batchCook, recipeType, url, text } = await searchParams;
|
||||
const sharedUrl = extractSharedUrl({ url, text });
|
||||
const query = (q ?? "").trim().slice(0, 200);
|
||||
const sortKey: SortKey = (sort && sort in SORT_MAP ? sort : "updated_desc") as SortKey;
|
||||
const tagFilter = tag?.trim().slice(0, 50) || undefined;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
|
||||
const whereClause = query
|
||||
? and(
|
||||
eq(recipes.authorId, session.user.id),
|
||||
or(
|
||||
ilike(recipes.title, `%${query}%`),
|
||||
ilike(recipes.description, `%${query}%`)
|
||||
const visibilityFilter = visibility && ["private", "unlisted", "public", "followers"].includes(visibility)
|
||||
? (visibility as "private" | "unlisted" | "public" | "followers")
|
||||
: undefined;
|
||||
const difficultyFilter = difficulty && ["easy", "medium", "hard"].includes(difficulty)
|
||||
? (difficulty as "easy" | "medium" | "hard")
|
||||
: undefined;
|
||||
const batchCookFilter = batchCook === "1" || batchCook === "0" ? batchCook : undefined;
|
||||
const recipeTypeFilter = recipeType === "dish" || recipeType === "drink" ? recipeType : undefined;
|
||||
|
||||
// Escape ilike wildcard chars (% and _) so a search like "100%" matches literally.
|
||||
const escapedQuery = query.replace(/[\\%_]/g, (c) => `\\${c}`);
|
||||
|
||||
const where = and(
|
||||
eq(recipes.authorId, session.user.id),
|
||||
batchCookFilter ? eq(recipes.isBatchCook, batchCookFilter === "1") : undefined,
|
||||
query
|
||||
? or(
|
||||
ilike(recipes.title, `%${escapedQuery}%`),
|
||||
ilike(recipes.description, `%${escapedQuery}%`),
|
||||
// Plain SQL identifiers rather than drizzle's column proxies —
|
||||
// inside db.query.recipes.findMany's `where`, the relational query
|
||||
// builder rewrites embedded column refs to the outer query's own
|
||||
// table alias regardless of which table they actually belong to,
|
||||
// producing broken SQL (recipes.raw_name doesn't exist). Using
|
||||
// literal identifiers for the ingredients subquery sidesteps that.
|
||||
sql`exists (select 1 from recipe_ingredients ri where ri.recipe_id = ${recipes.id} and ri.raw_name ilike ${`%${escapedQuery}%`})`,
|
||||
sql`exists (select 1 from unnest(${recipes.tags}) as tag where tag ilike ${`%${escapedQuery}%`})`
|
||||
)
|
||||
)
|
||||
: eq(recipes.authorId, session.user.id);
|
||||
: undefined,
|
||||
visibilityFilter ? eq(recipes.visibility, visibilityFilter) : undefined,
|
||||
difficultyFilter ? eq(recipes.difficulty, difficultyFilter) : undefined,
|
||||
tagFilter ? sql`${recipes.tags} @> ARRAY[${tagFilter}]::text[]` : undefined,
|
||||
recipeTypeFilter ? eq(recipes.recipeType, recipeTypeFilter) : undefined,
|
||||
);
|
||||
|
||||
const userRecipes = await db.query.recipes.findMany({
|
||||
where: whereClause,
|
||||
orderBy: desc(recipes.updatedAt),
|
||||
with: { photos: true },
|
||||
});
|
||||
const [userRecipes, totalRow] = await Promise.all([
|
||||
db.query.recipes.findMany({
|
||||
where,
|
||||
orderBy: SORT_MAP[sortKey],
|
||||
with: { photos: true, batchDishes: { columns: { id: true } } },
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
}),
|
||||
db.select({ count: count() }).from(recipes).where(where),
|
||||
]);
|
||||
|
||||
const totalCount = query ? undefined : userRecipes.length;
|
||||
const total = totalRow[0]?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
|
||||
const recipeIds = userRecipes.map((r) => r.id);
|
||||
const favoritedRows = recipeIds.length > 0
|
||||
? await db
|
||||
.select({ recipeId: favorites.recipeId })
|
||||
.from(favorites)
|
||||
.where(and(eq(favorites.userId, session.user.id), inArray(favorites.recipeId, recipeIds)))
|
||||
: [];
|
||||
const favoritedIds = new Set(favoritedRows.map((r) => r.recipeId));
|
||||
const recipesWithFavorites = userRecipes.map((r) => ({ ...r, isFavorited: favoritedIds.has(r.id), dishCount: r.batchDishes.length }));
|
||||
|
||||
const pageHref = (p: number) => {
|
||||
const params = new URLSearchParams();
|
||||
if (query) params.set("q", query);
|
||||
if (sortKey !== "updated_desc") params.set("sort", sortKey);
|
||||
if (visibilityFilter) params.set("visibility", visibilityFilter);
|
||||
if (difficultyFilter) params.set("difficulty", difficultyFilter);
|
||||
if (tagFilter) params.set("tag", tagFilter);
|
||||
if (batchCookFilter) params.set("batchCook", batchCookFilter);
|
||||
if (recipeTypeFilter) params.set("recipeType", recipeTypeFilter);
|
||||
if (p > 1) params.set("page", String(p));
|
||||
const qs = params.toString();
|
||||
return qs ? `/recipes?${qs}` : "/recipes";
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<RecipesHeader count={totalCount ?? userRecipes.length} initialQuery={query} />
|
||||
<div className="space-y-4 sm:space-y-6">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="rounded-full bg-accent px-3 py-1 font-medium">{m.recipes.tabMine}</span>
|
||||
<Link href="/recipes/favorites" className="rounded-full px-3 py-1 text-muted-foreground hover:bg-accent">
|
||||
{m.recipes.tabFavorites}
|
||||
</Link>
|
||||
</div>
|
||||
<RecipesHeader
|
||||
count={total}
|
||||
initialQuery={query}
|
||||
initialSort={sortKey}
|
||||
initialVisibility={visibilityFilter ?? ""}
|
||||
initialDifficulty={difficultyFilter ?? ""}
|
||||
initialTag={tagFilter ?? ""}
|
||||
initialBatchCook={batchCookFilter ?? ""}
|
||||
initialRecipeType={recipeTypeFilter ?? ""}
|
||||
sharedUrl={sharedUrl}
|
||||
/>
|
||||
<RecipesEmptyState query={query} count={total} />
|
||||
<RecipesGrid key={`${query}-${sortKey}-${visibilityFilter}-${difficultyFilter}-${tagFilter}-${batchCookFilter}-${recipeTypeFilter}-${page}`} recipes={recipesWithFavorites} />
|
||||
|
||||
<RecipesEmptyState query={query} count={userRecipes.length} />
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2">
|
||||
{page > 1 && (
|
||||
<Link href={pageHref(page - 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
|
||||
Previous
|
||||
</Link>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground px-2">
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
{page < totalPages && (
|
||||
<Link href={pageHref(page + 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
|
||||
Next
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<RecipesGrid recipes={userRecipes} />
|
||||
{featurePrefs.chatbots && <CookingAssistantPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { InfoCardSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function SearchLoading() {
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto space-y-6">
|
||||
<div>
|
||||
<Skeleton className="h-9 w-56 mb-6" />
|
||||
<Skeleton className="h-12 w-full rounded-md" />
|
||||
<div className="mt-3 flex flex-wrap items-center gap-3">
|
||||
<Skeleton className="h-9 w-40" />
|
||||
<Skeleton className="h-9 w-36" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 8 }).map((_, i) => (
|
||||
<InfoCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { SearchPageContent } from "@/components/search/search-page-content";
|
||||
|
||||
type Params = { searchParams: Promise<{ q?: string; difficulty?: string; dietary?: string }> };
|
||||
|
||||
export default async function SearchPage({ searchParams }: Params) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const { q } = await searchParams;
|
||||
return <SearchPageContent initialQuery={q ?? ""} />;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, userAiKeys, userModelPrefs, users, tierDefinitions, userUsage, eq, and } from "@epicure/db";
|
||||
import { UNLIMITED, getRecipeCount, getStorageUsedMb } from "@/lib/tiers";
|
||||
import { ByokManager } from "@/components/settings/byok-manager";
|
||||
import { ModelPrefsForm } from "@/components/settings/model-prefs-form";
|
||||
import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
|
||||
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AiSettingsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const currentMonth = new Date().toISOString().slice(0, 7);
|
||||
|
||||
const [aiKeys, modelPrefs, dbUser] = await Promise.all([
|
||||
db.query.userAiKeys.findMany({
|
||||
where: eq(userAiKeys.userId, session.user.id),
|
||||
columns: { provider: true },
|
||||
}),
|
||||
db.query.userModelPrefs.findFirst({
|
||||
where: eq(userModelPrefs.userId, session.user.id),
|
||||
}),
|
||||
// Tier comes from the DB, not the (up to 5-minute-stale) session cookie
|
||||
// cache, so a just-changed tier's limits show up immediately here.
|
||||
db.query.users.findFirst({ where: eq(users.id, session.user.id), columns: { tier: true, isByokEnabled: true } }),
|
||||
]);
|
||||
|
||||
const [tierDef, usage, recipeCount, storageUsedMb] = await Promise.all([
|
||||
db.query.tierDefinitions.findFirst({ where: eq(tierDefinitions.tier, dbUser?.tier ?? "free") }),
|
||||
db.query.userUsage.findFirst({ where: and(eq(userUsage.userId, session.user.id), eq(userUsage.month, currentMonth)) }),
|
||||
getRecipeCount(session.user.id),
|
||||
getStorageUsedMb(session.user.id),
|
||||
]);
|
||||
|
||||
const asLimit = (n: number | undefined) => (n === undefined || n === UNLIMITED ? null : n);
|
||||
|
||||
const usageMetrics = [
|
||||
{
|
||||
label: m.settings.usage.aiCalls,
|
||||
used: usage?.aiCallsUsed ?? 0,
|
||||
limit: asLimit(tierDef?.aiCallsPerMonth),
|
||||
unlimitedLabel: m.settings.usage.unlimited,
|
||||
},
|
||||
{
|
||||
label: m.settings.usage.recipes,
|
||||
used: recipeCount,
|
||||
limit: asLimit(tierDef?.maxRecipes),
|
||||
unlimitedLabel: m.settings.usage.unlimited,
|
||||
},
|
||||
{
|
||||
label: m.settings.usage.storage,
|
||||
used: storageUsedMb,
|
||||
limit: asLimit(tierDef?.storageMb),
|
||||
unit: " MB",
|
||||
unlimitedLabel: m.settings.usage.unlimited,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.usage.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{formatMessage(m.settings.usage.description, { month: currentMonth })}
|
||||
</p>
|
||||
</div>
|
||||
<UsageQuotaSection metrics={usageMetrics} />
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.byok.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settings.byok.description}
|
||||
</p>
|
||||
</div>
|
||||
{dbUser?.isByokEnabled ? (
|
||||
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
|
||||
) : (
|
||||
<DeveloperLockedNotice message={m.settings.byokLockedNotice} />
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.modelPrefs.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settings.modelPrefs.description}
|
||||
</p>
|
||||
</div>
|
||||
<ModelPrefsForm initialPrefs={modelPrefs ?? null} />
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, apiKeys, users, eq } from "@epicure/db";
|
||||
import { ApiKeysManager } from "@/components/settings/api-keys-manager";
|
||||
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||
import { DeveloperAccessToggle } from "@/components/settings/developer-access-toggle";
|
||||
import { DisableDeveloperAccessButton } from "@/components/settings/disable-developer-access-button";
|
||||
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function ApiKeysPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const dbUser = (await db.select({ isDeveloper: users.isDeveloper, tier: users.tier }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
||||
|
||||
const keys = dbUser?.isDeveloper
|
||||
? await db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
scope: apiKeys.scope,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
})
|
||||
.from(apiKeys)
|
||||
.where(eq(apiKeys.userId, session.user.id))
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.apiKeysPage.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settings.apiKeysPage.description}
|
||||
</p>
|
||||
<Link
|
||||
href="/docs"
|
||||
target="_blank"
|
||||
className="inline-flex items-center gap-1 text-sm text-primary hover:underline mt-2"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
{m.settings.apiKeysPage.docsLink}
|
||||
</Link>
|
||||
</div>
|
||||
{!dbUser?.isDeveloper && dbUser && canSelfServeDeveloperAccess(dbUser) && (
|
||||
<DeveloperAccessToggle message={m.settings.developerSelfServeNotice} />
|
||||
)}
|
||||
{!dbUser?.isDeveloper && (!dbUser || !canSelfServeDeveloperAccess(dbUser)) && (
|
||||
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
|
||||
)}
|
||||
{dbUser?.isDeveloper && (
|
||||
<>
|
||||
<ApiKeysManager
|
||||
initialKeys={keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name,
|
||||
scope: k.scope,
|
||||
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
<DisableDeveloperAccessButton />
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, users, tierDefinitions, tierEnum, userUsage, eq, and } from "@epicure/db";
|
||||
import { getRecipeCount, getStorageUsedMb, UNLIMITED } from "@/lib/tiers";
|
||||
import { BillingPlanCards } from "@/components/settings/billing-plan-cards";
|
||||
import { ManageBillingButton } from "@/components/settings/manage-billing-button";
|
||||
import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const TIER_NAMES: Record<string, string> = { free: "Free", pro: "Pro", family: "Family" };
|
||||
|
||||
function describeLimit(n: number, unit: string): string {
|
||||
return n === UNLIMITED ? `Unlimited ${unit}` : `${n} ${unit}`;
|
||||
}
|
||||
|
||||
export default async function BillingPage({ searchParams }: { searchParams: Promise<{ checkout?: string }> }) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const { checkout } = await searchParams;
|
||||
|
||||
const currentMonth = new Date().toISOString().slice(0, 7);
|
||||
|
||||
const [dbUser, allTierDefs, usage, recipeCount, storageUsedMb] = await Promise.all([
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, session.user.id),
|
||||
columns: { tier: true, subscriptionStatus: true, currentPeriodEnd: true, stripeCustomerId: true },
|
||||
}),
|
||||
db.select().from(tierDefinitions),
|
||||
db.query.userUsage.findFirst({ where: and(eq(userUsage.userId, session.user.id), eq(userUsage.month, currentMonth)) }),
|
||||
getRecipeCount(session.user.id),
|
||||
getStorageUsedMb(session.user.id),
|
||||
]);
|
||||
|
||||
const currentTier = dbUser?.tier ?? "free";
|
||||
const currentTierDef = allTierDefs.find((t) => t.tier === currentTier);
|
||||
|
||||
const asLimit = (n: number | undefined) => (n === undefined || n === UNLIMITED ? null : n);
|
||||
const usageMetrics = [
|
||||
{ label: "AI calls", used: usage?.aiCallsUsed ?? 0, limit: asLimit(currentTierDef?.aiCallsPerMonth), unlimitedLabel: "Unlimited" },
|
||||
{ label: "Recipes created", used: recipeCount, limit: asLimit(currentTierDef?.maxRecipes), unlimitedLabel: "Unlimited" },
|
||||
{ label: "Storage", used: storageUsedMb, limit: asLimit(currentTierDef?.storageMb), unit: " MB", unlimitedLabel: "Unlimited" },
|
||||
];
|
||||
|
||||
const plans = tierEnum.enumValues.map((tier) => {
|
||||
const def = allTierDefs.find((t) => t.tier === tier);
|
||||
return {
|
||||
tier,
|
||||
name: TIER_NAMES[tier] ?? tier,
|
||||
monthlyPrice: tier === "free" ? "€0" : "Contact for pricing",
|
||||
yearlyPrice: null,
|
||||
features: def
|
||||
? [
|
||||
describeLimit(def.maxRecipes, "recipes"),
|
||||
describeLimit(def.aiCallsPerMonth, "AI calls/month"),
|
||||
describeLimit(def.storageMb, "MB storage"),
|
||||
]
|
||||
: [],
|
||||
purchasable: tier === "free" || !!(def?.stripePriceIdMonthly),
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{checkout === "success" && (
|
||||
<div className="rounded-lg border border-primary/40 bg-primary/5 p-4 text-sm">
|
||||
Payment received — your plan updates within a few seconds as Stripe confirms it. Refresh if it doesn't show up right away.
|
||||
</div>
|
||||
)}
|
||||
{checkout === "canceled" && (
|
||||
<div className="rounded-lg border p-4 text-sm text-muted-foreground">
|
||||
Checkout canceled — no changes made.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">Current plan: {TIER_NAMES[currentTier] ?? currentTier}</h2>
|
||||
{dbUser?.currentPeriodEnd && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Renews {dbUser.currentPeriodEnd.toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{dbUser?.subscriptionStatus === "past_due" && (
|
||||
<Badge variant="destructive">Payment failed — update your card</Badge>
|
||||
)}
|
||||
</div>
|
||||
{dbUser?.stripeCustomerId && <ManageBillingButton />}
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">Usage this month</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">AI calls reset monthly. Recipes and storage are lifetime totals.</p>
|
||||
</div>
|
||||
<UsageQuotaSection metrics={usageMetrics} />
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<h2 className="font-semibold text-lg">Plans</h2>
|
||||
<BillingPlanCards currentTier={currentTier} plans={plans} />
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { FeatureTogglesForm } from "@/components/settings/feature-toggles-form";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function FeaturesSettingsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const m = getMessages((session?.user as { locale?: string })?.locale);
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settingsForm.featureToggles.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settingsForm.featureToggles.description}
|
||||
</p>
|
||||
</div>
|
||||
<FeatureTogglesForm />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { SettingsSidebar } from "@/components/settings/settings-sidebar";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||
|
||||
export default async function SettingsLayout({ children }: { children: React.ReactNode }) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const m = getMessages((session?.user as { locale?: string })?.locale);
|
||||
|
||||
const dbUser = session
|
||||
? (await db.select({ isDeveloper: users.isDeveloper, tier: users.tier }).from(users).where(eq(users.id, session.user.id)).limit(1))[0]
|
||||
: undefined;
|
||||
const showDeveloperNav = !!dbUser && (dbUser.isDeveloper || canSelfServeDeveloperAccess(dbUser));
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{m.settings.title}</h1>
|
||||
<p className="text-muted-foreground mt-1">{m.settings.subtitle}</p>
|
||||
</div>
|
||||
<div className="flex flex-col md:flex-row gap-4 md:gap-8 md:items-start">
|
||||
<SettingsSidebar showDeveloperNav={showDeveloperNav} />
|
||||
<main className="flex-1 min-w-0 space-y-6">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { PushSubscribeButton } from "@/components/pwa/push-subscribe-button";
|
||||
import { NotificationCategoriesForm } from "@/components/settings/notification-categories-form";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function NotificationsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const m = getMessages((session?.user as { locale?: string })?.locale);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.pushNotifications.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settings.pushNotifications.description}
|
||||
</p>
|
||||
</div>
|
||||
<PushSubscribeButton />
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settingsForm.notificationCategories.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settingsForm.notificationCategories.description}
|
||||
</p>
|
||||
</div>
|
||||
<NotificationCategoriesForm />
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, userNutritionGoals, eq } from "@epicure/db";
|
||||
import { NutritionGoalsForm } from "@/components/nutrition/nutrition-goals-form";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function NutritionPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const goals = await db.query.userNutritionGoals.findFirst({
|
||||
where: eq(userNutritionGoals.userId, session.user.id),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.nutritionGoals.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settings.nutritionGoals.description}
|
||||
</p>
|
||||
</div>
|
||||
<NutritionGoalsForm
|
||||
initialGoals={
|
||||
goals
|
||||
? {
|
||||
caloriesKcal: goals.caloriesKcal,
|
||||
proteinG: goals.proteinG,
|
||||
carbsG: goals.carbsG,
|
||||
fatG: goals.fatG,
|
||||
}
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
<section className="rounded-xl border p-6 space-y-3">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.nutritionDiary.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">{m.nutritionDiary.subtitle}</p>
|
||||
</div>
|
||||
<Link href="/nutrition" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
|
||||
{m.settings.nutritionGoals.viewDiaryCta}
|
||||
</Link>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { SettingsForm } from "@/components/settings/settings-form";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function SettingsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const dbUser = await db.query.users.findFirst({
|
||||
where: eq(users.id, session.user.id),
|
||||
columns: { bio: true, privateBio: true, isPrivate: true, hasCustomAvatar: true, avatarUrl: true, username: true, useGravatar: true },
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsForm
|
||||
user={{
|
||||
name: session.user.name,
|
||||
email: session.user.email,
|
||||
image: dbUser?.avatarUrl ?? null,
|
||||
locale: (session.user as { locale?: string }).locale ?? "en",
|
||||
bio: dbUser?.bio ?? null,
|
||||
privateBio: dbUser?.privateBio ?? null,
|
||||
isPrivate: dbUser?.isPrivate ?? false,
|
||||
hasCustomAvatar: dbUser?.hasCustomAvatar ?? false,
|
||||
username: dbUser?.username ?? null,
|
||||
useGravatar: dbUser?.useGravatar ?? false,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, accounts, users, eq, and } from "@epicure/db";
|
||||
import { SecurityForm } from "@/components/settings/security-form";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function SecurityPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const [dbUser, credentialAccount] = await Promise.all([
|
||||
db.query.users.findFirst({ where: eq(users.id, session.user.id), columns: { twoFactorEnabled: true } }),
|
||||
db.query.accounts.findFirst({ where: and(eq(accounts.userId, session.user.id), eq(accounts.providerId, "credential")) }),
|
||||
]);
|
||||
|
||||
return (
|
||||
<SecurityForm
|
||||
currentEmail={session.user.email}
|
||||
twoFactorEnabled={dbUser?.twoFactorEnabled ?? false}
|
||||
hasPassword={!!credentialAccount}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default function WebhookDocsPage() {
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto space-y-10 py-8">
|
||||
<Link href="/settings/webhooks" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
Back to Webhooks
|
||||
</Link>
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-2">Webhook Documentation</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Learn how to integrate Epicure webhooks with your own tools, Zapier, and Make.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Section 1: Webhook Events */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold mb-4">Webhook Events</h2>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-muted">
|
||||
<th className="text-left p-3 border border-border font-medium">Event</th>
|
||||
<th className="text-left p-3 border border-border font-medium">Description</th>
|
||||
<th className="text-left p-3 border border-border font-medium">Payload Fields</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">recipe.created</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when a recipe is created</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">id, title, authorId</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">recipe.updated</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when a recipe is updated</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">id, title, authorId</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">recipe.published</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when recipe visibility becomes public</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">id, title, authorId</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">recipe.deleted</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when a recipe is deleted</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">id, title</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">meal_plan.updated</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when a meal plan entry changes</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">weekStart, day, mealType</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">shopping_list.completed</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when shopping list marked complete</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">id, name</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="p-3 border border-border font-mono text-sm">comment.added</td>
|
||||
<td className="p-3 border border-border text-sm">Fired when a comment is added to your recipe</td>
|
||||
<td className="p-3 border border-border font-mono text-sm text-muted-foreground">commentId, recipeId, recipeTitle</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Section 2: Payload Format */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold mb-4">Payload Format</h2>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
Every webhook request is a POST with a JSON body in the following shape:
|
||||
</p>
|
||||
<pre className="bg-muted rounded-lg p-4 overflow-x-auto font-mono text-sm whitespace-pre">{`{
|
||||
"event": "recipe.created",
|
||||
"payload": { "id": "...", "title": "Pasta Carbonara", "authorId": "..." },
|
||||
"timestamp": "2024-01-15T10:30:00.000Z"
|
||||
}`}</pre>
|
||||
</section>
|
||||
|
||||
{/* Section 3: Signature Verification */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold mb-4">Signature Verification</h2>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Every request includes an{" "}
|
||||
<code className="font-mono bg-muted px-1.5 py-0.5 rounded text-xs">X-Epicure-Signature</code>{" "}
|
||||
header containing an HMAC-SHA256 digest of the raw request body, signed with your webhook
|
||||
secret. Always verify this signature before processing the payload.
|
||||
</p>
|
||||
|
||||
<p className="text-sm font-medium mb-2">TypeScript / Node.js</p>
|
||||
<pre className="bg-muted rounded-lg p-4 overflow-x-auto font-mono text-sm whitespace-pre mb-4">{`import crypto from "crypto";
|
||||
|
||||
function verify(body: string, secret: string, signature: string): boolean {
|
||||
const expected = crypto.createHmac("sha256", secret).update(body).digest("hex");
|
||||
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
|
||||
}`}</pre>
|
||||
|
||||
<p className="text-sm font-medium mb-2">Python</p>
|
||||
<pre className="bg-muted rounded-lg p-4 overflow-x-auto font-mono text-sm whitespace-pre">{`import hmac, hashlib
|
||||
|
||||
def verify(body: bytes, secret: str, signature: str) -> bool:
|
||||
expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
||||
return hmac.compare_digest(signature, expected)`}</pre>
|
||||
</section>
|
||||
|
||||
{/* Section 4: Zapier Integration */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold mb-4">Zapier Integration</h2>
|
||||
<ol className="list-decimal pl-6 space-y-2 text-sm mb-6">
|
||||
<li>Go to <span className="font-medium">zapier.com</span> and create a new Zap.</li>
|
||||
<li>Choose <span className="font-medium">Webhooks by Zapier</span> as the trigger and select <span className="font-medium">Catch Hook</span>.</li>
|
||||
<li>Copy the webhook URL provided by Zapier.</li>
|
||||
<li>Go to <span className="font-medium">Epicure Settings → Webhooks</span> and add that URL.</li>
|
||||
<li>Test the trigger in Zapier to confirm it receives the payload.</li>
|
||||
</ol>
|
||||
|
||||
<h3 className="text-base font-semibold mb-3">Example workflows</h3>
|
||||
<ul className="list-disc pl-6 space-y-2 text-sm text-muted-foreground">
|
||||
<li><span className="font-medium text-foreground">New Recipe Published</span> → Add row to Notion database</li>
|
||||
<li><span className="font-medium text-foreground">Shopping List Completed</span> → Send Slack message to #groceries</li>
|
||||
<li><span className="font-medium text-foreground">Comment Added</span> → Send email notification via Gmail</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{/* Section 5: Make (Integromat) */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold mb-4">Make (Integromat)</h2>
|
||||
<ol className="list-decimal pl-6 space-y-2 text-sm">
|
||||
<li>Go to <span className="font-medium">make.com</span> and create a new scenario.</li>
|
||||
<li>Add an <span className="font-medium">HTTP > Watch for Incoming Webhooks</span> module as the trigger.</li>
|
||||
<li>Copy the generated webhook URL from the module settings.</li>
|
||||
<li>Go to <span className="font-medium">Epicure Settings → Webhooks</span> and paste that URL.</li>
|
||||
<li>Run the scenario and trigger a test event in Epicure to verify the connection.</li>
|
||||
<li>Add downstream modules (Notion, Slack, Gmail, etc.) to act on the incoming data.</li>
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, webhooks, users, eq } from "@epicure/db";
|
||||
import { WebhooksManager } from "@/components/settings/webhooks-manager";
|
||||
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||
import { DeveloperAccessToggle } from "@/components/settings/developer-access-toggle";
|
||||
import { DisableDeveloperAccessButton } from "@/components/settings/disable-developer-access-button";
|
||||
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function WebhooksPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const dbUser = (await db.select({ isDeveloper: users.isDeveloper, tier: users.tier }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
||||
|
||||
const rows = dbUser?.isDeveloper
|
||||
? await db
|
||||
.select({
|
||||
id: webhooks.id,
|
||||
url: webhooks.url,
|
||||
events: webhooks.events,
|
||||
active: webhooks.active,
|
||||
createdAt: webhooks.createdAt,
|
||||
})
|
||||
.from(webhooks)
|
||||
.where(eq(webhooks.userId, session.user.id))
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">{m.settings.webhooksPage.title}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{m.settings.webhooksPage.description}
|
||||
</p>
|
||||
</div>
|
||||
{!dbUser?.isDeveloper && dbUser && canSelfServeDeveloperAccess(dbUser) && (
|
||||
<DeveloperAccessToggle message={m.settings.developerSelfServeNotice} />
|
||||
)}
|
||||
{!dbUser?.isDeveloper && (!dbUser || !canSelfServeDeveloperAccess(dbUser)) && (
|
||||
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
|
||||
)}
|
||||
{dbUser?.isDeveloper && (
|
||||
<>
|
||||
<WebhooksManager
|
||||
initialWebhooks={rows.map((w) => ({
|
||||
id: w.id,
|
||||
url: w.url,
|
||||
events: w.events,
|
||||
active: w.active,
|
||||
createdAt: w.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
<DisableDeveloperAccessButton />
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Printer } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, shoppingLists, eq } from "@epicure/db";
|
||||
import { ShoppingListView } from "@/components/meal-plan/shopping-list-view";
|
||||
import { ShareShoppingListButton } from "@/components/shopping-lists/share-shopping-list-button";
|
||||
import { GroceryExportButton } from "@/components/shopping-lists/grocery-export-button";
|
||||
import { ShoppingListActionsMenu } from "@/components/shopping-lists/shopping-list-actions-menu";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
|
||||
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
|
||||
import { shoppingListToMarkdown } from "@/lib/markdown/shopping-list";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function ShoppingListPage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const access = await getShoppingListAccess(id, session.user.id);
|
||||
if (!access) notFound();
|
||||
|
||||
const list = await db.query.shoppingLists.findFirst({
|
||||
where: eq(shoppingLists.id, id),
|
||||
with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.sortOrder), asc(t.rawName)] } },
|
||||
});
|
||||
if (!list) notFound();
|
||||
|
||||
const canEdit = canWriteShoppingList(access.role);
|
||||
const instacartEnabled = process.env["NEXT_PUBLIC_GROCERY_PROVIDER"] === "instacart";
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{list.name}</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{formatMessage(list.items.length === 1 ? m.shoppingLists.itemCount : m.shoppingLists.itemCountPlural, { count: list.items.length })}
|
||||
{list.generatedAt ? m.shoppingLists.fromMealPlan : ""}
|
||||
</p>
|
||||
</div>
|
||||
<TooltipProvider>
|
||||
<div className="flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
|
||||
<GroceryExportButton listId={id} instacartEnabled={instacartEnabled} />
|
||||
{access.role === "owner" && (
|
||||
<ShareShoppingListButton listId={id} initialIsPublic={list.isPublic} initialPublicEditable={list.publicEditable} />
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={
|
||||
<Link href={`/print/shopping-list/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))} aria-label={m.common.print}>
|
||||
<Printer className="h-4 w-4" />
|
||||
</Link>
|
||||
} />
|
||||
<TooltipContent>{m.common.print}</TooltipContent>
|
||||
</Tooltip>
|
||||
<ExportMarkdownButton
|
||||
markdown={shoppingListToMarkdown({ name: list.name, items: list.items })}
|
||||
filename={list.name}
|
||||
/>
|
||||
{access.role === "owner" && (
|
||||
<ShoppingListActionsMenu listId={id} name={list.name} redirectAfterDeleteTo="/shopping-lists" />
|
||||
)}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<ShoppingListView
|
||||
listId={id}
|
||||
readOnly={!canEdit}
|
||||
initialItems={list.items.map((i) => ({
|
||||
id: i.id,
|
||||
rawName: i.rawName,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
aisle: i.aisle,
|
||||
checked: i.checked,
|
||||
sortOrder: i.sortOrder,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function ShoppingListsLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeaderSkeleton actions={1} />
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<ListRowSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, shoppingLists, shoppingListMembers, eq, desc } from "@epicure/db";
|
||||
import { ShoppingListsPageContent } from "@/components/shopping-lists/shopping-lists-page-content";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function ShoppingListsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const [lists, memberships] = await Promise.all([
|
||||
db.query.shoppingLists.findMany({
|
||||
where: eq(shoppingLists.userId, session.user.id),
|
||||
orderBy: desc(shoppingLists.createdAt),
|
||||
with: { items: { columns: { id: true, checked: true } } },
|
||||
}),
|
||||
db.query.shoppingListMembers.findMany({
|
||||
where: eq(shoppingListMembers.userId, session.user.id),
|
||||
with: { list: { with: { user: true } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
return (
|
||||
<ShoppingListsPageContent
|
||||
lists={lists.map((list) => ({
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
generatedAt: list.generatedAt ? list.generatedAt.toISOString() : null,
|
||||
totalItems: list.items.length,
|
||||
checkedItems: list.items.filter((i) => i.checked).length,
|
||||
}))}
|
||||
sharedLists={memberships.map((m) => ({
|
||||
id: m.list.id,
|
||||
name: m.list.name,
|
||||
ownerName: m.list.user?.name ?? "Unknown",
|
||||
role: m.role,
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, supportTickets, eq, desc } from "@epicure/db";
|
||||
import { SupportManager } from "@/components/support/support-manager";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { FEATURE_DEFINITIONS } from "@/lib/feature-flags";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function SupportPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ upgrade?: string }>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const { upgrade } = await searchParams;
|
||||
const upgradeFeature = FEATURE_DEFINITIONS.find((f) => f.key === upgrade);
|
||||
const prefill = upgradeFeature
|
||||
? { type: "suggestion" as const, title: `Interested in upgrading for: ${upgradeFeature.label}` }
|
||||
: undefined;
|
||||
|
||||
const rows = await db.query.supportTickets.findMany({
|
||||
where: eq(supportTickets.userId, session.user.id),
|
||||
orderBy: desc(supportTickets.createdAt),
|
||||
with: { attachments: true },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-8 max-w-3xl">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">{m.support.title}</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">{m.support.subtitle}</p>
|
||||
</div>
|
||||
<SupportManager
|
||||
prefill={prefill}
|
||||
initialTickets={rows.map((r) => ({
|
||||
id: r.id,
|
||||
type: r.type,
|
||||
title: r.title,
|
||||
description: r.description,
|
||||
status: r.status,
|
||||
giteaIssueUrl: r.giteaIssueUrl,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
attachments: r.attachments.map((a) => ({
|
||||
id: a.id,
|
||||
contentType: a.contentType,
|
||||
url: getPublicUrl(a.storageKey),
|
||||
})),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { SquareTileSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function UserProfileLoading() {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto space-y-10">
|
||||
<div className="flex flex-col sm:flex-row gap-6 items-start sm:items-center">
|
||||
<Skeleton className="h-24 w-24 shrink-0 rounded-full" />
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-7 w-40" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-64" />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Skeleton className="h-6 w-20 rounded-full" />
|
||||
<Skeleton className="h-6 w-24 rounded-full" />
|
||||
<Skeleton className="h-6 w-24 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-6 w-24" />
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 8 }).map((_, i) => (
|
||||
<SquareTileSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { Lock } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import {
|
||||
db,
|
||||
users,
|
||||
recipes,
|
||||
userFollows,
|
||||
userBlocks,
|
||||
cookingHistory,
|
||||
ratings,
|
||||
eq,
|
||||
and,
|
||||
desc,
|
||||
count,
|
||||
isNotNull,
|
||||
} from "@epicure/db";
|
||||
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { FollowButton } from "@/components/social/follow-button";
|
||||
import { BlockButton } from "@/components/social/block-button";
|
||||
import { MessageButton } from "@/components/social/message-button";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { RecipeCoverPlaceholder } from "@/components/recipe/recipe-cover-placeholder";
|
||||
import { ProfileTabs, type HistoryData, type PhotosData } from "@/components/profile/profile-tabs";
|
||||
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
type Params = {
|
||||
params: Promise<{ username: string }>;
|
||||
searchParams: Promise<{ page?: string; tab?: string; ppage?: string }>;
|
||||
};
|
||||
|
||||
/** Consecutive-day streak (UTC calendar days) ending today or yesterday. */
|
||||
function computeStreak(dates: Date[]): number {
|
||||
const daySet = new Set(dates.map((d) => d.toISOString().slice(0, 10)));
|
||||
const cursor = new Date();
|
||||
cursor.setUTCHours(0, 0, 0, 0);
|
||||
if (!daySet.has(cursor.toISOString().slice(0, 10))) {
|
||||
cursor.setUTCDate(cursor.getUTCDate() - 1);
|
||||
if (!daySet.has(cursor.toISOString().slice(0, 10))) return 0;
|
||||
}
|
||||
let streak = 0;
|
||||
while (daySet.has(cursor.toISOString().slice(0, 10))) {
|
||||
streak++;
|
||||
cursor.setUTCDate(cursor.getUTCDate() - 1);
|
||||
}
|
||||
return streak;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Params) {
|
||||
const { username } = await params;
|
||||
const user = await db.query.users.findFirst({ where: eq(users.username, username) });
|
||||
return { title: user ? `${user.name} (@${user.username})` : "Profile" };
|
||||
}
|
||||
|
||||
export default async function UserProfilePage({ params, searchParams }: Params) {
|
||||
const { username } = await params;
|
||||
const { page: pageParam, tab: tabParam, ppage: ppageParam } = await searchParams;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
const photoPage = Math.max(1, parseInt(ppageParam ?? "1", 10) || 1);
|
||||
const photoOffset = (photoPage - 1) * PAGE_SIZE;
|
||||
const activeTab = tabParam === "history" || tabParam === "photos" ? tabParam : "recipes";
|
||||
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
|
||||
const user = await db.query.users.findFirst({ where: eq(users.username, username) });
|
||||
if (!user) notFound();
|
||||
|
||||
const [followerCountRow, followingCountRow, recipeCountRow, publicRecipes] = await Promise.all([
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(userFollows)
|
||||
.where(eq(userFollows.followingId, user.id)),
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(userFollows)
|
||||
.where(eq(userFollows.followerId, user.id)),
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(recipes)
|
||||
.where(and(eq(recipes.authorId, user.id), eq(recipes.visibility, "public"))),
|
||||
db.query.recipes.findMany({
|
||||
where: and(eq(recipes.authorId, user.id), eq(recipes.visibility, "public")),
|
||||
orderBy: desc(recipes.createdAt),
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
with: {
|
||||
photos: { orderBy: (t, { asc }) => asc(t.order), limit: 1 },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const followerCount = followerCountRow[0]?.count ?? 0;
|
||||
const followingCount = followingCountRow[0]?.count ?? 0;
|
||||
const recipeCount = recipeCountRow[0]?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(recipeCount / PAGE_SIZE));
|
||||
|
||||
let isFollowing = false;
|
||||
let isBlocked = false;
|
||||
const isOwnProfile = session?.user.id === user.id;
|
||||
if (session && !isOwnProfile) {
|
||||
const [followRow, blockRow] = await Promise.all([
|
||||
db.query.userFollows.findFirst({
|
||||
where: and(
|
||||
eq(userFollows.followerId, session.user.id),
|
||||
eq(userFollows.followingId, user.id),
|
||||
),
|
||||
}),
|
||||
db.query.userBlocks.findFirst({
|
||||
where: and(
|
||||
eq(userBlocks.blockerId, session.user.id),
|
||||
eq(userBlocks.blockedId, user.id),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
isFollowing = !!followRow;
|
||||
isBlocked = !!blockRow;
|
||||
}
|
||||
|
||||
// Private accounts hide their recipe grid from anyone who isn't the owner or an
|
||||
// existing follower. This only affects what's rendered on this direct-link profile
|
||||
// page — it does not change access to a specific recipe's own direct URL, and it
|
||||
// does not gate new follow requests (following stays immediate, no approval step).
|
||||
const isPrivateHidden = user.isPrivate && !isOwnProfile && !isFollowing;
|
||||
|
||||
// Cooking history and "cooked it" photo gallery are only meaningful (and visible) to the
|
||||
// profile owner: history reveals private behavioral/timing patterns, and photos may be
|
||||
// attached to reviews of recipes that aren't visible to other viewers (private recipes),
|
||||
// so surfacing them to non-owners could leak the existence of content they can't access.
|
||||
let historyData: HistoryData | null = null;
|
||||
let photosData: PhotosData | null = null;
|
||||
|
||||
if (isOwnProfile) {
|
||||
const [totalCookedRow, cookedDatesRows, lastCookedRow, recentEntries, totalPhotosRow, photoRows] =
|
||||
await Promise.all([
|
||||
db.select({ count: count() }).from(cookingHistory).where(eq(cookingHistory.userId, user.id)),
|
||||
db.query.cookingHistory.findMany({
|
||||
where: eq(cookingHistory.userId, user.id),
|
||||
columns: { cookedAt: true },
|
||||
orderBy: desc(cookingHistory.cookedAt),
|
||||
limit: 3650,
|
||||
}),
|
||||
db.query.cookingHistory.findFirst({
|
||||
where: eq(cookingHistory.userId, user.id),
|
||||
orderBy: desc(cookingHistory.cookedAt),
|
||||
with: { recipe: { columns: { id: true, title: true } } },
|
||||
}),
|
||||
db.query.cookingHistory.findMany({
|
||||
where: eq(cookingHistory.userId, user.id),
|
||||
orderBy: desc(cookingHistory.cookedAt),
|
||||
limit: 20,
|
||||
with: { recipe: { columns: { id: true, title: true } } },
|
||||
}),
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(ratings)
|
||||
.where(and(eq(ratings.userId, user.id), isNotNull(ratings.photoKey))),
|
||||
db.query.ratings.findMany({
|
||||
where: and(eq(ratings.userId, user.id), isNotNull(ratings.photoKey)),
|
||||
orderBy: desc(ratings.createdAt),
|
||||
limit: PAGE_SIZE,
|
||||
offset: photoOffset,
|
||||
with: { recipe: { columns: { id: true, title: true } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const totalCooked = totalCookedRow[0]?.count ?? 0;
|
||||
const streak = computeStreak(cookedDatesRows.map((r) => r.cookedAt));
|
||||
const totalPhotos = totalPhotosRow[0]?.count ?? 0;
|
||||
|
||||
historyData = {
|
||||
totalCooked,
|
||||
streak,
|
||||
lastCooked:
|
||||
lastCookedRow && lastCookedRow.recipe
|
||||
? {
|
||||
recipeId: lastCookedRow.recipe.id,
|
||||
recipeTitle: lastCookedRow.recipe.title,
|
||||
cookedAt: lastCookedRow.cookedAt.toISOString(),
|
||||
}
|
||||
: null,
|
||||
recentEntries: recentEntries
|
||||
.filter((e) => e.recipe)
|
||||
.map((e) => ({
|
||||
id: e.id,
|
||||
recipeId: e.recipe!.id,
|
||||
recipeTitle: e.recipe!.title,
|
||||
cookedAt: e.cookedAt.toISOString(),
|
||||
servings: e.servings,
|
||||
})),
|
||||
};
|
||||
|
||||
photosData = {
|
||||
items: photoRows
|
||||
.filter((r) => r.recipe && r.photoKey)
|
||||
.map((r) => ({
|
||||
id: r.id,
|
||||
recipeId: r.recipe!.id,
|
||||
recipeTitle: r.recipe!.title,
|
||||
photoKey: r.photoKey!,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
})),
|
||||
page: photoPage,
|
||||
totalPages: Math.max(1, Math.ceil(totalPhotos / PAGE_SIZE)),
|
||||
total: totalPhotos,
|
||||
};
|
||||
}
|
||||
|
||||
const initials = user.name
|
||||
.split(" ")
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0])
|
||||
.join("")
|
||||
.toUpperCase();
|
||||
|
||||
const recipesSection = isPrivateHidden ? (
|
||||
<div className="text-center py-16 text-muted-foreground space-y-2">
|
||||
<Lock className="mx-auto h-8 w-8" />
|
||||
<p className="text-lg font-medium">This account is private</p>
|
||||
<p className="text-sm">Follow @{user.username} to see their recipes.</p>
|
||||
</div>
|
||||
) : (
|
||||
publicRecipes.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-xl font-semibold">Recipes</h2>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||
{publicRecipes.map((recipe) => {
|
||||
const cover = recipe.photos[0];
|
||||
return (
|
||||
<Link
|
||||
key={recipe.id}
|
||||
href={`/recipes/${recipe.id}`}
|
||||
className="group block rounded-xl overflow-hidden border bg-card hover:shadow-md transition-shadow"
|
||||
>
|
||||
<div className="relative aspect-square bg-muted overflow-hidden">
|
||||
{cover ? (
|
||||
<Image
|
||||
src={getPublicUrl(cover.storageKey)}
|
||||
unoptimized
|
||||
alt={recipe.title}
|
||||
fill
|
||||
sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
|
||||
className="object-cover group-hover:scale-105 transition-transform duration-200"
|
||||
/>
|
||||
) : (
|
||||
<RecipeCoverPlaceholder recipe={recipe} />
|
||||
)}
|
||||
</div>
|
||||
<div className="p-2">
|
||||
<p className="text-sm font-medium leading-tight line-clamp-2">{recipe.title}</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2">
|
||||
{page > 1 && (
|
||||
<Link
|
||||
href={`/u/${username}${page - 1 > 1 ? `?page=${page - 1}` : ""}`}
|
||||
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
|
||||
>
|
||||
Previous
|
||||
</Link>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground px-2">
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
{page < totalPages && (
|
||||
<Link
|
||||
href={`/u/${username}?page=${page + 1}`}
|
||||
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
|
||||
>
|
||||
Next
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-16 text-muted-foreground">
|
||||
<p className="text-lg">No public recipes yet.</p>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto space-y-10">
|
||||
{/* Profile header */}
|
||||
<div className="flex flex-col sm:flex-row gap-6 items-start sm:items-center">
|
||||
<Avatar className="h-24 w-24 shrink-0">
|
||||
{user.avatarUrl && <AvatarImage src={user.avatarUrl} alt={user.name} />}
|
||||
<AvatarFallback className="text-2xl">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold leading-tight flex items-center gap-2">
|
||||
{user.name}
|
||||
{isOwnProfile && user.isPrivate && (
|
||||
<Badge variant="outline" className="gap-1 text-xs font-normal">
|
||||
<Lock className="h-3 w-3" /> Private
|
||||
</Badge>
|
||||
)}
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">@{user.username}</p>
|
||||
</div>
|
||||
{!isOwnProfile && session && (
|
||||
<div className="flex items-center gap-2">
|
||||
<FollowButton
|
||||
targetUserId={user.id}
|
||||
targetUsername={user.username!}
|
||||
initialFollowing={isFollowing}
|
||||
/>
|
||||
{!isBlocked && <MessageButton targetUsername={user.username!} />}
|
||||
<BlockButton targetUsername={user.username!} initialBlocked={isBlocked} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{user.bio && !isPrivateHidden && (
|
||||
<p className="text-sm leading-relaxed max-w-prose">{user.bio}</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant="secondary">
|
||||
<span className="font-semibold mr-1">{recipeCount}</span> recipes
|
||||
</Badge>
|
||||
<Badge variant="secondary">
|
||||
<span className="font-semibold mr-1">{followerCount}</span> followers
|
||||
</Badge>
|
||||
<Badge variant="secondary">
|
||||
<span className="font-semibold mr-1">{followingCount}</span> following
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recipes / cooking history / photos */}
|
||||
{isOwnProfile && historyData && photosData ? (
|
||||
<ProfileTabs
|
||||
username={username}
|
||||
defaultTab={activeTab}
|
||||
recipesContent={recipesSection}
|
||||
history={historyData}
|
||||
photos={photosData}
|
||||
/>
|
||||
) : (
|
||||
recipesSection
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,7 @@ export default function LoginPage() {
|
||||
e.preventDefault();
|
||||
setUnverified(false);
|
||||
setLoading(true);
|
||||
const { error } = await authClient.signIn.email({ email, password, callbackURL: "/recipes" });
|
||||
const { data, error } = await authClient.signIn.email({ email, password, callbackURL: "/recipes" });
|
||||
setLoading(false);
|
||||
if (error) {
|
||||
if (error.code === "EMAIL_NOT_VERIFIED") {
|
||||
@@ -33,7 +33,11 @@ export default function LoginPage() {
|
||||
} else {
|
||||
toast.error(error.message ?? "Sign in failed");
|
||||
}
|
||||
} else {
|
||||
} else if (!(data as { twoFactorRedirect?: boolean } | null)?.twoFactorRedirect) {
|
||||
// 2FA-enabled accounts resolve with no `error` but `twoFactorRedirect: true` —
|
||||
// no full session exists yet, so pushing to /recipes here races the SDK's own
|
||||
// window.location.href to /verify-2fa (see twoFactorClient's onSuccess hook)
|
||||
// and can lose, bouncing off middleware back to /login with no visible error.
|
||||
router.push("/recipes");
|
||||
}
|
||||
}
|
||||
@@ -53,10 +57,6 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGoogle() {
|
||||
await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
@@ -65,9 +65,15 @@ export default function LoginPage() {
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
<Button variant="outline" className="w-full" type="button" onClick={handleGoogle}>
|
||||
{t("continueWithGoogle")}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<Button variant="outline" className="w-full gap-2" type="button" onClick={() => authClient.signIn.social({ provider: "google", callbackURL: "/recipes" })}>
|
||||
<GoogleIcon />
|
||||
{t("continueWithGoogle")}
|
||||
</Button>
|
||||
<SocialButton provider="github" label={t("continueWithGithub")} icon={<GithubIcon />} />
|
||||
<SocialButton provider="discord" label={t("continueWithDiscord")} icon={<DiscordIcon />} />
|
||||
<AuthentikButton label={t("continueWithAuthentik")} />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Separator className="flex-1" />
|
||||
<span className="text-xs text-muted-foreground">{t("or")}</span>
|
||||
@@ -118,3 +124,59 @@ export default function LoginPage() {
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SocialButton({ provider, label, icon }: { provider: "github" | "discord"; label: string; icon: React.ReactNode }) {
|
||||
const envKey = provider === "github" ? process.env["NEXT_PUBLIC_GITHUB_ENABLED"] : process.env["NEXT_PUBLIC_DISCORD_ENABLED"];
|
||||
if (!envKey) return null;
|
||||
return (
|
||||
<Button variant="outline" className="w-full gap-2" type="button" onClick={() => authClient.signIn.social({ provider, callbackURL: "/recipes" })}>
|
||||
{icon}
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthentikButton({ label }: { label: string }) {
|
||||
if (!process.env["NEXT_PUBLIC_AUTHENTIK_ENABLED"]) return null;
|
||||
return (
|
||||
<Button variant="outline" className="w-full gap-2" type="button" onClick={() => (authClient as unknown as { signIn: { genericOAuth: (opts: { providerId: string; callbackURL: string }) => Promise<void> } }).signIn.genericOAuth({ providerId: "authentik", callbackURL: "/recipes" })}>
|
||||
<AuthentikIcon />
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function GoogleIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className="h-4 w-4" aria-hidden="true">
|
||||
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
|
||||
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
|
||||
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
|
||||
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function GithubIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className="h-4 w-4 fill-current" aria-hidden="true">
|
||||
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function DiscordIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className="h-4 w-4 fill-current" aria-hidden="true">
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057.1 18.08.11 18.1.128 18.11a19.9 19.9 0 0 0 5.993 3.03.077.077 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthentikIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className="h-4 w-4" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,86 +1,13 @@
|
||||
"use client";
|
||||
import { isSignupsDisabled } from "@/lib/site-settings";
|
||||
import { SignupForm } from "./signup-form";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
export default async function SignupPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ invite?: string }>;
|
||||
}) {
|
||||
const { invite } = await searchParams;
|
||||
const signupsDisabled = await isSignupsDisabled();
|
||||
|
||||
export default function SignupPage() {
|
||||
const router = useRouter();
|
||||
const t = useTranslations("auth");
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
const { error } = await authClient.signUp.email({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
callbackURL: "/recipes",
|
||||
});
|
||||
setLoading(false);
|
||||
if (error) {
|
||||
toast.error(error.message ?? "Sign up failed");
|
||||
} else {
|
||||
toast.success("Account created — check your email to verify");
|
||||
router.push("/login");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGoogle() {
|
||||
await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-semibold tracking-tight">{t("signUpTitle")}</CardTitle>
|
||||
<CardDescription>{t("signUpSubtitle")}</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
<Button variant="outline" className="w-full" type="button" onClick={handleGoogle}>
|
||||
{t("continueWithGoogle")}
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Separator className="flex-1" />
|
||||
<span className="text-xs text-muted-foreground">{t("or")}</span>
|
||||
<Separator className="flex-1" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">{t("name")}</Label>
|
||||
<Input id="name" type="text" placeholder={t("namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t("email")}</Label>
|
||||
<Input id="email" type="email" placeholder={t("emailPlaceholder")} value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t("password")}</Label>
|
||||
<Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
|
||||
</div>
|
||||
<Button className="w-full" type="submit" disabled={loading}>
|
||||
{loading ? t("signUpLoading") : t("signUpTitle")}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</form>
|
||||
<CardFooter className="flex justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("alreadyHaveAccount")}{" "}
|
||||
<Link href="/login" className="underline underline-offset-4 hover:text-foreground">{t("signIn")}</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
return <SignupForm signupsDisabled={signupsDisabled} inviteToken={invite ?? null} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
const INVITE_COOKIE = "epicure_invite";
|
||||
|
||||
export function SignupForm({ signupsDisabled, inviteToken }: { signupsDisabled: boolean; inviteToken: string | null }) {
|
||||
const router = useRouter();
|
||||
const t = useTranslations("auth");
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [inviteState, setInviteState] = useState<"checking" | "valid" | "invalid" | "none">(
|
||||
inviteToken ? "checking" : "none"
|
||||
);
|
||||
const [inviteEmail, setInviteEmail] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!inviteToken) return;
|
||||
fetch(`/api/v1/invites/${inviteToken}`)
|
||||
.then((res) => res.json())
|
||||
.then((data: { valid: boolean; email: string | null }) => {
|
||||
setInviteState(data.valid ? "valid" : "invalid");
|
||||
if (data.valid && data.email) {
|
||||
setInviteEmail(data.email);
|
||||
setEmail(data.email);
|
||||
}
|
||||
})
|
||||
.catch(() => setInviteState("invalid"));
|
||||
}, [inviteToken]);
|
||||
|
||||
function setInviteCookie() {
|
||||
if (inviteToken && inviteState === "valid") {
|
||||
document.cookie = `${INVITE_COOKIE}=${inviteToken}; path=/; max-age=600; samesite=lax`;
|
||||
}
|
||||
}
|
||||
|
||||
const locked = signupsDisabled && inviteState !== "valid";
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setInviteCookie();
|
||||
const { error } = await authClient.signUp.email({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
callbackURL: "/recipes",
|
||||
});
|
||||
setLoading(false);
|
||||
if (error) {
|
||||
toast.error(error.message ?? "Sign up failed");
|
||||
} else {
|
||||
toast.success("Account created — check your email to verify");
|
||||
router.push("/login");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGoogle() {
|
||||
setInviteCookie();
|
||||
await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
|
||||
}
|
||||
|
||||
if (signupsDisabled && inviteState === "checking") {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="py-10 text-center text-muted-foreground">Checking invite…</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (signupsDisabled && inviteState === "none") {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-semibold tracking-tight">Signups are closed</CardTitle>
|
||||
<CardDescription>Epicure isn't accepting new accounts right now. You'll need an invite link.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex justify-center">
|
||||
<Link href="/login" className="text-sm underline underline-offset-4 hover:text-foreground">
|
||||
Back to login
|
||||
</Link>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (signupsDisabled && inviteState === "invalid") {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-semibold tracking-tight">Invite invalid or expired</CardTitle>
|
||||
<CardDescription>This invite link no longer works. Ask whoever sent it for a new one.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex justify-center">
|
||||
<Link href="/login" className="text-sm underline underline-offset-4 hover:text-foreground">
|
||||
Back to login
|
||||
</Link>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-semibold tracking-tight">{t("signUpTitle")}</CardTitle>
|
||||
<CardDescription>{t("signUpSubtitle")}</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
<Button variant="outline" className="w-full" type="button" onClick={() => { void handleGoogle(); }} disabled={locked}>
|
||||
{t("continueWithGoogle")}
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Separator className="flex-1" />
|
||||
<span className="text-xs text-muted-foreground">{t("or")}</span>
|
||||
<Separator className="flex-1" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">{t("name")}</Label>
|
||||
<Input id="name" type="text" placeholder={t("namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t("email")}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder={t("emailPlaceholder")}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
readOnly={!!inviteEmail}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t("password")}</Label>
|
||||
<Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
|
||||
</div>
|
||||
<Button className="w-full" type="submit" disabled={loading || locked}>
|
||||
{loading ? t("signUpLoading") : t("signUpTitle")}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</form>
|
||||
<CardFooter className="flex justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("alreadyHaveAccount")}{" "}
|
||||
<Link href="/login" className="underline underline-offset-4 hover:text-foreground">{t("signIn")}</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default function Verify2faPage() {
|
||||
const router = useRouter();
|
||||
const t = useTranslations("auth");
|
||||
const [code, setCode] = useState("");
|
||||
const [useBackupCode, setUseBackupCode] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
const { error } = useBackupCode
|
||||
? await authClient.twoFactor.verifyBackupCode({ code: code.trim() })
|
||||
: await authClient.twoFactor.verifyTotp({ code: code.trim() });
|
||||
setLoading(false);
|
||||
if (error) {
|
||||
setError(error.message ?? t("twoFactorInvalidCode"));
|
||||
} else {
|
||||
router.push("/recipes");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-semibold tracking-tight">{t("twoFactorTitle")}</CardTitle>
|
||||
<CardDescription>
|
||||
{useBackupCode ? t("twoFactorBackupDescription") : t("twoFactorAppDescription")}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="code">{useBackupCode ? t("twoFactorBackupCodeLabel") : t("twoFactorCodeLabel")}</Label>
|
||||
<Input
|
||||
id="code"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
autoFocus
|
||||
inputMode={useBackupCode ? "text" : "numeric"}
|
||||
placeholder={useBackupCode ? undefined : "000000"}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<Button className="w-full" type="submit" disabled={loading || !code.trim()}>
|
||||
{loading ? t("twoFactorVerifying") : t("twoFactorVerify")}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</form>
|
||||
<CardFooter className="flex justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setUseBackupCode(!useBackupCode); setCode(""); setError(null); }}
|
||||
className="text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground"
|
||||
>
|
||||
{useBackupCode ? t("twoFactorUseApp") : t("twoFactorUseBackupCode")}
|
||||
</button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { getEffectiveMarketingLocale } from "@/lib/marketing-locale";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "About — Epicure",
|
||||
description: "The story behind Epicure.",
|
||||
};
|
||||
|
||||
export default async function AboutPage() {
|
||||
const m = getMessages(await getEffectiveMarketingLocale());
|
||||
const t = m.marketing.about;
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16 max-w-2xl space-y-6">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{t.title}</h1>
|
||||
<div className="space-y-4 text-muted-foreground leading-relaxed">
|
||||
{t.paragraphs.map((p, i) => (
|
||||
<p key={i}>{p}</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Mail } from "lucide-react";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { getEffectiveMarketingLocale } from "@/lib/marketing-locale";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Contact — Epicure",
|
||||
description: "Get in touch with the Epicure team.",
|
||||
};
|
||||
|
||||
const SUPPORT_EMAIL = "support@epicure.app";
|
||||
|
||||
export default async function ContactPage() {
|
||||
const m = getMessages(await getEffectiveMarketingLocale());
|
||||
const t = m.marketing.contact;
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16 max-w-lg text-center space-y-6">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{t.title}</h1>
|
||||
<p className="text-muted-foreground">{t.subtitle}</p>
|
||||
<a
|
||||
href={`mailto:${SUPPORT_EMAIL}`}
|
||||
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2.5 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<Mail className="h-4 w-4" />
|
||||
{SUPPORT_EMAIL}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { Sparkles, Calendar, Package, MessageCircle, Users, ChefHat, Camera, ListChecks, Utensils, Wand2, Sparkle, Replace } from "lucide-react";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { getEffectiveMarketingLocale } from "@/lib/marketing-locale";
|
||||
import { isSignupsDisabled } from "@/lib/site-settings";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Features — Epicure",
|
||||
description: "AI recipe generation, meal planning, pantry tracking, cook mode, and a cooking assistant that can act on your behalf.",
|
||||
};
|
||||
|
||||
const FEATURES = [
|
||||
{ icon: Sparkles, key: "ai" },
|
||||
{ icon: Camera, key: "photoImport" },
|
||||
{ icon: MessageCircle, key: "assistant" },
|
||||
{ icon: Utensils, key: "cookMode" },
|
||||
{ icon: Wand2, key: "variations" },
|
||||
{ icon: Sparkle, key: "recommendations" },
|
||||
{ icon: Replace, key: "substitution" },
|
||||
{ icon: Calendar, key: "mealPlan" },
|
||||
{ icon: Package, key: "pantry" },
|
||||
{ icon: ListChecks, key: "shoppingList" },
|
||||
{ icon: Users, key: "social" },
|
||||
{ icon: ChefHat, key: "batchCook" },
|
||||
] as const;
|
||||
|
||||
export default async function FeaturesPage() {
|
||||
const [locale, signupsDisabled] = await Promise.all([getEffectiveMarketingLocale(), isSignupsDisabled()]);
|
||||
const m = getMessages(locale);
|
||||
const t = m.marketing.features;
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16 space-y-12">
|
||||
<div className="text-center space-y-4 max-w-2xl mx-auto">
|
||||
<h1 className="text-3xl sm:text-4xl font-bold tracking-tight">{t.title}</h1>
|
||||
<p className="text-lg text-muted-foreground">{t.subtitle}</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl mx-auto">
|
||||
{FEATURES.map(({ icon: Icon, key }) => (
|
||||
<div key={key} className="rounded-xl border bg-card p-6 space-y-3">
|
||||
<div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
<Icon className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg">{t.items[key].title}</h3>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">{t.items[key].description}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="text-center pt-4">
|
||||
<Link href="/signup" className={cn(buttonVariants({ size: "lg" }))}>
|
||||
{signupsDisabled ? m.marketing.nav.signupClosed : t.cta}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { MarketingNav } from "@/components/marketing/marketing-nav";
|
||||
import { MarketingFooter } from "@/components/marketing/marketing-footer";
|
||||
import { getEffectiveMarketingLocale } from "@/lib/marketing-locale";
|
||||
|
||||
export default async function MarketingLayout({ children }: { children: React.ReactNode }) {
|
||||
const locale = await getEffectiveMarketingLocale();
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col">
|
||||
<MarketingNav />
|
||||
<main className="flex-1">{children}</main>
|
||||
<MarketingFooter locale={locale} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
import { getEffectiveMarketingLocale } from "@/lib/marketing-locale";
|
||||
import { isSignupsDisabled } from "@/lib/site-settings";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Sparkles, Calendar, Package, MessageCircle, Users, ChefHat, Utensils, Wand2, Sparkle } from "lucide-react";
|
||||
|
||||
const HIGHLIGHTS = [
|
||||
{ icon: Sparkles, key: "ai" },
|
||||
{ icon: MessageCircle, key: "assistant" },
|
||||
{ icon: Calendar, key: "mealPlan" },
|
||||
{ icon: Package, key: "pantry" },
|
||||
{ icon: Utensils, key: "cookMode" },
|
||||
{ icon: Wand2, key: "variations" },
|
||||
{ icon: Users, key: "social" },
|
||||
{ icon: ChefHat, key: "batchCook" },
|
||||
{ icon: Sparkle, key: "recommendations" },
|
||||
] as const;
|
||||
|
||||
export default async function MarketingHomePage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (session) redirect("/recipes");
|
||||
|
||||
const [locale, signupsDisabled] = await Promise.all([getEffectiveMarketingLocale(), isSignupsDisabled()]);
|
||||
const m = getMessages(locale);
|
||||
const t = m.marketing.home;
|
||||
const ctaLabel = signupsDisabled ? m.marketing.nav.signupClosed : t.ctaPrimary;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<section className="container mx-auto px-4 py-20 sm:py-28 text-center space-y-6">
|
||||
<h1 className="text-4xl sm:text-5xl font-bold tracking-tight max-w-2xl mx-auto">
|
||||
{t.heroTitle}
|
||||
</h1>
|
||||
<p className="text-lg text-muted-foreground max-w-xl mx-auto">
|
||||
{t.heroSubtitle}
|
||||
</p>
|
||||
<div className="flex items-center justify-center gap-3 pt-2">
|
||||
<Link href="/signup" className={cn(buttonVariants({ size: "lg" }))}>
|
||||
{ctaLabel}
|
||||
</Link>
|
||||
<Link href="/features" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
|
||||
{t.ctaSecondary}
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="container mx-auto px-4 py-16 border-t">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{HIGHLIGHTS.map(({ icon: Icon, key }) => (
|
||||
<div key={key} className="rounded-xl border bg-card p-6 space-y-3">
|
||||
<div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
<Icon className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<h3 className="font-semibold">{t.highlights[key].title}</h3>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">{t.highlights[key].description}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="container mx-auto px-4 py-16 border-t text-center space-y-4">
|
||||
<h2 className="text-2xl font-semibold">{t.bottomCtaTitle}</h2>
|
||||
<p className="text-muted-foreground max-w-lg mx-auto">{t.bottomCtaSubtitle}</p>
|
||||
<Link href="/signup" className={cn(buttonVariants({ size: "lg" }))}>
|
||||
{ctaLabel}
|
||||
</Link>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Privacy Policy — Epicure",
|
||||
description: "How Epicure collects, uses, and protects your data.",
|
||||
};
|
||||
|
||||
export default function PrivacyPage() {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16 max-w-2xl space-y-6">
|
||||
<div className="rounded-lg border border-yellow-500/40 bg-yellow-500/10 p-4 flex gap-3 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 text-yellow-600 shrink-0 mt-0.5" />
|
||||
<p>
|
||||
<strong>Draft — not yet reviewed by counsel.</strong> This page is a
|
||||
placeholder structure, not a finished, legally-binding policy. Replace
|
||||
before accepting real signups/payments (see <code>STRIPE_PLAN.md</code> §10).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<h1 className="text-3xl font-bold tracking-tight">Privacy Policy</h1>
|
||||
|
||||
<div className="space-y-6 text-sm text-muted-foreground leading-relaxed">
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Data we collect</h2>
|
||||
<p>Account information (email, name), recipes and content you create, usage data (AI calls, storage), and payment information (processed by Stripe — we never store card details ourselves).</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">How we use it</h2>
|
||||
<p>To provide the service (store your recipes, run AI features you request, process subscriptions), and nothing beyond that — no data is sold to third parties.</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Third parties</h2>
|
||||
<p>AI providers (OpenAI/Anthropic/OpenRouter/Ollama, depending on your configuration), Stripe for payments, and your own configured integrations (webhooks, API keys) that you explicitly set up.</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Your rights</h2>
|
||||
<p>Access, export, correct, or delete your data at any time from Settings, or by contacting us (see Contact page). EU/EEA users have rights under GDPR.</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Contact</h2>
|
||||
<p>Questions about this policy — see the Contact page.</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Terms of Service — Epicure",
|
||||
description: "The terms governing use of Epicure.",
|
||||
};
|
||||
|
||||
export default function TermsPage() {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16 max-w-2xl space-y-6">
|
||||
<div className="rounded-lg border border-yellow-500/40 bg-yellow-500/10 p-4 flex gap-3 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 text-yellow-600 shrink-0 mt-0.5" />
|
||||
<p>
|
||||
<strong>Draft — not yet reviewed by counsel.</strong> This page is a
|
||||
placeholder structure, not finished, legally-binding terms. Replace
|
||||
before accepting real signups/payments (see <code>STRIPE_PLAN.md</code> §10).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<h1 className="text-3xl font-bold tracking-tight">Terms of Service</h1>
|
||||
|
||||
<div className="space-y-6 text-sm text-muted-foreground leading-relaxed">
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Using Epicure</h2>
|
||||
<p>You're responsible for the content you create and share, and for keeping your account credentials secure.</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Subscriptions</h2>
|
||||
<p>Paid tiers (Pro, Family) renew automatically until cancelled. Cancel anytime from Settings — access continues until the end of the paid period.</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Content ownership</h2>
|
||||
<p>You own what you create. We only use it to provide the service to you (and, if you set a recipe public/unlisted/followers-visible, to whoever you've chosen to share it with).</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">AI-generated content</h2>
|
||||
<p>AI-generated recipes are provided as-is — always use your own judgment, especially around allergens and food safety.</p>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h2 className="font-semibold text-foreground">Changes</h2>
|
||||
<p>We may update these terms; meaningful changes will be communicated in-app.</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { getAllSiteSettings } from "@/lib/site-settings";
|
||||
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
|
||||
import { AdminDefaultModelForm } from "@/components/admin/admin-default-model-form";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const SETTING_GROUP = {
|
||||
title: "Provider Keys & Routing",
|
||||
description: "Override the environment variable API keys at runtime (encrypted at rest), and set the OpenRouter/Ollama routing defaults. DB values here take precedence over environment variables — clear a value to fall back to the env var.",
|
||||
keys: ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "OPENROUTER_API_KEY", "OPENROUTER_DEFAULT_MODEL", "OLLAMA_BASE_URL"] as const,
|
||||
};
|
||||
|
||||
function resolveProvider(settings: Record<string, { value: string | null }>) {
|
||||
if (settings["OPENROUTER_API_KEY"]?.value) return { provider: "OpenRouter", description: "Routes to many models via openrouter.ai" };
|
||||
if (settings["OPENAI_API_KEY"]?.value) return { provider: "OpenAI", description: "Direct OpenAI API (GPT-4 etc.)" };
|
||||
if (settings["ANTHROPIC_API_KEY"]?.value) return { provider: "Anthropic", description: "Direct Anthropic API (Claude models)" };
|
||||
const url = settings["OLLAMA_BASE_URL"]?.value || "http://localhost:11434";
|
||||
return { provider: "Ollama", description: `Local inference at ${url}` };
|
||||
}
|
||||
|
||||
export default async function AdminAiConfigPage() {
|
||||
await requireFullAdminPage();
|
||||
const settings = await getAllSiteSettings();
|
||||
const active = resolveProvider(settings);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">AI Configuration</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Provider keys, routing, and default models for AI generation.
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-3">
|
||||
<span className="text-xs text-muted-foreground">Fallback provider (no default set below):</span>
|
||||
<Badge variant="secondary" className="text-xs">{active.provider}</Badge>
|
||||
<span className="text-xs text-muted-foreground">— {active.description}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminSettingsForm group={SETTING_GROUP} settings={settings} />
|
||||
|
||||
<AdminDefaultModelForm
|
||||
initialValues={{
|
||||
DEFAULT_TEXT_PROVIDER: settings["DEFAULT_TEXT_PROVIDER"]?.value ?? null,
|
||||
DEFAULT_TEXT_MODEL: settings["DEFAULT_TEXT_MODEL"]?.value ?? null,
|
||||
DEFAULT_CHAT_PROVIDER: settings["DEFAULT_CHAT_PROVIDER"]?.value ?? null,
|
||||
DEFAULT_CHAT_MODEL: settings["DEFAULT_CHAT_MODEL"]?.value ?? null,
|
||||
DEFAULT_VISION_PROVIDER: settings["DEFAULT_VISION_PROVIDER"]?.value ?? null,
|
||||
DEFAULT_VISION_MODEL: settings["DEFAULT_VISION_MODEL"]?.value ?? null,
|
||||
DEFAULT_MEAL_PLAN_PROVIDER: settings["DEFAULT_MEAL_PLAN_PROVIDER"]?.value ?? null,
|
||||
DEFAULT_MEAL_PLAN_MODEL: settings["DEFAULT_MEAL_PLAN_MODEL"]?.value ?? null,
|
||||
}}
|
||||
initialToolCallingEnabled={settings["AI_TOOL_CALLING_ENABLED"]?.value !== "false"}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, auditLogs, users, eq, desc } from "@epicure/db";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
interface PageProps {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}
|
||||
|
||||
export default async function AdminAuditLogsPage({ searchParams }: PageProps) {
|
||||
await requireFullAdminPage();
|
||||
const { page: pageParam } = await searchParams;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10));
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: auditLogs.id,
|
||||
action: auditLogs.action,
|
||||
targetType: auditLogs.targetType,
|
||||
targetId: auditLogs.targetId,
|
||||
metadata: auditLogs.metadata,
|
||||
createdAt: auditLogs.createdAt,
|
||||
actorName: users.name,
|
||||
actorEmail: users.email,
|
||||
})
|
||||
.from(auditLogs)
|
||||
.leftJoin(users, eq(auditLogs.userId, users.id))
|
||||
.orderBy(desc(auditLogs.createdAt))
|
||||
.limit(PAGE_SIZE)
|
||||
.offset(offset);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Audit Logs</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Admin actions recorded for accountability. Page {page}.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Actor</th>
|
||||
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Action</th>
|
||||
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Target</th>
|
||||
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Metadata</th>
|
||||
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Timestamp</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
|
||||
No audit log entries yet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rows.map((row) => (
|
||||
<tr key={row.id} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-medium">{row.actorName ?? "System"}</div>
|
||||
{row.actorEmail && (
|
||||
<div className="text-xs text-muted-foreground">{row.actorEmail}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs">{row.action}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground text-xs">
|
||||
{row.targetType ? (
|
||||
<span>
|
||||
{row.targetType}
|
||||
{row.targetId ? `: ${row.targetId.slice(0, 8)}…` : ""}
|
||||
</span>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs text-muted-foreground max-w-xs truncate">
|
||||
{row.metadata ?? "—"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
|
||||
{row.createdAt.toLocaleString()}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{page > 1 && (
|
||||
<a
|
||||
href={`/admin/audit-logs?page=${page - 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Previous
|
||||
</a>
|
||||
)}
|
||||
{rows.length === PAGE_SIZE && (
|
||||
<a
|
||||
href={`/admin/audit-logs?page=${page + 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Next
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import { db, users, auditLogs, count, eq, sql, like, desc } from "@epicure/db";
|
||||
import { getAllSiteSettings, getSiteSetting } from "@/lib/site-settings";
|
||||
import { isStripeTestMode } from "@/lib/stripe";
|
||||
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const STRIPE_GROUP = {
|
||||
title: "Stripe Connection",
|
||||
description:
|
||||
"Get keys from your Stripe Dashboard (Developers -> API keys). The webhook secret comes from " +
|
||||
"the endpoint you configure there pointed at /api/webhooks/stripe (events: checkout.session.completed, " +
|
||||
"customer.subscription.updated, customer.subscription.deleted, invoice.payment_failed, invoice.paid). " +
|
||||
"Price/Product IDs per tier are set on the Tier Limits page, not here.",
|
||||
keys: ["STRIPE_SECRET_KEY", "STRIPE_PUBLISHABLE_KEY", "STRIPE_WEBHOOK_SECRET"] as const,
|
||||
};
|
||||
|
||||
export default async function AdminBillingPage() {
|
||||
await requireFullAdminPage();
|
||||
|
||||
const [settings, secretKey] = await Promise.all([
|
||||
getAllSiteSettings(),
|
||||
getSiteSetting("STRIPE_SECRET_KEY"),
|
||||
]);
|
||||
|
||||
const [subscriberCounts, pastDueUsers, recentBillingEvents] = await Promise.all([
|
||||
db.select({ tier: users.tier, count: count() }).from(users).where(sql`${users.tier} != 'free'`).groupBy(users.tier),
|
||||
db
|
||||
.select({ id: users.id, name: users.name, email: users.email })
|
||||
.from(users)
|
||||
.where(eq(users.subscriptionStatus, "past_due"))
|
||||
.limit(20),
|
||||
db
|
||||
.select({ id: auditLogs.id, action: auditLogs.action, targetId: auditLogs.targetId, metadata: auditLogs.metadata, createdAt: auditLogs.createdAt })
|
||||
.from(auditLogs)
|
||||
.where(like(auditLogs.action, "billing.%"))
|
||||
.orderBy(desc(auditLogs.createdAt))
|
||||
.limit(20),
|
||||
]);
|
||||
|
||||
const proCount = subscriberCounts.find((r) => r.tier === "pro")?.count ?? 0;
|
||||
const familyCount = subscriberCounts.find((r) => r.tier === "family")?.count ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Billing</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Stripe connection status, subscriber insights, and recent billing events. Price mapping per tier
|
||||
lives on the <Link href="/admin/tiers" className="underline underline-offset-4">Tier Limits</Link> page.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{secretKey ? (
|
||||
<Badge variant={isStripeTestMode(secretKey) ? "secondary" : "default"}>
|
||||
{isStripeTestMode(secretKey) ? "Test mode" : "Live mode"}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-muted-foreground">Not configured</Badge>
|
||||
)}
|
||||
<a
|
||||
href="https://dashboard.stripe.com"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
|
||||
>
|
||||
Stripe Dashboard
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<AdminSettingsForm group={STRIPE_GROUP} settings={settings} />
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Pro subscribers</CardTitle></CardHeader>
|
||||
<CardContent><p className="text-2xl font-bold">{proCount}</p></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Family subscribers</CardTitle></CardHeader>
|
||||
<CardContent><p className="text-2xl font-bold">{familyCount}</p></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Past due</CardTitle></CardHeader>
|
||||
<CardContent><p className="text-2xl font-bold">{pastDueUsers.length}</p></CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{pastDueUsers.length > 0 && (
|
||||
<section className="rounded-xl border p-6 space-y-3">
|
||||
<h2 className="font-semibold text-lg">Payments needing attention</h2>
|
||||
<ul className="space-y-1.5">
|
||||
{pastDueUsers.map((u) => (
|
||||
<li key={u.id} className="flex items-center justify-between text-sm">
|
||||
<span>{u.name} <span className="text-muted-foreground">({u.email})</span></span>
|
||||
<Link href={`/admin/users/${u.id}`} className="text-primary hover:underline">View</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-3">
|
||||
<h2 className="font-semibold text-lg">Recent billing events</h2>
|
||||
{recentBillingEvents.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">Nothing yet.</p>
|
||||
) : (
|
||||
<ul className="space-y-1.5">
|
||||
{recentBillingEvents.map((e) => (
|
||||
<li key={e.id} className="flex items-center justify-between text-sm border-b last:border-0 pb-1.5">
|
||||
<span>
|
||||
<span className="font-mono text-xs">{e.action}</span>
|
||||
{e.targetId && (
|
||||
<Link href={`/admin/users/${e.targetId}`} className="text-primary hover:underline ml-2">user</Link>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs">{e.createdAt.toLocaleString()}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Metadata } from "next";
|
||||
import { ChangelogList } from "@/components/shared/changelog-list";
|
||||
import { APP_VERSION } from "@/lib/changelog";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminChangelogPage() {
|
||||
await requireFullAdminPage();
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Changelog</h1>
|
||||
<p className="text-muted-foreground mt-1">Currently running v{APP_VERSION}. Edit apps/web/lib/changelog.ts to update.</p>
|
||||
</div>
|
||||
<ChangelogList />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function AdminError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
console.error(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
|
||||
<h2 className="text-xl font-semibold">Something went wrong</h2>
|
||||
<p className="text-muted-foreground max-w-md">
|
||||
An unexpected error occurred in the admin panel. You can try again.
|
||||
</p>
|
||||
<Button onClick={() => reset()}>Try again</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, users, recipes, userUsage, supportTickets, gte, sql } from "@epicure/db";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { BarChart } from "@/components/admin/charts/bar-chart";
|
||||
import { TimeSeriesChart } from "@/components/admin/charts/time-series-chart";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const DAYS = 30;
|
||||
|
||||
function lastNDays(n: number): string[] {
|
||||
const out: string[] = [];
|
||||
const now = new Date();
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
const d = new Date(now);
|
||||
d.setDate(d.getDate() - i);
|
||||
out.push(d.toISOString().slice(0, 10));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function formatShortDate(d: string) {
|
||||
const date = new Date(`${d}T00:00:00Z`);
|
||||
return date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
|
||||
}
|
||||
|
||||
function lastNMonths(n: number): string[] {
|
||||
const out: string[] = [];
|
||||
const now = new Date();
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
out.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export default async function AdminInsightsPage() {
|
||||
await requireFullAdminPage();
|
||||
const since = new Date();
|
||||
since.setDate(since.getDate() - DAYS);
|
||||
|
||||
// Promise.allSettled, not all — six independent aggregate queries feeding
|
||||
// six independent charts; one query breaking (e.g. a table that's empty
|
||||
// in a fresh install) shouldn't take down every chart on the page.
|
||||
const results = await Promise.allSettled([
|
||||
db
|
||||
.select({ day: sql<string>`to_char(${users.createdAt}, 'YYYY-MM-DD')`.as("day"), n: sql<number>`count(*)::int` })
|
||||
.from(users)
|
||||
.where(gte(users.createdAt, since))
|
||||
.groupBy(sql`to_char(${users.createdAt}, 'YYYY-MM-DD')`),
|
||||
db
|
||||
.select({
|
||||
day: sql<string>`to_char(${recipes.createdAt}, 'YYYY-MM-DD')`.as("day"),
|
||||
aiGenerated: recipes.aiGenerated,
|
||||
n: sql<number>`count(*)::int`,
|
||||
})
|
||||
.from(recipes)
|
||||
.where(gte(recipes.createdAt, since))
|
||||
.groupBy(sql`to_char(${recipes.createdAt}, 'YYYY-MM-DD')`, recipes.aiGenerated),
|
||||
db.select({ tier: users.tier, n: sql<number>`count(*)::int` }).from(users).groupBy(users.tier),
|
||||
db.select({ visibility: recipes.visibility, n: sql<number>`count(*)::int` }).from(recipes).groupBy(recipes.visibility),
|
||||
db
|
||||
.select({ month: userUsage.month, n: sql<number>`coalesce(sum(${userUsage.aiCallsUsed}), 0)::int` })
|
||||
.from(userUsage)
|
||||
.groupBy(userUsage.month),
|
||||
db.select({ status: supportTickets.status, n: sql<number>`count(*)::int` }).from(supportTickets).groupBy(supportTickets.status),
|
||||
]);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "rejected") console.error("[admin/insights] query failed", r.reason);
|
||||
}
|
||||
|
||||
const [signupRows, recipeRows, tierRows, visibilityRows, usageRows, ticketRows] = results.map((r) =>
|
||||
r.status === "fulfilled" ? r.value : []
|
||||
) as [
|
||||
{ day: string; n: number }[],
|
||||
{ day: string; aiGenerated: boolean; n: number }[],
|
||||
{ tier: "free" | "pro" | "family"; n: number }[],
|
||||
{ visibility: "private" | "unlisted" | "public" | "followers"; n: number }[],
|
||||
{ month: string; n: number }[],
|
||||
{ status: "open" | "triaged" | "closed"; n: number }[],
|
||||
];
|
||||
|
||||
const signupByDay = new Map(signupRows.map((r) => [r.day, r.n]));
|
||||
const signupSeries = lastNDays(DAYS).map((day) => ({ date: day, value: signupByDay.get(day) ?? 0 }));
|
||||
|
||||
const recipesByDay = new Map<string, { manual: number; ai: number }>();
|
||||
for (const r of recipeRows) {
|
||||
const entry = recipesByDay.get(r.day) ?? { manual: 0, ai: 0 };
|
||||
if (r.aiGenerated) entry.ai += r.n; else entry.manual += r.n;
|
||||
recipesByDay.set(r.day, entry);
|
||||
}
|
||||
const recipesSeries = lastNDays(DAYS).map((day) => {
|
||||
const entry = recipesByDay.get(day) ?? { manual: 0, ai: 0 };
|
||||
return { label: formatShortDate(day), values: [entry.manual, entry.ai] };
|
||||
});
|
||||
|
||||
const TIER_ORDER = ["free", "pro", "family"] as const;
|
||||
const tierByKey = new Map(tierRows.map((r) => [r.tier, r.n]));
|
||||
const tierData = TIER_ORDER.map((tier) => ({ label: tier, values: [tierByKey.get(tier) ?? 0] }));
|
||||
|
||||
const VISIBILITY_ORDER = ["private", "unlisted", "followers", "public"] as const;
|
||||
const visByKey = new Map(visibilityRows.map((r) => [r.visibility, r.n]));
|
||||
const visibilityData = VISIBILITY_ORDER.map((v) => ({ label: v, values: [visByKey.get(v) ?? 0] }));
|
||||
|
||||
const usageByMonth = new Map(usageRows.map((r) => [r.month, r.n]));
|
||||
const usageSeries = lastNMonths(6).map((month) => ({ date: month, value: usageByMonth.get(month) ?? 0 }));
|
||||
|
||||
const STATUS_ORDER = ["open", "triaged", "closed"] as const;
|
||||
const statusByKey = new Map(ticketRows.map((r) => [r.status, r.n]));
|
||||
const statusData = STATUS_ORDER.map((s) => ({ label: s, values: [statusByKey.get(s) ?? 0] }));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Insights</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">Trends and breakdowns across the last {DAYS} days (or 6 months for usage).</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">New signups</CardTitle>
|
||||
<CardDescription>Daily, last {DAYS} days</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<TimeSeriesChart data={signupSeries} dateFormat="day" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Recipes created</CardTitle>
|
||||
<CardDescription>Daily, manual vs AI-generated</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BarChart data={recipesSeries} seriesLabels={["Manual", "AI-generated"]} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Users by tier</CardTitle>
|
||||
<CardDescription>All-time</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BarChart data={tierData} seriesLabels={["Users"]} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Recipes by visibility</CardTitle>
|
||||
<CardDescription>All-time</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BarChart data={visibilityData} seriesLabels={["Recipes"]} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">AI calls</CardTitle>
|
||||
<CardDescription>Monthly total across all users, last 6 months</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<TimeSeriesChart data={usageSeries} dateFormat="month" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Support tickets by status</CardTitle>
|
||||
<CardDescription>All-time</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BarChart data={statusData} seriesLabels={["Tickets"]} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listInvites } from "@/lib/invites";
|
||||
import { InvitesManager } from "@/components/admin/invites-manager";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminInvitesPage() {
|
||||
await requireFullAdminPage();
|
||||
const invites = await listInvites();
|
||||
const appUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Invites</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Generate shareable signup links. Required when signups are disabled in{" "}
|
||||
<span className="font-medium">Settings</span>.
|
||||
</p>
|
||||
</div>
|
||||
<InvitesManager
|
||||
invites={invites.map((i) => ({
|
||||
id: i.id,
|
||||
token: i.token,
|
||||
email: i.email,
|
||||
role: i.role,
|
||||
tier: i.tier,
|
||||
createdAt: i.createdAt.toISOString(),
|
||||
expiresAt: i.expiresAt?.toISOString() ?? null,
|
||||
}))}
|
||||
appUrl={appUrl}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import Link from "next/link";
|
||||
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge, Mail, Flag, History, LifeBuoy, TrendingUp, Webhook, CreditCard } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getStaffRole } from "@/lib/require-admin-page";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// adminOnly items are hidden from moderators (and, redundantly but safely,
|
||||
// each of those pages also redirects moderators away server-side via
|
||||
// requireFullAdminPage — the nav filter here is UX, not the real gate).
|
||||
const adminNav = [
|
||||
{ href: "/admin", label: "Overview", icon: BarChart3, adminOnly: true },
|
||||
{ href: "/admin/insights", label: "Insights", icon: TrendingUp, adminOnly: true },
|
||||
{ href: "/admin/users", label: "Users", icon: Users, adminOnly: true },
|
||||
{ href: "/admin/invites", label: "Invites", icon: Mail, adminOnly: true },
|
||||
{ href: "/admin/recipes", label: "Recipes", icon: BookOpen, adminOnly: false },
|
||||
{ href: "/admin/reports", label: "Reports", icon: Flag, adminOnly: false },
|
||||
{ href: "/admin/support", label: "Support", icon: LifeBuoy, adminOnly: true },
|
||||
{ href: "/admin/tiers", label: "Tier Limits", icon: Gauge, adminOnly: true },
|
||||
{ href: "/admin/billing", label: "Billing", icon: CreditCard, adminOnly: true },
|
||||
{ href: "/admin/webhooks", label: "Webhooks", icon: Webhook, adminOnly: true },
|
||||
{ href: "/admin/audit-logs", label: "Audit Logs", icon: ClipboardList, adminOnly: true },
|
||||
{ href: "/admin/storage", label: "Storage", icon: HardDrive, adminOnly: true },
|
||||
{ href: "/admin/ai-config", label: "AI Config", icon: Bot, adminOnly: true },
|
||||
{ href: "/admin/settings", label: "Settings", icon: Settings, adminOnly: true },
|
||||
{ href: "/admin/changelog", label: "Changelog", icon: History, adminOnly: true },
|
||||
];
|
||||
|
||||
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const role = await getStaffRole();
|
||||
if (!role) redirect("/recipes");
|
||||
|
||||
const visibleNav = role === "admin" ? adminNav : adminNav.filter((item) => !item.adminOnly);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col md:flex-row min-h-screen">
|
||||
<aside className="w-full md:w-56 md:shrink-0 border-b md:border-b-0 md:border-r bg-muted/30 flex flex-col md:sticky md:top-0 md:h-screen">
|
||||
<div className="flex items-center justify-between gap-2 p-4 border-b font-semibold">
|
||||
<span className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-destructive" />
|
||||
{role === "admin" ? "Admin" : "Moderator"}
|
||||
</span>
|
||||
<Link
|
||||
href="/recipes"
|
||||
className="md:hidden flex items-center gap-1 text-xs font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
Back to app
|
||||
</Link>
|
||||
</div>
|
||||
<nav className="flex overflow-x-auto gap-1 p-2 md:flex-col md:overflow-visible md:flex-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{visibleNav.map(({ href, label, icon: Icon }) => (
|
||||
<Link
|
||||
key={href}
|
||||
href={href}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-md px-3 py-2 text-sm whitespace-nowrap shrink-0 md:shrink transition-colors",
|
||||
"hover:bg-accent hover:text-accent-foreground"
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<div className="p-2 border-t hidden md:block">
|
||||
<Link
|
||||
href="/recipes"
|
||||
className="flex items-center gap-2 rounded-md px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to app
|
||||
</Link>
|
||||
</div>
|
||||
</aside>
|
||||
<main className="flex-1 p-4 md:p-8 overflow-auto min-w-0">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { StatCardSkeleton } from "@/components/shared/skeletons";
|
||||
|
||||
export default function AdminLoading() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-8 w-32" />
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<StatCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { db } from "@epicure/db";
|
||||
import { users, recipes, userUsage, recipePhotos, ratings, reports, cookingHistory, webhooks, apiKeys } from "@epicure/db";
|
||||
import { count, eq, gte, sql } from "@epicure/db";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Users, BookOpen, Sparkles, Image, History, UserPlus, ChefHat, Flag, HardDrive, Webhook, KeyRound } from "lucide-react";
|
||||
import { APP_VERSION, CHANGELOG } from "@/lib/changelog";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminPage() {
|
||||
await requireFullAdminPage();
|
||||
const currentMonth = new Date().toISOString().slice(0, 7);
|
||||
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const [
|
||||
userCount,
|
||||
recipeCount,
|
||||
proUserCount,
|
||||
publicRecipeCount,
|
||||
aiUsage,
|
||||
imageCount,
|
||||
storageUsage,
|
||||
newUsers7d,
|
||||
newRecipes7d,
|
||||
cooked7d,
|
||||
pendingReports,
|
||||
webhookCount,
|
||||
apiKeyCount,
|
||||
] = await Promise.all([
|
||||
db.select({ count: count() }).from(users).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(recipes).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(users).where(eq(users.tier, "pro")).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(recipes).where(eq(recipes.visibility, "public")).then((r) => r[0]),
|
||||
db
|
||||
.select({ total: sql<string>`coalesce(sum(${userUsage.aiCallsUsed}), 0)` })
|
||||
.from(userUsage)
|
||||
.where(eq(userUsage.month, currentMonth))
|
||||
.then((r) => r[0]),
|
||||
db.select({ count: count() }).from(recipePhotos).then((r) => r[0]),
|
||||
Promise.all([
|
||||
db.select({ total: sql<string>`coalesce(sum(${recipePhotos.sizeMb}), 0)` }).from(recipePhotos).then((r) => r[0]),
|
||||
db.select({ total: sql<string>`coalesce(sum(${ratings.photoSizeMb}), 0)` }).from(ratings).then((r) => r[0]),
|
||||
db.select({ total: sql<string>`coalesce(sum(${users.avatarSizeMb}), 0)` }).from(users).then((r) => r[0]),
|
||||
]).then(([photos, reviews, avatars]) => Number(photos?.total ?? 0) + Number(reviews?.total ?? 0) + Number(avatars?.total ?? 0)),
|
||||
db.select({ count: count() }).from(users).where(gte(users.createdAt, sevenDaysAgo)).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(recipes).where(gte(recipes.createdAt, sevenDaysAgo)).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(cookingHistory).where(gte(cookingHistory.cookedAt, sevenDaysAgo)).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(reports).where(eq(reports.status, "pending")).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(webhooks).where(eq(webhooks.active, true)).then((r) => r[0]),
|
||||
db.select({ count: count() }).from(apiKeys).then((r) => r[0]),
|
||||
]);
|
||||
|
||||
const stats = [
|
||||
{ label: "Total Users", value: userCount?.count ?? 0, sub: `${proUserCount?.count ?? 0} pro`, icon: Users },
|
||||
{ label: "New Users (7d)", value: newUsers7d?.count ?? 0, icon: UserPlus },
|
||||
{ label: "Total Recipes", value: recipeCount?.count ?? 0, sub: `${publicRecipeCount?.count ?? 0} public`, icon: BookOpen },
|
||||
{ label: "New Recipes (7d)", value: newRecipes7d?.count ?? 0, icon: BookOpen },
|
||||
{ label: "Cooked (7d)", value: cooked7d?.count ?? 0, icon: ChefHat },
|
||||
{ label: "AI Calls This Month", value: Number(aiUsage?.total ?? 0), icon: Sparkles },
|
||||
{ label: "Recipe Photos", value: imageCount?.count ?? 0, icon: Image },
|
||||
{ label: "Total Storage", value: storageUsage, unit: "MB", icon: HardDrive },
|
||||
{
|
||||
label: "Pending Reports",
|
||||
value: pendingReports?.count ?? 0,
|
||||
icon: Flag,
|
||||
href: "/admin/reports",
|
||||
highlight: (pendingReports?.count ?? 0) > 0,
|
||||
},
|
||||
{ label: "Active Webhooks", value: webhookCount?.count ?? 0, icon: Webhook },
|
||||
{ label: "API Keys Issued", value: apiKeyCount?.count ?? 0, icon: KeyRound },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Overview</h1>
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{stats.map(({ label, value, sub, unit, icon: Icon, href, highlight }) => {
|
||||
const card = (
|
||||
<Card className={highlight ? "border-destructive/50" : undefined}>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">{label}</CardTitle>
|
||||
<Icon className={highlight ? "h-4 w-4 text-destructive" : "h-4 w-4 text-muted-foreground"} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className={highlight ? "text-2xl font-bold text-destructive" : "text-2xl font-bold"}>
|
||||
{value.toLocaleString()}{unit ? ` ${unit}` : ""}
|
||||
</div>
|
||||
{sub && <p className="text-xs text-muted-foreground mt-1">{sub}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
return (
|
||||
<div key={label}>
|
||||
{href ? <Link href={href}>{card}</Link> : card}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Version</CardTitle>
|
||||
<History className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">v{APP_VERSION}</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Released {CHANGELOG[0]?.date} ·{" "}
|
||||
<Link href="/admin/changelog" className="underline hover:text-foreground">
|
||||
View changelog
|
||||
</Link>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, recipes, users, eq, desc, count } from "@epicure/db";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import Link from "next/link";
|
||||
import { UnpublishRecipeButton } from "@/components/admin/unpublish-recipe-button";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
const VISIBILITY_COLORS = {
|
||||
public: "default",
|
||||
unlisted: "outline",
|
||||
followers: "outline",
|
||||
private: "secondary",
|
||||
} as const;
|
||||
|
||||
interface PageProps {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}
|
||||
|
||||
export default async function AdminRecipesPage({ searchParams }: PageProps) {
|
||||
const { page: pageParam } = await searchParams;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
|
||||
const [publicRecipes, totalRow] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
visibility: recipes.visibility,
|
||||
createdAt: recipes.createdAt,
|
||||
authorName: users.name,
|
||||
authorId: users.id,
|
||||
})
|
||||
.from(recipes)
|
||||
.leftJoin(users, eq(recipes.authorId, users.id))
|
||||
.where(eq(recipes.visibility, "public"))
|
||||
.orderBy(desc(recipes.createdAt))
|
||||
.limit(PAGE_SIZE)
|
||||
.offset(offset),
|
||||
db.select({ count: count() }).from(recipes).where(eq(recipes.visibility, "public")),
|
||||
]);
|
||||
const total = totalRow[0]?.count ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Recipe Moderation</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Public recipes sorted by newest. Review and decide manually.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">Title</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Author</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Visibility</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Created</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Link</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{publicRecipes.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
|
||||
No public recipes yet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
publicRecipes.map((recipe) => (
|
||||
<tr key={recipe.id} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3 font-medium">{recipe.title}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{recipe.authorId ? (
|
||||
<Link
|
||||
href={`/admin/users/${recipe.authorId}`}
|
||||
className="hover:underline underline-offset-4"
|
||||
>
|
||||
{recipe.authorName ?? "Unknown"}
|
||||
</Link>
|
||||
) : (
|
||||
<span>{recipe.authorName ?? "Unknown"}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={VISIBILITY_COLORS[recipe.visibility]}>
|
||||
{recipe.visibility}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{recipe.createdAt.toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Link
|
||||
href={`/r/${recipe.id}`}
|
||||
className="text-primary underline-offset-4 hover:underline text-xs"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<UnpublishRecipeButton recipeId={recipe.id} />
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{page > 1 && (
|
||||
<Link
|
||||
href={`/admin/recipes?page=${page - 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Previous
|
||||
</Link>
|
||||
)}
|
||||
{offset + publicRecipes.length < total && (
|
||||
<Link
|
||||
href={`/admin/recipes?page=${page + 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Next
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { db, reports, users, eq, desc, count } from "@epicure/db";
|
||||
import { ReportsQueue } from "@/components/admin/reports-queue";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
interface PageProps {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}
|
||||
|
||||
export default async function AdminReportsPage({ searchParams }: PageProps) {
|
||||
const { page: pageParam } = await searchParams;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
|
||||
const [rows, totalRow] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: reports.id,
|
||||
targetType: reports.targetType,
|
||||
targetId: reports.targetId,
|
||||
reason: reports.reason,
|
||||
createdAt: reports.createdAt,
|
||||
reporterName: users.name,
|
||||
reporterEmail: users.email,
|
||||
})
|
||||
.from(reports)
|
||||
.innerJoin(users, eq(reports.reporterId, users.id))
|
||||
.where(eq(reports.status, "pending"))
|
||||
.orderBy(desc(reports.createdAt))
|
||||
.limit(PAGE_SIZE)
|
||||
.offset(offset),
|
||||
db.select({ count: count() }).from(reports).where(eq(reports.status, "pending")),
|
||||
]);
|
||||
const total = totalRow[0]?.count ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Reports</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Content flagged by users. Dismiss if unfounded, or review and take action manually.
|
||||
</p>
|
||||
</div>
|
||||
<ReportsQueue
|
||||
reports={rows.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))}
|
||||
/>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{page > 1 && (
|
||||
<Link
|
||||
href={`/admin/reports?page=${page - 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Previous
|
||||
</Link>
|
||||
)}
|
||||
{offset + rows.length < total && (
|
||||
<Link
|
||||
href={`/admin/reports?page=${page + 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Next
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getAllSiteSettings, isSignupsDisabled } from "@/lib/site-settings";
|
||||
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
|
||||
import { SignupsToggle } from "@/components/admin/signups-toggle";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const SETTING_GROUPS = [
|
||||
{
|
||||
title: "Push Notifications (VAPID)",
|
||||
description: "Keys for web push notifications. Generate with: npx web-push generate-vapid-keys",
|
||||
keys: ["NEXT_PUBLIC_VAPID_PUBLIC_KEY", "VAPID_PRIVATE_KEY"] as const,
|
||||
},
|
||||
{
|
||||
title: "Gitea Integration",
|
||||
description:
|
||||
"Support tickets submitted in-app automatically open an issue on this Gitea repo. Setup: " +
|
||||
"GITEA_URL = your Gitea base URL, no trailing slash (e.g. https://git.example.com). " +
|
||||
"GITEA_REPO = owner/repo (e.g. owner/my-app). " +
|
||||
"GITEA_TOKEN = a personal access token — Gitea → Settings → Applications → Generate New Token — " +
|
||||
"with the \"issue\" scope (read + write) only; nothing broader is needed since this integration " +
|
||||
"never touches code or repo settings, just creates issues.",
|
||||
keys: ["GITEA_URL", "GITEA_TOKEN", "GITEA_REPO"] as const,
|
||||
},
|
||||
{
|
||||
title: "USDA FoodData Central",
|
||||
description:
|
||||
"Improves recipe nutrition estimates with real per-ingredient data instead of AI-only guesses, " +
|
||||
"for ingredients whose quantity/unit can be converted to grams. Free — get a key at " +
|
||||
"fdc.nal.usda.gov/api-key-signup. Unset falls back to the previous AI-only estimation for every ingredient.",
|
||||
keys: ["USDA_API_KEY"] as const,
|
||||
},
|
||||
];
|
||||
|
||||
export default async function AdminSettingsPage() {
|
||||
await requireFullAdminPage();
|
||||
const settings = await getAllSiteSettings();
|
||||
const signupsDisabled = await isSignupsDisabled();
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Site Settings</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Override .env values at runtime. DB values take precedence over environment variables.
|
||||
Clear a value to fall back to the environment variable. AI provider keys and model
|
||||
defaults have moved to AI Config.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<SignupsToggle initialDisabled={signupsDisabled} />
|
||||
|
||||
{SETTING_GROUPS.map((group) => (
|
||||
<AdminSettingsForm key={group.title} group={group} settings={settings} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, users, recipePhotos, recipes, eq, desc, sql, count } from "@epicure/db";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { HardDrive } from "lucide-react";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminStoragePage() {
|
||||
await requireFullAdminPage();
|
||||
const [totalPhotos, recipesWithPhotos, photosByTier, topUsers] = await Promise.all([
|
||||
db.select({ count: count() }).from(recipePhotos).then((r) => r[0]),
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(recipePhotos)
|
||||
.where(eq(recipePhotos.isCover, true))
|
||||
.then((r) => r[0]),
|
||||
db
|
||||
.select({
|
||||
tier: users.tier,
|
||||
photoCount: sql<string>`count(${recipePhotos.id})`,
|
||||
})
|
||||
.from(recipePhotos)
|
||||
.innerJoin(recipes, eq(recipePhotos.recipeId, recipes.id))
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.groupBy(users.tier),
|
||||
db
|
||||
.select({
|
||||
userId: users.id,
|
||||
name: users.name,
|
||||
email: users.email,
|
||||
tier: users.tier,
|
||||
photoCount: sql<string>`count(${recipePhotos.id})`,
|
||||
})
|
||||
.from(recipePhotos)
|
||||
.innerJoin(recipes, eq(recipePhotos.recipeId, recipes.id))
|
||||
.innerJoin(users, eq(recipes.authorId, users.id))
|
||||
.groupBy(users.id, users.name, users.email, users.tier)
|
||||
.orderBy(desc(sql`count(${recipePhotos.id})`))
|
||||
.limit(10),
|
||||
]);
|
||||
|
||||
const freePhotos = Number(photosByTier.find((r) => r.tier === "free")?.photoCount ?? 0);
|
||||
const proPhotos = Number(photosByTier.find((r) => r.tier === "pro")?.photoCount ?? 0);
|
||||
const familyPhotos = Number(photosByTier.find((r) => r.tier === "family")?.photoCount ?? 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Storage Usage</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Photo storage breakdown by tier and user.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Total Photos</CardTitle>
|
||||
<HardDrive className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{(totalPhotos?.count ?? 0).toLocaleString()}</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">{recipesWithPhotos?.count ?? 0} cover photos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Free Tier Photos</CardTitle>
|
||||
<HardDrive className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{freePhotos.toLocaleString()}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Pro Tier Photos</CardTitle>
|
||||
<HardDrive className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{proPhotos.toLocaleString()}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Family Tier Photos</CardTitle>
|
||||
<HardDrive className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{familyPhotos.toLocaleString()}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-3">Top 10 Users by Photo Count</h2>
|
||||
<div className="rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">User</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Tier</th>
|
||||
<th className="px-4 py-3 text-right font-medium">Photos</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{topUsers.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={3} className="px-4 py-8 text-center text-muted-foreground">
|
||||
No photos uploaded yet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
topUsers.map((row) => (
|
||||
<tr key={row.userId} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-medium">{row.name ?? "Unknown"}</div>
|
||||
{row.email && (
|
||||
<div className="text-xs text-muted-foreground">{row.email}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={row.tier === "pro" ? "default" : "secondary"}>
|
||||
{row.tier ?? "—"}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right font-mono">
|
||||
{Number(row.photoCount).toLocaleString()}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, supportTickets, desc } from "@epicure/db";
|
||||
import { AdminSupportManager } from "@/components/admin/admin-support-manager";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminSupportPage() {
|
||||
await requireFullAdminPage();
|
||||
const rows = await db.query.supportTickets.findMany({
|
||||
orderBy: desc(supportTickets.createdAt),
|
||||
with: {
|
||||
attachments: true,
|
||||
user: { columns: { email: true, username: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Support Tickets</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Bug reports, suggestions, and questions submitted through the app.
|
||||
</p>
|
||||
</div>
|
||||
<AdminSupportManager
|
||||
initialTickets={rows.map((r) => ({
|
||||
id: r.id,
|
||||
userEmail: r.user.email,
|
||||
username: r.user.username,
|
||||
type: r.type,
|
||||
title: r.title,
|
||||
description: r.description,
|
||||
status: r.status,
|
||||
giteaIssueUrl: r.giteaIssueUrl,
|
||||
giteaError: r.giteaError,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
attachments: r.attachments.map((a) => ({
|
||||
id: a.id,
|
||||
contentType: a.contentType,
|
||||
url: getPublicUrl(a.storageKey),
|
||||
})),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, tierDefinitions } from "@epicure/db";
|
||||
import { TierLimitsForm } from "@/components/admin/tier-limits-form";
|
||||
import { FeatureFlagsForm } from "@/components/admin/feature-flags-form";
|
||||
import { getFeatureFlagMatrix, FEATURE_DEFINITIONS } from "@/lib/feature-flags";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminTiersPage() {
|
||||
await requireFullAdminPage();
|
||||
const [tiers, featureFlagMatrix] = await Promise.all([
|
||||
db.select().from(tierDefinitions),
|
||||
getFeatureFlagMatrix(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Tier Limits</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Change monthly quotas per tier. Takes effect immediately for all users on that tier.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{tiers.map((tierDefinition) => (
|
||||
<TierLimitsForm key={tierDefinition.tier} tierDefinition={tierDefinition} />
|
||||
))}
|
||||
|
||||
<FeatureFlagsForm
|
||||
features={FEATURE_DEFINITIONS.map((f) => ({ key: f.key, label: f.label, description: f.description }))}
|
||||
initialMatrix={featureFlagMatrix}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { db, users, recipes, userUsage, eq, desc, count, and } from "@epicure/db";
|
||||
import { getStorageUsedMb } from "@/lib/tiers";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { UserEditor } from "@/components/admin/user-editor";
|
||||
import { ResetUsageButton } from "@/components/admin/reset-usage-button";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
const ROLE_COLORS = {
|
||||
user: "secondary",
|
||||
moderator: "outline",
|
||||
admin: "destructive",
|
||||
} as const;
|
||||
|
||||
const TIER_COLORS = {
|
||||
free: "secondary",
|
||||
pro: "default",
|
||||
family: "default",
|
||||
} as const;
|
||||
|
||||
export default async function AdminUserDetailPage({ params }: PageProps) {
|
||||
await requireFullAdminPage();
|
||||
const { id } = await params;
|
||||
|
||||
const [user] = await db.select().from(users).where(eq(users.id, id)).limit(1);
|
||||
if (!user) notFound();
|
||||
|
||||
const currentMonth = new Date().toISOString().slice(0, 7);
|
||||
|
||||
const [usage] = await db
|
||||
.select()
|
||||
.from(userUsage)
|
||||
.where(and(eq(userUsage.userId, id), eq(userUsage.month, currentMonth)))
|
||||
.limit(1);
|
||||
|
||||
const [[recipeCountRow], storageUsedMb] = await Promise.all([
|
||||
db.select({ count: count() }).from(recipes).where(eq(recipes.authorId, id)),
|
||||
getStorageUsedMb(id),
|
||||
]);
|
||||
|
||||
const recentRecipes = await db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
visibility: recipes.visibility,
|
||||
createdAt: recipes.createdAt,
|
||||
})
|
||||
.from(recipes)
|
||||
.where(eq(recipes.authorId, id))
|
||||
.orderBy(desc(recipes.createdAt))
|
||||
.limit(10);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
href="/admin/users"
|
||||
className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Users
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<Avatar className="h-16 w-16">
|
||||
<AvatarImage src={user.avatarUrl ?? ""} alt={user.name} />
|
||||
<AvatarFallback className="text-lg">
|
||||
{user.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">{user.name}</h1>
|
||||
<p className="text-muted-foreground">{user.email}</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Joined {user.createdAt.toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<div className="ml-auto flex gap-2">
|
||||
<Badge variant={ROLE_COLORS[user.role]}>{user.role}</Badge>
|
||||
<Badge variant={TIER_COLORS[user.tier]}>{user.tier}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Edit Role & Tier</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<UserEditor userId={user.id} currentRole={user.role} currentTier={user.tier} currentIsDeveloper={user.isDeveloper} currentIsByokEnabled={user.isByokEnabled} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Usage & Limits</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">AI Calls Used ({currentMonth})</span>
|
||||
<span className="font-medium">{usage?.aiCallsUsed ?? 0}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Total Recipes</span>
|
||||
<span className="font-medium">{recipeCountRow?.count ?? 0}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Storage Used</span>
|
||||
<span className="font-medium">{storageUsedMb} MB</span>
|
||||
</div>
|
||||
<div className="pt-2">
|
||||
<ResetUsageButton userId={user.id} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-3">Recent Recipes</h2>
|
||||
{recentRecipes.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">No recipes yet.</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">Title</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Visibility</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Created</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Link</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{recentRecipes.map((recipe) => (
|
||||
<tr key={recipe.id} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3 font-medium">{recipe.title}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant="outline">{recipe.visibility}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{recipe.createdAt.toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Link
|
||||
href={`/r/${recipe.id}`}
|
||||
className="text-primary underline-offset-4 hover:underline text-xs"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, count } from "@epicure/db";
|
||||
import { users } from "@epicure/db";
|
||||
import { desc } from "@epicure/db";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { CreateUserDialog } from "@/components/admin/create-user-dialog";
|
||||
import Link from "next/link";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
interface PageProps {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}
|
||||
|
||||
const ROLE_COLORS = {
|
||||
user: "secondary",
|
||||
moderator: "outline",
|
||||
admin: "destructive",
|
||||
} as const;
|
||||
|
||||
const TIER_COLORS = {
|
||||
free: "secondary",
|
||||
pro: "default",
|
||||
family: "default",
|
||||
} as const;
|
||||
|
||||
export default async function AdminUsersPage({ searchParams }: PageProps) {
|
||||
await requireFullAdminPage();
|
||||
const { page: pageParam } = await searchParams;
|
||||
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
|
||||
const offset = (page - 1) * PAGE_SIZE;
|
||||
|
||||
const [allUsers, totalRow] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(users)
|
||||
.orderBy(desc(users.createdAt))
|
||||
.limit(PAGE_SIZE)
|
||||
.offset(offset),
|
||||
db.select({ count: count() }).from(users),
|
||||
]);
|
||||
const total = totalRow[0]?.count ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Users</h1>
|
||||
<CreateUserDialog />
|
||||
</div>
|
||||
<div className="rounded-md border overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">User</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Role</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Tier</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Joined</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{allUsers.map((user) => (
|
||||
<tr key={user.id} className="border-b last:border-0 hover:bg-muted/30">
|
||||
<td className="px-4 py-3">
|
||||
<Link href={`/admin/users/${user.id}`} className="flex items-center gap-3 group">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={user.avatarUrl ?? ""} alt={user.name} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{user.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<div className="font-medium group-hover:underline underline-offset-4">{user.name}</div>
|
||||
<div className="text-muted-foreground text-xs">{user.email}</div>
|
||||
</div>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={ROLE_COLORS[user.role]}>{user.role}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={TIER_COLORS[user.tier]}>{user.tier}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{user.createdAt.toLocaleDateString()}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{page > 1 && (
|
||||
<Link
|
||||
href={`/admin/users?page=${page - 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Previous
|
||||
</Link>
|
||||
)}
|
||||
{offset + allUsers.length < total && (
|
||||
<Link
|
||||
href={`/admin/users?page=${page + 1}`}
|
||||
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
|
||||
>
|
||||
Next
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Metadata } from "next";
|
||||
import { db, adminWebhooks } from "@epicure/db";
|
||||
import { AdminWebhooksManager } from "@/components/admin/admin-webhooks-manager";
|
||||
import { requireFullAdminPage } from "@/lib/require-admin-page";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
export default async function AdminWebhooksPage() {
|
||||
await requireFullAdminPage();
|
||||
const rows = await db
|
||||
.select({
|
||||
id: adminWebhooks.id,
|
||||
url: adminWebhooks.url,
|
||||
events: adminWebhooks.events,
|
||||
active: adminWebhooks.active,
|
||||
createdAt: adminWebhooks.createdAt,
|
||||
})
|
||||
.from(adminWebhooks);
|
||||
|
||||
const webhooks = rows.map((w) => ({ ...w, createdAt: w.createdAt.toISOString() }));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Webhooks</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Site-wide ops events (new signups, support tickets, reports) — deliver to any HTTP endpoint (Slack/Discord incoming webhook, internal alerting, etc). Fires regardless of who's involved, unlike the per-user webhooks under Settings.
|
||||
</p>
|
||||
</div>
|
||||
<AdminWebhooksManager initialWebhooks={webhooks} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const HTML = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Epicure API Docs</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
|
||||
<style>
|
||||
body { margin: 0; }
|
||||
.swagger-ui .topbar { background-color: #18181b; }
|
||||
.swagger-ui .topbar .download-url-wrapper .select-label select { border-color: #52525b; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
SwaggerUIBundle({
|
||||
url: "/api/v1/openapi.json",
|
||||
dom_id: "#swagger-ui",
|
||||
presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
|
||||
layout: "BaseLayout",
|
||||
deepLinking: true,
|
||||
tryItOutEnabled: true,
|
||||
persistAuthorization: true,
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
export async function GET() {
|
||||
return new NextResponse(HTML, {
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { db, chatMessages, lt } from "@epicure/db";
|
||||
|
||||
// Internal cron endpoint — triggered daily by a cron container (see
|
||||
// compose.prod.yml / cron/crontab). Not part of the public API surface;
|
||||
// protected by a shared secret rather than user auth.
|
||||
//
|
||||
// AI chat history (both the per-recipe chat and the general cooking
|
||||
// assistant) has no size cap and no per-user retention setting — this just
|
||||
// deletes anything past a fixed retention window so the table doesn't grow
|
||||
// unbounded.
|
||||
|
||||
const RETENTION_DAYS = 90;
|
||||
|
||||
function isAuthorized(req: NextRequest): boolean {
|
||||
const secret = process.env["CRON_SECRET"];
|
||||
if (!secret) return false;
|
||||
|
||||
const header = req.headers.get("authorization");
|
||||
if (!header?.startsWith("Bearer ")) return false;
|
||||
const provided = header.slice("Bearer ".length);
|
||||
|
||||
const a = Buffer.from(provided);
|
||||
const b = Buffer.from(secret);
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isAuthorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const cutoff = new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1000);
|
||||
const deleted = await db.delete(chatMessages).where(lt(chatMessages.createdAt, cutoff)).returning({ id: chatMessages.id });
|
||||
|
||||
return NextResponse.json({ ok: true, deleted: deleted.length });
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { db, cookingHistory, eq, and, isNotNull, isNull } from "@epicure/db";
|
||||
import { sendEmail, notificationEmailHtml } from "@/lib/email";
|
||||
import { sendPushNotification } from "@/lib/push";
|
||||
import { isLeftoverExpiringSoon } from "@/lib/leftover-match";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
import { isNotificationCategoryEnabled } from "@/lib/notification-prefs";
|
||||
|
||||
// Internal cron endpoint — triggered daily by a cron container (see
|
||||
// compose.prod.yml / cron/crontab). Not part of the public API surface;
|
||||
// protected by a shared secret rather than user auth.
|
||||
//
|
||||
// For every cooking_history row tied to a batch-cook dish, checks whether it
|
||||
// expires soon (see lib/leftover-match.ts) and hasn't already been reminded
|
||||
// about, then sends one push + email and marks it reminded so it never fires
|
||||
// twice for the same cooked dish.
|
||||
|
||||
function isAuthorized(req: NextRequest): boolean {
|
||||
const secret = process.env["CRON_SECRET"];
|
||||
if (!secret) return false;
|
||||
|
||||
const header = req.headers.get("authorization");
|
||||
if (!header?.startsWith("Bearer ")) return false;
|
||||
const provided = header.slice("Bearer ".length);
|
||||
|
||||
const a = Buffer.from(provided);
|
||||
const b = Buffer.from(secret);
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isAuthorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const candidates = await db.query.cookingHistory.findMany({
|
||||
where: and(isNotNull(cookingHistory.batchDishId), isNull(cookingHistory.expiryReminderSentAt)),
|
||||
with: {
|
||||
batchDish: { columns: { id: true, name: true, fridgeDays: true } },
|
||||
recipe: { columns: { id: true, title: true } },
|
||||
user: { columns: { id: true, email: true, locale: true } },
|
||||
},
|
||||
});
|
||||
|
||||
let sent = 0;
|
||||
for (const log of candidates) {
|
||||
if (!log.batchDish || !log.user) continue;
|
||||
if (!isLeftoverExpiringSoon(log.cookedAt, log.batchDish.fridgeDays)) continue;
|
||||
|
||||
const messages = getMessages(log.user.locale);
|
||||
const template = messages.notifications.detail.leftoverExpiring;
|
||||
const title = messages.notifications.pushTitle.leftoverExpiring;
|
||||
const body = formatMessage(template, { dish: log.batchDish.name, title: log.recipe.title });
|
||||
const url = `/recipes/${log.recipe.id}`;
|
||||
const pushEnabled = await isNotificationCategoryEnabled(log.user.id, "leftoverExpiring");
|
||||
|
||||
await Promise.all([
|
||||
pushEnabled
|
||||
? sendPushNotification(log.user.id, { title, body, url }).catch((err) => {
|
||||
console.error("[leftover-reminders] push failed", err);
|
||||
})
|
||||
: Promise.resolve(),
|
||||
log.user.email
|
||||
? sendEmail({
|
||||
to: log.user.email,
|
||||
subject: title,
|
||||
html: notificationEmailHtml(title, body, `${process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"}${url}`),
|
||||
}).catch((err) => {
|
||||
console.error("[leftover-reminders] email failed", err);
|
||||
})
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
|
||||
await db.update(cookingHistory)
|
||||
.set({ expiryReminderSentAt: new Date() })
|
||||
.where(eq(cookingHistory.id, log.id));
|
||||
sent++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, checked: candidates.length, sent });
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import {
|
||||
db,
|
||||
users,
|
||||
recipes,
|
||||
comments,
|
||||
ratings,
|
||||
userFollows,
|
||||
favorites,
|
||||
userNotificationPrefs,
|
||||
eq,
|
||||
and,
|
||||
gte,
|
||||
desc,
|
||||
count,
|
||||
sql,
|
||||
} from "@epicure/db";
|
||||
import { sendEmail, weeklyDigestHtml } from "@/lib/email";
|
||||
|
||||
// Internal cron endpoint — triggered by the `digest-cron` container on a weekly
|
||||
// schedule (see compose.prod.yml). Not part of the public API surface;
|
||||
// protected by a shared secret rather than user auth.
|
||||
//
|
||||
// Computes, for every opted-in user: new followers / new comments / new
|
||||
// ratings on their recipes in the last 7 days, plus a site-wide top-3
|
||||
// trending list, and emails a summary. Excludes users who turned off
|
||||
// "Weekly digest" in Settings → Notifications (userNotificationPrefs.weeklyDigestEmail,
|
||||
// default true — no row means opted in).
|
||||
|
||||
const CHUNK_SIZE = 20;
|
||||
|
||||
function isAuthorized(req: NextRequest): boolean {
|
||||
const secret = process.env["CRON_SECRET"];
|
||||
if (!secret) return false;
|
||||
|
||||
const header = req.headers.get("authorization");
|
||||
if (!header?.startsWith("Bearer ")) return false;
|
||||
const provided = header.slice("Bearer ".length);
|
||||
|
||||
const a = Buffer.from(provided);
|
||||
const b = Buffer.from(secret);
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
function chunk<T>(arr: T[], size: number): T[][] {
|
||||
const out: T[][] = [];
|
||||
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isAuthorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
|
||||
const [allUsers, optedOutRows, followerRows, commentRows, ratingRows, trending] = await Promise.all([
|
||||
db.select({ id: users.id, email: users.email }).from(users),
|
||||
db
|
||||
.select({ userId: userNotificationPrefs.userId })
|
||||
.from(userNotificationPrefs)
|
||||
.where(eq(userNotificationPrefs.weeklyDigestEmail, false)),
|
||||
db
|
||||
.select({ userId: userFollows.followingId, n: count() })
|
||||
.from(userFollows)
|
||||
.where(gte(userFollows.createdAt, weekAgo))
|
||||
.groupBy(userFollows.followingId),
|
||||
db
|
||||
.select({ userId: recipes.authorId, n: count() })
|
||||
.from(comments)
|
||||
.innerJoin(recipes, eq(comments.recipeId, recipes.id))
|
||||
.where(gte(comments.createdAt, weekAgo))
|
||||
.groupBy(recipes.authorId),
|
||||
db
|
||||
.select({ userId: recipes.authorId, n: count() })
|
||||
.from(ratings)
|
||||
.innerJoin(recipes, eq(ratings.recipeId, recipes.id))
|
||||
.where(gte(ratings.createdAt, weekAgo))
|
||||
.groupBy(recipes.authorId),
|
||||
db
|
||||
.select({
|
||||
id: recipes.id,
|
||||
title: recipes.title,
|
||||
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
|
||||
})
|
||||
.from(recipes)
|
||||
.leftJoin(
|
||||
favorites,
|
||||
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, weekAgo))
|
||||
)
|
||||
.where(eq(recipes.visibility, "public"))
|
||||
.groupBy(recipes.id)
|
||||
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
|
||||
.limit(3),
|
||||
]);
|
||||
|
||||
const optedOut = new Set(optedOutRows.map((r) => r.userId));
|
||||
const recipients = allUsers.filter((u) => !optedOut.has(u.id));
|
||||
|
||||
const followerMap = new Map(followerRows.map((r) => [r.userId, r.n]));
|
||||
const commentMap = new Map(commentRows.map((r) => [r.userId, r.n]));
|
||||
const ratingMap = new Map(ratingRows.map((r) => [r.userId, r.n]));
|
||||
const trendingList = trending.map((r) => ({ id: r.id, title: r.title }));
|
||||
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (const batch of chunk(recipients, CHUNK_SIZE)) {
|
||||
const results = await Promise.allSettled(
|
||||
batch.map((user) => {
|
||||
const newFollowers = followerMap.get(user.id) ?? 0;
|
||||
const newComments = commentMap.get(user.id) ?? 0;
|
||||
const newRatings = ratingMap.get(user.id) ?? 0;
|
||||
|
||||
return sendEmail({
|
||||
to: user.email,
|
||||
subject: "Your weekly digest — Epicure",
|
||||
html: weeklyDigestHtml({
|
||||
newFollowers,
|
||||
newComments,
|
||||
newRatings,
|
||||
trending: trendingList,
|
||||
baseUrl,
|
||||
}),
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled") sent++;
|
||||
else failed++;
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, totalUsers: allUsers.length, optedOut: optedOut.size, sent, failed });
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireAdmin } from "@/lib/api-auth";
|
||||
import { getFeatureFlagMatrix, setFeatureFlag, FEATURE_KEYS, TIERS } from "@/lib/feature-flags";
|
||||
|
||||
export async function GET() {
|
||||
const { response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
|
||||
const matrix = await getFeatureFlagMatrix();
|
||||
return NextResponse.json(matrix);
|
||||
}
|
||||
|
||||
const UpdateBody = z.object({
|
||||
featureKey: z.enum(FEATURE_KEYS as [string, ...string[]]),
|
||||
tier: z.enum(TIERS as [string, ...string[]]),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const { session, response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
|
||||
const body = (await req.json()) as unknown;
|
||||
const parsed = UpdateBody.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
await setFeatureFlag(
|
||||
parsed.data.featureKey as (typeof FEATURE_KEYS)[number],
|
||||
parsed.data.tier as (typeof TIERS)[number],
|
||||
parsed.data.enabled,
|
||||
session!.user.id
|
||||
);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAdmin } from "@/lib/api-auth";
|
||||
import { db, invites, auditLogs, eq } from "@epicure/db";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export async function DELETE(_req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
const [deleted] = await db.delete(invites).where(eq(invites.id, id)).returning();
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: "Invite not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
await db.insert(auditLogs).values({
|
||||
id: randomUUID(),
|
||||
userId: session!.user.id,
|
||||
action: "admin.invite.revoke",
|
||||
targetType: "invite",
|
||||
targetId: id,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAdmin } from "@/lib/api-auth";
|
||||
import { db, auditLogs } from "@epicure/db";
|
||||
import { createInvite, listInvites } from "@/lib/invites";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
const VALID_ROLES = ["user", "moderator", "admin"] as const;
|
||||
const VALID_TIERS = ["free", "pro", "family"] as const;
|
||||
|
||||
export async function GET() {
|
||||
const { response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
|
||||
const invites = await listInvites();
|
||||
return NextResponse.json({ invites });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
|
||||
const body = (await req.json()) as {
|
||||
email?: string;
|
||||
role?: string;
|
||||
tier?: string;
|
||||
expiresInDays?: number;
|
||||
};
|
||||
|
||||
const role = body.role ?? "user";
|
||||
const tier = body.tier ?? "free";
|
||||
if (!VALID_ROLES.includes(role as (typeof VALID_ROLES)[number])) {
|
||||
return NextResponse.json({ error: "Invalid role" }, { status: 400 });
|
||||
}
|
||||
if (!VALID_TIERS.includes(tier as (typeof VALID_TIERS)[number])) {
|
||||
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
|
||||
}
|
||||
|
||||
const invite = await createInvite({
|
||||
createdById: session!.user.id,
|
||||
email: body.email,
|
||||
role: role as (typeof VALID_ROLES)[number],
|
||||
tier: tier as (typeof VALID_TIERS)[number],
|
||||
expiresInDays: body.expiresInDays ?? 7,
|
||||
});
|
||||
|
||||
await db.insert(auditLogs).values({
|
||||
id: randomUUID(),
|
||||
userId: session!.user.id,
|
||||
action: "admin.invite.create",
|
||||
targetType: "invite",
|
||||
targetId: invite!.id,
|
||||
metadata: JSON.stringify({ email: body.email, role, tier }),
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
return NextResponse.json({ invite });
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { randomUUID } from "crypto";
|
||||
import { z } from "zod";
|
||||
import { requireAdmin } from "@/lib/api-auth";
|
||||
import { db, recipes, auditLogs, eq } from "@epicure/db";
|
||||
|
||||
const PatchSchema = z.object({
|
||||
action: z.literal("unpublish"),
|
||||
});
|
||||
|
||||
/** Admin/moderator takedown action — flips a public recipe to private.
|
||||
* Deliberately narrow (just this one transition) rather than exposing full
|
||||
* visibility management here, since that's the recipe owner's call. */
|
||||
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { session, response } = await requireAdmin({ allowModerator: true });
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
const parsed = PatchSchema.safeParse(await req.json());
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(recipes)
|
||||
.set({ visibility: "private" })
|
||||
.where(eq(recipes.id, id))
|
||||
.returning({ id: recipes.id });
|
||||
|
||||
if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
await db.insert(auditLogs).values({
|
||||
id: randomUUID(),
|
||||
userId: session!.user.id,
|
||||
action: "admin.recipe.unpublish",
|
||||
targetType: "recipe",
|
||||
targetId: id,
|
||||
metadata: null,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAdmin } from "@/lib/api-auth";
|
||||
import { db, reports, auditLogs, eq } from "@epicure/db";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireAdmin({ allowModerator: true });
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
const body = (await req.json()) as { status?: string };
|
||||
if (body.status !== "reviewed" && body.status !== "dismissed") {
|
||||
return NextResponse.json({ error: "Invalid status" }, { status: 400 });
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(reports)
|
||||
.set({ status: body.status, reviewedById: session!.user.id, reviewedAt: new Date() })
|
||||
.where(eq(reports.id, id))
|
||||
.returning();
|
||||
|
||||
if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
await db.insert(auditLogs).values({
|
||||
id: randomUUID(),
|
||||
userId: session!.user.id,
|
||||
action: "admin.report.resolve",
|
||||
targetType: "report",
|
||||
targetId: id,
|
||||
metadata: JSON.stringify({ status: body.status }),
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
return NextResponse.json({ report: updated });
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user