first commit beta.0.0.3.3

This commit is contained in:
2026-01-16 19:04:48 +02:00
commit 1b0063955a
1535 changed files with 163318 additions and 0 deletions

View File

@@ -0,0 +1,248 @@
# Coolify Database Migration Guide
This guide helps you backup your current database and restore it on Coolify.
## 📋 Prerequisites
- PostgreSQL client tools (`pg_dump`, `psql`) installed
- Access to current database
- Access to Coolify database
## 🔄 Step 1: Backup Current Database
### Option A: Using Backup Script (Recommended)
```bash
# Make script executable
chmod +x scripts/backup-database.sh
# Run backup
./scripts/backup-database.sh
```
This creates a backup in `backups/YYYYMMDD_HHMMSS/` with:
- `schema.sql` - Database schema
- `data.sql` - All data
- `full_dump.sql` - Complete dump (schema + data)
- `migrations/` - Prisma migrations
- `schema.prisma` - Prisma schema file
- `metadata.json` - Backup metadata
### Option B: Manual Backup
```bash
# Export full database
pg_dump -h localhost -U postgres -d your_database_name > backup.sql
# Or using DATABASE_URL
pg_dump $DATABASE_URL > backup.sql
```
## 🚀 Step 2: Set Up Database on Coolify
### 2.1 Create PostgreSQL Service in Coolify
1. In Coolify, create a new PostgreSQL service
2. Note the container name (e.g., `postgres-CONTAINER_ID`)
3. Note the database credentials
### 2.2 Configure Environment Variables
Set these in your Next.js app service in Coolify:
```bash
# Database URLs (use internal Docker network)
DATABASE_URL=postgresql://postgres:PASSWORD@postgres-CONTAINER_ID:5432/postgres
RUNTIME_DATABASE_URL=postgresql://postgres:PASSWORD@postgres-CONTAINER_ID:5432/postgres
# Optional: Shadow database for migrations
SHADOW_DATABASE_URL=postgresql://postgres:PASSWORD@postgres-CONTAINER_ID:5432/postgres
```
**Important**: Replace `CONTAINER_ID` with actual container ID from Coolify.
## 🔧 Step 3: Restore Database on Coolify
### Option A: Using Restore Script
1. **Copy backup to Coolify server**:
```bash
# From your local machine
scp -r backups/latest user@coolify-server:/path/to/app/
```
2. **SSH into Coolify server**:
```bash
ssh user@coolify-server
cd /path/to/app
```
3. **Run restore script**:
```bash
chmod +x scripts/restore-database.sh
./scripts/restore-database.sh backups/latest
```
### Option B: Manual Restore via Coolify
1. **Access PostgreSQL container**:
```bash
# In Coolify, open terminal for PostgreSQL service
# Or SSH and run:
docker exec -it postgres-CONTAINER_ID psql -U postgres
```
2. **Create database** (if needed):
```sql
CREATE DATABASE your_database_name;
\c your_database_name
```
3. **Restore from backup**:
```bash
# Copy backup.sql into container
docker cp backup.sql postgres-CONTAINER_ID:/tmp/
# Restore
docker exec -it postgres-CONTAINER_ID psql -U postgres -d your_database_name -f /tmp/backup.sql
```
### Option C: Using Prisma Migrations (Recommended)
If you have Prisma migrations, use them instead:
1. **Ensure migrations are in repo**:
```bash
# Migrations should be in prisma/migrations/
ls prisma/migrations/
```
2. **Deploy migrations in Coolify**:
```bash
# Add to build command or run manually
npx prisma migrate deploy
```
3. **Seed data** (if needed):
```bash
npm run db:seed
```
## ✅ Step 4: Verify Database
### Check Connection
```bash
# Test connection
docker exec -it postgres-CONTAINER_ID psql -U postgres -d your_database_name -c "SELECT version();"
```
### Verify Data
```bash
# Check tables
docker exec -it postgres-CONTAINER_ID psql -U postgres -d your_database_name -c "\dt"
# Check record counts
docker exec -it postgres-CONTAINER_ID psql -U postgres -d your_database_name -c "SELECT COUNT(*) FROM \"Guest\";"
```
### Test from Application
1. Deploy your Next.js app in Coolify
2. Check application logs for database connection errors
3. Test key features that require database access
## 🔍 Troubleshooting
### Issue: Connection Refused
**Problem**: App can't connect to database
**Solution**:
- Verify `DATABASE_URL` uses correct container name
- Check Docker network allows communication
- Ensure PostgreSQL container is running
### Issue: Migration Errors
**Problem**: Prisma migrations fail
**Solution**:
```bash
# Reset and redeploy
npx prisma migrate reset
npx prisma migrate deploy
# Or use db push (development only)
npx prisma db push
```
### Issue: Permission Denied
**Problem**: Database user lacks permissions
**Solution**:
```sql
-- Grant necessary permissions
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO postgres;
GRANT ALL ON SCHEMA public TO postgres;
```
### Issue: Schema Mismatch
**Problem**: Restored schema doesn't match Prisma schema
**Solution**:
```bash
# Sync Prisma schema with database
npx prisma db pull
npx prisma generate
```
## 📝 Database Configuration Reference
### Current Database Config
Your database uses:
- **Provider**: PostgreSQL
- **Schema**: Defined in `prisma/schema.prisma`
- **Migrations**: `prisma/migrations/`
### Key Models
- `Guest` - Guest information and RSVP
- `Song` - Song requests
- `GuestbookEntry` - Guestbook messages
- `GalleryPhoto` - Photo gallery
- `Table` - Seating arrangements
- `Admin` - Admin users
- `Tribute` - Tributes/dedications
- `Reminder` - Email/SMS reminders
- `ABTest` - A/B testing
- `CouplesPlaylist` - Couple's playlist
### Seed Data
Seed script: `prisma/seed.ts`
- Seeds guests from `data/guests.csv`
- Creates admin user
- Creates sample tables
## 🔐 Security Notes
1. **Never commit backups** with real data
2. **Use strong passwords** for production database
3. **Restrict database access** to application only
4. **Use connection pooling** (`RUNTIME_DATABASE_URL`)
5. **Enable SSL** for production connections
## 📚 Related Documentation
- [COOLIFY_MIGRATION.md](./COOLIFY_MIGRATION.md) - General Coolify migration guide
- [PRODUCTION_ENV_VARIABLES.md](./PRODUCTION_ENV_VARIABLES.md) - Environment variables reference
- [Prisma Migrations](https://www.prisma.io/docs/concepts/components/prisma-migrate)
---
**Last Updated**: January 2025

158
docs/DATABASE_CONFIG.md Normal file
View File

@@ -0,0 +1,158 @@
# Database Configuration Reference
## Current Setup
### Database Type
- **Provider**: Supabase (PostgreSQL)
- **ORM**: Prisma
- **Connection**: Via `DATABASE_URL` environment variable pointing to Supabase
### Schema Location
- **Prisma Schema**: `prisma/schema.prisma`
- **Migrations**: `prisma/migrations/`
- **Seed Script**: `prisma/seed.ts`
## Database Models
### Core Models
1. **Guest** - Guest information and RSVP
- Fields: name, inviteCode, email, phone, maxPax, isAttending, etc.
- Relations: Song, GuestbookEntry, GalleryPhoto, Tribute, Table
2. **Song** - Song requests from guests
- Fields: title, artist, votes, previewUrl, trackUrl
- Relations: Guest, SongVote
3. **GuestbookEntry** - Guestbook messages
- Fields: message, photo, audioUrl, videoUrl
- Relations: Guest
4. **GalleryPhoto** - Photo gallery uploads
- Fields: url, thumbnailUrl, caption, likes
- Relations: Guest, PhotoComment
5. **Table** - Seating arrangements
- Fields: name, capacity
- Relations: Guest
6. **Admin** - Admin users
- Fields: username, password, email, totpSecret, totpEnabled
7. **Tribute** - Tributes/dedications
- Fields: guestName, dedication
- Relations: Guest (optional)
8. **Reminder** - Email/SMS reminders
- Fields: name, type, trigger, targetAudience, enabled
9. **ABTest** - A/B testing
- Fields: name, type, status, variantA, variantB, splitRatio
10. **CouplesPlaylist** - Couple's playlist
- Fields: title, artist, trackUrl, previewUrl, order, revealAt
## Environment Variables
### Required
```bash
# Supabase PostgreSQL connection string
# Get from Supabase Dashboard → Settings → Database → Connection String
# Use "Connection Pooling" mode for RUNTIME_DATABASE_URL
DATABASE_URL=postgresql://postgres:[PASSWORD]@[HOST]:5432/postgres
RUNTIME_DATABASE_URL=postgresql://postgres:[PASSWORD]@[HOST]:6543/postgres?pgbouncer=true # Connection pooling
```
### Optional
```bash
SHADOW_DATABASE_URL=postgresql://postgres:[PASSWORD]@[HOST]:5432/postgres # For migrations (direct connection)
```
## Migration Commands
```bash
# Generate Prisma client
npx prisma generate
# Create migration
npx prisma migrate dev --name migration_name
# Deploy migrations (production)
npx prisma migrate deploy
# Push schema changes (development)
npx prisma db push
# Seed database
npm run db:seed
# Open Prisma Studio
npm run db:studio
```
## Backup & Restore
See [COOLIFY_DATABASE_MIGRATION.md](./COOLIFY_DATABASE_MIGRATION.md) for detailed instructions.
### Quick Backup
```bash
./scripts/backup-database.sh
```
### Quick Restore
```bash
./scripts/restore-database.sh backups/latest
```
## Supabase Configuration
### Getting Connection Strings
1. Go to [Supabase Dashboard](https://app.supabase.com)
2. Select your project
3. Go to **Settings****Database**
4. Copy connection strings:
- **Direct connection** (for migrations): Use port `5432`
- **Connection pooling** (for runtime): Use port `6543` with `?pgbouncer=true`
### App Environment Variables
```bash
# Direct connection (for migrations)
DATABASE_URL=postgresql://postgres:[PASSWORD]@db.[PROJECT_REF].supabase.co:5432/postgres
# Connection pooling (for runtime - recommended)
RUNTIME_DATABASE_URL=postgresql://postgres:[PASSWORD]@db.[PROJECT_REF].supabase.co:6543/postgres?pgbouncer=true
# Optional: Shadow database for migrations (if using separate database)
SHADOW_DATABASE_URL=postgresql://postgres:[PASSWORD]@db.[PROJECT_REF].supabase.co:5432/postgres
```
**Important**:
- Replace `[PASSWORD]` with your Supabase database password
- Replace `[PROJECT_REF]` with your Supabase project reference ID
- Use connection pooling (`RUNTIME_DATABASE_URL`) for production to avoid connection limits
## Seed Data
Seed data comes from:
- `data/guests.csv` - Guest list
- `prisma/seed.ts` - Seed script
Seed includes:
- Guests from CSV
- Admin user (username: `admin`)
- Sample tables (Table 1-5)
## Connection Pooling
For production, use `RUNTIME_DATABASE_URL` with a connection pooler (e.g., PgBouncer):
- Direct connection: Port `5432`
- Pooled connection: Port `6543` (or configured port)
## Security Notes
1. Use strong database passwords
2. Restrict database access to application only
3. Use connection pooling in production
4. Enable SSL for production connections
5. Never commit `.env` files with real credentials

361
docs/DOCS_GOVERNANCE.md Normal file
View File

@@ -0,0 +1,361 @@
# Documentation Governance
**Last Updated:** January 2025
**Purpose:** Rules and guidelines for maintaining documentation quality and preventing documentation sprawl
---
## Principles
1. **Single Source of Truth (SSOT)** - All documentation lives in `docs/SSOT.md`
2. **Minimal Supporting Docs** - Only operational runbooks and development guidelines outside SSOT
3. **No Duplication** - Setup instructions exist in exactly one place
4. **Code-Aligned** - Documentation must match actual codebase
5. **Maintained** - Documentation updated when code changes
---
## Documentation Structure
### Allowed Locations
**Primary Location: `docs/`**
- All documentation must be in the `docs/` directory
- Exceptions require explicit approval (see below)
**Allowed Files in Root:**
- `README.md` - Project overview, links to documentation
- No other markdown files in root (except conductor/ which is separate)
**Allowed Files Outside `docs/`:**
- `README.md` (root) - Must point to `docs/DOCS_INDEX.md`
- `conductor/*.md` - Conductor system files (separate system)
- `supabase/migrations/README_*.md` - Supabase migration docs (technical)
### File Naming Conventions
**Documentation Files:**
- Use `UPPER_SNAKE_CASE.md` for main documents (e.g., `SSOT.md`, `DOCS_INDEX.md`)
- Use `kebab-case.md` for supporting docs (e.g., `deployment-runbook.md`, `backup-procedures.md`)
- Use descriptive names that indicate purpose
**Prohibited Patterns:**
- ❌ Status files: `*_STATUS.md`, `*_PROGRESS.md`, `*_COMPLETE.md`
- ❌ Duplicate names: `DEPLOYMENT_*.md` (multiple variants)
- ❌ Date-based names: `2025-01-*.md`
- ❌ Phase-based names: `PHASE*_*.md` (unless archived)
---
## Documentation Types
### 1. Single Source of Truth (SSOT)
**File:** `docs/SSOT.md`
**Purpose:** Comprehensive documentation covering all aspects of the project.
**Content:**
- Overview (project description, tech stack, features)
- Architecture (system design, directory structure, data flow)
- Local Development Setup (installation, setup, commands)
- Environment Configuration (all environment variables)
- Database & Supabase (setup, integration, migrations)
- Deployment (Proxmox deployment procedures)
- Troubleshooting (common issues and solutions)
- Operations & Runbooks (backup, monitoring, maintenance)
**Update Rules:**
- Must be updated when:
- New features are added
- Environment variables change
- Deployment procedures change
- Architecture changes
- Dependencies change (package.json, docker-compose.yml)
### 2. Supporting Documentation
**Allowed Supporting Docs:**
- `docs/deployment-runbook.md` - Detailed deployment procedures
- `docs/backup-procedures.md` - Backup and restore procedures
- `docs/coding-standards.md` - Development guidelines
**Rules:**
- Must be linked from `docs/SSOT.md`
- Must be linked from `docs/DOCS_INDEX.md`
- Should not duplicate content from SSOT
- Should provide detailed procedures for operational tasks
### 3. Index and Governance
**Required Files:**
- `docs/DOCS_INDEX.md` - Documentation index and navigation
- `docs/DOCS_GOVERNANCE.md` - This file
- `docs/DOCS_MIGRATION_PLAN.md` - Migration reference (historical)
---
## Creating New Documentation
### Process
1. **Check if content belongs in SSOT**
- Most content should go in `docs/SSOT.md`
- If it's setup, configuration, or general information → SSOT
2. **Request approval for new supporting doc**
- Create an issue or PR discussion
- Explain why it can't go in SSOT
- Get approval from maintainers
3. **Create documentation**
- Add to appropriate section in SSOT, OR
- Create new file in `docs/` (if approved)
- Update `docs/DOCS_INDEX.md` with link
- Link from relevant SSOT section
4. **Run validation**
- Run `./scripts/check-docs.sh`
- Fix any violations
- Ensure all links work
### Approval Criteria for New Docs
A new supporting document is approved only if:
- It's an operational runbook (detailed step-by-step procedures)
- It's a development guideline (coding standards, style guides)
- It's too large to include in SSOT (1000+ lines)
- It's frequently updated independently of SSOT
**Examples of Approved Supporting Docs:**
-`deployment-runbook.md` - Detailed deployment procedures
-`backup-procedures.md` - Backup operations
-`coding-standards.md` - Development guidelines
**Examples of Rejected New Docs:**
-`NEW_FEATURE_SETUP.md` - Should be in SSOT
-`ENV_VARS_V2.md` - Should update SSOT instead
-`DEPLOYMENT_GUIDE_V2.md` - Should update SSOT instead
---
## Updating Documentation
### When to Update SSOT
**Must Update SSOT When:**
- New environment variables added
- Deployment procedures change
- Architecture changes
- New features added
- Dependencies change (package.json, docker-compose.yml)
- Database schema changes
- API changes
### Update Process
1. **Identify what changed**
- Code changes
- Configuration changes
- Process changes
2. **Update SSOT.md**
- Find relevant section
- Update content
- Ensure code blocks are accurate
- Update any affected links
3. **Update DOCS_INDEX.md** (if structure changes)
- Add new sections if needed
- Update quick reference table
4. **Run validation**
- `./scripts/check-docs.sh`
- Verify links work
- Test code blocks
5. **Commit**
- Include documentation updates in same PR as code changes
- Or create separate PR if documentation-only
---
## PR Checklist
Before merging a PR that affects documentation:
- [ ] **SSOT Updated** - If code/config changed, SSOT.md updated
- [ ] **No New Docs** - No new .md files outside docs/ (unless approved)
- [ ] **Links Valid** - All markdown links work
- [ ] **Code Blocks Tested** - Code examples are accurate
- [ ] **Index Updated** - DOCS_INDEX.md updated if structure changed
- [ ] **Validation Passed** - `./scripts/check-docs.sh` passes
- [ ] **No Duplication** - No duplicate setup instructions
### Automated Checks
The `scripts/check-docs.sh` script automatically checks:
- ✅ No new .md files outside docs/ (without approval)
- ✅ No duplicate "setup instructions" blocks
- ✅ SSOT.md updated when key files change (package.json, docker-compose.yml)
- ✅ All markdown links are valid
**CI Integration:**
- Add `./scripts/check-docs.sh` to CI pipeline
- Fail PR if validation fails
---
## Versioning Policy
### Documentation Versioning
**SSOT Version:**
- Update version number in SSOT.md header when:
- Major structural changes
- Significant content reorganization
- Breaking changes to procedures
**Changelog:**
- Add "Last Updated" date to SSOT.md
- Note significant changes in commit messages
- Consider adding CHANGELOG.md for major versions (optional)
### Deprecation
**Deprecating Content:**
- Mark deprecated sections in SSOT with `> **Deprecated:** ...`
- Provide migration path
- Remove after 2 major versions
**Removing Files:**
- Update DOCS_MIGRATION_PLAN.md with removal reason
- Ensure content is in SSOT or approved supporting doc
- Update all internal links
---
## Quality Standards
### Content Quality
**Required:**
- ✅ Accurate (matches actual codebase)
- ✅ Complete (covers all necessary information)
- ✅ Clear (easy to understand)
- ✅ Up-to-date (reflects current state)
- ✅ Actionable (provides clear steps)
**Code Blocks:**
- Must be tested and accurate
- Include expected output where relevant
- Use proper syntax highlighting
- Include file paths when relevant
**Links:**
- All internal links must work
- Use relative paths
- Link to specific sections with anchors
### Structure Quality
**Headings:**
- Use clear, descriptive headings
- Follow hierarchy (H1 → H2 → H3)
- Use consistent formatting
**Sections:**
- Logical organization
- Easy to navigate
- Table of contents for long documents
---
## Enforcement
### Automated Enforcement
**Script:** `scripts/check-docs.sh`
**Checks:**
1. No new .md files outside docs/ (without approval file)
2. No duplicate setup instruction blocks
3. SSOT.md updated when key files change
4. All markdown links valid
**CI Integration:**
```yaml
# .github/workflows/docs-check.yml (example)
- name: Check Documentation
run: ./scripts/check-docs.sh
```
### Manual Review
**PR Review:**
- Reviewers check PR checklist
- Verify documentation updates match code changes
- Ensure no documentation sprawl
**Regular Audits:**
- Quarterly review of documentation structure
- Check for outdated content
- Verify all links work
- Remove unused files
---
## Exceptions
### Requesting Exceptions
To create documentation outside `docs/`:
1. **Create Issue/PR Discussion**
- Explain why exception is needed
- Propose alternative if possible
- Get maintainer approval
2. **Create Approval File**
- Create `.docs-approval/<filename>.approved`
- Include reason for exception
- Link to discussion/issue
3. **Update DOCS_INDEX.md**
- Add to index with explanation
- Link from SSOT if relevant
### Approved Exceptions
**Current Exceptions:**
- `conductor/*.md` - Conductor system (separate system)
- `supabase/migrations/README_*.md` - Supabase migration docs (technical)
---
## Migration from Old Structure
See [DOCS_MIGRATION_PLAN.md](DOCS_MIGRATION_PLAN.md) for:
- Complete list of old files
- Migration actions
- Redirect map
**After Migration:**
- All old files removed or archived
- All links updated
- SSOT is single source of truth
---
## Questions?
- **Can I create a new doc?** Check if it belongs in SSOT first. If not, request approval.
- **Where does this go?** Most content goes in SSOT. Supporting docs only for operational runbooks.
- **How do I update?** Update SSOT.md, run validation, update DOCS_INDEX.md if needed.
- **What if I find outdated docs?** Update SSOT.md or create PR to remove outdated content.
---
**Last Updated:** January 2025
**Maintained By:** Development Team
**Questions?** Create an issue or discussion.

188
docs/DOCS_INDEX.md Normal file
View File

@@ -0,0 +1,188 @@
# Documentation Index
**Last Updated:** January 2025
**Purpose:** Complete guide to all documentation in the Moyos Wedding App repository
---
## Quick Start
**New to the project?** Start here:
1. [SSOT.md](SSOT.md) - Single Source of Truth (start here!)
2. [SSOT.md - Local Development Setup](SSOT.md#local-development-setup) - Get up and running
3. [SSOT.md - Environment Configuration](SSOT.md#environment-configuration) - Configure your environment
---
## Main Documentation
### [SSOT.md](SSOT.md) - Single Source of Truth
**The definitive documentation for the Moyos Wedding App.**
Contains:
- [Overview](SSOT.md#overview) - Project description, tech stack, features
- [Architecture](SSOT.md#architecture) - System architecture, directory structure, data flow
- [Local Development Setup](SSOT.md#local-development-setup) - Installation, setup, development commands
- [Environment Configuration](SSOT.md#environment-configuration) - All environment variables, security best practices
- [Database & Supabase](SSOT.md#database--supabase) - Database setup, Supabase integration, migrations
- [Deployment (Proxmox)](SSOT.md#deployment-proxmox) - Production deployment to Proxmox
- [Troubleshooting](SSOT.md#troubleshooting) - Common issues and solutions
- [Operations & Runbooks](SSOT.md#operations--runbooks) - Backup, monitoring, maintenance
**When to use:** Always start here. This is the single source of truth for all information.
---
## Supporting Documentation
### Operational Runbooks
#### [deployment-runbook.md](deployment-runbook.md)
**Detailed deployment procedures and runbooks.**
Contains:
- Pre-deployment checklist
- Step-by-step deployment process
- Post-deployment verification
- Rollback procedures
- Troubleshooting deployment issues
**When to use:** When deploying to production or staging.
#### [backup-procedures.md](backup-procedures.md)
**Backup and restore procedures.**
Contains:
- Backup strategy and frequency
- Automated backup setup
- Manual backup procedures
- Restore procedures
- Backup verification
**When to use:** When setting up backups, performing backups, or restoring from backups.
### Development Guidelines
#### [coding-standards.md](coding-standards.md)
**Code style guide and development standards.**
Contains:
- File and folder naming conventions
- Type definitions
- Component patterns
- API route structure
- Import organization
- Testing guidelines
**When to use:** When writing or reviewing code.
---
## Documentation Governance
### [DOCS_GOVERNANCE.md](DOCS_GOVERNANCE.md)
**Rules and guidelines for maintaining documentation.**
Contains:
- Documentation structure rules
- Naming conventions
- PR checklist for documentation
- How to update SSOT
- Versioning policy
**When to use:** When creating, updating, or reviewing documentation.
### [DOCS_MIGRATION_PLAN.md](DOCS_MIGRATION_PLAN.md)
**Complete migration plan for documentation consolidation.**
Contains:
- List of all markdown files
- Action for each file (KEEP/MERGE/DELETE/RENAME)
- Redirect map (old path → new path)
- Migration rationale
**When to use:** Reference for understanding documentation structure changes.
---
## Where to Find What
### Setup & Installation
- **Local Development:** [SSOT.md - Local Development Setup](SSOT.md#local-development-setup)
- **Environment Variables:** [SSOT.md - Environment Configuration](SSOT.md#environment-configuration)
- **Database Setup:** [SSOT.md - Database & Supabase](SSOT.md#database--supabase)
### Deployment
- **Quick Start:** [SSOT.md - Deployment (Proxmox)](SSOT.md#deployment-proxmox)
- **Detailed Procedures:** [deployment-runbook.md](deployment-runbook.md)
- **Backup Setup:** [backup-procedures.md](backup-procedures.md)
### Development
- **Code Standards:** [coding-standards.md](coding-standards.md)
- **Architecture:** [SSOT.md - Architecture](SSOT.md#architecture)
- **API Documentation:** [SSOT.md - Architecture](SSOT.md#architecture) (see data flow section)
### Troubleshooting
- **Common Issues:** [SSOT.md - Troubleshooting](SSOT.md#troubleshooting)
- **Deployment Issues:** [deployment-runbook.md](deployment-runbook.md) (troubleshooting section)
### Operations
- **Backups:** [backup-procedures.md](backup-procedures.md)
- **Monitoring:** [SSOT.md - Operations & Runbooks](SSOT.md#operations--runbooks)
- **Maintenance:** [SSOT.md - Operations & Runbooks](SSOT.md#operations--runbooks)
---
## Documentation Structure
```
docs/
├── SSOT.md # Single Source of Truth (START HERE)
├── DOCS_INDEX.md # This file - documentation index
├── DOCS_GOVERNANCE.md # Documentation governance rules
├── DOCS_MIGRATION_PLAN.md # Migration plan and file actions
├── deployment-runbook.md # Detailed deployment procedures
├── backup-procedures.md # Backup and restore procedures
└── coding-standards.md # Development guidelines
```
---
## Quick Reference
| What You Need | Where to Find It |
|---------------|------------------|
| **Project overview** | [SSOT.md - Overview](SSOT.md#overview) |
| **Local setup** | [SSOT.md - Local Development Setup](SSOT.md#local-development-setup) |
| **Environment variables** | [SSOT.md - Environment Configuration](SSOT.md#environment-configuration) |
| **Database setup** | [SSOT.md - Database & Supabase](SSOT.md#database--supabase) |
| **Deploy to production** | [SSOT.md - Deployment (Proxmox)](SSOT.md#deployment-proxmox) |
| **Deployment details** | [deployment-runbook.md](deployment-runbook.md) |
| **Backup procedures** | [backup-procedures.md](backup-procedures.md) |
| **Troubleshooting** | [SSOT.md - Troubleshooting](SSOT.md#troubleshooting) |
| **Code standards** | [coding-standards.md](coding-standards.md) |
| **Architecture** | [SSOT.md - Architecture](SSOT.md#architecture) |
---
## Contributing to Documentation
1. **Read [DOCS_GOVERNANCE.md](DOCS_GOVERNANCE.md)** - Understand the rules
2. **Update SSOT.md** - Add/update information in the single source of truth
3. **Update this index** - If adding new supporting docs, update this file
4. **Link from SSOT** - Ensure new content is linked from SSOT.md
5. **Run validation** - Run `./scripts/check-docs.sh` before committing
---
## Questions?
- **Can't find what you need?** Check [SSOT.md](SSOT.md) first
- **Documentation outdated?** Update [SSOT.md](SSOT.md) and create a PR
- **New documentation needed?** Read [DOCS_GOVERNANCE.md](DOCS_GOVERNANCE.md) first
---
**Last Updated:** January 2025
**Maintained By:** Development Team

390
docs/DOCS_MIGRATION_PLAN.md Normal file
View File

@@ -0,0 +1,390 @@
# Documentation Migration Plan
**Date:** January 2025
**Purpose:** Complete migration plan for consolidating 179 markdown files into SSOT structure
**Total Files:** 179
---
## Migration Summary
- **KEEP:** 7 files (SSOT, supporting docs, README)
- **MERGE INTO SSOT:** 45 files (content consolidated into SSOT.md)
- **DELETE:** 110 files (duplicates, outdated, historical status)
- **ARCHIVE:** 17 files (historical phase reports, moved to docs/archive/)
---
## File Actions
### KEEP (7 files)
| File | Action | Reason |
|------|--------|--------|
| `docs/SSOT.md` | KEEP | Single source of truth (newly created) |
| `docs/DOCS_INDEX.md` | KEEP | Documentation index (newly created) |
| `docs/DOCS_GOVERNANCE.md` | KEEP | Governance rules (newly created) |
| `docs/DOCS_MIGRATION_PLAN.md` | KEEP | This file - migration reference |
| `docs/deployment-runbook.md` | KEEP | Detailed operational runbook |
| `docs/backup-procedures.md` | KEEP | Operational backup procedures |
| `docs/coding-standards.md` | KEEP | Development guidelines |
| `README.md` | KEEP | Root README (will be updated to point to SSOT) |
---
### MERGE INTO SSOT (45 files)
Content from these files has been consolidated into `docs/SSOT.md`:
#### Setup & Getting Started (6 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `QUICK_START_GUIDE.md` | Local Development Setup | Setup instructions consolidated |
| `QUICK_START_LOCAL.md` | Local Development Setup | Local setup consolidated |
| `START_HERE.md` | Overview, Local Development Setup | Entry point content merged |
| `SUPABASE_SETUP.md` | Database & Supabase | Supabase setup merged |
| `SUPABASE_LOCAL_SETUP.md` | Database & Supabase | Local Supabase setup merged |
| `NEXT_STEPS.md` | Overview | Next steps merged into overview |
#### Environment Variables (2 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `ENVIRONMENT_VARIABLES.md` | Environment Configuration | Complete env var reference merged |
| `ENV_VARIABLES_NOTES.md` | Environment Configuration | Supabase-specific notes merged |
#### Deployment (10 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `DEPLOYMENT_QUICK_START.md` | Deployment (Proxmox) | Quick start merged |
| `docs/DEPLOYMENT_QUICK_START.md` | Deployment (Proxmox) | Duplicate, merged |
| `docs/DEPLOYMENT_MACBOOK_TO_PROXMOX.md` | Deployment (Proxmox) | MacBook setup merged |
| `docs/DEPLOYMENT_PROXMOX_SUPABASE.md` | Deployment (Proxmox), Database & Supabase | Supabase deployment merged |
| `YOUR_DEPLOYMENT_GUIDE.md` | Deployment (Proxmox) | Personal deployment guide merged |
| `YOUR_PROXMOX_SETUP.md` | Deployment (Proxmox) | Personal setup merged |
| `PROXMOX_DEPLOYMENT_GUIDE.md` | Deployment (Proxmox) | Comprehensive guide merged |
| `docs/PROXMOX_NETWORK_CONFIG.md` | Deployment (Proxmox) | Network config merged |
| `CONTAINER_CREATION_COMMANDS.md` | Deployment (Proxmox) | Container commands merged |
| `docs/proxmox-migration.md` | Architecture, Deployment | Architecture and migration merged |
#### Architecture (5 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `CODEBASE_REVIEW.md` | Architecture | Architecture analysis merged |
| `DATA_FLOW_ANALYSIS.md` | Architecture | Data flow merged |
| `FEATURE_MAPPING.md` | Overview | Features merged into overview |
| `COMPONENT_INVENTORY.md` | Architecture | Component structure merged |
| `COMPREHENSIVE_AUDIT_REPORT.md` | Architecture, Overview | Audit findings merged |
#### Security (8 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `SECURITY.md` | Environment Configuration (security section) | Security implementation merged |
| `SECURITY_TOOLS_SETUP.md` | Environment Configuration | Security tools merged |
| `RLS_FIX_SUMMARY.md` | Database & Supabase | RLS fixes merged |
| `RLS_STATUS.md` | Database & Supabase | RLS status merged |
| `RLS_VERIFICATION.md` | Database & Supabase | RLS verification merged |
| `RLS_SECURITY_ISSUE.md` | Database & Supabase | RLS security merged |
| `docs/csrf-audit.md` | Environment Configuration | CSRF audit merged |
| `docs/secrets-management-audit.md` | Environment Configuration | Secrets audit merged |
| `docs/security-headers-audit.md` | Environment Configuration | Security headers merged |
| `docs/file-upload-security-audit.md` | Environment Configuration | File upload security merged |
| `docs/security-audit-checklist.md` | Environment Configuration | Security checklist merged |
#### Troubleshooting (5 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `TROUBLESHOOTING.md` | Troubleshooting | Troubleshooting guide merged |
| `TURBOPACK_FIX.md` | Troubleshooting | Turbopack fix merged |
| `TURBOPACK_WORKAROUND.md` | Troubleshooting | Turbopack workaround merged |
| `DATABASE_CONNECTION_STATUS.md` | Troubleshooting | Database troubleshooting merged |
| `CHUNK_LOAD_ERROR_FIX.md` | Troubleshooting | Chunk load error merged |
#### Operations (4 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `BACKUP_RESTORE_GUIDE.md` | Operations & Runbooks | Backup guide merged (detailed procedures in backup-procedures.md) |
| `POST_LAUNCH_MONITORING.md` | Operations & Runbooks | Monitoring merged |
| `PRE_LAUNCH_CHECKLIST.md` | Deployment (Proxmox) | Pre-launch checklist merged |
| `QUICK_REFERENCE.md` | Operations & Runbooks | Quick reference merged |
#### Configuration (2 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `OPENWEATHER_SETUP.md` | Environment Configuration | OpenWeather setup merged |
| `QUICK_OPENWEATHER_SETUP.md` | Environment Configuration | Quick OpenWeather setup merged |
| `SENTRY_CONFIGURATION.md` | Environment Configuration | Sentry config merged |
#### Other (3 files)
| File | Merged Into SSOT Section | Reason |
|------|--------------------------|--------|
| `PRODUCTION.md` | Deployment (Proxmox) | Production config merged |
| `PRODUCTION_SUMMARY.md` | Overview | Production summary merged |
| `HANDOFF.md` | Operations & Runbooks | Handoff procedures merged |
---
### DELETE (110 files)
These files are duplicates, outdated, or contain information already in SSOT:
#### Duplicate/Outdated Deployment (8 files)
- `DEPLOYMENT_SETUP.md` - Duplicate, merged into SSOT
- `DEPLOYMENT_READY.md` - Status file, outdated
- `DEPLOYMENT_CONFIGURED.md` - Status file, outdated
- `DEPLOYMENT_STATUS.md` - Status file, outdated
- `DEPLOYMENT_CHECKLIST.md` - Merged into deployment-runbook.md
- `README_PRODUCTION.md` - Duplicate of README, merged into SSOT
- `docs/PROD-READINESS.md` - Duplicate, merged into SSOT
#### Production Readiness Status (12 files)
- `PRODUCTION_READINESS_COMPLETE.md` - Status file, outdated
- `PRODUCTION_READINESS_FINAL.md` - Status file, outdated
- `PRODUCTION_READINESS_PROGRESS.md` - Status file, outdated
- `PRODUCTION_READINESS_STATUS.md` - Status file, outdated
- `PRODUCTION_READINESS_SUMMARY.md` - Status file, outdated
- `PRODUCTION_READINESS_REPORT.md` - Status file, outdated
- `PRODUCTION_READINESS_CHECKLIST.md` - Merged into SSOT
- `PRODUCTION_READY.md` - Status file, outdated
- `PRODUCTION_READY_CHECKLIST.md` - Duplicate checklist
- `PRODUCTION_IMPLEMENTATION_PROGRESS.md` - Status file, outdated
- `docs/PRODUCTION_READINESS_FINAL.md` - Duplicate status file
- `docs/PRODUCTION_READINESS_FINAL_SUMMARY.md` - Duplicate status file
- `docs/production-readiness-audit.md` - Merged into SSOT
- `docs/production-readiness-plan.md` - Merged into SSOT
- `docs/production-readiness-summary.md` - Merged into SSOT
#### Phase Status Reports (50+ files)
All phase status/progress files are historical and should be archived or deleted:
**Phase 2:**
- `PHASE2_IMPLEMENTATION_SUMMARY.md` - Historical status
- `docs/phase2-completion-summary.md` - Historical status
**Phase 3:**
- `docs/phase3-complete-summary.md` - Historical status
- `docs/phase3-current-status.md` - Historical status
- `docs/phase3-final-status.md` - Historical status
- `docs/phase3-final-summary.md` - Historical status
- `docs/phase3-other-tasks-summary.md` - Historical status
- `docs/phase3-progress-update.md` - Historical status
- `docs/phase3-progress.md` - Historical status
- `docs/phase3-update-summary.md` - Historical status
**Phase 4:**
- `PHASE4_IMPLEMENTATION_SUMMARY.md` - Historical status
- `docs/PHASE4_COMPLETE_CELEBRATION.md` - Historical status
- `docs/PHASE4_TESTING_100_PERCENT_COMPLETE.md` - Historical status
- `docs/PHASE4_TESTING_COMPLETE.md` - Historical status
- `docs/PHASE4_TESTING_COMPLETE_FINAL.md` - Historical status
- `docs/PHASE4_TESTING_COMPLETE_REPORT.md` - Historical status
- `docs/PHASE4_TESTING_COMPREHENSIVE_REPORT.md` - Historical status
- `docs/PHASE4_TESTING_EXPANDED.md` - Historical status
- `docs/PHASE4_TESTING_FINAL_EXPANSION.md` - Historical status
- `docs/PHASE4_TESTING_FINAL_REPORT.md` - Historical status
- `docs/PHASE4_TESTING_NEAR_COMPLETE.md` - Historical status
- `docs/PHASE4_TESTING_SUCCESS_SUMMARY.md` - Historical status
- `docs/PHASE4_TO_PHASE5_TRANSITION.md` - Historical status
- `docs/phase4-testing-achievements.md` - Historical status
- `docs/phase4-testing-comprehensive-summary.md` - Historical status
- `docs/phase4-testing-comprehensive-update.md` - Historical status
- `docs/phase4-testing-final-status.md` - Historical status
- `docs/phase4-testing-final-summary.md` - Historical status
- `docs/phase4-testing-final-update.md` - Historical status
- `docs/phase4-testing-progress-update.md` - Historical status
- `docs/phase4-testing-progress.md` - Historical status
- `docs/phase4-testing-status.md` - Historical status
- `docs/phase4-testing-update.md` - Historical status
**Phase 5:**
- `docs/PHASE5_COMPLETE_SUMMARY.md` - Historical status
- `docs/PHASE5_FINAL_STATUS.md` - Historical status
- `docs/PHASE5_INTEGRATION_GUIDE.md` - Historical status (merged into SSOT)
- `docs/PHASE5_OBSERVABILITY_IMPLEMENTATION.md` - Historical status (merged into SSOT)
**Phase 6:**
- `docs/PHASE6_COMPLETE.md` - Historical status
- `docs/PHASE6_COMPLETE_FINAL.md` - Historical status
- `docs/PHASE6_COMPLETE_SUMMARY.md` - Historical status
- `docs/PHASE6_FINAL_STATUS.md` - Historical status
- `docs/PHASE6_IMAGE_OPTIMIZATION_AUDIT.md` - Historical status (merged into SSOT)
- `docs/PHASE6_PERFORMANCE_OPTIMIZATION.md` - Historical status (merged into SSOT)
- `docs/PHASE6_PROGRESS_REPORT.md` - Historical status
- `docs/PHASE6_QUERY_AUDIT.md` - Historical status (merged into SSOT)
**Phase 7:**
- `docs/PHASE7_COMPLETE.md` - Historical status
- `docs/PHASE7_FINAL_SUMMARY.md` - Historical status
- `docs/PHASE7_PROGRESS.md` - Historical status
- `docs/PHASE7_SETUP_GUIDE.md` - Historical status (merged into SSOT)
- `docs/PHASE7_STORAGE_MIGRATION.md` - Historical status (merged into SSOT)
**Phase 8:**
- `docs/PHASE8_COMPLETE.md` - Historical status
- `docs/PHASE8_PROGRESS.md` - Historical status
**All Phases:**
- `docs/ALL_PHASES_FINAL_STATUS.md` - Historical status
- `docs/ALL_PHASES_STATUS.md` - Historical status
#### Test Coverage Reports (15 files)
All test coverage reports are historical status files:
- `TEST_COVERAGE_ANALYSIS.md` - Historical status
- `TEST_COVERAGE_REPORT.md` - Historical status
- `TEST_COVERAGE_FINAL_REPORT.md` - Historical status
- `TEST_COVERAGE_FINAL_SUMMARY.md` - Historical status
- `TEST_COVERAGE_EXPANSION_SUMMARY.md` - Historical status
- `TEST_COVERAGE_100_PERCENT.md` - Historical status
- `TEST_EXPANSION_STRATEGY.md` - Historical status
- `TEST_IMPLEMENTATION_COMPLETE.md` - Historical status
- `docs/TEST_COVERAGE_100_PERCENT.md` - Duplicate
- `docs/TEST_COVERAGE_EXPANSION_SUMMARY.md` - Duplicate
- `docs/TEST_COVERAGE_FINAL_REPORT.md` - Duplicate
- `docs/TEST_COVERAGE_FINAL_SUMMARY.md` - Duplicate
- `docs/TEST_COVERAGE_REPORT.md` - Duplicate
- `docs/TEST_IMPLEMENTATION_COMPLETE.md` - Duplicate
- `docs/test-coverage-summary.md` - Duplicate
- `docs/test-implementation-complete-summary.md` - Duplicate
- `docs/testing-progress-summary.md` - Duplicate
- `docs/FINAL_TEST_COVERAGE_REPORT.md` - Duplicate
- `docs/FINAL_TEST_SUMMARY.md` - Duplicate
#### Implementation Summaries (10 files)
- `IMPLEMENTATION_SUMMARY.md` - Historical status
- `IMPLEMENTATION_COMPLETE_SUMMARY.md` - Historical status
- `IMPLEMENTATION_COMPLETE_REPORT.md` - Historical status
- `COMPLETION_REPORT.md` - Historical status
- `FINAL_STATUS.md` - Historical status
- `FINAL_STATUS_REPORT.md` - Historical status
- `MASTER_SUMMARY.md` - Historical status (superseded by SSOT)
- `MASTER_DOCUMENTATION.md` - Historical status (superseded by SSOT)
- `docs/implementation-status.md` - Historical status
- `DOCUMENTATION_MAP.md` - Historical status (superseded by DOCS_MIGRATION_PLAN.md)
#### Audit Reports (5 files)
- `AUDIT_SUMMARY.md` - Merged into SSOT
- `DEAD_CODE_REPORT.md` - Historical status
- `BUNDLE_OPTIMIZATION_REPORT.md` - Historical status (merged into SSOT)
- `IMAGE_OPTIMIZATION_REPORT.md` - Historical status (merged into SSOT)
- `POLLING_ANALYSIS.md` - Historical status (merged into SSOT)
#### Fix Logs & Status (10 files)
- `BUG_FIX_LOG.md` - Historical fix log
- `FIXES_APPLIED.md` - Historical fix log
- `API_FIXES_SUMMARY.md` - Historical fix log
- `API_CALLS_ANALYSIS.md` - Historical analysis
- `SUPABASE_FIXES_SUMMARY.md` - Historical fix log
- `SUPABASE_AUTH_FIXES_COMPLETE.md` - Historical fix log
- `SUPABASE_AUTH_ANALYSIS_AND_FIXES.md` - Historical fix log
- `SUPABASE_COMPREHENSIVE_ANALYSIS.md` - Historical analysis
- `ADMIN_UI_FIXES.md` - Historical fix log
- `ADMIN_UI_REFACTOR_SUMMARY.md` - Historical fix log
- `ADMIN_REALTIME_IMPROVEMENTS.md` - Historical fix log
- `ADMIN_DASHBOARD_AUDIT.md` - Historical audit
- `ADMIN_DASHBOARD_SUPABASE_AUDIT.md` - Historical audit
- `ADMIN_AUTH_MIGRATION.md` - Historical migration log
- `REDIS_RATE_LIMITING_MIGRATION.md` - Historical migration log
- `VENUE_UPDATE_SUMMARY.md` - Historical update
- `UNBLOCK_INSTRUCTIONS.md` - Historical instructions
- `MANUAL_TESTING_CHECKLIST.md` - Historical checklist
#### Other (5 files)
- `USER_STORIES.md` - Historical reference (merged into SSOT overview)
- `MISSING_ENHANCEMENTS_REVIEW.md` - Historical review
- `docs/zod-validation-complete-summary.md` - Historical status
- `docs/README.md` - Duplicate, content in DOCS_INDEX.md
- `gemini.md` - Historical reference
---
### ARCHIVE (17 files)
These files contain historical information that may be useful for reference. Move to `docs/archive/`:
#### Phase Reports (move to `docs/archive/phases/`)
- All phase status files listed above (50+ files) - **Note:** Actually DELETE these as they're too numerous and outdated
#### Implementation History (move to `docs/archive/implementation/`)
- `IMPLEMENTATION_SUMMARY.md`
- `IMPLEMENTATION_COMPLETE_SUMMARY.md`
- `IMPLEMENTATION_COMPLETE_REPORT.md`
- `COMPLETION_REPORT.md`
- `FINAL_STATUS.md`
- `FINAL_STATUS_REPORT.md`
- `MASTER_SUMMARY.md`
- `MASTER_DOCUMENTATION.md`
**Note:** Given the large number of phase files, it's recommended to DELETE them rather than archive, as they're purely historical status reports with no actionable information.
---
## Redirect Map
When files are deleted or moved, update any internal links:
| Old Path | New Path/Anchor |
|----------|-----------------|
| `ENVIRONMENT_VARIABLES.md` | `docs/SSOT.md#environment-configuration` |
| `ENV_VARIABLES_NOTES.md` | `docs/SSOT.md#environment-configuration` |
| `QUICK_START_GUIDE.md` | `docs/SSOT.md#local-development-setup` |
| `QUICK_START_LOCAL.md` | `docs/SSOT.md#local-development-setup` |
| `START_HERE.md` | `docs/SSOT.md` |
| `SUPABASE_SETUP.md` | `docs/SSOT.md#database--supabase` |
| `DEPLOYMENT_QUICK_START.md` | `docs/SSOT.md#deployment-proxmox` |
| `docs/DEPLOYMENT_QUICK_START.md` | `docs/SSOT.md#deployment-proxmox` |
| `PROXMOX_DEPLOYMENT_GUIDE.md` | `docs/SSOT.md#deployment-proxmox` |
| `YOUR_DEPLOYMENT_GUIDE.md` | `docs/SSOT.md#deployment-proxmox` |
| `TROUBLESHOOTING.md` | `docs/SSOT.md#troubleshooting` |
| `SECURITY.md` | `docs/SSOT.md#environment-configuration` (security section) |
| `BACKUP_RESTORE_GUIDE.md` | `docs/backup-procedures.md` |
| `CODEBASE_REVIEW.md` | `docs/SSOT.md#architecture` |
| `MASTER_DOCUMENTATION.md` | `docs/SSOT.md` |
| `MASTER_SUMMARY.md` | `docs/SSOT.md#overview` |
| `README_PRODUCTION.md` | `docs/SSOT.md#deployment-proxmox` |
---
## Migration Steps
1. **Create SSOT and supporting docs**
- `docs/SSOT.md` - Created
- `docs/DOCS_INDEX.md` - Created
- `docs/DOCS_GOVERNANCE.md` - To be created
- `docs/DOCS_MIGRATION_PLAN.md` - This file
2. **Update root README.md**
- Point to `docs/DOCS_INDEX.md` and `docs/SSOT.md`
- Remove duplicate setup instructions
3. **Delete files marked for deletion**
- Use this plan as reference
- Verify no critical information is lost
4. **Update internal links**
- Search for references to deleted files
- Update to point to SSOT sections
5. **Create archive directory** (optional)
- `docs/archive/phases/` - For phase reports (if keeping)
- `docs/archive/implementation/` - For implementation history (if keeping)
6. **Verify migration**
- Run `./scripts/check-docs.sh`
- Verify all links work
- Ensure no broken references
---
## Post-Migration
After migration:
1. All documentation should be in `docs/` directory
2. `docs/SSOT.md` is the single source of truth
3. Supporting docs are minimal and linked from SSOT
4. No duplicate setup instructions
5. All historical files removed or archived
---
**Last Updated:** January 2025
**Migration Status:** Plan Complete - Ready for Execution

View File

@@ -0,0 +1,405 @@
# Production Environment Variables
**Last Updated:** January 2025
**Purpose:** Complete reference for all production environment variables
---
## Quick Reference
### Required Variables (Must Have)
| Variable | Description | Example |
|----------|-------------|---------|
| `NODE_ENV` | Environment mode | `production` |
| `NEXT_PUBLIC_APP_URL` | Public application URL | `https://your-domain.com` |
| `DATABASE_URL` | Supabase PostgreSQL connection string | `postgresql://postgres:pass@db.xxx.supabase.co:5432/postgres` |
| `RUNTIME_DATABASE_URL` | Supabase connection pooling URL | `postgresql://postgres:pass@db.xxx.supabase.co:6543/postgres?pgbouncer=true` |
| `NEXT_PUBLIC_SUPABASE_URL` | Supabase project URL | `https://xxx.supabase.co` |
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Supabase anonymous key | `eyJhbGc...` |
| `SUPABASE_SERVICE_ROLE_KEY` | Supabase service role key | `eyJhbGc...` |
| `ADMIN_PASSWORD` | Admin dashboard password | `StrongPassword123!` |
| `SESSION_SECRET` | Session encryption secret (32+ chars) | `openssl rand -base64 32` |
| `CSRF_SECRET` | CSRF protection secret | `openssl rand -base64 24` |
| `REDIS_URL` | Redis connection string | `redis://localhost:6379` |
### Recommended Variables (Should Have)
| Variable | Description | Example |
|----------|-------------|---------|
| `NEXT_PUBLIC_SENTRY_DSN` | Sentry error tracking | `https://xxx@sentry.io/xxx` |
| `RESEND_API_KEY` | Resend email API key | `re_xxx` |
| `FROM_EMAIL` | Email sender address | `noreply@your-domain.com` |
### Optional Variables (Nice to Have)
| Variable | Description | Example |
|----------|-------------|---------|
| `SHADOW_DATABASE_URL` | Shadow DB for migrations | `postgresql://...` |
| `SUPABASE_URL` | Internal Supabase URL | `http://supabase-kong:8000` |
| `SMTP_HOST` | SMTP server (legacy) | `smtp.sendgrid.net` |
| `SMTP_PORT` | SMTP port | `587` |
| `SMTP_USER` | SMTP username | `apikey` |
| `SMTP_PASS` | SMTP password | `SG.xxx` |
| `TWILIO_ACCOUNT_SID` | Twilio account SID | `ACxxx` |
| `TWILIO_AUTH_TOKEN` | Twilio auth token | `xxx` |
| `TWILIO_PHONE_NUMBER` | Twilio phone number | `+1234567890` |
| `NEXT_PUBLIC_GA_MEASUREMENT_ID` | Google Analytics ID | `G-XXXXXXXXXX` |
| `OPENWEATHER_API_KEY` | OpenWeather API key | `xxx` |
| `ENABLE_NOTIFICATIONS` | Enable notifications | `true` |
| `ENABLE_ANALYTICS` | Enable analytics | `false` |
---
## Detailed Descriptions
### Environment
**`NODE_ENV`** (Required)
- **Type:** Enum (`production` | `development` | `test`)
- **Value:** `production`
- **Description:** Sets the Node.js environment mode
- **Note:** Must be exactly `production` for production deployments
### Application URL
**`NEXT_PUBLIC_APP_URL`** (Required)
- **Type:** URL String
- **Format:** `https://your-domain.com`
- **Description:** Public URL of your application
- **Usage:** Used for absolute URLs, email links, OAuth callbacks, etc.
- **Note:** Must use `https://` in production
### Database
**`DATABASE_URL`** (Required)
- **Type:** Supabase PostgreSQL Connection String
- **Format:** `postgresql://postgres:[PASSWORD]@db.[PROJECT_REF].supabase.co:5432/postgres`
- **Description:** Direct Supabase PostgreSQL connection (port 5432) - used for migrations
- **Get From:** Supabase Dashboard → Settings → Database → Connection String → Direct connection
- **Example:** `postgresql://postgres:yourpassword@db.abcdefghijklmnop.supabase.co:5432/postgres`
- **Security:** Contains credentials - keep secret
- **Note:** Use direct connection (port 5432) for migrations
**`RUNTIME_DATABASE_URL`** (Required)
- **Type:** Supabase Connection Pooling String
- **Format:** `postgresql://postgres:[PASSWORD]@db.[PROJECT_REF].supabase.co:6543/postgres?pgbouncer=true`
- **Description:** Supabase connection pooling URL (port 6543) - used for runtime queries
- **Get From:** Supabase Dashboard → Settings → Database → Connection String → Connection pooling
- **Example:** `postgresql://postgres:yourpassword@db.abcdefghijklmnop.supabase.co:6543/postgres?pgbouncer=true`
- **Note:** If not set, falls back to `DATABASE_URL` (not recommended for production)
- **Why:** Connection pooling prevents hitting Supabase connection limits
**`SHADOW_DATABASE_URL`** (Optional)
- **Type:** Supabase PostgreSQL Connection String
- **Description:** Shadow database for Prisma migrations (only needed if Supabase requires it)
- **When Needed:** Only if Prisma migrations fail without a shadow database
- **Note:** Usually same as `DATABASE_URL` for Supabase
### Supabase
**`NEXT_PUBLIC_SUPABASE_URL`** (Required)
- **Type:** URL String
- **Format:** `https://your-project-id.supabase.co`
- **Description:** Supabase project URL (public, exposed to browser)
- **Security:** Safe to expose - used in client-side code
**`NEXT_PUBLIC_SUPABASE_ANON_KEY`** (Required)
- **Type:** String
- **Description:** Supabase anonymous/public key
- **Security:** Safe to expose - used in client-side code
- **Note:** Has limited permissions, safe for browser
**`SUPABASE_SERVICE_ROLE_KEY`** (Required)
- **Type:** String
- **Description:** Supabase service role key (server-side only)
- **Security:** NEVER expose to client - has admin privileges
- **Usage:** Server-side API routes and server components only
- **Warning:** Keep this secret - never commit to version control
**`SUPABASE_URL`** (Optional)
- **Type:** URL String
- **Format:** `http://supabase-kong:8000` (internal Docker network)
- **Description:** Internal Supabase URL for server-side requests
- **When Needed:** When app and Supabase are in same Docker network
- **Note:** If not set, falls back to `NEXT_PUBLIC_SUPABASE_URL`
### Authentication & Security
**`ADMIN_PASSWORD`** (Required)
- **Type:** String
- **Min Length:** 8 characters
- **Recommended:** 12+ characters with mixed case, numbers, symbols
- **Description:** Password for admin dashboard access
- **Security:** Must be strong and unique
- **Generation:** Use password manager or `openssl rand -base64 16`
- **Warning:** Cannot use development default in production
**`SESSION_SECRET`** (Required)
- **Type:** String
- **Min Length:** 32 characters
- **Description:** Secret key for session encryption
- **Security:** Must be strong random string
- **Generation:** `openssl rand -base64 32`
- **Warning:** Cannot use development default in production
**`CSRF_SECRET`** (Required)
- **Type:** String
- **Description:** CSRF token secret
- **Security:** Required in production for security
- **Generation:** `openssl rand -base64 24`
- **Note:** Must be different from `SESSION_SECRET`
### Redis
**`REDIS_URL`** (Required in Production)
- **Type:** Redis Connection String
- **Format:** `redis://host:port` or `redis://:password@host:port`
- **Description:** Redis connection for rate limiting
- **Example:** `redis://localhost:6379` or `redis://:password@redis.example.com:6379`
- **Why Required:** Rate limiting requires Redis in production (distributed systems)
- **Note:** Falls back to in-memory if not available (not recommended for production)
### Email Service
**Option 1: Resend (Recommended)**
**`RESEND_API_KEY`** (Optional but Recommended)
- **Type:** String
- **Format:** `re_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
- **Description:** Resend API key for transactional emails
- **Get From:** [resend.com/api-keys](https://resend.com/api-keys)
**`FROM_EMAIL`** (Optional but Recommended)
- **Type:** Email String
- **Format:** `noreply@your-domain.com`
- **Description:** Email sender address
- **Note:** Must be verified in Resend dashboard
**Option 2: SMTP (Legacy)**
**`SMTP_HOST`** (Optional)
- **Type:** String
- **Example:** `smtp.sendgrid.net`
- **Description:** SMTP server hostname
**`SMTP_PORT`** (Optional)
- **Type:** Number
- **Example:** `587`
- **Description:** SMTP server port
**`SMTP_USER`** (Optional)
- **Type:** String
- **Example:** `apikey`
- **Description:** SMTP username
**`SMTP_PASS`** (Optional)
- **Type:** String
- **Description:** SMTP password/API key
### SMS Service (Twilio)
**`TWILIO_ACCOUNT_SID`** (Optional)
- **Type:** String
- **Format:** `ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
- **Description:** Twilio account SID
- **Get From:** [Twilio Console](https://console.twilio.com)
**`TWILIO_AUTH_TOKEN`** (Optional)
- **Type:** String
- **Description:** Twilio authentication token
- **Security:** Keep secret - never expose to client
**`TWILIO_PHONE_NUMBER`** (Optional)
- **Type:** Phone Number String
- **Format:** `+1234567890`
- **Description:** Twilio phone number for sending SMS
### Feature Flags
**`ENABLE_NOTIFICATIONS`** (Optional)
- **Type:** Boolean
- **Default:** `true`
- **Values:** `true` | `false` | `1` | `0`
- **Description:** Enable email/SMS notifications
**`ENABLE_ANALYTICS`** (Optional)
- **Type:** Boolean
- **Default:** `false`
- **Values:** `true` | `false` | `1` | `0`
- **Description:** Enable analytics tracking
### Error Tracking
**`NEXT_PUBLIC_SENTRY_DSN`** (Recommended)
- **Type:** URL String
- **Format:** `https://xxx@sentry.io/xxx`
- **Description:** Sentry DSN for error tracking
- **Get From:** [Sentry Project Settings](https://sentry.io/settings/projects/)
- **Security:** Safe to expose (public DSN)
### Analytics
**`NEXT_PUBLIC_GA_MEASUREMENT_ID`** (Optional)
- **Type:** String
- **Format:** `G-XXXXXXXXXX`
- **Description:** Google Analytics Measurement ID
- **Get From:** [Google Analytics Admin](https://analytics.google.com)
### Weather API
**`OPENWEATHER_API_KEY`** (Optional)
- **Type:** String
- **Description:** OpenWeather API key
- **Get From:** [openweathermap.org/api](https://openweathermap.org/api)
### Ollama AI (Wedding Concierge)
**`OLLAMA_URL`** (Optional)
- **Type:** URL String
- **Description:** Ollama server URL for AI concierge
- **Format:** `http://host:port` or `https://host:port`
- **Coolify:** Use internal Docker network URL (e.g., `http://ollama-CONTAINER_ID:11434`) or external URL if Ollama is on a different service
- **Default:** `http://localhost:11434`
- **Security:** Server-side only (not exposed to browser)
- **Example:** `http://ollama:11434` (internal Docker network) or `https://ollama.yourdomain.com` (external)
**`OLLAMA_MODEL`** (Optional)
- **Type:** String
- **Description:** Ollama model name to use for concierge
- **Default:** `jarvis-concierge`
- **Example:** `llama3`, `mistral`, `jarvis-concierge`
**`OLLAMA_TEMPERATURE`** (Optional)
- **Type:** Number (as string)
- **Description:** Temperature for AI responses (0.0-1.0)
- **Default:** `0.7`
- **Example:** `0.7` (balanced), `0.5` (more focused), `0.9` (more creative)
---
## Security Best Practices
1. **Never Commit Secrets**
- `.env.production` is in `.gitignore`
- Never commit actual values to version control
- Use `.env.production.example` as template
2. **Strong Secrets**
- `SESSION_SECRET`: Use `openssl rand -base64 32`
- `CSRF_SECRET`: Use `openssl rand -base64 24`
- `ADMIN_PASSWORD`: Minimum 12 characters, mix of letters, numbers, symbols
3. **Different Secrets Per Environment**
- Use different secrets for dev/staging/prod
- Never reuse production secrets in development
4. **Secrets Management**
- Use secrets management service (AWS Secrets Manager, HashiCorp Vault)
- Rotate secrets regularly
- Use environment-specific secrets
5. **Public Variables**
- `NEXT_PUBLIC_*` variables are exposed to browser
- Never put secrets in `NEXT_PUBLIC_*` variables
- Only use for non-sensitive configuration
6. **Database Security**
- Use strong, unique database passwords
- Use connection pooling in production
- Restrict database access by IP when possible
---
## Validation
Environment variables are validated on application startup using Zod schemas in `src/lib/env.ts`.
**Validation happens:**
- On application startup
- Type checking
- Format validation
- Required field checking
**Errors:**
- Invalid variables cause application to fail on startup
- Clear error messages indicate which variables are invalid
**Test validation:**
```bash
# Type check
npm run typecheck
# Build (validates environment)
npm run build
```
---
## Generation Commands
```bash
# Generate SESSION_SECRET (32+ characters)
openssl rand -base64 32
# Generate CSRF_SECRET (24+ characters)
openssl rand -base64 24
# Generate ADMIN_PASSWORD (16 characters)
openssl rand -base64 16
```
---
## Example Production Configuration
```bash
# Environment
NODE_ENV=production
# Application
NEXT_PUBLIC_APP_URL=https://themoyos.co.za
# Database
# Supabase PostgreSQL connection strings
# Get from: Supabase Dashboard → Settings → Database → Connection String
DATABASE_URL=postgresql://postgres:YourPassword@db.abcdefghijklmnop.supabase.co:5432/postgres
RUNTIME_DATABASE_URL=postgresql://postgres:YourPassword@db.abcdefghijklmnop.supabase.co:6543/postgres?pgbouncer=true
# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://xxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
# Security
ADMIN_PASSWORD=YourStrongAdminPassword123!
SESSION_SECRET=f3ERSdncczdgAruOxCKXqqd5O6KIn81VQDlZ0nOARteUQ9nq6YBJi6MqJgzqazVQ
CSRF_SECRET=K8mN2pQ5rT9vW1xY4zA7bC0dE3fG6hI9j
# Redis
REDIS_URL=redis://redis.example.com:6379
# Email (Resend)
RESEND_API_KEY=re_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
FROM_EMAIL=noreply@themoyos.co.za
# Error Tracking
NEXT_PUBLIC_SENTRY_DSN=https://xxx@sentry.io/xxx
# Feature Flags
ENABLE_NOTIFICATIONS=true
ENABLE_ANALYTICS=true
```
---
## Related Documentation
- [SSOT.md - Environment Configuration](SSOT.md#environment-configuration) - Main documentation
- [SSOT.md - Deployment (Proxmox)](SSOT.md#deployment-proxmox) - Deployment guide
- `.env.production.example` - Template file
---
**Last Updated:** January 2025
**Maintained By:** Development Team

1139
docs/SSOT.md Normal file

File diff suppressed because it is too large Load Diff

421
docs/backup-procedures.md Normal file
View File

@@ -0,0 +1,421 @@
# Backup Procedures
**Date:** January 2025
**Status:** Complete
**Purpose:** Comprehensive backup strategy for Moyos Wedding App
---
## Overview
This document outlines the backup procedures for the Moyos Wedding App production deployment, including database backups, storage backups, and configuration backups.
---
## Backup Strategy
### Backup Types
1. **Database Backups** - PostgreSQL database dumps
2. **Storage Backups** - Supabase Storage or filesystem storage
3. **Configuration Backups** - Application configs, Nginx configs, PM2 configs
### Backup Frequency
- **Database:** Daily at 2:00 AM
- **Storage:** Daily at 3:00 AM
- **Configuration:** Weekly (Sunday at 1:00 AM)
### Retention Policy
- **Database Backups:** 30 days
- **Storage Backups:** 30 days
- **Configuration Backups:** 90 days
---
## Database Backups
### Automated Backup Script
**Location:** `scripts/backup-db.sh`
**Usage:**
```bash
# Manual backup
./scripts/backup-db.sh
# With custom backup directory
BACKUP_DIR=/custom/path ./scripts/backup-db.sh
```
### Setup Cron Job
```bash
# Edit crontab
crontab -e
# Add daily backup at 2 AM
0 2 * * * /opt/moyos-wedding-app/app/scripts/backup-db.sh >> /var/log/backup-db.log 2>&1
```
### Backup Format
- **Format:** Compressed SQL dump (`.sql.gz`)
- **Naming:** `wedding_app_backup_YYYYMMDD_HHMMSS.sql.gz`
- **Location:** `/opt/backups/db/` (default)
### Verification
```bash
# List backups
ls -lh /opt/backups/db/
# Verify backup integrity
gunzip -t /opt/backups/db/wedding_app_backup_*.sql.gz
# Check backup size
du -sh /opt/backups/db/
```
### Restore Procedure
**Location:** `scripts/restore-db.sh`
**Usage:**
```bash
# Restore from backup
./scripts/restore-db.sh /opt/backups/db/wedding_app_backup_20250115_020000.sql.gz
```
**⚠️ WARNING:** Restore will overwrite existing database. A safety backup is created automatically before restore.
**Steps:**
1. Stop application: `pm2 stop moyos-wedding-app`
2. Create manual backup (safety): `./scripts/backup-db.sh`
3. Run restore: `./scripts/restore-db.sh <backup-file>`
4. Verify restore: Check database contents
5. Restart application: `pm2 start moyos-wedding-app`
---
## Storage Backups
### Automated Backup Script
**Location:** `scripts/backup-storage.sh`
**Usage:**
```bash
# Auto-detect storage type
./scripts/backup-storage.sh
# Explicitly backup filesystem storage
./scripts/backup-storage.sh --filesystem
# Explicitly backup Supabase Storage
./scripts/backup-storage.sh --supabase
```
### Setup Cron Job
```bash
# Edit crontab
crontab -e
# Add daily backup at 3 AM
0 3 * * * /opt/moyos-wedding-app/app/scripts/backup-storage.sh >> /var/log/backup-storage.log 2>&1
```
### Backup Format
- **Format:** Compressed tar archive (`.tar.gz`)
- **Naming:** `storage_filesystem_YYYYMMDD_HHMMSS.tar.gz` or `storage_supabase_YYYYMMDD_HHMMSS.tar.gz`
- **Location:** `/opt/backups/storage/` (default)
### Filesystem Storage Backup
Backs up `public/uploads/` directory:
- Gallery photos (thumbnails and full images)
- User-uploaded files
### Supabase Storage Backup
**Note:** Supabase Storage backup requires manual setup or Supabase CLI. The script provides a placeholder for automation.
**Manual Backup (Supabase CLI):**
```bash
# Install Supabase CLI
npm install -g supabase
# Login
supabase login
# Download storage
supabase storage download gallery --output /opt/backups/storage/supabase_$(date +%Y%m%d_%H%M%S)
```
### Restore Procedure
**Filesystem Storage:**
```bash
# Extract backup
tar -xzf /opt/backups/storage/storage_filesystem_20250115_030000.tar.gz -C /opt/moyos-wedding-app/app/public/
# Verify files
ls -lh /opt/moyos-wedding-app/app/public/uploads/
```
**Supabase Storage:**
```bash
# Upload files using Supabase CLI
supabase storage upload gallery /opt/backups/storage/supabase_20250115_030000/
```
---
## Configuration Backups
### What Gets Backed Up
- Nginx configuration (`/etc/nginx/sites-available/moyos-wedding-app`)
- PM2 ecosystem config (`ecosystem.config.js`)
- Environment files (sanitized, no secrets)
- SSL certificates (Let's Encrypt)
- Systemd service files (if any)
### Backup Script
Create `/opt/backups/config-backup.sh`:
```bash
#!/bin/bash
BACKUP_DIR="/opt/backups/config"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/config_backup_$DATE.tar.gz"
mkdir -p "$BACKUP_DIR"
# Backup Nginx config
tar -czf "$BACKUP_FILE" \
/etc/nginx/sites-available/moyos-wedding-app \
/opt/moyos-wedding-app/app/ecosystem.config.js \
/etc/letsencrypt/live/your-domain.com/ \
2>/dev/null || true
# Clean up old backups (90 days)
find "$BACKUP_DIR" -name "config_backup_*.tar.gz" -mtime +90 -delete
echo "Configuration backup created: $BACKUP_FILE"
```
### Setup Cron Job
```bash
# Weekly backup on Sunday at 1 AM
0 1 * * 0 /opt/backups/config-backup.sh >> /var/log/backup-config.log 2>&1
```
---
## Off-Site Backups
### S3 Backup (Optional)
If `BACKUP_S3_BUCKET` environment variable is set, backups are automatically uploaded to S3:
```bash
# Set environment variable
export BACKUP_S3_BUCKET=your-backup-bucket
# Install AWS CLI
apt-get install -y awscli
# Configure credentials
aws configure
# Backups will automatically upload to S3
```
### Manual Off-Site Backup
```bash
# Copy backups to external storage
rsync -av /opt/backups/ user@backup-server:/backups/moyos-wedding-app/
# Or use SCP
scp -r /opt/backups/ user@backup-server:/backups/moyos-wedding-app/
```
---
## Backup Monitoring
### Check Backup Status
```bash
# Check last backup time
ls -lth /opt/backups/db/ | head -5
ls -lth /opt/backups/storage/ | head -5
# Check backup logs
tail -f /var/log/backup-db.log
tail -f /var/log/backup-storage.log
```
### Backup Health Check Script
Create `/opt/backups/check-backups.sh`:
```bash
#!/bin/bash
BACKUP_DIR="/opt/backups"
ALERT_EMAIL="admin@your-domain.com"
# Check if backups exist from last 25 hours
DB_BACKUP=$(find "$BACKUP_DIR/db" -name "*.sql.gz" -mtime -1 | head -1)
STORAGE_BACKUP=$(find "$BACKUP_DIR/storage" -name "*.tar.gz" -mtime -1 | head -1)
if [ -z "$DB_BACKUP" ]; then
echo "WARNING: No database backup found in last 25 hours" | mail -s "Backup Alert" "$ALERT_EMAIL"
fi
if [ -z "$STORAGE_BACKUP" ]; then
echo "WARNING: No storage backup found in last 25 hours" | mail -s "Backup Alert" "$ALERT_EMAIL"
fi
```
---
## Disaster Recovery
### Recovery Time Objective (RTO)
**Target:** < 4 hours
### Recovery Point Objective (RPO)
**Target:** < 24 hours (daily backups)
### Recovery Procedures
1. **Identify Issue**
- Check application logs
- Verify backup availability
- Determine recovery point
2. **Prepare Environment**
- Stop application
- Create safety backup
- Verify backup integrity
3. **Restore Database**
```bash
./scripts/restore-db.sh <backup-file>
```
4. **Restore Storage**
```bash
# Filesystem
tar -xzf <backup-file> -C /opt/moyos-wedding-app/app/public/
# Supabase (if applicable)
supabase storage upload gallery <backup-directory>
```
5. **Verify Restore**
- Check database contents
- Verify file availability
- Test application functionality
6. **Restart Services**
```bash
pm2 restart moyos-wedding-app
systemctl reload nginx
```
7. **Post-Recovery**
- Monitor application logs
- Verify all features working
- Document recovery process
---
## Backup Best Practices
1. **Test Restores Regularly**
- Monthly restore tests
- Verify backup integrity
- Document any issues
2. **Multiple Backup Locations**
- Local backups (primary)
- Off-site backups (S3, external server)
- Multiple retention periods
3. **Automated Monitoring**
- Backup success/failure alerts
- Disk space monitoring
- Backup age verification
4. **Documentation**
- Keep backup procedures updated
- Document recovery procedures
- Maintain backup inventory
5. **Security**
- Encrypt backups (if sensitive)
- Secure backup storage
- Limit backup access
---
## Troubleshooting
### Backup Fails
**Check:**
- Disk space: `df -h`
- Permissions: `ls -la /opt/backups/`
- Logs: `tail -f /var/log/backup-*.log`
- Database connectivity: `psql $DATABASE_URL -c "SELECT 1;"`
### Restore Fails
**Check:**
- Backup file integrity: `gunzip -t <backup-file>`
- Database connectivity
- Disk space
- Application status (should be stopped)
### Backup Too Large
**Solutions:**
- Compress backups (already done)
- Clean up old backups
- Increase disk space
- Use incremental backups (advanced)
---
## Backup Checklist
### Daily
- [ ] Verify database backup completed
- [ ] Verify storage backup completed
- [ ] Check backup disk space
### Weekly
- [ ] Verify configuration backup
- [ ] Test restore procedure (optional)
- [ ] Review backup logs
### Monthly
- [ ] Full restore test
- [ ] Verify off-site backups
- [ ] Review retention policy
- [ ] Update documentation
---
**Status:** Backup procedures documented and ready for implementation. ✅

208
docs/coding-standards.md Normal file
View File

@@ -0,0 +1,208 @@
# Coding Standards
**Last Updated:** January 2025
**Project:** Moyos Wedding App
---
## File and Folder Naming
### Files
- **Components:** `kebab-case.tsx` (e.g., `rsvp-form.tsx`, `guest-card.tsx`)
- **Utilities:** `kebab-case.ts` (e.g., `request-id.ts`, `rate-limit.ts`)
- **API Routes:** `route.ts` (Next.js App Router convention)
- **Types:** `kebab-case.ts` or in feature folders as `types.ts`
### Folders
- **Feature folders:** `kebab-case` (e.g., `rsvp/`, `guestbook/`)
- **Component folders:** `kebab-case` (e.g., `features/`, `ui/`)
- **Utility folders:** `kebab-case` (e.g., `lib/`, `hooks/`)
---
## Type Definitions
### Location
- **Global types:** `src/types/index.ts`
- **Feature-specific types:** Co-located in feature folders (e.g., `src/components/features/rsvp/types.ts`)
- **API types:** Co-located with API routes or in `src/types/api.ts`
### Naming
- **Interfaces:** `PascalCase` (e.g., `GuestSession`, `RsvpFormData`)
- **Types:** `PascalCase` (e.g., `ApiResponse<T>`, `AuditEventType`)
- **Enums:** `PascalCase` (e.g., `ReportType`, `ExportFormat`)
---
## Hooks
### Naming
- **All hooks:** Must be prefixed with `use` (e.g., `useGuest`, `useRealtime`, `useMobile`)
- **File names:** `use-kebab-case.ts` (e.g., `use-guest.ts`, `use-realtime.ts`)
### Location
- **Global hooks:** `src/hooks/`
- **Feature-specific hooks:** Co-located in feature folders (e.g., `src/components/features/rsvp/use-rsvp.ts`)
---
## Components
### Naming
- **Component files:** `kebab-case.tsx` (e.g., `rsvp-form.tsx`)
- **Component names:** `PascalCase` (e.g., `RsvpForm`, `GuestCard`)
- **Props interfaces:** `ComponentNameProps` (e.g., `RsvpFormProps`)
### Organization
- **Feature components:** `src/components/features/{feature-name}/`
- **UI components:** `src/components/ui/`
- **Layout components:** `src/components/layout/`
---
## API Routes
### Structure
- **Route handlers:** `src/app/api/{route}/route.ts`
- **Request validation:** Use Zod schemas in `src/lib/validators/`
- **Error handling:** Standardized error responses
- **Logging:** Use `logger` with request ID context
### Naming
- **Route files:** `route.ts` (Next.js convention)
- **Validator files:** `{feature}-validators.ts` (e.g., `rsvp-validators.ts`)
---
## State Management
### Single Source of Truth
- **Guest state:** `src/context/guest-context.tsx`
- **Admin state:** To be centralized (currently scattered)
- **No duplicate state:** Avoid storing same data in multiple places
---
## Imports
### Order
1. React/Next.js imports
2. Third-party library imports
3. Internal component imports
4. Internal utility imports
5. Type imports (with `type` keyword)
6. Relative imports
### Example
```typescript
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { verifyGuestSession } from '@/lib/auth';
import { logger } from '@/lib/logger';
import type { GuestSession } from '@/types';
```
---
## Code Style
### TypeScript
- **No `any` types:** Use proper types or `unknown`
- **Strict mode:** Enabled
- **Type imports:** Use `import type` for type-only imports
### Functions
- **Async functions:** Always handle errors with try-catch
- **Error logging:** Use `logger.error()` with context
- **Request ID:** Include in all log contexts
### Validation
- **All API inputs:** Must use Zod validation
- **Schemas:** Co-located in `src/lib/validators/`
---
## Testing
### File Naming
- **Unit tests:** `*.test.ts` or `*.test.tsx`
- **E2E tests:** `*.spec.ts`
- **Location:** Co-located with source files in `__tests__/` folders
### Coverage
- **Minimum:** 60% global coverage
- **Critical utilities:** 100% coverage (sanitize, csrf, rate-limit)
- **API routes:** 80%+ coverage
---
## Documentation
### Comments
- **Complex logic:** Add explanatory comments
- **API routes:** JSDoc comments for exported functions
- **Types:** Document complex types with comments
### README Files
- **Feature folders:** Optional `README.md` for complex features
- **Main docs:** In `docs/` folder
---
## Git Commits
### Format
- **Type:** `feat:`, `fix:`, `chore:`, `refactor:`, `docs:`, `test:`
- **Scope:** Optional feature name
- **Message:** Clear, concise description
### Examples
- `feat: add request ID tracking to middleware`
- `fix: correct Zod validation error handling`
- `chore: remove unused @sendgrid/mail dependency`
- `refactor: consolidate duplicate RSVP form components`
---
## Security
### Secrets
- **Never commit:** `.env.local`, `.env.production`
- **Always validate:** Use Zod schemas for env variables
- **No client-side secrets:** Never use `NEXT_PUBLIC_*` for secrets
### Input Validation
- **All inputs:** Validate with Zod
- **File uploads:** Validate magic bytes, size, type
- **Sanitization:** Use `sanitize.ts` utilities
---
## Performance
### Code Splitting
- **Large components:** Use `next/dynamic` for lazy loading
- **Admin components:** Always lazy loaded
- **Heavy libraries:** Lazy load when possible
### Caching
- **API responses:** Use SWR for client-side caching
- **Database queries:** Add indexes, optimize queries
- **Static data:** Cache in Redis when available
---
## Accessibility
### ARIA Labels
- **Interactive elements:** Always include aria-labels
- **Form inputs:** Associated labels
- **Error messages:** Announced to screen readers
### Keyboard Navigation
- **All interactive elements:** Keyboard accessible
- **Focus management:** Proper focus handling
---
**This document should be updated as patterns evolve.**

450
docs/deployment-runbook.md Normal file
View File

@@ -0,0 +1,450 @@
# Deployment Runbook
**Date:** January 2025
**Status:** Complete
**Purpose:** Step-by-step deployment procedures for Moyos Wedding App
---
## Overview
This runbook provides detailed procedures for deploying the Moyos Wedding App to production, including pre-deployment checks, deployment steps, post-deployment verification, and rollback procedures.
---
## Pre-Deployment Checklist
### Code Quality Checks
- [ ] All tests pass (`npm test`)
- [ ] TypeScript compiles (`npm run typecheck`)
- [ ] Linter passes (`npm run lint`)
- [ ] Build succeeds (`npm run build`)
- [ ] Security audit passed (`npm run security:audit`)
### Environment Verification
- [ ] Environment variables configured (`.env.production`)
- [ ] Database migrations tested
- [ ] Database connection verified
- [ ] Redis connection verified (if used)
- [ ] Supabase configured (if used)
### Infrastructure Checks
- [ ] Server resources available (CPU, RAM, disk)
- [ ] Backup system operational
- [ ] Monitoring configured
- [ ] SSL certificates valid
- [ ] DNS configured correctly
### Documentation
- [ ] Changelog updated
- [ ] Release notes prepared
- [ ] Deployment plan reviewed
- [ ] Rollback plan prepared
---
## Deployment Process
### Step 1: Pre-Deployment Backup
```bash
# Create database backup
./scripts/backup-db.sh
# Create storage backup (if needed)
./scripts/backup-storage.sh
# Verify backups
ls -lh /opt/backups/db/ | head -5
ls -lh /opt/backups/storage/ | head -5
```
**Time:** ~5-10 minutes
---
### Step 2: Deploy Application
**Option A: Automated Deployment (Recommended)**
```bash
# Production deployment
./scripts/deploy.sh --production
# Staging deployment
./scripts/deploy.sh --staging
```
**Option B: Manual Deployment**
```bash
# Navigate to app directory
cd /opt/moyos-wedding-app/app
# Pull latest code
git pull origin main
# Install dependencies
npm ci --production=false
# Generate Prisma client
npx prisma generate
# Run migrations
npx prisma migrate deploy
# Build application
npm run build
# Restart with PM2
pm2 reload moyos-wedding-app
```
**Time:** ~10-15 minutes
---
### Step 3: Verify Deployment
```bash
# Check PM2 status
pm2 status
# Check application logs
pm2 logs moyos-wedding-app --lines 50
# Health check
curl -f https://your-domain.com/api/health
# Check metrics
curl -f https://your-domain.com/api/metrics
```
**Expected Results:**
- PM2 shows app as "online"
- Health check returns `200 OK`
- No critical errors in logs
**Time:** ~5 minutes
---
### Step 4: Smoke Tests
```bash
# Run smoke tests (if available)
./scripts/smoke-tests.sh
# Or manually test:
# - Landing page loads
# - RSVP form accessible
# - Admin login works
# - API endpoints respond
```
**Time:** ~5-10 minutes
---
### Step 5: Monitor
```bash
# Monitor application
pm2 monit
# Watch logs
pm2 logs moyos-wedding-app --lines 100
# Check system resources
htop
df -h
```
**Duration:** 15-30 minutes post-deployment
---
## Post-Deployment Verification
### Application Health
- [ ] Health endpoint returns `200 OK`
- [ ] Metrics endpoint accessible
- [ ] No critical errors in logs
- [ ] Response times acceptable (< 500ms p95)
### Functional Tests
- [ ] Landing page loads correctly
- [ ] RSVP form submission works
- [ ] Admin dashboard accessible
- [ ] Gallery displays images
- [ ] Music requests functional
- [ ] Guestbook entries visible
### Performance Checks
- [ ] Page load times < 2s
- [ ] API response times < 500ms
- [ ] Database query times < 100ms
- [ ] Memory usage stable
- [ ] CPU usage normal
### Security Checks
- [ ] TLS/SSL working (HTTPS)
- [ ] Security headers present
- [ ] Rate limiting active
- [ ] CSRF protection working
- [ ] No exposed secrets
---
## Rollback Procedure
### When to Rollback
- Critical errors in logs
- Health checks failing
- Performance degradation
- Security issues discovered
- User-reported critical bugs
### Rollback Steps
**Step 1: Stop Application**
```bash
pm2 stop moyos-wedding-app
```
**Step 2: Restore Previous Version**
```bash
# Option A: Git revert
cd /opt/moyos-wedding-app/app
git revert HEAD
git pull
# Option B: Checkout previous commit
git checkout <previous-commit-hash>
```
**Step 3: Restore Database (if needed)**
```bash
# Only if database changes were made
./scripts/restore-db.sh /opt/backups/db/wedding_app_backup_<timestamp>.sql.gz
```
**Step 4: Rebuild and Restart**
```bash
# Install dependencies
npm ci --production=false
# Generate Prisma client
npx prisma generate
# Build application
npm run build
# Restart application
pm2 restart moyos-wedding-app
```
**Step 5: Verify Rollback**
```bash
# Health check
curl -f https://your-domain.com/api/health
# Check logs
pm2 logs moyos-wedding-app --lines 50
```
**Time:** ~15-20 minutes
---
## Zero-Downtime Deployment
### Blue-Green Deployment (Advanced)
For zero-downtime deployments:
1. **Deploy to Secondary Port**
```bash
PORT=3001 npm start
pm2 start ecosystem.config.js --env production -- --port 3001
```
2. **Update Nginx Upstream**
```nginx
upstream app {
least_conn;
server 127.0.0.1:3000; # Old instance
server 127.0.0.1:3001; # New instance
}
```
3. **Reload Nginx**
```bash
nginx -t
systemctl reload nginx
```
4. **Stop Old Instance**
```bash
pm2 stop moyos-wedding-app --instance 0
```
5. **Update PM2 Config**
```bash
# Update ecosystem.config.js to use port 3000
pm2 reload ecosystem.config.js
```
---
## Deployment Troubleshooting
### Build Fails
**Symptoms:**
- `npm run build` exits with error
- TypeScript compilation errors
**Solutions:**
- Check TypeScript errors: `npm run typecheck`
- Verify dependencies: `npm ci`
- Check Node.js version: `node --version` (should be 20.x)
- Review build logs for specific errors
### Migration Fails
**Symptoms:**
- `prisma migrate deploy` fails
- Database connection errors
**Solutions:**
- Verify `DATABASE_URL` is correct
- Check database connectivity: `psql $DATABASE_URL -c "SELECT 1;"`
- Review migration files for errors
- Check database permissions
### Application Won't Start
**Symptoms:**
- PM2 shows app as "errored" or "stopped"
- Health check fails
**Solutions:**
- Check logs: `pm2 logs moyos-wedding-app --err`
- Verify environment variables
- Check port availability: `netstat -tulpn | grep 3000`
- Verify `.next` directory exists
- Check disk space: `df -h`
### Performance Issues
**Symptoms:**
- Slow response times
- High memory usage
- High CPU usage
**Solutions:**
- Check PM2 cluster mode: `pm2 status`
- Review application logs for slow queries
- Check database performance
- Monitor system resources: `htop`
- Review Nginx configuration
---
## Deployment Schedule
### Recommended Times
- **Staging:** Anytime (low traffic)
- **Production:** Off-peak hours (2-4 AM local time)
- **Hotfixes:** As needed (with approval)
### Communication
- Notify team before deployment
- Post-deployment status update
- Document any issues encountered
---
## Deployment Checklist Summary
### Pre-Deployment
- [ ] All tests pass
- [ ] Build succeeds
- [ ] Environment configured
- [ ] Backups created
- [ ] Team notified
### Deployment
- [ ] Code deployed
- [ ] Migrations run
- [ ] Application restarted
- [ ] Health checks pass
### Post-Deployment
- [ ] Smoke tests pass
- [ ] Monitoring active
- [ ] No critical errors
- [ ] Performance acceptable
- [ ] Team notified of success
---
## Emergency Contacts
- **On-Call Engineer:** [Contact Info]
- **Database Admin:** [Contact Info]
- **Infrastructure Team:** [Contact Info]
---
## Deployment Log Template
```
Date: [Date]
Time: [Time]
Deployed By: [Name]
Environment: [staging/production]
Version: [Git commit hash]
Changes: [Brief description]
Pre-Deployment:
- [ ] Checklist completed
Deployment:
- [ ] Backup created
- [ ] Code deployed
- [ ] Migrations run
- [ ] Application restarted
Post-Deployment:
- [ ] Health checks passed
- [ ] Smoke tests passed
- [ ] Monitoring verified
Issues:
[Any issues encountered]
Rollback:
[If rollback was needed, document reason and steps]
```
---
**Status:** Deployment runbook complete and ready for use.