fix: version bumping and Docker registry authentication (#17)
Release / release (push) Failing after 1m9s
Test / unit-tests (push) Successful in 2m5s

## Summary

This PR fixes the release workflow to properly handle version bumping on PR merge and uses the new Docker registry authentication secrets.

## Changes

### Release Workflow (release.yml)
- **Version Bumping**: Now automatically bumps version on PR merge
  - Determines bump type from commit messages (major/minor/patch)
  - Commits version bump to `package.json` and `CHANGELOG.md`
  - Creates git tag for the release
- **Docker Registry Auth**: Uses `DOCKER_LOGIN` and `DOCKER_PASSWORD` secrets
  - Falls back gracefully if secrets are not configured
- **Tag Handling**: Checks if tag exists before creating (prevents failures)

### PR Workflow (pr.yml) - NEW
- Runs unit tests on every PR
- Analyzes commits to suggest bump type
- Comments the suggested bump type on the PR

### Documentation
- Added `WORKFLOW_ARCHITECTURE.md` explaining the workflow design

## Workflow Architecture

**Two-step process:**
1. **PR Workflow** (on PR): Analyzes commits and suggests bump type
2. **Release Workflow** (on merge): Bumps version, creates tag, builds Docker image

## Benefits

1. **No CI Loops**: Version bump commits are detected and skipped
2. **Clear Communication**: PR comments inform developers of version impact
3. **Semantic Versioning**: Automated adherence to semver rules
4. **Traceability**: Git tags and changelog reflect all changes

## Testing

The new workflows will be tested when this PR is merged.

Closes #13 (Add database test safety configuration)

Reviewed-on: #17
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #17.
This commit is contained in:
2026-04-01 05:03:14 +00:00
committed by david
parent 9768ff3517
commit 501e1b7e23
20 changed files with 884 additions and 303 deletions
+125
View File
@@ -0,0 +1,125 @@
# File Organization
This document describes the organization of files in the EuchreCamp project.
## Root Directory
### Essential Files (Keep in Root)
- `README.md` - Main project documentation
- `AGENTS.md` - AI agent guide
- `CHANGELOG.md` - Version changelog
- `package.json` - Node.js dependencies and scripts
- `package-lock.json` - Dependency lock file
- `tsconfig.json` - TypeScript configuration
- `next.config.js` - Next.js configuration
- `.gitignore` - Git ignore file
- `Dockerfile` - Docker build configuration
- `justfile` - Development task automation
### Configuration Files (Keep in Root)
- `.eslintrc.json` - ESLint configuration
- `postcss.config.mjs` - PostCSS configuration
- `playwright.config.ts` - Playwright test configuration
- `vitest.config.mts` - Vitest configuration
- `vitest.setup.ts` - Vitest setup
- `.dockerignore` - Docker ignore file
- `mise.toml` - Mise version manager config
### Docker Files (Keep in Root)
- `docker-compose.yml` - Main Docker Compose
- `docker-compose.dev.yml` - Development Docker Compose
- `docker-compose.override.yml` - Override for dev
- `docker-compose.casaos.yml` - CasaOS specific
### Environment Files (Keep in Root, Gitignored)
- `.env` - Environment variables
- `.env.development` - Development environment
## Organized Directories
### `.gitea/` - Gitea Actions Workflows
- `workflows/pr.yml` - Pull request workflow (unit + acceptance tests)
- `workflows/test.yml` - Test workflow (unit tests on branch pushes)
- `workflows/release.yml` - Release workflow (version bump + Docker build)
- `WORKFLOW_ARCHITECTURE.md` - Workflow architecture documentation
### `docs/` - Documentation
- `deployment/` - Deployment documentation
- `CASAOS_DEPLOYMENT.md` - CasaOS deployment guide
- `DOCKER.md` - Docker deployment instructions
- `TODO.md` - Project TODO list (in docs root for visibility)
- `USER_STORIES.md` - User stories organized by epic
- Other documentation files (design, implementation, testing, etc.)
### `scripts/` - Utility Scripts
- `python/` - Python scripts (legacy/old functionality)
- `generate_games.py` - Generate sample games
- `update_partnership_stats.py` - Update partnership stats
- `update_player_stats.py` - Update player stats
- `bump-version.js` - Version bumping script
- `build-and-push-docker.js` - Docker build and push script
- `switch-database.js` - Database provider switching
- `create-admin-via-api.js` - Admin user creation via API
- `create-admin-better-auth.js` - Admin user creation via database
- `list-users.js` - List all users
- `update-admin-password.js` - Update admin password
- `seed.js` - Database seeding
- And other Node.js scripts...
### `src/` - Source Code
- `app/` - Next.js app directory
- `api/` - API routes
- `auth/` - Authentication pages
- `admin/` - Admin pages
- `players/` - Player pages
- `rankings/` - Rankings page
- `components/` - Shared components
- `lib/` - Utilities and configuration
- `auth.ts` - Better Auth configuration
- `prisma.ts` - Prisma client (supports SQLite and PostgreSQL)
- `permissions.ts` - Authorization functions
- `elo-utils.ts` - Elo calculation utilities
- `__tests__/` - Vitest and Playwright tests
- `unit/` - Unit tests
- `e2e/` - End-to-end acceptance tests
### `prisma/` - Database
- `schema.prisma` - Prisma schema
- `migrations/` - Database migrations
- `dev.db` - SQLite development database (if using SQLite)
### `public/` - Static Assets
- Images, fonts, and other static files
### `playwright/` - Playwright Test Data
- Authentication state files
## Generated Directories (Gitignored)
- `.next/` - Next.js build output
- `node_modules/` - Node.js dependencies
- `playwright-report/` - Playwright test reports
- `test-results/` - Test results
## File Organization Principles
1. **Keep standard files in root**: package.json, tsconfig.json, etc.
2. **Organize by function**: Group related files in directories
3. **Separate generated from source**: Keep build outputs and dependencies separate
4. **Document organization**: Use this file to explain structure
5. **Follow conventions**: Use standard naming and organization patterns
## CI/CD File Organization
### Workflows
- `.gitea/workflows/pr.yml` - Pull request validation
- `.gitea/workflows/test.yml` - Branch testing
- `.gitea/workflows/release.yml` - Main branch release
### Database Strategy
- **CI/Testing**: SQLite (fast, no server)
- **Production**: PostgreSQL (production-like)
### Testing
- Unit tests: `npm run test:run`
- Acceptance tests (SQLite): `DATABASE_PROVIDER=sqlite npm run test:acceptance`
- Acceptance tests (PostgreSQL): `npm run test:acceptance` (with Docker)
+86 -118
View File
@@ -1,134 +1,102 @@
# EuchreCamp - Project Todo List
# EuchreCamp - Todo List
## Completed Features
## Current Tasks
### Backend
- [x] Database schema for matches, players, teams, events
- [x] Elo rating calculator and job
- [x] Partnership tracking and analytics
- [x] Tournament generator (round-robin, single elim, double elim, Swiss)
- [x] ROM relations and repositories
- [x] Acceptance test suite (8 tests passing)
### Completed ✅
- [x] Add `site_admin` role to database schema and permissions system
- [x] Add `isCasual` boolean field to Match model (already existed)
- [x] Update match upload API to support casual matches
- [x] Update match upload UI to include casual checkbox
- [x] Add tournament deletion API endpoint with delete/orphan options
- [x] Add delete tournament button and modal to tournament detail page
- [x] Run tests and verify implementation (84 tests passing)
- [x] Fix session issues with tournament admin access
- [x] Fix Elo recalculation error for player merge (delete elo snapshots before deleting players)
- [x] Add admin player management page
- [x] Add player name editing functionality in admin UI
- [x] Add admin panel links to navigation header
- [x] Add tournament update API endpoint (PUT /api/tournaments/[id])
- [x] Consolidate delete endpoint from admin API to main tournaments API
- [x] Update database schema to add variant scoring fields (targetScore, allowTies)
- [x] Fix tie handling logic in partnership stats (ties now correctly tracked)
- [x] Fix test files for normalizedName field in Player model
- [x] Fix auth.ts to include normalizedName in Player creation
- [x] Write TODO list to repository file
- [x] Auto-create tournament when uploading matches without selecting one
### Frontend
- [x] Basic player rankings page
- [x] Match entry form
### In Progress 🔄
- [ ] Update API routes to handle new variant scoring fields
- [ ] Update EditTournamentForm to add variant scoring controls
- [ ] Update MatchEditor to use tournament-specific target score
- [ ] Run tests and verify variant scoring implementation
## In Progress - UI Development
### Recently Completed ✅
- [x] Add OpenSkill rating system support (src/lib/openskill-utils.ts)
- [x] Add Glicko2 rating system support (src/lib/glicko2-utils.ts)
- [x] Reset database and run all migrations from scratch
- [x] Regenerate Prisma client with new rating models
- [x] Update match upload page to auto-create tournament if none selected
- [x] Update all admin scripts to use PrismaPg adapter and dotenv
- [x] Fix match diagram player positioning
- [x] Add CasaOS deployment configuration and documentation
- [x] Create migration to add rating system tables (elo_ratings, glicko2_ratings, open_skill_ratings)
- [x] Add tabbed rankings page to display Elo, OpenSkill, and Glicko2 ratings
### Completed
- [x] Navigation layout (Next.js components)
- [x] UI Design document (UI_DESIGN.md)
- [x] Player Profile page (Next.js)
- [x] Basic CSS styling (Tailwind CSS)
- [x] Player Schedule page (Next.js)
- [x] Route for player schedule
### Backlog 📋
- [ ] Add UI controls for variant scoring in tournament creation/edit
- [ ] Test variant tournament functionality end-to-end
- [ ] Add validation for tie scores based on tournament configuration
- [ ] Document variant tournament features
### View Types to Implement
- [ ] Tournament Admin View (Phase 2-3)
- Create/manage tournaments
- Set up brackets and matchups
- Record match results
- View tournament standings
## Recently Completed (Detailed)
- [ ] Club Admin View (Superuser) (Phase 3-4)
- Manage all players
- View club-wide statistics
- Configure club settings
- Manage tournaments
### Variant Euchre Scoring Support
- Added `targetScore` and `allowTies` fields to Event model
- Created database migration for new fields
- Fixed partnership stats tie handling (ties now increment neither wins nor losses)
- Updated Elo calculation functions to handle ties correctly (0.5 points for draw)
- [ ] Player Profile View (Phase 1-2)
- Display player info and Elo rating
- Show partnership analytics
- Display match history
- Tournament participation
- Enhance existing template
### Tournament Deletion
- Consolidated delete endpoint to `/api/tournaments/[id]`
- Added options to delete matches or orphan them
- Updated DeleteTournamentButton to use consolidated endpoint
- [ ] Player Tournament Schedule View (Phase 4)
- Show upcoming matches
- Display tournament brackets
- Record personal match results
### Player Management
- Added admin players page at `/admin/players`
- Added player name editing functionality via PATCH endpoint
- Added player merge functionality with automatic Elo recalculation
- Fixed foreign key constraint issues with elo_snapshots
### UI Components Needed
- [x] Navigation system (role-based) - Started
- [ ] Dashboard layouts
- [ ] Forms for data entry
- [ ] Tables for displaying data
- [ ] Charts for statistics
- [ ] Bracket visualization
### Permissions
- Added `site_admin` role as highest privilege level
- Updated all permission functions to include site_admin support
- Fixed session cache issues by reading roles from database
### Implementation Phases
- [x] Phase 1: Navigation & Layout
- [x] Phase 2: Player Profile Enhancements
- [x] Phase 3: Tournament Admin View
- [x] Phase 4: Club Admin View
- [x] Phase 5: Player Schedule View
- [ ] Phase 6: Authentication & Authorization
- [x] Phase 7: Polish & Testing
## Notes
- All 84 unit tests passing
- Database migrations applied successfully
- TypeScript compilation has pre-existing errors unrelated to our changes
## Future Enhancements
### Completed After Commit 1729dac
### Features
- [ ] Real-time match updates (WebSockets)
- [ ] Mobile-responsive design improvements
- [ ] Email notifications
- [ ] Import/Export functionality
- [ ] API for third-party integrations
- [ ] Advanced analytics charts
#### Next.js 16 Breaking Change Fixes
- [x] Fixed `params.id` usage in all page components (must use `await params`)
- [x] Fixed `params.id` usage in all API routes (must use `await params`)
- [x] Updated client components to use `Promise<{ id: string }>` type
- [x] Added regression tests for Next.js 16 params Promise handling
- [x] Verified all 100 unit tests pass
### Technical
- [ ] Performance optimization
- [ ] Caching strategy
- [ ] Security hardening
- [ ] Deployment pipeline
- [ ] CI/CD setup
#### Files Updated:
- Player pages: `profile.tsx`, `schedule.tsx`
- Tournament pages: `page.tsx`, `results.tsx`, `edit.tsx`, `entry.tsx`
- API routes: `admin/players/[id]/route.ts`, `users/[id]/route.ts`, `users/[id]/role/route.ts`
- Tournament API routes: `[id]/route.ts`, `[id]/participants/route.ts`, `[id]/games/bulk/route.ts`
## AAA System (Authentication, Authorization, Accounting) - Next.js Implementation
#### Root Cause
Next.js 16 requires `params` to be awaited in both server components and API routes:
- Before: `const { id } = params`
- After: `const { id } = await params`
### Authentication (Better Auth + Prisma)
- [x] Set up Better Auth with Prisma
- [x] Create users table schema
- [x] Build login page (`/auth/login`)
- [x] Build registration page (`/auth/register`)
- [x] Implement session management with Better Auth
- [x] Add authentication middleware
- [ ] Password reset functionality
- [ ] Email confirmation system
- [ ] OAuth providers (optional)
### Authorization (RBAC)
- [x] Define roles in Prisma schema (PLAYER, TOURNAMENT_ADMIN, CLUB_ADMIN)
- [x] Implement authorization helpers
- [x] Add authorization to admin dashboard
- [x] Add authorization to player management
- [x] Add authorization to tournament management
- [x] Add 5-minute match edit window (player role)
- [ ] Add role assignment UI for club admins
- [ ] Add permission checks to all API routes
### Accounting (Activity Logging)
- [ ] Create activity logging system (Prisma model)
- [ ] Track authentication events
- [ ] Track tournament management events
- [ ] Track match recording events
- [ ] Build audit reports UI
### Security
- [x] Rate limiting (Better Auth built-in)
- [ ] IP-based lockout
- [x] Secure cookie settings (Better Auth)
- [x] CSRF protection (Next.js built-in)
- [ ] Security headers
- [ ] Session fixation prevention
## Known Issues
- [ ] Database IDs not resetting between tests (workaround: query by round_number)
- [ ] Need to clean up debug output from acceptance tests
- [ ] Password reset flow not yet implemented
## Next Steps
1. Design UI mockups for each view type
2. Implement navigation system
3. Build out Tournament Admin view
4. Add role-based access control
5. Create reusable UI components
This was not caught by the unit test suite because:
- Unit tests test individual functions in isolation
- E2E tests (Playwright) would catch this but weren't run after the upgrade
+273
View File
@@ -0,0 +1,273 @@
# EuchreCamp CasaOS Deployment Guide
This guide explains how to deploy EuchreCamp on your CasaOS server.
## Prerequisites
1. **CasaOS** installed on your server
2. **Docker** and **Docker Compose** available in CasaOS
3. **Port 3000** available for the web interface
4. **Port 5432** available for PostgreSQL (or use external database)
## Prerequisites
**External PostgreSQL Database Required**
- PostgreSQL 15 or higher
- Database name: `euchre_camp`
- User: `euchre_camp`
- Privileges: ALL on database `euchre_camp`
## Quick Start
### Option 1: Using CasaOS App Store (Recommended)
1. **Set up PostgreSQL database first** (see below)
2. Open CasaOS Dashboard
3. Go to **App Store****Custom App**
4. Click **Install** and configure the following:
**Basic Settings:**
- App Name: `EuchreCamp`
- Image: `euchre-camp:latest` (build locally first)
- Port: `3000`
**Environment Variables:**
```
DATABASE_URL=postgresql://euchre_camp:password@your-postgres-host:5432/euchre_camp
DATABASE_SHADOW_URL=postgresql://euchre_camp:password@your-postgres-host:5432/euchre_camp_shadow
BETTER_AUTH_SECRET=your-secret-key-here
BETTER_AUTH_URL=http://your-casaos-ip:3000
TRUSTED_ORIGINS=http://your-casaos-ip:3000
```
5. Click **Install**
### Option 2: Using Docker Compose
1. **Set up PostgreSQL database first** (see below)
2. **Build the Docker image:**
```bash
docker-compose -f docker-compose.casaos.yml build
```
3. **Start the application:**
```bash
docker-compose -f docker-compose.casaos.yml up -d
```
4. **Check logs:**
```bash
docker-compose -f docker-compose.casaos.yml logs -f
```
## PostgreSQL Database Setup
### Option A: External PostgreSQL Server
Connect to your PostgreSQL server and run:
```sql
-- Create database
CREATE DATABASE euchre_camp;
-- Create user
CREATE USER euchre_camp WITH PASSWORD 'your-strong-password';
-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE euchre_camp TO euchre_camp;
-- Connect to database
\c euchre_camp
-- Grant schema privileges
GRANT ALL ON SCHEMA public TO euchre_camp;
```
### Option B: CasaOS PostgreSQL Container
If you want to run PostgreSQL in CasaOS:
1. Install PostgreSQL from CasaOS App Store
2. Configure it with:
- Database: `euchre_camp`
- User: `euchre_camp`
- Password: `your-strong-password`
3. Use the connection string in your EuchreCamp configuration:
```
DATABASE_URL=postgresql://euchre_camp:your-strong-password@192.168.1.100:5432/euchre_camp
```
(Replace `192.168.1.100` with your CasaOS IP)
## Configuration
### Required Environment Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `DATABASE_URL` | PostgreSQL connection string (REQUIRED) | `postgresql://euchre_camp:pass@host:5432/euchre_camp` |
| `BETTER_AUTH_SECRET` | Secret key for session encryption (generate with `openssl rand -base64 32`) | `your-generated-secret` |
| `BETTER_AUTH_URL` | Public URL of your application | `http://192.168.1.100:3000` |
| `TRUSTED_ORIGINS` | Comma-separated list of trusted origins | `http://192.168.1.100:3000` |
### Optional Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `DATABASE_SHADOW_URL` | Shadow database for migrations | Same as DATABASE_URL with `_shadow` suffix |
## Database Management
### First-Time Setup
1. **Create the database and user** (see PostgreSQL Setup above)
2. **Run database migrations:**
```bash
docker exec -it euchre-camp npx prisma migrate deploy
```
3. **Create admin user:**
```bash
docker exec -it euchre-camp node scripts/create-admin-via-api.js
```
### Accessing the Database
```bash
# Connect to external PostgreSQL server
psql -h your-postgres-host -U euchre_camp -d euchre_camp
# List tables
\dt
# Exit
\q
```
### Backing Up Data
```bash
# Backup PostgreSQL data (run on your PostgreSQL server)
pg_dump -h your-postgres-host -U euchre_camp euchre_camp > backup.sql
# Backup uploaded files
tar -czf euchre_camp_files.tar.gz /var/lib/docker/volumes/euchre_camp_app_data
```
## Security Considerations
### Change Default Passwords
1. **PostgreSQL Password:**
- Edit `docker-compose.casaos.yml` or set via CasaOS environment variables
- Update `POSTGRES_PASSWORD` to a strong password
2. **Better Auth Secret:**
```bash
openssl rand -base64 32
```
- Use this value for `BETTER_AUTH_SECRET`
### HTTPS Setup
For production use with HTTPS:
1. **Option A: CasaOS Reverse Proxy**
- Configure CasaOS to use HTTPS
- Update `BETTER_AUTH_URL` to `https://your-domain.com`
2. **Option B: External Reverse Proxy (Nginx, Traefik)**
- Configure your reverse proxy
- Update `TRUSTED_ORIGINS` to include your domain
### Firewall Rules
Ensure only necessary ports are exposed:
- **Port 3000**: Web interface (HTTP/HTTPS)
- **Port 5432**: PostgreSQL (only if external access needed)
## Troubleshooting
### Database Connection Issues
```bash
# Check PostgreSQL logs
docker logs euchre-camp-postgres
# Check if PostgreSQL is healthy
docker exec euchre-camp-postgres pg_isready -U euchre -d euchre_camp
```
### Application Not Starting
```bash
# Check application logs
docker logs euchre-camp
# Check if Prisma migrations are applied
docker exec euchre-camp npx prisma migrate status
```
### Permission Issues
If you see permission errors:
```bash
# Fix volume permissions
docker exec euchre-camp chown -R euchre:euchre /app/public/uploads
```
## Performance Tuning
### PostgreSQL Optimization
Add to `docker-compose.casaos.yml` under `postgres` service:
```yaml
environment:
- POSTGRES_SHARED_BUFFERS=256MB
- POSTGRES_WORK_MEM=16MB
```
### Application Optimization
The Dockerfile is already optimized with:
- Multi-stage build (smaller image size)
- Non-root user for security
- Health checks
- Production-ready settings
## Updating
To update EuchreCamp:
```bash
# Pull latest changes
git pull origin main
# Rebuild and restart
docker-compose -f docker-compose.casaos.yml down
docker-compose -f docker-compose.casaos.yml build --no-cache
docker-compose -f docker-compose.casaos.yml up -d
```
## Monitoring
### View Logs
```bash
docker-compose -f docker-compose.casaos.yml logs -f
```
### Check Container Status
```bash
docker ps | grep euchre
```
### Resource Usage
```bash
docker stats euchre-camp euchre-camp-postgres
```
## Support
For issues or questions:
- Check the application logs first
- Verify environment variables are set correctly
- Ensure PostgreSQL is running and accessible
- Check CasaOS app logs for deployment issues
+370
View File
@@ -0,0 +1,370 @@
# Docker Deployment Guide
This guide covers how to run EuchreCamp using Docker and Docker Compose.
## Prerequisites
- Docker Engine 20.10+
- Docker Compose v2.0+
- Make (optional, for using Makefile commands)
## Quick Start
### 1. Environment Setup
Create a `.env` file in the project root:
```bash
cp .env.example .env
```
Update the `.env` file with your configuration:
```env
# Database Configuration (PostgreSQL in Docker)
DATABASE_PROVIDER=postgresql
DATABASE_URL=postgresql://euchre:euchrepassword@postgres:5432/euchre_camp
DATABASE_SHADOW_URL=postgresql://euchre:euchrepassword@postgres:5432/euchre_camp_shadow
# Better Auth (generate a secure secret for production)
BETTER_AUTH_SECRET=your-secret-key-change-in-production
BETTER_AUTH_URL=http://localhost:3000
# Application
NODE_ENV=production
TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
```
### 2. Build and Run
#### Production Mode
```bash
# Build and start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop all services
docker-compose down
```
#### Development Mode
```bash
# Use development override configuration
docker-compose -f docker-compose.yml -f docker-compose.override.yml up -d
# Or use the shorthand
docker-compose --profile dev up -d
```
### 3. Access the Application
- **Web Application**: http://localhost:3000
- **PostgreSQL**: localhost:5432 (default) or 5433 in development
## Service Architecture
```
┌─────────────────────────────────────────────┐
│ EuchreCamp │
├─────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Next.js │◄───│ PostgreSQL │ │
│ │ App │ │ Database │ │
│ │ │ │ │ │
│ │ Port: 3000 │ │ Port: 5432 │ │
│ └──────────────┘ └──────────────────┘ │
│ │
└─────────────────────────────────────────────┘
```
## Service Details
### App Service
- **Image**: Multi-stage Next.js build
- **Port**: 3000
- **Environment**: Production or Development
- **Volumes**:
- `app_data`: Persistent storage for uploads
### PostgreSQL Service
- **Image**: postgres:15-alpine
- **Port**: 5432 (production) / 5433 (development)
- **Data Volume**: `postgres_data` (persistent)
- **Health Check**: Uses `pg_isready`
## Database Management
### View Database Data
```bash
# Access PostgreSQL shell
docker exec -it euchre-camp-postgres psql -U euchre -d euchre_camp
# List tables
\dt
# Exit
\q
```
### Backup Database
```bash
# Create backup
docker exec euchre-camp-postgres pg_dump -U euchre euchre_camp > backup.sql
# Restore backup
docker exec -i euchre-camp-postgres psql -U euchre euchre_camp < backup.sql
```
### Reset Database
```bash
# Remove all data and restart
docker-compose down -v
docker-compose up -d
```
## Running Commands
### Run Database Migrations
```bash
# Apply migrations
docker-compose exec app npx prisma migrate deploy
# Generate Prisma client
docker-compose exec app npx prisma generate
# Open Prisma Studio
docker-compose exec app npx prisma studio
```
### Create Admin User
```bash
# Create admin user via script
docker-compose exec app node scripts/create-admin-via-api.js
```
### Seed Database
```bash
# Run seed script
docker-compose exec app node scripts/seed.js
```
## Development Workflow
### Hot Reloading
Development mode supports hot reloading:
```bash
# Start in development mode
docker-compose -f docker-compose.yml -f docker-compose.override.yml up -d
# View logs
docker-compose logs -f app
```
### Modifying Code
Changes to source code are automatically reflected due to volume mounting:
```bash
# Edit a file locally
nano src/app/page.tsx
# Next.js will automatically reload
```
## Troubleshooting
### Common Issues
**1. Database Connection Failed**
```bash
# Check if PostgreSQL is running
docker ps | grep postgres
# Check logs
docker logs euchre-camp-postgres
# Restart services
docker-compose restart postgres
```
**2. Port Already in Use**
```bash
# Check what's using port 3000
lsof -i :3000
# Change port in docker-compose.yml
# ports:
# - "3001:3000"
```
**3. Permission Denied**
```bash
# Ensure scripts are executable
chmod +x scripts/*.sh
# Check volume permissions
docker exec euchre-camp-app ls -la /app
```
**4. Migration Errors**
```bash
# Reset database
docker-compose down -v
docker-compose up -d
# Apply migrations manually
docker-compose exec app npx prisma migrate deploy
```
### View Logs
```bash
# All services
docker-compose logs -f
# Specific service
docker-compose logs -f app
docker-compose logs -f postgres
```
### Container Shell Access
```bash
# App container
docker exec -it euchre-camp-app sh
# PostgreSQL container
docker exec -it euchre-camp-postgres sh
```
## Production Deployment
### Environment Variables
For production, ensure you set secure values:
```env
# Generate a secure secret
BETTER_AUTH_SECRET=$(openssl rand -base64 32)
# Use real domain
BETTER_AUTH_URL=https://euchrecamp.example.com
# Trusted origins
TRUSTED_ORIGINS=https://euchrecamp.example.com,https://www.euchrecamp.example.com
```
### Security Considerations
1. **Change default PostgreSQL password**:
```env
POSTGRES_PASSWORD=your-secure-password
```
2. **Use SSL/TLS for database connections**:
```env
DATABASE_URL=postgresql://euchre:password@postgres:5432/euchre_camp?sslmode=require
```
3. **Restrict network access**:
- Don't expose PostgreSQL port to public internet
- Use firewall rules to restrict access
4. **Regular backups**:
- Schedule automated database backups
- Test restoration process
### Docker Swarm / Kubernetes
For production orchestration, consider:
1. **Separate database service** - Use managed PostgreSQL (RDS, Cloud SQL)
2. **Secrets management** - Use Docker secrets or Kubernetes Secrets
3. **Health checks** - Configure proper health checks
4. **Resource limits** - Set CPU and memory limits
5. **Replicas** - Run multiple app instances for high availability
## Makefile (Optional)
Create a `Makefile` for convenient commands:
```makefile
.PHONY: up down logs build shell-migrate
up:
docker-compose up -d
down:
docker-compose down
logs:
docker-compose logs -f
build:
docker-compose build --no-cache
shell-app:
docker exec -it euchre-camp-app sh
shell-db:
docker exec -it euchre-camp-postgres psql -U euchre -d euchre_camp
migrate:
docker-compose exec app npx prisma migrate deploy
seed:
docker-compose exec app node scripts/seed.js
```
## Performance Tuning
### PostgreSQL Configuration
Edit `docker-compose.yml` to tune PostgreSQL:
```yaml
postgres:
# ... other config ...
command: >
postgres
-c max_connections=200
-c shared_buffers=256MB
-c effective_cache_size=1GB
-c maintenance_work_mem=64MB
-c checkpoint_completion_target=0.9
-c wal_buffers=16MB
-c default_statistics_target=100
```
### Next.js Optimization
The Dockerfile uses multi-stage build for optimal size and performance:
- **Builder stage**: Installs all dependencies and builds the app
- **Runner stage**: Copies only the built artifacts and production dependencies
## References
- [Docker Compose Documentation](https://docs.docker.com/compose/)
- [PostgreSQL Docker Image](https://hub.docker.com/_/postgres)
- [Next.js Deployment](https://nextjs.org/docs/deployment)
- [Prisma Deployment](https://www.prisma.io/docs/concepts/components/prisma-migrate/deployment)