19 Commits

Author SHA1 Message Date
david 381bf630c7 chore: bump version to v0.1.1 2026-03-31 18:44:33 -07:00
david 1f4bdc2756 Merge branch 'feat/database-test-safety' of ssh://git.notsosm.art/david/euchre_camp 2026-03-31 18:44:08 -07:00
david f9d6321721 fix: use ELO change instead of win rate for best partner calculation 2026-03-31 18:39:27 -07:00
david b38b88f67d chore: regenerate docker-compose files with environment variables 2026-03-31 18:33:51 -07:00
david 237f128779 fix: remove hardcoded passwords from docker-compose generation 2026-03-31 18:32:32 -07:00
david 6989decf6f fix: load .env.development in test setup files 2026-03-31 18:30:19 -07:00
david 4e112c92ae fix: remove hardcoded database URLs and use environment variables 2026-03-31 18:28:17 -07:00
david a9fc5c312a fix: set DATABASE_URL for acceptance tests 2026-03-31 18:24:53 -07:00
david abc1963aea feat: add database test safety configuration 2026-03-31 18:23:47 -07:00
david 6cef0ac342 chore: update admin script to set site_admin role by default 2026-03-31 17:52:46 -07:00
david 74e6180a35 chore: update Docker repository from dhg.lol:5000 to euchre-camp/euchre-camp 2026-03-31 17:43:12 -07:00
david 8440962649 chore: release v0.1.0
- Update docker-compose files to use v0.1.0 image tag
- Add CHANGELOG.md with release notes
2026-03-31 17:33:58 -07:00
david 255b330695 fix: allowTies not saved when editing tournaments (closes #6)
Fix the allowTies checkbox not being saved when editing tournaments. Added comprehensive unit and E2E tests to verify the fix.

Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-04-01 00:20:25 +00:00
david 8c9a8b0d9f chore: update cleanup scripts to delete Home Match Player and Admin User patterns 2026-03-31 17:02:22 -07:00
david a82ec3c9fc chore: add production database cleanup scripts 2026-03-31 16:57:36 -07:00
david b5af4b2e34 docs: add development database and testing documentation 2026-03-31 16:53:42 -07:00
david 26c5158724 feat: set up development database and test cleanup utilities 2026-03-31 16:52:56 -07:00
david 48a96ce65f fix: improve availablePlayers query to handle undefined playerId 2026-03-31 16:44:48 -07:00
david 1f9f708f19 fix: handle empty playerId string in user edit API 2026-03-31 16:44:26 -07:00
24 changed files with 1349 additions and 59 deletions
+98
View File
@@ -0,0 +1,98 @@
## [0.1.1] - 2026-04-01
### Patch Changes
- Merge branch 'feat/database-test-safety' of ssh://git.notsosm.art/david/euchre_camp
- fix: use ELO change instead of win rate for best partner calculation
- fix: remove hardcoded passwords from docker-compose generation
- fix: load .env.development in test setup files
- fix: remove hardcoded database URLs and use environment variables
- fix: set DATABASE_URL for acceptance tests
- feat: add database test safety configuration
- fix: allowTies not saved when editing tournaments (closes #6)
- docs: add development database and testing documentation
- feat: set up development database and test cleanup utilities
- fix: improve availablePlayers query to handle undefined playerId
- fix: handle empty playerId string in user edit API
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.0] - 2026-03-31
### Added
- **Authentication System**: Complete Better Auth integration with session management
- **Authorization (RBAC)**: Role-based access control with player, tournament_admin, club_admin, and site_admin roles
- **Tournament Management**: Full CRUD operations with multiple formats (round-robin, single/double elimination, Swiss)
- **Rating Systems**: Support for Elo, Glicko2, and OpenSkill rating calculations
- **Admin Panel**: Comprehensive admin interface for managing players, tournaments, and matches
- **Player Profiles**: Detailed player statistics with partnership analytics
- **Match Recording**: CSV upload functionality for batch match entry
- **Development Database**: Isolated development database for testing
- **Test Cleanup System**: Automatic cleanup of test records
- **Production Database Cleanup**: Tools to remove test data while preserving real data
- **Semantic Versioning**: Git tagging and Docker image tagging system
### Fixed
- **Session Refresh**: Fixed navigation not updating immediately after login (closes #6)
- **allowTies Save Bug**: Fixed "Allow Ties" checkbox not being saved when editing tournaments
- **Next.js 16 Compatibility**: Fixed params Promise handling across all API routes and pages
- **Match Diagram Positioning**: Fixed player positioning in match diagrams
### Changed
- **Database**: Migrated from SQLite to PostgreSQL with production-ready configuration
- **Docker**: Updated image tagging to use versioned tags (e.g., v0.1.0, latest)
- **Testing**: Improved test coverage with 103 passing unit tests
- **Documentation**: Added comprehensive README with development setup instructions
### Removed
- N/A
## [0.0.1] - Initial Development
### Added
- Basic database schema for Euchre tournament management
- Initial Next.js application structure
- Basic navigation and layout
- Player rankings page
---
## Release Process
This project follows semantic versioning (Semver):
1. **Version Format**: `MAJOR.MINOR.PATCH`
- `MAJOR`: Breaking changes (API changes, database migrations requiring data migration)
- `MINOR`: New features (backward compatible)
- `PATCH`: Bug fixes, security updates
2. **Pre-release Versions**: `MAJOR.MINOR.PATCH-alpha.N`, `MAJOR.MINOR.PATCH-beta.N`, `MAJOR.MINOR.PATCH-rc.N`
3. **Creating a Release**:
```bash
# Bump version
npm run version:patch # or version:minor, version:major
# Create git tag
git tag -a v0.1.0 -m "Release v0.1.0"
# Push changes and tag
git push origin main
git push origin v0.1.0
# Build and push Docker images
npm run docker:build:push
# Create release in Gitea
tea release create v0.1.0 --title "Release v0.1.0" --note-file CHANGELOG.md
```
+40
View File
@@ -161,6 +161,46 @@ DATABASE_URL="postgresql://username:password@localhost:5432/euchre_camp"
DATABASE_SHADOW_URL="postgresql://username:password@localhost:5432/euchre_camp_shadow" DATABASE_SHADOW_URL="postgresql://username:password@localhost:5432/euchre_camp_shadow"
``` ```
## Development Database
For development and testing, use a separate development database to avoid conflicts with production data.
**Setup Development Database:**
```bash
# Create and setup the development database
npm run db:setup-dev
# Reset the development database (drops and recreates)
npm run db:reset-dev
# Clean development database (drop and recreate with migrations)
npm run db:setup-dev:clean
```
**Environment Configuration:**
The development database uses `.env.development` which is automatically configured for:
- Database: `euchre_camp_dev`
- NODE_ENV: `development`
**Testing with Development Database:**
```bash
# Run unit tests (uses test database automatically)
npm run test
# Run acceptance tests (uses development database)
npm run test:acceptance
```
**Test Data Cleanup:**
All tests automatically clean up their created records:
- Global setup/teardown handles Playwright tests
- Test utilities provide `cleanupTestRecords()` for manual cleanup
- Tests use `beforeEach` and `afterEach` hooks for automatic cleanup
## Usage ## Usage
### Creating a Tournament ### Creating a Tournament
+4 -4
View File
@@ -7,15 +7,15 @@
services: services:
app: app:
image: dhg.lol:5000/euchre-camp:0.1.0 image: euchre-camp/euchre-camp:0.1.0.dev
container_name: euchre-camp container_name: euchre-camp
ports: ports:
- "51193:3000" - "51193:3000"
environment: environment:
# Database Configuration (REQUIRED: Set via CasaOS environment variables) # Database Configuration (REQUIRED: Set via CasaOS environment variables)
- DATABASE_PROVIDER=postgresql - DATABASE_PROVIDER=postgresql
- DATABASE_URL="postgresql://euchre_camp:LINGO5row_hiding@dhg.lol:5432/euchre_camp" - DATABASE_URL=${DATABASE_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp}
- DATABASE_SHADOW_URL="postgresql://euchre_camp:LINGO5row_hiding@dhg.lol:5432/euchre_camp_shadow" - DATABASE_SHADOW_URL=${DATABASE_SHADOW_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp_shadow}
# Better Auth Configuration # Better Auth Configuration
- BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-change-this-secret-in-production} - BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-change-this-secret-in-production}
@@ -28,7 +28,7 @@ services:
- TRUSTED_ORIGINS=${TRUSTED_ORIGINS:-http://localhost:3000,http://127.0.0.1:3000} - TRUSTED_ORIGINS=${TRUSTED_ORIGINS:-http://localhost:3000,http://127.0.0.1:3000}
# Version tracking # Version tracking
- IMAGE_VERSION=0.1.0 - IMAGE_VERSION=0.1.0.dev
volumes: volumes:
# Persist uploaded files and static content # Persist uploaded files and static content
+3 -3
View File
@@ -14,8 +14,8 @@ services:
environment: environment:
# Database Configuration # Database Configuration
- DATABASE_PROVIDER=postgresql - DATABASE_PROVIDER=postgresql
- DATABASE_URL=postgresql://euchre_camp:password@db:5432/euchre_camp - DATABASE_URL=${DATABASE_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp}
- DATABASE_SHADOW_URL=postgresql://euchre_camp:password@db:5432/euchre_camp_shadow - DATABASE_SHADOW_URL=${DATABASE_SHADOW_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp_shadow}
# Better Auth Configuration # Better Auth Configuration
- BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-dev-secret-change-in-production} - BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-dev-secret-change-in-production}
@@ -28,7 +28,7 @@ services:
- TRUSTED_ORIGINS=${TRUSTED_ORIGINS:-http://localhost:3000,http://127.0.0.1:3000} - TRUSTED_ORIGINS=${TRUSTED_ORIGINS:-http://localhost:3000,http://127.0.0.1:3000}
# Version tracking # Version tracking
- IMAGE_VERSION=0.1.0 - IMAGE_VERSION=0.1.0.dev-dev
volumes: volumes:
# Mount source code for hot reload # Mount source code for hot reload
+4 -4
View File
@@ -3,15 +3,15 @@
services: services:
app: app:
image: dhg.lol:5000/euchre-camp:0.1.0 image: euchre-camp/euchre-camp:0.1.0.dev
container_name: euchre-camp-app container_name: euchre-camp-app
ports: ports:
- "3000:3000" - "3000:3000"
environment: environment:
# Database Configuration # Database Configuration
- DATABASE_PROVIDER=postgresql - DATABASE_PROVIDER=postgresql
- DATABASE_URL=postgresql://euchre_camp:password@db:5432/euchre_camp - DATABASE_URL=${DATABASE_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp}
- DATABASE_SHADOW_URL=postgresql://euchre_camp:password@db:5432/euchre_camp_shadow - DATABASE_SHADOW_URL=${DATABASE_SHADOW_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp_shadow}
# Better Auth Configuration # Better Auth Configuration
- BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-change-this-secret-in-production} - BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:-change-this-secret-in-production}
@@ -24,7 +24,7 @@ services:
- TRUSTED_ORIGINS=${TRUSTED_ORIGINS:-http://localhost:3000,http://127.0.0.1:3000} - TRUSTED_ORIGINS=${TRUSTED_ORIGINS:-http://localhost:3000,http://127.0.0.1:3000}
# Version tracking # Version tracking
- IMAGE_VERSION=0.1.0 - IMAGE_VERSION=0.1.0.dev
depends_on: depends_on:
- db - db
+7 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "euchre_camp", "name": "euchre_camp",
"version": "0.1.0", "version": "0.1.1",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "NEXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) next dev", "dev": "NEXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) next dev",
@@ -13,6 +13,12 @@
"test:acceptance:headed": "playwright test src/__tests__/e2e/ --headed", "test:acceptance:headed": "playwright test src/__tests__/e2e/ --headed",
"db:switch": "node scripts/switch-database.js", "db:switch": "node scripts/switch-database.js",
"db:setup-postgres": "node scripts/setup-postgres.js", "db:setup-postgres": "node scripts/setup-postgres.js",
"db:setup-dev": "node scripts/setup-postgres.js",
"db:setup-dev:clean": "node scripts/setup-postgres.js --drop",
"db:reset-dev": "node scripts/reset-dev-db.js",
"db:use-dev": "node scripts/use-dev-db.js",
"db:cleanup-prod": "node scripts/cleanup-prod-db.js",
"db:check-prod": "node scripts/check-test-records.js",
"db:seed": "node scripts/seed.js", "db:seed": "node scripts/seed.js",
"docker:up": "docker-compose up -d", "docker:up": "docker-compose up -d",
"docker:down": "docker-compose down", "docker:down": "docker-compose down",
+1 -1
View File
@@ -14,7 +14,7 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
// Configuration // Configuration
const REGISTRY = 'dhg.lol:5000'; const REGISTRY = 'euchre-camp';
const IMAGE_NAME = 'euchre-camp'; const IMAGE_NAME = 'euchre-camp';
const FULL_IMAGE_NAME = `${REGISTRY}/${IMAGE_NAME}`; const FULL_IMAGE_NAME = `${REGISTRY}/${IMAGE_NAME}`;
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env node
/**
* Check for test records in production database (read-only)
* Shows what would be deleted without making any changes
*/
const { execSync } = require('child_process');
// Database connection string - must be explicitly set via environment variable
const DB_URL = process.env.PROD_DATABASE_URL || process.env.DATABASE_URL;
// Check if database URL is set
if (!DB_URL) {
console.error('❌ No database URL set');
console.error('Please set PROD_DATABASE_URL or DATABASE_URL environment variable');
console.error('For production: PROD_DATABASE_URL="postgresql://user:pass@host:port/dbname"');
process.exit(1);
}
// Validate that we're not accidentally using dev database
if (DB_URL.includes('_dev') || DB_URL.includes('_dev_')) {
console.error('❌ ERROR: This script should not be used with the development database!');
console.error(' Current DATABASE_URL:', DB_URL);
console.error(' Please set PROD_DATABASE_URL for production database operations.');
process.exit(1);
}
// Helper to run SQL and log results
function runSQL(sql, description) {
console.log(`\n🔍 ${description}...`);
try {
const result = execSync(`psql "${DB_URL}" -c "${sql}"`, { encoding: 'utf8' });
console.log(result);
return true;
} catch (error) {
console.error(`❌ Error: ${error.message}`);
return false;
}
}
// Helper to count records matching pattern
function countRecords(table, column, pattern) {
const sql = `SELECT COUNT(*) FROM ${table} WHERE ${column} LIKE '${pattern}';`;
try {
const result = execSync(`psql "${DB_URL}" -c "${sql}" -t`, { encoding: 'utf8' }).trim();
return parseInt(result);
} catch (error) {
return 0;
}
}
console.log('🔍 Checking test records in production database');
console.log('=============================================\n');
// Count test players
const testPlayerCount = countRecords('players', 'name', '%Test%') +
countRecords('players', 'name', '%Setup%') +
countRecords('players', 'name', '%Home Test%') +
countRecords('players', 'name', '%Home Match Player%') +
countRecords('players', 'name', '%Admin User%');
console.log(`Test players found: ${testPlayerCount}`);
// Count test tournaments
const testEventCount = countRecords('events', 'name', '%Test%') +
countRecords('events', 'name', '%Setup%') +
countRecords('events', 'name', '%Recent%');
console.log(`Test tournaments found: ${testEventCount}`);
// Count test users
const testUserCount = countRecords('users', 'email', '%test%') +
countRecords('users', 'email', '%setup%');
console.log(`Test users found: ${testUserCount}`);
// Show test players
runSQL(`
SELECT id, name
FROM players
WHERE name LIKE '%Test%' OR name LIKE '%Setup%' OR name LIKE '%Home Test%' OR name LIKE '%Home Match Player%' OR name LIKE '%Admin User%'
ORDER BY name;
`, 'Test players list');
// Show test events
runSQL(`
SELECT id, name
FROM events
WHERE name LIKE '%Test%' OR name LIKE '%Setup%' OR name LIKE '%Recent%'
ORDER BY name;
`, 'Test events list');
// Show test users
runSQL(`
SELECT id, email, name
FROM users
WHERE email LIKE '%test%' OR email LIKE '%setup%'
ORDER BY email;
`, 'Test users list');
// Check which test players have matches (simplified query)
runSQL(`
SELECT p.id, p.name
FROM players p
WHERE (p.name LIKE '%Test%' OR p.name LIKE '%Setup%' OR p.name LIKE '%Home Test%' OR p.name LIKE '%Home Match Player%' OR p.name LIKE '%Admin User%')
ORDER BY p.name;
`, 'Test players (will be deleted)');
// Check which test events exist
runSQL(`
SELECT e.id, e.name
FROM events e
WHERE (e.name LIKE '%Test%' OR e.name LIKE '%Setup%' OR e.name LIKE '%Recent%')
ORDER BY e.name;
`, 'Test events (will be deleted with matches via cascade)');
console.log('\n✅ Check complete!');
console.log('\n💡 Summary:');
console.log(' - Test tournaments (with matches) can be deleted');
console.log(' - Test players can be deleted');
console.log(' - Test users without player associations can be deleted');
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env node
/**
* Clean up production database - remove test records only
*
* WARNING: This script modifies the production database.
* It only removes records that match test patterns.
* It preserves actual player data, matches, and tournaments.
*/
const { execSync } = require('child_process');
// Database connection string - must be explicitly set via environment variable
const DB_URL = process.env.PROD_DATABASE_URL || process.env.DATABASE_URL;
// Check if database URL is set
if (!DB_URL) {
console.error('❌ No database URL set');
console.error('Please set PROD_DATABASE_URL or DATABASE_URL environment variable');
console.error('For production: PROD_DATABASE_URL="postgresql://user:pass@host:port/dbname"');
process.exit(1);
}
// Validate that we're not accidentally using dev database
if (DB_URL.includes('_dev') || DB_URL.includes('_dev_')) {
console.error('❌ ERROR: This script should not be used with the development database!');
console.error(' Current DATABASE_URL:', DB_URL);
console.error(' Please set PROD_DATABASE_URL for production database operations.');
process.exit(1);
}
// Helper to run SQL and log results
function runSQL(sql, description) {
console.log(`\n🔍 ${description}...`);
try {
const result = execSync(`psql "${DB_URL}" -c "${sql}"`, { encoding: 'utf8' });
console.log(result);
return true;
} catch (error) {
console.error(`❌ Error: ${error.message}`);
return false;
}
}
// Helper to run multi-line SQL
function runMultiLineSQL(sqlLines, description) {
console.log(`\n🔍 ${description}...`);
try {
const sql = sqlLines.join('\n');
const result = execSync(`psql "${DB_URL}" -c "${sql}"`, { encoding: 'utf8' });
console.log(result);
return true;
} catch (error) {
console.error(`❌ Error: ${error.message}`);
return false;
}
}
// Helper to count records matching pattern
function countRecords(table, column, pattern) {
const sql = `SELECT COUNT(*) FROM ${table} WHERE ${column} LIKE '${pattern}';`;
try {
const result = execSync(`psql "${DB_URL}" -c "${sql}" -t`, { encoding: 'utf8' }).trim();
return parseInt(result);
} catch (error) {
return 0;
}
}
async function main() {
console.log('🧹 Cleaning up test records from production database');
console.log('=============================================\n');
// Confirm with user
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('⚠️ This will DELETE test records from PRODUCTION database. Continue? (y/N) ', async (answer) => {
if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {
console.log('❌ Cleanup cancelled');
rl.close();
process.exit(0);
}
rl.close();
console.log('\n📋 Checking test records...\n');
// Count test players
const testPlayerCount = countRecords('players', 'name', '%Test%') +
countRecords('players', 'name', '%Setup%') +
countRecords('players', 'name', '%Home Test%') +
countRecords('players', 'name', '%Home Match Player%') +
countRecords('players', 'name', '%Admin User%');
console.log(`Test players found: ${testPlayerCount}`);
// Count test tournaments
const testEventCount = countRecords('events', 'name', '%Test%') +
countRecords('events', 'name', '%Setup%') +
countRecords('events', 'name', '%Recent%');
console.log(`Test tournaments found: ${testEventCount}`);
// Count test users
const testUserCount = countRecords('users', 'email', '%test%') +
countRecords('users', 'email', '%setup%');
console.log(`Test users found: ${testUserCount}`);
console.log('\n🔄 Starting cleanup...\n');
// Step 1: Delete test tournaments (with matches due to cascade delete)
console.log('1. Deleting test tournaments (matches will be deleted via cascade)...');
runSQL(
"DELETE FROM events WHERE (name LIKE '%Test%' OR name LIKE '%Setup%' OR name LIKE '%Recent%');",
'Deleted test tournaments'
);
// Step 2: Delete test players (all of them, since we deleted their matches)
console.log('\n2. Deleting test players...');
runSQL(
"DELETE FROM players WHERE (name LIKE '%Test%' OR name LIKE '%Setup%' OR name LIKE '%Home Test%' OR name LIKE '%Home Match Player%' OR name LIKE '%Admin User%');",
'Deleted test players'
);
// Step 3: Delete test users (they shouldn't have player associations)
console.log('\n3. Deleting test users...');
runSQL(
"DELETE FROM users WHERE (email LIKE '%test%' OR email LIKE '%setup%') AND \"playerId\" IS NULL;",
'Deleted test users'
);
// Summary
console.log('\n✅ Cleanup complete!');
console.log('\n📊 Remaining test records:');
runSQL("SELECT COUNT(*) FROM players WHERE name LIKE '%Test%' OR name LIKE '%Setup%' OR name LIKE '%Home Test%';", 'Remaining test players');
runSQL("SELECT COUNT(*) FROM events WHERE name LIKE '%Test%' OR name LIKE '%Setup%';", 'Remaining test tournaments');
runSQL("SELECT COUNT(*) FROM users WHERE email LIKE '%test%' OR email LIKE '%setup%';", 'Remaining test users');
console.log('\n💡 Note: All test records deleted. Matches are automatically deleted');
console.log(' via cascade delete when their parent tournament is deleted.');
});
}
// Run main function
main();
+14 -5
View File
@@ -43,8 +43,17 @@ async function main() {
}); });
if (existing) { if (existing) {
console.log('User exists, deleting...'); console.log('User exists, updating role to site_admin...');
await prisma.user.delete({ where: { id: existing.id } }); await prisma.user.update({
where: { id: existing.id },
data: { role: 'site_admin' }
});
console.log('✅ User role updated to site_admin (superuser)');
console.log('\nSuperuser created successfully!');
console.log('Email: david@dhg.lol');
console.log('Password: adminadmin');
console.log('Role: site_admin');
return;
} }
// Create user using Better Auth's internal method // Create user using Better Auth's internal method
@@ -62,13 +71,13 @@ async function main() {
console.log(' Name:', signUpResult.user.name); console.log(' Name:', signUpResult.user.name);
console.log(' Password: adminadmin'); console.log(' Password: adminadmin');
// Update the user to have club_admin role // Update the user to have site_admin role (superuser)
await prisma.user.update({ await prisma.user.update({
where: { id: signUpResult.user.id }, where: { id: signUpResult.user.id },
data: { role: 'club_admin' } data: { role: 'site_admin' }
}); });
console.log('✅ User role updated to club_admin'); console.log('✅ User role updated to site_admin (superuser)');
} catch (error) { } catch (error) {
console.error('❌ Error:', error.message); console.error('❌ Error:', error.message);
+7 -7
View File
@@ -12,7 +12,7 @@ const path = require('path');
const { execSync } = require('child_process'); const { execSync } = require('child_process');
// Configuration // Configuration
const REGISTRY = 'dhg.lol:5000'; const REGISTRY = 'euchre-camp';
const IMAGE_NAME = 'euchre-camp'; const IMAGE_NAME = 'euchre-camp';
// Get current version from package.json // Get current version from package.json
@@ -64,8 +64,8 @@ services:
environment: environment:
# Database Configuration (REQUIRED: Set via CasaOS environment variables) # Database Configuration (REQUIRED: Set via CasaOS environment variables)
- DATABASE_PROVIDER=postgresql - DATABASE_PROVIDER=postgresql
- DATABASE_URL="postgresql://euchre_camp:LINGO5row_hiding@dhg.lol:5432/euchre_camp" - DATABASE_URL=\${DATABASE_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp}
- DATABASE_SHADOW_URL="postgresql://euchre_camp:LINGO5row_hiding@dhg.lol:5432/euchre_camp_shadow" - DATABASE_SHADOW_URL=\${DATABASE_SHADOW_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp_shadow}
# Better Auth Configuration # Better Auth Configuration
- BETTER_AUTH_SECRET=\${BETTER_AUTH_SECRET:-change-this-secret-in-production} - BETTER_AUTH_SECRET=\${BETTER_AUTH_SECRET:-change-this-secret-in-production}
@@ -113,8 +113,8 @@ services:
environment: environment:
# Database Configuration # Database Configuration
- DATABASE_PROVIDER=postgresql - DATABASE_PROVIDER=postgresql
- DATABASE_URL=postgresql://euchre_camp:password@db:5432/euchre_camp - DATABASE_URL=\${DATABASE_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp}
- DATABASE_SHADOW_URL=postgresql://euchre_camp:password@db:5432/euchre_camp_shadow - DATABASE_SHADOW_URL=\${DATABASE_SHADOW_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp_shadow}
# Better Auth Configuration # Better Auth Configuration
- BETTER_AUTH_SECRET=\${BETTER_AUTH_SECRET:-change-this-secret-in-production} - BETTER_AUTH_SECRET=\${BETTER_AUTH_SECRET:-change-this-secret-in-production}
@@ -181,8 +181,8 @@ services:
environment: environment:
# Database Configuration # Database Configuration
- DATABASE_PROVIDER=postgresql - DATABASE_PROVIDER=postgresql
- DATABASE_URL=postgresql://euchre_camp:password@db:5432/euchre_camp - DATABASE_URL=\${DATABASE_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp}
- DATABASE_SHADOW_URL=postgresql://euchre_camp:password@db:5432/euchre_camp_shadow - DATABASE_SHADOW_URL=\${DATABASE_SHADOW_URL:-postgresql://euchre_camp:password@db:5432/euchre_camp_shadow}
# Better Auth Configuration # Better Auth Configuration
- BETTER_AUTH_SECRET=\${BETTER_AUTH_SECRET:-dev-secret-change-in-production} - BETTER_AUTH_SECRET=\${BETTER_AUTH_SECRET:-dev-secret-change-in-production}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env node
/**
* Reset Development Database
*
* Drops and recreates the development database with a clean state.
* Useful for development and testing.
*/
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
// Load environment variables - prioritize explicit DEV_DATABASE_URL
// Falls back to DATABASE_URL, then .env.development
const envPath = path.resolve(__dirname, '..', '.env.development');
if (fs.existsSync(envPath)) {
require('dotenv').config({ path: envPath });
}
// Use DEV_DATABASE_URL if set, otherwise use DATABASE_URL
const databaseUrl = process.env.DEV_DATABASE_URL || process.env.DATABASE_URL;
// Check if database URL is set
if (!databaseUrl) {
console.error('❌ No database URL set');
console.error('Please set DEV_DATABASE_URL or DATABASE_URL environment variable');
console.error('Or ensure .env.development file exists with DATABASE_URL');
process.exit(1);
}
// Validate that we're using the dev database
if (!databaseUrl.includes('_dev') && !databaseUrl.includes('_dev_')) {
console.error('❌ ERROR: This script should only be used with the development database!');
console.error(' Current URL:', databaseUrl);
console.error(' Expected pattern: euchre_camp_dev');
console.error(' Please set DEV_DATABASE_URL for development database operations.');
process.exit(1);
}
// Extract database name from URL
const dbUrl = databaseUrl;
const dbName = dbUrl.split('/').pop();
console.log('🔄 Resetting development database...\n');
console.log(`Database: ${dbName}`);
console.log(`URL: ${dbUrl}\n`);
try {
// Drop existing connections
console.log('Dropping existing connections...');
execSync(
`psql "${dbUrl}" -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${dbName}' AND pid <> pg_backend_pid();" 2>/dev/null || true`,
{ stdio: 'pipe' }
);
// Drop the database
console.log('Dropping database...');
execSync(
`psql "${dbUrl}" -c "DROP DATABASE IF EXISTS ${dbName};" 2>/dev/null || true`,
{ stdio: 'pipe' }
);
// Recreate the database
console.log('Creating database...');
execSync(`psql "${dbUrl}" -c "CREATE DATABASE ${dbName};"`, { stdio: 'pipe' });
// Run migrations
console.log('Running migrations...');
execSync('npx prisma migrate deploy', { stdio: 'inherit' });
console.log('\n✅ Development database reset successfully!');
console.log('\nNext steps:');
console.log('1. Seed the database (optional): npm run db:seed');
console.log('2. Start development server: npm run dev');
} catch (error) {
console.error('\n❌ Failed to reset database:', error.message);
process.exit(1);
}
+32 -1
View File
@@ -9,8 +9,12 @@ const { execSync } = require('child_process');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
// Load .env file if it exists // Load .env.development file first (if it exists), then .env file
const envDevPath = path.resolve(__dirname, '..', '.env.development');
const envPath = path.resolve(__dirname, '..', '.env'); const envPath = path.resolve(__dirname, '..', '.env');
if (fs.existsSync(envDevPath)) {
require('dotenv').config({ path: envDevPath });
}
if (fs.existsSync(envPath)) { if (fs.existsSync(envPath)) {
require('dotenv').config({ path: envPath }); require('dotenv').config({ path: envPath });
} }
@@ -51,6 +55,22 @@ function createDatabase() {
} }
} }
function dropDatabase() {
try {
const dbUrl = process.env.DATABASE_URL;
const dbName = dbUrl.split('/').pop();
// Drop existing connections and database
execSync(`psql "${dbUrl}" -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${dbName}' AND pid <> pg_backend_pid();" 2>/dev/null || true`, { stdio: 'pipe' });
execSync(`psql "${dbUrl}" -c "DROP DATABASE IF EXISTS ${dbName};" 2>/dev/null || true`, { stdio: 'pipe' });
console.log(`✅ Database "${dbName}" dropped`);
return true;
} catch (error) {
console.error('❌ Failed to drop database:', error.message);
return false;
}
}
function runMigrations() { function runMigrations() {
try { try {
console.log('🔄 Running migrations...'); console.log('🔄 Running migrations...');
@@ -76,6 +96,9 @@ function generatePrismaClient() {
} }
function main() { function main() {
const args = process.argv.slice(2);
const shouldDrop = args.includes('--drop');
console.log('=== PostgreSQL Setup for EuchreCamp ===\n'); console.log('=== PostgreSQL Setup for EuchreCamp ===\n');
// Check if DATABASE_URL is set // Check if DATABASE_URL is set
@@ -90,6 +113,14 @@ function main() {
process.exit(1); process.exit(1);
} }
// Drop database if requested
if (shouldDrop) {
console.log('Dropping existing database...');
if (!dropDatabase()) {
process.exit(1);
}
}
// Create database // Create database
if (!createDatabase()) { if (!createDatabase()) {
process.exit(1); process.exit(1);
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env node
/**
* Switch to development database
* Creates a .env.development.local file with development database settings
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const envDevPath = path.join(__dirname, '..', '.env.development');
const envDevLocalPath = path.join(__dirname, '..', '.env.development.local');
console.log('🔧 Setting up development database...\n');
// Check if .env.development exists
if (!fs.existsSync(envDevPath)) {
console.error('❌ .env.development file not found');
console.error('Please create it first or run: npm run db:setup-dev');
process.exit(1);
}
// Copy .env.development to .env.development.local if it doesn't exist
if (!fs.existsSync(envDevLocalPath)) {
fs.copyFileSync(envDevPath, envDevLocalPath);
console.log('✅ Created .env.development.local');
} else {
console.log('️ .env.development.local already exists');
}
// Set NODE_ENV for the current session
process.env.NODE_ENV = 'development';
process.env.DATABASE_PROVIDER = 'postgresql';
// Read the development database URL
const envContent = fs.readFileSync(envDevPath, 'utf8');
const match = envContent.match(/DATABASE_URL="([^"]+)"/);
if (match) {
process.env.DATABASE_URL = match[1];
console.log(`✅ Development database URL: ${process.env.DATABASE_URL}`);
}
console.log('\n✅ Development database configured!');
console.log('\nNext steps:');
console.log('1. Setup the dev database: npm run db:setup-dev');
console.log('2. Start development server: npm run dev');
console.log('\nNote: This script sets environment variables for the current session.');
console.log('For persistent configuration, use .env.development.local');
+59 -10
View File
@@ -5,10 +5,64 @@
import { chromium, type FullConfig } from '@playwright/test'; import { chromium, type FullConfig } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
import { cleanupAllTestData } from '@/__tests__/test-utils';
import path from 'path';
import fs from 'fs';
// Load .env file first, then .env.development (which will override .env)
const envPath = path.resolve(process.cwd(), '.env');
const envDevPath = path.resolve(process.cwd(), '.env.development');
// Load base .env file
if (fs.existsSync(envPath)) {
require('dotenv').config({ path: envPath });
}
// Load .env.development file (will override .env settings)
if (fs.existsSync(envDevPath)) {
require('dotenv').config({ path: envDevPath, override: true });
}
const authFile = 'playwright/.auth/user.json'; const authFile = 'playwright/.auth/user.json';
const adminAuthFile = 'playwright/.auth/admin.json'; const adminAuthFile = 'playwright/.auth/admin.json';
// Check if we're using the dev database
function isDevDatabase(): boolean {
const dbUrl = process.env.DATABASE_URL || '';
return dbUrl.includes('euchre_camp_dev');
}
function isProductionDatabase(): boolean {
const dbUrl = process.env.DATABASE_URL || '';
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev');
}
// Strict check - fail if using production database
if (isProductionDatabase()) {
console.error('');
console.error('='.repeat(80));
console.error('CRITICAL ERROR: Tests are attempting to run against PRODUCTION database!');
console.error('='.repeat(80));
console.error('');
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
console.error('');
console.error('Tests MUST run against the development database (euchre_camp_dev)');
console.error('');
console.error('To fix this:');
console.error(' 1. Run: npm run test:acceptance');
console.error(' 2. Or set: DATABASE_URL environment variable to dev database URL');
console.error(' 3. Or load .env.development: source .env.development && npm run test:acceptance');
console.error('');
console.error('Aborting test execution to prevent data corruption.');
console.error('');
process.exit(1);
}
if (!isDevDatabase()) {
console.warn('⚠️ WARNING: DATABASE_URL does not contain euchre_camp_dev');
console.warn(' Current DATABASE_URL:', process.env.DATABASE_URL);
}
export default async function globalSetup(config: FullConfig) { export default async function globalSetup(config: FullConfig) {
const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000'; const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000';
@@ -144,18 +198,13 @@ export default async function globalSetup(config: FullConfig) {
// Return teardown function // Return teardown function
return async () => { return async () => {
// Clean up test users console.log('\n=== Global Teardown ===');
// Clean up all test data
try { try {
await prisma.user.deleteMany({ await cleanupAllTestData();
where: {
email: {
startsWith: 'setup-'
}
}
});
console.log('Cleaned up test users');
} catch (error) { } catch (error) {
console.error('Error cleaning up test users:', error); console.error('Error cleaning up test data:', error);
} finally { } finally {
await prisma.$disconnect(); await prisma.$disconnect();
} }
+17 -13
View File
@@ -1,22 +1,27 @@
import { test, expect } from '@playwright/test' import { test, expect } from '@playwright/test'
import { prisma } from '@/lib/prisma' import { prisma } from '@/lib/prisma'
import { createTestPlayer, cleanupTestRecords, getCreatedRecordCounts } from '@/__tests__/test-utils'
test.describe('Home Page', () => { test.describe('Home Page', () => {
test.beforeEach(async () => {
// Clean up any existing test records before each test
await cleanupTestRecords();
});
test.afterEach(async () => {
// Clean up test records after each test
await cleanupTestRecords();
});
test('should display top 10 players', async ({ page }) => { test('should display top 10 players', async ({ page }) => {
// Create some test players with unique names and very high Elo to ensure they're in top 10 // Create some test players with unique names and very high Elo to ensure they're in top 10
const timestamp = Date.now() const timestamp = Date.now()
const players = [] const players = []
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
const playerName = `Home Test Player ${timestamp} ${i + 1}` const playerName = `Home Test Player ${timestamp} ${i + 1}`
const player = await prisma.player.create({ const player = await createTestPlayer({
data: { name: playerName,
name: playerName, currentElo: 2000 - i * 10,
normalizedName: playerName.toLowerCase(),
currentElo: 2000 - i * 10, // Very high Elo to ensure they're in top 10
gamesPlayed: 10 + i,
wins: 5 + Math.floor(i / 2),
losses: 5 + Math.ceil(i / 2),
},
}) })
players.push(player) players.push(player)
} }
@@ -33,10 +38,9 @@ test.describe('Home Page', () => {
page.locator(`a:has-text("Home Test Player ${timestamp} 1")`) page.locator(`a:has-text("Home Test Player ${timestamp} 1")`)
).toBeVisible() ).toBeVisible()
// Clean up // Verify cleanup will work
for (const player of players) { const counts = getCreatedRecordCounts();
await prisma.player.delete({ where: { id: player.id } }) expect(counts.players).toBe(3);
}
}) })
test('should display club president', async ({ page }) => { test('should display club president', async ({ page }) => {
@@ -0,0 +1,117 @@
/**
* E2E Test: Tournament Edit with allowTies
*
* User Story: As a tournament admin, I want to edit tournament settings including allowTies
*
* Acceptance Criteria:
* - Can edit tournament settings
* - allowTies checkbox can be toggled
* - allowTies value is saved correctly
*/
import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma';
test.describe('Tournament Edit - allowTies functionality', () => {
let tournamentId: number;
test.beforeAll(async () => {
// Create a test tournament for editing
const tournament = await prisma.event.create({
data: {
name: 'Test Tournament for AllowTies Edit',
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
allowTies: false,
targetScore: 5,
createdAt: new Date(),
updatedAt: new Date(),
},
});
tournamentId = tournament.id;
});
test.afterAll(async () => {
// Clean up test tournament
if (tournamentId) {
await prisma.event.delete({
where: { id: tournamentId },
});
}
});
test('should display allowTies checkbox on edit form', async ({ page }) => {
// Navigate to tournament edit page
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
// Wait for form to load
await expect(page.locator('text=Tournament Name')).toBeVisible();
// Check that allowTies checkbox exists
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
await expect(allowTiesCheckbox).toBeVisible();
await expect(allowTiesCheckbox).not.toBeChecked();
});
test('should save allowTies when toggled to true', async ({ page }) => {
// Navigate to tournament edit page
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
// Wait for form to load
await expect(page.locator('text=Tournament Name')).toBeVisible();
// Toggle allowTies checkbox
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
await allowTiesCheckbox.check();
await expect(allowTiesCheckbox).toBeChecked();
// Submit form
await page.click('button[type="submit"]');
// Wait for success message
await expect(page.locator('text=Tournament updated successfully')).toBeVisible({ timeout: 5000 });
// Verify allowTies was saved by checking the database
const updatedTournament = await prisma.event.findUnique({
where: { id: tournamentId },
});
expect(updatedTournament?.allowTies).toBe(true);
});
test('should save allowTies when toggled to false', async ({ page }) => {
// First, set allowTies to true
await prisma.event.update({
where: { id: tournamentId },
data: { allowTies: true },
});
// Navigate to tournament edit page
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
// Wait for form to load
await expect(page.locator('text=Tournament Name')).toBeVisible();
// Verify checkbox is checked
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
await expect(allowTiesCheckbox).toBeChecked();
// Uncheck allowTies checkbox
await allowTiesCheckbox.uncheck();
await expect(allowTiesCheckbox).not.toBeChecked();
// Submit form
await page.click('button[type="submit"]');
// Wait for success message
await expect(page.locator('text=Tournament updated successfully')).toBeVisible({ timeout: 5000 });
// Verify allowTies was saved by checking the database
const updatedTournament = await prisma.event.findUnique({
where: { id: tournamentId },
});
expect(updatedTournament?.allowTies).toBe(false);
});
});
+274
View File
@@ -0,0 +1,274 @@
/**
* Test Utilities for EuchreCamp
*
* Provides helper functions for creating and cleaning up test data
*/
import { prisma } from '@/lib/prisma';
import type { User, Player, Event, Match } from '@prisma/client';
// Track created test records for cleanup
const createdRecords = {
users: [] as string[],
players: [] as number[],
events: [] as number[],
matches: [] as number[],
};
/**
* Create a test user with optional player association
*/
export async function createTestUser(options: {
email?: string;
name?: string;
role?: string;
playerId?: number | null;
} = {}) {
const timestamp = Date.now();
const email = options.email || `test-user-${timestamp}@example.com`;
const name = options.name || `Test User ${timestamp}`;
const role = options.role || 'player';
const user = await prisma.user.create({
data: {
email,
name,
role,
playerId: options.playerId,
},
});
createdRecords.users.push(user.id);
return user;
}
/**
* Create a test player
*/
export async function createTestPlayer(options: {
name?: string;
currentElo?: number;
} = {}) {
const timestamp = Date.now();
const name = options.name || `Test Player ${timestamp}`;
const player = await prisma.player.create({
data: {
name,
normalizedName: name.toLowerCase(),
currentElo: options.currentElo || 1000,
},
});
createdRecords.players.push(player.id);
return player;
}
/**
* Create a test event (tournament)
*/
export async function createTestEvent(options: {
name?: string;
ownerId?: string;
} = {}) {
const timestamp = Date.now();
const name = options.name || `Test Event ${timestamp}`;
const event = await prisma.event.create({
data: {
name,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
ownerId: options.ownerId,
},
});
createdRecords.events.push(event.id);
return event;
}
/**
* Create a test match
*/
export async function createTestMatch(options: {
eventId?: number;
team1P1Id: number;
team1P2Id: number;
team2P1Id: number;
team2P2Id: number;
team1Score?: number;
team2Score?: number;
}) {
const timestamp = Date.now();
const match = await prisma.match.create({
data: {
eventId: options.eventId,
team1P1Id: options.team1P1Id,
team1P2Id: options.team1P2Id,
team2P1Id: options.team2P1Id,
team2P2Id: options.team2P2Id,
team1Score: options.team1Score ?? 10,
team2Score: options.team2Score ?? 5,
status: 'completed',
},
});
createdRecords.matches.push(match.id);
return match;
}
/**
* Clean up all created test records
*/
export async function cleanupTestRecords() {
console.log('🧹 Cleaning up test records...');
try {
// Delete matches first (they reference players)
if (createdRecords.matches.length > 0) {
await prisma.match.deleteMany({
where: { id: { in: createdRecords.matches } },
});
console.log(` Deleted ${createdRecords.matches.length} matches`);
}
// Delete events
if (createdRecords.events.length > 0) {
await prisma.event.deleteMany({
where: { id: { in: createdRecords.events } },
});
console.log(` Deleted ${createdRecords.events.length} events`);
}
// Delete users first (to break player associations)
if (createdRecords.users.length > 0) {
await prisma.user.deleteMany({
where: { id: { in: createdRecords.users } },
});
console.log(` Deleted ${createdRecords.users.length} users`);
}
// Delete players
if (createdRecords.players.length > 0) {
await prisma.player.deleteMany({
where: { id: { in: createdRecords.players } },
});
console.log(` Deleted ${createdRecords.players.length} players`);
}
// Reset tracking
createdRecords.users = [];
createdRecords.players = [];
createdRecords.events = [];
createdRecords.matches = [];
console.log('✅ Test records cleaned up successfully');
} catch (error) {
console.error('❌ Error cleaning up test records:', error);
// Still reset tracking to avoid trying to delete again
createdRecords.users = [];
createdRecords.players = [];
createdRecords.events = [];
createdRecords.matches = [];
}
}
/**
* Get count of created records (for assertions)
*/
export function getCreatedRecordCounts() {
return {
users: createdRecords.users.length,
players: createdRecords.players.length,
events: createdRecords.events.length,
matches: createdRecords.matches.length,
};
}
/**
* Clean up test users by email pattern
*/
export async function cleanupTestUsersByEmailPattern(pattern: string = 'test-') {
try {
const result = await prisma.user.deleteMany({
where: {
email: {
contains: pattern,
},
},
});
console.log(` Deleted ${result.count} test users matching pattern "${pattern}"`);
return result.count;
} catch (error) {
console.error('❌ Error cleaning up test users:', error);
return 0;
}
}
/**
* Clean up test players by name pattern
*/
export async function cleanupTestPlayersByNamePattern(pattern: string = 'Test ') {
try {
const result = await prisma.player.deleteMany({
where: {
name: {
contains: pattern,
},
},
});
console.log(` Deleted ${result.count} test players matching pattern "${pattern}"`);
return result.count;
} catch (error) {
console.error('❌ Error cleaning up test players:', error);
return 0;
}
}
/**
* Clean up all test data (aggressive cleanup)
*/
export async function cleanupAllTestData() {
console.log('🧹 Aggressive cleanup of all test data...');
try {
// Delete test users first
const userResult = await prisma.user.deleteMany({
where: {
email: {
contains: 'test-',
},
},
});
console.log(` Deleted ${userResult.count} test users`);
// Delete test players
const playerResult = await prisma.player.deleteMany({
where: {
name: {
contains: 'Test ',
},
},
});
console.log(` Deleted ${playerResult.count} test players`);
// Delete test events
const eventResult = await prisma.event.deleteMany({
where: {
name: {
contains: 'Test ',
},
},
});
console.log(` Deleted ${eventResult.count} test events`);
console.log('✅ All test data cleaned up');
} catch (error) {
console.error('❌ Error during aggressive cleanup:', error);
}
}
// Export cleanup function for global setup/teardown
export const testCleanup = cleanupTestRecords;
@@ -0,0 +1,200 @@
/**
* Unit tests for tournament update functionality
* Tests the allowTies field is properly saved when updating tournaments
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { prisma } from '@/lib/prisma';
// Mock the prisma client
vi.mock('@/lib/prisma', () => ({
prisma: {
event: {
findUnique: vi.fn(),
update: vi.fn(),
},
},
}));
// Mock the permissions module
vi.mock('@/lib/permissions', () => ({
canManageTournament: vi.fn().mockResolvedValue({ allowed: true }),
canDeleteTournament: vi.fn().mockResolvedValue({ allowed: true }),
}));
// Import the route handler after mocking
import { PUT } from '@/app/api/tournaments/[id]/route';
describe('Tournament Update API', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should update allowTies field when provided', async () => {
// Mock existing tournament
vi.mocked(prisma.event.findUnique).mockResolvedValue({
id: 1,
name: 'Test Tournament',
allowTies: false,
targetScore: 5,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
eventDate: null,
description: null,
maxParticipants: null,
ownerId: null,
createdAt: new Date(),
updatedAt: new Date(),
} as any);
// Mock successful update
vi.mocked(prisma.event.update).mockResolvedValue({
id: 1,
name: 'Test Tournament',
allowTies: true,
targetScore: 5,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
eventDate: null,
description: null,
maxParticipants: null,
ownerId: null,
createdAt: new Date(),
updatedAt: new Date(),
} as any);
const request = new Request('http://localhost/api/tournaments/1', {
method: 'PUT',
body: JSON.stringify({
name: 'Test Tournament',
allowTies: true,
targetScore: 5,
}),
});
const params = Promise.resolve({ id: '1' });
const response = await PUT(request, { params });
expect(response.status).toBe(200);
expect(vi.mocked(prisma.event.update)).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
allowTies: true,
}),
})
);
});
it('should default allowTies to false when not provided', async () => {
// Mock existing tournament
vi.mocked(prisma.event.findUnique).mockResolvedValue({
id: 1,
name: 'Test Tournament',
allowTies: true,
targetScore: 5,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
eventDate: null,
description: null,
maxParticipants: null,
ownerId: null,
createdAt: new Date(),
updatedAt: new Date(),
} as any);
// Mock successful update
vi.mocked(prisma.event.update).mockResolvedValue({
id: 1,
name: 'Test Tournament',
allowTies: false,
targetScore: 5,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
eventDate: null,
description: null,
maxParticipants: null,
ownerId: null,
createdAt: new Date(),
updatedAt: new Date(),
} as any);
const request = new Request('http://localhost/api/tournaments/1', {
method: 'PUT',
body: JSON.stringify({
name: 'Test Tournament',
targetScore: 5,
// allowTies not provided
}),
});
const params = Promise.resolve({ id: '1' });
const response = await PUT(request, { params });
expect(response.status).toBe(200);
expect(vi.mocked(prisma.event.update)).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
allowTies: false, // Should default to false
}),
})
);
});
it('should preserve allowTies value when updating other fields', async () => {
// Mock existing tournament with allowTies = true
vi.mocked(prisma.event.findUnique).mockResolvedValue({
id: 1,
name: 'Test Tournament',
allowTies: true,
targetScore: 5,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
eventDate: null,
description: null,
maxParticipants: null,
ownerId: null,
createdAt: new Date(),
updatedAt: new Date(),
} as any);
// Mock successful update
vi.mocked(prisma.event.update).mockResolvedValue({
id: 1,
name: 'Updated Tournament Name',
allowTies: true,
targetScore: 10,
eventType: 'tournament',
format: 'round_robin',
status: 'planned',
eventDate: null,
description: null,
maxParticipants: null,
ownerId: null,
createdAt: new Date(),
updatedAt: new Date(),
} as any);
const request = new Request('http://localhost/api/tournaments/1', {
method: 'PUT',
body: JSON.stringify({
name: 'Updated Tournament Name',
allowTies: true,
targetScore: 10,
}),
});
const params = Promise.resolve({ id: '1' });
const response = await PUT(request, { params });
expect(response.status).toBe(200);
const updateCall = vi.mocked(prisma.event.update).mock.calls[0][0];
expect(updateCall.data.allowTies).toBe(true);
expect(updateCall.data.name).toBe('Updated Tournament Name');
expect(updateCall.data.targetScore).toBe(10);
});
});
+1 -1
View File
@@ -37,7 +37,7 @@ export default async function EditUserPage({
where: { where: {
OR: [ OR: [
{ user: null }, { user: null },
{ id: user.playerId || -1 }, // Include the currently associated player if any ...(user.playerId ? [{ id: user.playerId }] : []), // Include the currently associated player if any
], ],
}, },
orderBy: { name: "asc" }, orderBy: { name: "asc" },
+8 -4
View File
@@ -32,6 +32,10 @@ export async function PUT(
); );
} }
// Parse playerId - handle empty string case
const parsedPlayerId = playerId ? parseInt(playerId) : undefined;
const isValidPlayerId = parsedPlayerId !== undefined && !isNaN(parsedPlayerId);
// Update the user // Update the user
const user = await prisma.user.update({ const user = await prisma.user.update({
where: { id }, where: { id },
@@ -39,14 +43,14 @@ export async function PUT(
email: email || existingUser.email, email: email || existingUser.email,
name: name !== undefined ? name : existingUser.name, name: name !== undefined ? name : existingUser.name,
role: role || existingUser.role, role: role || existingUser.role,
playerId: playerId ? parseInt(playerId) : null, playerId: isValidPlayerId ? parsedPlayerId : null,
}, },
}); });
// Update the player's user relation if needed // Update the player's user relation if needed
if (playerId !== undefined) { if (playerId !== undefined) {
// First, remove user from any existing player // First, remove user from any existing player
if (existingUser.playerId && existingUser.playerId !== parseInt(playerId)) { if (existingUser.playerId && existingUser.playerId !== parsedPlayerId) {
await prisma.player.update({ await prisma.player.update({
where: { id: existingUser.playerId }, where: { id: existingUser.playerId },
data: { user: { disconnect: true } }, data: { user: { disconnect: true } },
@@ -54,9 +58,9 @@ export async function PUT(
} }
// Then, connect user to the new player // Then, connect user to the new player
if (playerId) { if (isValidPlayerId) {
await prisma.player.update({ await prisma.player.update({
where: { id: parseInt(playerId) }, where: { id: parsedPlayerId! },
data: { user: { connect: { id: user.id } } }, data: { user: { connect: { id: user.id } } },
}); });
} }
+7 -5
View File
@@ -86,12 +86,14 @@ export default async function PlayerProfilePage({ params }: PageProps) {
const totalWins = player.wins const totalWins = player.wins
const winRate = totalGames > 0 ? ((totalWins / totalGames) * 100).toFixed(1) : "0.0" const winRate = totalGames > 0 ? ((totalWins / totalGames) * 100).toFixed(1) : "0.0"
// Get best partnership // Get best partnership based on ELO contribution
// Best partner is the one who contributed most to your rating (highest totalEloChange)
// Must have played at least 2 games together to be considered
const bestPartnership = partnershipStats.reduce((best, stat) => { const bestPartnership = partnershipStats.reduce((best, stat) => {
if (stat.gamesPlayed < 3) return best // Need at least 3 games for partnership to be meaningful if (stat.gamesPlayed < 2) return best // Need at least 2 games for partnership to be meaningful
const currentRate = stat.wins / stat.gamesPlayed const currentEloChange = stat.totalEloChange
const bestRate = best ? best.wins / best.gamesPlayed : 0 const bestEloChange = best ? best.totalEloChange : -Infinity
return currentRate > bestRate ? stat : best return currentEloChange > bestEloChange ? stat : best
}, null as (typeof partnershipStats[0] | null)) }, null as (typeof partnershipStats[0] | null))
return ( return (
+1
View File
@@ -52,6 +52,7 @@ export default function EditTournamentForm({ tournament }: EditTournamentFormPro
maxParticipants: formData.maxParticipants ? parseInt(formData.maxParticipants) : null, maxParticipants: formData.maxParticipants ? parseInt(formData.maxParticipants) : null,
eventDate: formData.eventDate ? new Date(formData.eventDate).toISOString() : null, eventDate: formData.eventDate ? new Date(formData.eventDate).toISOString() : null,
targetScore: formData.targetScore ? parseInt(formData.targetScore) : null, targetScore: formData.targetScore ? parseInt(formData.targetScore) : null,
allowTies: formData.allowTies,
}), }),
}) })
+61
View File
@@ -1 +1,62 @@
import '@testing-library/jest-dom' import '@testing-library/jest-dom'
import path from 'path'
import fs from 'fs'
/**
* Vitest Setup File
*
* This file runs before each test file in the Vitest environment.
* It validates that tests are running against the development database
* to prevent accidental data corruption.
*/
// Load .env file first, then .env.development (which will override .env)
const envPath = path.resolve(process.cwd(), '.env');
const envDevPath = path.resolve(process.cwd(), '.env.development');
// Load base .env file
if (fs.existsSync(envPath)) {
require('dotenv').config({ path: envPath });
}
// Load .env.development file (will override .env settings)
if (fs.existsSync(envDevPath)) {
require('dotenv').config({ path: envDevPath, override: true });
}
// Check if DATABASE_URL is set and points to dev database
const databaseUrl = process.env.DATABASE_URL;
if (databaseUrl) {
const isDevDatabase = databaseUrl.includes('euchre_camp_dev');
const isProductionDatabase =
databaseUrl.includes('euchre_camp') &&
!databaseUrl.includes('_dev') &&
!databaseUrl.includes('_dev_');
if (isProductionDatabase) {
console.error('');
console.error('='.repeat(80));
console.error('CRITICAL ERROR: Tests are attempting to run against PRODUCTION database!');
console.error('='.repeat(80));
console.error('');
console.error('Current DATABASE_URL:', databaseUrl);
console.error('');
console.error('Tests MUST run against the development database (euchre_camp_dev)');
console.error('');
console.error('To fix this:');
console.error(' 1. Run: npm run test:run');
console.error(' 2. Or set: DATABASE_URL environment variable to dev database URL');
console.error(' 3. Or load .env.development: source .env.development && npm run test:run');
console.error('');
console.error('Aborting test execution to prevent data corruption.');
console.error('');
process.exit(1);
}
if (isDevDatabase) {
console.log('✓ Tests running against development database (euchre_camp_dev)');
}
} else {
console.warn('⚠ No DATABASE_URL set - tests may fail or use unexpected database');
}