Compare commits
52 Commits
main
..
b2fcf0fae7
| Author | SHA1 | Date | |
|---|---|---|---|
| b2fcf0fae7 | |||
| 0f53f8a08f | |||
| 36e273e2a1 | |||
| e61e020d9d | |||
| 4120cc9a8e | |||
| c4e88d3658 | |||
| 5ab6ece5ef | |||
| b3907d046d | |||
| 9026ac7fe3 | |||
| 73f5905990 | |||
| 5519ed1de0 | |||
| f51f3caa34 | |||
| 933f2cf808 | |||
| a1d754a5fb | |||
| 78ff75b941 | |||
| d5dc170417 | |||
| 1093449e46 | |||
| 54aa22d1a3 | |||
| 22f7b79a3d | |||
| 999cdd821c | |||
| 496541b144 | |||
| d21e14c3b0 | |||
| 8f0d5c4cf5 | |||
| 15661356d2 | |||
| 603cc238fa | |||
| 63ef1d124c | |||
| c222e55a52 | |||
| e0c986f594 | |||
| 1f7d589698 | |||
| e5f679e54c | |||
| 803b79f03c | |||
| aa98600147 | |||
| ad7724cda6 | |||
| ada163f538 | |||
| 4d685558aa | |||
| 07283d0334 | |||
| dca35ec0bf | |||
| c3b0466092 | |||
| a75d7d3cc6 | |||
| 37eb1f8e21 | |||
| 9b15d7e61f | |||
| 322ab2a5fa | |||
| c4d2130d5b | |||
| 051b729451 | |||
| 443a0f460e | |||
| 7367fce4a6 | |||
| ab50ae0bdf | |||
| 90fb0f223e | |||
| a49c8e01ac | |||
| 19402be375 | |||
| 84afa88ca4 | |||
| df856c62df |
+32
-22
@@ -1,44 +1,54 @@
|
|||||||
# EuchreCamp Environment Configuration
|
# EuchreCamp Environment Configuration
|
||||||
# ============================================
|
# Copy this file to .env and fill in your values
|
||||||
# Copy this file to .env or use
|
|
||||||
# .env.development / .env.production for specific environments
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Database Configuration
|
# Database Configuration
|
||||||
# ============================================
|
# ============================================
|
||||||
# IMPORTANT: Use the appropriate DATABASE_URL for your environment:
|
# PostgreSQL connection string
|
||||||
#
|
# Format: postgresql://username:password@host:port/database
|
||||||
# - Development: euchre_camp_dev (in .env.development)
|
DATABASE_URL=postgresql://euchre:euchrepassword@localhost:5432/euchre_camp
|
||||||
# - CI/Testing: euchre_camp_ci (set via CI_DATABASE_URL secret)
|
|
||||||
# - Production: euchre_camp (in .env.production, DO NOT USE FOR TESTS)
|
|
||||||
|
|
||||||
|
# Shadow database for Prisma migrations (optional for PostgreSQL)
|
||||||
|
DATABASE_SHADOW_URL=postgresql://euchre:euchrepassword@localhost:5432/euchre_camp_shadow
|
||||||
|
|
||||||
|
# Database provider (postgresql, mysql, sqlite, etc.)
|
||||||
DATABASE_PROVIDER=postgresql
|
DATABASE_PROVIDER=postgresql
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Better Auth Configuration
|
# Better Auth Configuration
|
||||||
# ============================================
|
# ============================================
|
||||||
# Generate a new secret with: openssl rand -base64 32
|
# Secret key for session encryption (generate a strong random string)
|
||||||
BETTER_AUTH_SECRET=generate-new-secret-in-production
|
# Run: openssl rand -base64 32
|
||||||
|
BETTER_AUTH_SECRET=your-secret-key-change-in-production
|
||||||
|
|
||||||
# Base URL - update for production
|
# Base URL for authentication callbacks
|
||||||
|
# For production: https://your-domain.com
|
||||||
BETTER_AUTH_URL=http://localhost:3000
|
BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Application Configuration
|
# Application Configuration
|
||||||
# ============================================
|
# ============================================
|
||||||
NODE_ENV=development
|
# Environment: development, production, test
|
||||||
|
NODE_ENV=production
|
||||||
|
|
||||||
# Comma-separated list of trusted origins
|
# Trusted origins for CORS and authentication
|
||||||
|
# Add your domain(s) for production
|
||||||
TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Environment-Specific Overrides
|
# Optional: External Services
|
||||||
# ============================================
|
# ============================================
|
||||||
# For development (.env.development):
|
# If using external database (e.g., Supabase, Railway)
|
||||||
# DATABASE_URL from .credentials (euchre_camp_dev)
|
# DATABASE_URL=postgresql://user:pass@host:port/db
|
||||||
# NODE_ENV=development
|
|
||||||
# BETTER_AUTH_URL=http://localhost:3000
|
# If using external auth provider
|
||||||
#
|
# BETTER_AUTH_URL=https://your-app.com
|
||||||
# For CI (set via secrets):
|
|
||||||
# DATABASE_URL set as CI_DATABASE_URL secret (euchre_camp_ci)
|
# ============================================
|
||||||
# NODE_ENV=test
|
# CasaOS Deployment Notes
|
||||||
|
# ============================================
|
||||||
|
# When deploying to CasaOS, set these via the UI:
|
||||||
|
# 1. DATABASE_URL: Your PostgreSQL connection string
|
||||||
|
# 2. BETTER_AUTH_SECRET: Generate with: openssl rand -base64 32
|
||||||
|
# 3. BETTER_AUTH_URL: Your app's public URL
|
||||||
|
# 4. TRUSTED_ORIGINS: Your app's public URL(s)
|
||||||
|
|||||||
@@ -132,11 +132,11 @@ When a PR is merged to `main`:
|
|||||||
|
|
||||||
## Database Configuration for CI
|
## Database Configuration for CI
|
||||||
|
|
||||||
### PostgreSQL for CI Acceptance Tests
|
### SQLite for CI Acceptance Tests
|
||||||
- **Why PostgreSQL**: Matches production database, catches PG-specific issues
|
- **Why SQLite**: No database server required, perfect for CI environments
|
||||||
- **Usage**: PR workflow runs acceptance tests with PostgreSQL database
|
- **Usage**: PR workflow runs acceptance tests with SQLite database
|
||||||
- **Configuration**: `CI_DATABASE_URL` secret, set as `DATABASE_URL` env var
|
- **Configuration**: `DATABASE_PROVIDER=sqlite`, `DATABASE_URL=file:./prisma/ci.db`
|
||||||
- **Benefits**: Production-like environment, consistent with dev and prod
|
- **Benefits**: Fast, isolated, no external dependencies
|
||||||
|
|
||||||
### PostgreSQL for Production
|
### PostgreSQL for Production
|
||||||
- **Usage**: Release workflow runs tests in Docker with PostgreSQL
|
- **Usage**: Release workflow runs tests in Docker with PostgreSQL
|
||||||
|
|||||||
@@ -5,14 +5,13 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
paths:
|
paths:
|
||||||
- "Dockerfile.ci-base"
|
- 'Dockerfile.ci-base'
|
||||||
- "package.json"
|
- 'package.json'
|
||||||
- "bun.lock"
|
- 'bun.lockb'
|
||||||
- "package-lock.json"
|
- '.gitea/workflows/build-ci-images.yml'
|
||||||
- ".gitea/workflows/build-ci-images.yml"
|
|
||||||
schedule:
|
schedule:
|
||||||
# Weekly rebuild to get latest Playwright/Bun versions
|
# Weekly rebuild to get latest Playwright/Bun versions
|
||||||
- cron: "0 2 * * 0" # Every Sunday at 2 AM
|
- cron: '0 2 * * 0' # Every Sunday at 2 AM
|
||||||
workflow_dispatch: # Manual trigger
|
workflow_dispatch: # Manual trigger
|
||||||
|
|
||||||
env:
|
env:
|
||||||
@@ -41,7 +40,7 @@ jobs:
|
|||||||
id: meta
|
id: meta
|
||||||
run: |
|
run: |
|
||||||
# Get Playwright version from package.json
|
# Get Playwright version from package.json
|
||||||
PLAYWRIGHT_VERSION=$(grep -o '"@playwright/test": "[^"]*"' package.json | cut -d'"' -f4 | sed 's/^\^//')
|
PLAYWRIGHT_VERSION=$(grep -o '"@playwright/test": "[^"]*"' package.json | cut -d'"' -f4)
|
||||||
echo "playwright_version=${PLAYWRIGHT_VERSION}" >> $GITHUB_OUTPUT
|
echo "playwright_version=${PLAYWRIGHT_VERSION}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
# Get Bun version (latest)
|
# Get Bun version (latest)
|
||||||
@@ -53,16 +52,20 @@ jobs:
|
|||||||
|
|
||||||
- name: Build and push CI base image
|
- name: Build and push CI base image
|
||||||
run: |
|
run: |
|
||||||
|
# Build with multiple tags
|
||||||
docker build \
|
docker build \
|
||||||
--file Dockerfile.ci-base \
|
--file Dockerfile.ci-base \
|
||||||
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:latest \
|
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:latest \
|
||||||
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:playwright-${{ steps.meta.outputs.playwright_version }} \
|
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:playwright-${{ steps.meta.outputs.playwright_version }} \
|
||||||
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:${{ github.sha }} \
|
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:${{ github.sha }} \
|
||||||
--push \
|
|
||||||
.
|
.
|
||||||
|
|
||||||
|
# Push all tags
|
||||||
|
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:latest
|
||||||
|
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:playwright-${{ steps.meta.outputs.playwright_version }}
|
||||||
|
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:${{ github.sha }}
|
||||||
|
|
||||||
- name: Clean up
|
- name: Clean up
|
||||||
if: always()
|
if: always()
|
||||||
run: |
|
run: |
|
||||||
docker logout ${{ env.REGISTRY }}
|
docker logout ${{ env.REGISTRY }}
|
||||||
|
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
name: Deploy Production
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: 'Version tag to deploy (e.g., v0.1.21)'
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.notsosm.art
|
|
||||||
IMAGE_NAME: euchre-camp
|
|
||||||
PROD_APPS_PATH: /apps/youthful_simon
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
deploy-prod:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
container:
|
|
||||||
image: docker.notsosm.art/euchre-camp/ci-base:latest
|
|
||||||
options: --user root
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Deploy to production
|
|
||||||
run: |
|
|
||||||
VERSION="${{ inputs.version }}"
|
|
||||||
COMPOSE_FILE="${{ env.PROD_APPS_PATH }}/docker-compose.yml"
|
|
||||||
|
|
||||||
echo "Deploying ${VERSION} to production..."
|
|
||||||
|
|
||||||
# Update prod compose file with the release tag
|
|
||||||
# Note: Standardizing to docker.notsosm.art registry
|
|
||||||
sed -i "s|image: euchre-camp/euchre-camp:[a-zA-Z0-9.-]*|image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}|" ${COMPOSE_FILE}
|
|
||||||
sed -i "s|image: docker.notsosm.art/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:${VERSION}|" ${COMPOSE_FILE}
|
|
||||||
|
|
||||||
# Pull and restart the prod container
|
|
||||||
cd ${{ env.PROD_APPS_PATH }}
|
|
||||||
docker compose pull app
|
|
||||||
docker compose up -d app
|
|
||||||
|
|
||||||
# Wait for production site to be healthy
|
|
||||||
echo "Waiting for production site to be healthy..."
|
|
||||||
for i in {1..6}; do
|
|
||||||
if curl -sf https://euchre.notsosm.art/api/health > /dev/null 2>&1; then
|
|
||||||
echo "✅ Production successfully deployed with version ${VERSION}"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 15
|
|
||||||
done
|
|
||||||
echo "❌ Production deployment failed"
|
|
||||||
docker compose logs app
|
|
||||||
exit 1
|
|
||||||
+13
-68
@@ -5,110 +5,56 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.notsosm.art
|
|
||||||
IMAGE_NAME: euchre-camp
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
unit-tests:
|
unit-tests:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
image: docker.notsosm.art/euchre-camp/ci-base:latest
|
image: docker.notsosm.art/euchre-camp/ci-base:latest
|
||||||
options: --user root
|
options: --user root
|
||||||
env:
|
|
||||||
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci --legacy-peer-deps
|
run: bun install
|
||||||
|
|
||||||
- name: Generate Prisma client
|
- name: Generate Prisma client
|
||||||
run: npx prisma generate
|
run: bun x prisma generate
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
|
||||||
|
|
||||||
- name: Run unit tests
|
- name: Run unit tests
|
||||||
run: npm test
|
run: bun test src/__tests__/unit/ src/__tests__/*.test.tsx src/__tests__/auth-simple.test.ts
|
||||||
|
|
||||||
build-and-deploy-ci:
|
e2e-tests:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: unit-tests
|
needs: unit-tests
|
||||||
container:
|
container:
|
||||||
image: docker.notsosm.art/euchre-camp/ci-base:latest
|
image: docker.notsosm.art/euchre-camp/ci-base:latest
|
||||||
options: --user root
|
options: --user root
|
||||||
volumes:
|
|
||||||
- /var/lib/casaos/apps:/apps
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
# Required for acceptance tests - they import prisma via @/ path alias
|
|
||||||
# and @cucumber/cucumber for cucumber-e2e tests
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci --legacy-peer-deps
|
run: bun install
|
||||||
|
|
||||||
- name: Generate Prisma client
|
- name: Generate Prisma client
|
||||||
run: npx prisma generate
|
run: bun x prisma generate
|
||||||
env:
|
env:
|
||||||
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
|
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
|
||||||
|
|
||||||
- name: Extract PR number and commit info
|
- name: Run E2E tests
|
||||||
id: info
|
run: npm run test:acceptance:cucumber:prod
|
||||||
run: |
|
|
||||||
echo "pr_number=$(echo $GITHUB_REF | grep -oP 'refs/pull/\K[0-9]+')" >> $GITHUB_OUTPUT
|
|
||||||
echo "short_sha=$(echo $GITHUB_SHA | cut -c1-7)" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Build Docker image for PR
|
|
||||||
run: |
|
|
||||||
IMAGE_TAG="pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }}"
|
|
||||||
docker build \
|
|
||||||
--target runner \
|
|
||||||
--build-arg GIT_COMMIT=$GITHUB_SHA \
|
|
||||||
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${IMAGE_TAG} \
|
|
||||||
.
|
|
||||||
|
|
||||||
- name: Update CI site compose and restart
|
|
||||||
run: |
|
|
||||||
IMAGE_TAG="pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }}"
|
|
||||||
COMPOSE_FILE="/apps/euchre_camp_ci/docker-compose.yml"
|
|
||||||
|
|
||||||
# Update the image tag in the compose file
|
|
||||||
sed -i "s|image: docker.notsosm.art/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:${IMAGE_TAG}|" ${COMPOSE_FILE}
|
|
||||||
|
|
||||||
# Image was built locally in the previous step; compose uses it without pulling
|
|
||||||
cd /apps/euchre_camp_ci
|
|
||||||
docker compose up -d app
|
|
||||||
|
|
||||||
- name: Wait for CI site to be ready
|
|
||||||
run: |
|
|
||||||
echo "Waiting for Next.js to start..."
|
|
||||||
sleep 20
|
|
||||||
for i in {1..6}; do
|
|
||||||
if curl -sf https://euchre-ci.notsosm.art/api/health > /dev/null 2>&1; then
|
|
||||||
echo "CI site is healthy"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 15
|
|
||||||
done
|
|
||||||
echo "CI site failed to become healthy after 90 seconds"
|
|
||||||
docker compose -f /apps/euchre_camp_ci/docker-compose.yml logs app
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Run acceptance tests
|
|
||||||
run: DATABASE_URL="${{ secrets.CI_DATABASE_URL }}" npx playwright test e2e/
|
|
||||||
env:
|
env:
|
||||||
CI: true
|
DATABASE_URL: postgresql://euchre_camp:${{ secrets.DB_PASSWORD }}@dhg.lol:5432/euchre_camp_dev
|
||||||
|
DATABASE_PROVIDER: postgresql
|
||||||
- name: Cleanup PR images
|
|
||||||
if: always()
|
|
||||||
run: |
|
|
||||||
docker rmi --force ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }} || true
|
|
||||||
|
|
||||||
analyze-bump-type:
|
analyze-bump-type:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: unit-tests
|
needs: e2e-tests
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
@@ -148,7 +94,6 @@ jobs:
|
|||||||
echo "reason=$REASON" >> $GITHUB_OUTPUT
|
echo "reason=$REASON" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
- name: Comment bump type on PR
|
- name: Comment bump type on PR
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
uses: actions/github-script@v7
|
uses: actions/github-script@v7
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
|
|||||||
@@ -73,10 +73,10 @@ jobs:
|
|||||||
echo "Bumping version: $BUMP"
|
echo "Bumping version: $BUMP"
|
||||||
|
|
||||||
# Run the bump script
|
# Run the bump script
|
||||||
node scripts/bump-version.js "$BUMP" --yes
|
bun run scripts/bump-version.js "$BUMP" --yes
|
||||||
|
|
||||||
# Get new version
|
# Get new version
|
||||||
NEW_VERSION=$(node -e "console.log(require('./package.json').version)")
|
NEW_VERSION=$(bun -e "console.log(require('./package.json').version)")
|
||||||
echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
|
echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
|
||||||
echo "New version: $NEW_VERSION"
|
echo "New version: $NEW_VERSION"
|
||||||
|
|
||||||
@@ -121,9 +121,8 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
-e DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" \
|
-e DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" \
|
||||||
-e NODE_ENV=test \
|
|
||||||
${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \
|
${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \
|
||||||
npm test
|
bun test 'src/__tests__/unit/**' 'src/__tests__/*.test.tsx' 'src/__tests__/auth-simple.test.ts'
|
||||||
|
|
||||||
- name: Build production image
|
- name: Build production image
|
||||||
if: steps.commit.outputs.committed == 'true'
|
if: steps.commit.outputs.committed == 'true'
|
||||||
@@ -165,25 +164,31 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
echo "Deploying version ${{ steps.version.outputs.new_version }} to dev environment..."
|
echo "Deploying version ${{ steps.version.outputs.new_version }} to dev environment..."
|
||||||
|
|
||||||
# Update dev compose file with new image tag
|
# Update docker-compose.yml with new image tag using full registry path
|
||||||
|
# The registry is docker.notsosm.art and image is euchre-camp
|
||||||
IMAGE_TAG="${{ steps.version.outputs.new_version }}"
|
IMAGE_TAG="${{ steps.version.outputs.new_version }}"
|
||||||
COMPOSE_FILE="/apps/intelligent_silasak/docker-compose.yml"
|
sed -i "s|image: docker.notsosm.art/euchre-camp:[0-9.]*|image: docker.notsosm.art/euchre-camp:${IMAGE_TAG}|" docker-compose.yml
|
||||||
sed -i "s|image: docker.notsosm.art/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:${IMAGE_TAG}|" ${COMPOSE_FILE}
|
|
||||||
|
# Copy the updated docker-compose.yml to the deployment location
|
||||||
|
# The runners are on the same Docker server where the container is running
|
||||||
|
sudo mkdir -p /home/euchre_camp
|
||||||
|
sudo cp docker-compose.yml /home/euchre_camp/
|
||||||
|
sudo chown -R euchre:euchre /home/euchre_camp
|
||||||
|
|
||||||
# Pull and restart the dev container
|
# Pull and restart the dev container
|
||||||
cd /apps/intelligent_silasak
|
cd /home/euchre_camp
|
||||||
docker compose pull app
|
docker-compose pull app
|
||||||
docker compose up -d app
|
docker-compose up -d app
|
||||||
|
|
||||||
# Wait for container to be healthy
|
# Wait for container to be healthy
|
||||||
echo "Waiting for dev site to be healthy..."
|
echo "Waiting for container to start..."
|
||||||
for i in {1..6}; do
|
sleep 10
|
||||||
if curl -sf https://euchre-dev.notsosm.art/api/health > /dev/null 2>&1; then
|
|
||||||
|
# Check if container is running
|
||||||
|
if docker ps --filter "name=euchre-camp-app" --format "{{.Status}}" | grep -q "Up"; then
|
||||||
echo "✅ Dev environment successfully deployed with version ${{ steps.version.outputs.new_version }}"
|
echo "✅ Dev environment successfully deployed with version ${{ steps.version.outputs.new_version }}"
|
||||||
exit 0
|
else
|
||||||
fi
|
|
||||||
sleep 15
|
|
||||||
done
|
|
||||||
echo "❌ Dev environment deployment failed"
|
echo "❌ Dev environment deployment failed"
|
||||||
docker compose logs app
|
docker-compose logs app
|
||||||
exit 1
|
exit 1
|
||||||
|
fi
|
||||||
|
|||||||
+4
-2
@@ -15,7 +15,6 @@
|
|||||||
/playwright/.auth/
|
/playwright/.auth/
|
||||||
/test-results
|
/test-results
|
||||||
/cookies.txt
|
/cookies.txt
|
||||||
# .env.test was removed — tests use DATABASE_URL from shell or .env.development
|
|
||||||
|
|
||||||
# next.js
|
# next.js
|
||||||
/.next/
|
/.next/
|
||||||
@@ -54,10 +53,13 @@ next-env.d.ts
|
|||||||
/src/generated/prisma
|
/src/generated/prisma
|
||||||
|
|
||||||
# database
|
# database
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
prisma/dev.db*
|
||||||
|
prisma/prisma/dev.db*
|
||||||
playwright-report/
|
playwright-report/
|
||||||
.env.development
|
.env.development
|
||||||
.env.dev
|
.env.dev
|
||||||
|
|
||||||
cucumber-pretty
|
cucumber-pretty
|
||||||
.env.production
|
.env.production
|
||||||
.credentials
|
|
||||||
|
|||||||
@@ -165,9 +165,9 @@ npm run db:setup-postgres
|
|||||||
- **Acceptance tests**: `npm run test:acceptance`
|
- **Acceptance tests**: `npm run test:acceptance`
|
||||||
- **Specific test**: `npm run test:acceptance -- --grep "test name"`
|
- **Specific test**: `npm run test:acceptance -- --grep "test name"`
|
||||||
|
|
||||||
**CI-style acceptance tests (uses PostgreSQL, set DATABASE_URL in your shell):**
|
**CI-style acceptance tests with SQLite:**
|
||||||
```bash
|
```bash
|
||||||
DATABASE_PROVIDER=postgresql DATABASE_URL="your_dev_db_url" npm run test:acceptance
|
DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance
|
||||||
```
|
```
|
||||||
|
|
||||||
### CI Runner Image
|
### CI Runner Image
|
||||||
|
|||||||
-114
@@ -1,117 +1,3 @@
|
|||||||
## [0.1.21] - 2026-05-20
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- fix: mount /apps and docker socket in PR workflow build-and-deploy-ci job (#41)
|
|
||||||
- feat: SDLC database separation for CI/testing (#35)
|
|
||||||
|
|
||||||
## [0.1.20] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'main' of https://git.notsosm.art/david/euchre_camp
|
|
||||||
- Merge branch 'fix/schedule-test-reliability': Reliable schedule generation tests
|
|
||||||
- fix: make schedule generation tests reliable (#33)
|
|
||||||
|
|
||||||
## [0.1.19] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'main' of https://git.notsosm.art/david/euchre_camp
|
|
||||||
- test: mark bye rounds scenario as @wip pending schedule generator fix
|
|
||||||
|
|
||||||
## [0.1.18] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'main' of https://git.notsosm.art/david/euchre_camp
|
|
||||||
- fix: resolve schedule test timing issues (#33)
|
|
||||||
|
|
||||||
## [0.1.17] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'main' of https://git.notsosm.art/david/euchre_camp
|
|
||||||
- refactor: remove all SQLite code, standardize on PostgreSQL
|
|
||||||
|
|
||||||
## [0.1.16] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'main' of https://git.notsosm.art/david/euchre_camp
|
|
||||||
- feat: add bracket visualization for tournament schedule (#8)
|
|
||||||
|
|
||||||
## [0.1.15] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'main' of https://git.notsosm.art/david/euchre_camp
|
|
||||||
- feat: add view-as-role feature for site admins (#15)
|
|
||||||
|
|
||||||
## [0.1.14] - 2026-05-02
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- Merge branch 'bugfix/7-tournament-schedule-tests': Schedule generation, clickable matchups, and test fixes
|
|
||||||
- Merge branch 'bugfix/9-player-schedule-tests': Player schedule clickable matches
|
|
||||||
- Merge branch 'bugfix/10-password-reset-tests': Password reset API and form wiring
|
|
||||||
- fix: resolve schedule generation tests - round display, clickable links, and team count
|
|
||||||
- fix: rename variable to avoid shadowing expectedRounds function
|
|
||||||
- fix: improve link click handling to wait for networkidle
|
|
||||||
- feat: implement password reset API endpoint and wire up form
|
|
||||||
- fix: make player schedule matches clickable links to match detail page
|
|
||||||
- fix: support matchup query param for direct navigation to entry page
|
|
||||||
- fix: correct wordmark link to point to home page
|
|
||||||
- fix: resolve schedule data staleness in production builds
|
|
||||||
- wip: Tournament schedule tests - 27/30 passing
|
|
||||||
- feat: add ScheduleDisplay component and wire up schedule page with Generator
|
|
||||||
- test: add tournament schedule step definitions
|
|
||||||
- test: enable player schedule tests with match data setup
|
|
||||||
- test: enable password reset page test and add navigation step
|
|
||||||
|
|
||||||
## [0.1.13] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- ci: update Playwright to v1.59.1 in CI base image
|
|
||||||
|
|
||||||
## [0.1.12] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- ci: clear Bun cache before install to fix integrity check failures
|
|
||||||
|
|
||||||
## [0.1.11] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## [0.1.10] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- fix: prevent content overflow on right side of screen
|
|
||||||
|
|
||||||
## [0.1.9] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- test: remove migrated Playwright tests (epic3-rankings, home-page)
|
|
||||||
|
|
||||||
## [0.1.8] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- test: migrate rankings and home-page tests from Playwright to Cucumber
|
|
||||||
|
|
||||||
## [0.1.7] - 2026-04-27
|
|
||||||
|
|
||||||
### Patch Changes
|
|
||||||
|
|
||||||
- fix: replace waitForLoadState('networkidle') with domcontentloaded in all E2E tests
|
|
||||||
- feat: Implement tournament schedule tab and fix E2E tests (#27)
|
|
||||||
|
|
||||||
## [0.1.6] - 2026-04-26
|
## [0.1.6] - 2026-04-26
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
+11
-11
@@ -4,7 +4,7 @@
|
|||||||
FROM oven/bun:alpine AS builder
|
FROM oven/bun:alpine AS builder
|
||||||
|
|
||||||
# Install dependencies (needed for native modules)
|
# Install dependencies (needed for native modules)
|
||||||
RUN apk add --no-cache python3 make g++ nodejs npm
|
RUN apk add --no-cache python3 make g++
|
||||||
|
|
||||||
# Set working directory
|
# Set working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
@@ -13,14 +13,14 @@ WORKDIR /app
|
|||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
|
|
||||||
# Install dependencies (including dev dependencies for building)
|
# Install dependencies (including dev dependencies for building)
|
||||||
RUN npm ci --legacy-peer-deps
|
RUN bun install
|
||||||
|
|
||||||
# Copy source code
|
# Copy source code
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Generate Prisma client (with dummy PostgreSQL DATABASE_URL for build-time generation)
|
# Generate Prisma client (with dummy PostgreSQL DATABASE_URL for build-time generation)
|
||||||
# Note: A dummy URL is used since the real database is not available during build
|
# Note: A dummy URL is used since the real database is not available during build
|
||||||
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate
|
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" bun x prisma generate
|
||||||
|
|
||||||
# Build the application (with dummy DATABASE_URL for static page generation and git commit)
|
# Build the application (with dummy DATABASE_URL for static page generation and git commit)
|
||||||
ARG GIT_COMMIT=unknown
|
ARG GIT_COMMIT=unknown
|
||||||
@@ -30,7 +30,7 @@ RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:
|
|||||||
FROM oven/bun:alpine AS test-runner
|
FROM oven/bun:alpine AS test-runner
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
RUN apk add --no-cache python3 make g++ git nodejs npm
|
RUN apk add --no-cache python3 make g++ git
|
||||||
|
|
||||||
# Set working directory
|
# Set working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
@@ -39,19 +39,19 @@ WORKDIR /app
|
|||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
|
|
||||||
# Install ALL dependencies (including dev dependencies for testing)
|
# Install ALL dependencies (including dev dependencies for testing)
|
||||||
RUN npm ci --legacy-peer-deps
|
RUN bun install
|
||||||
|
|
||||||
# Copy source code
|
# Copy source code
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Generate Prisma client
|
# Generate Prisma client
|
||||||
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate
|
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" bun x prisma generate
|
||||||
|
|
||||||
# Stage 3: Production runner
|
# Stage 3: Production runner
|
||||||
FROM oven/bun:alpine AS runner
|
FROM oven/bun:alpine AS runner
|
||||||
|
|
||||||
# Install dumb-init and npm for production install
|
# Install dumb-init for proper signal handling
|
||||||
RUN apk add --no-cache dumb-init nodejs npm
|
RUN apk add --no-cache dumb-init
|
||||||
|
|
||||||
# Create non-root user
|
# Create non-root user
|
||||||
RUN addgroup --system --gid 1001 euchre && \
|
RUN addgroup --system --gid 1001 euchre && \
|
||||||
@@ -64,15 +64,15 @@ WORKDIR /app
|
|||||||
COPY --from=builder --chown=euchre:euchre /app/.next ./.next
|
COPY --from=builder --chown=euchre:euchre /app/.next ./.next
|
||||||
COPY --from=builder --chown=euchre:euchre /app/public ./public
|
COPY --from=builder --chown=euchre:euchre /app/public ./public
|
||||||
COPY --from=builder --chown=euchre:euchre /app/package.json ./package.json
|
COPY --from=builder --chown=euchre:euchre /app/package.json ./package.json
|
||||||
COPY --from=builder --chown=euchre:euchre /app/package-lock.json ./package-lock.json
|
COPY --from=builder --chown=euchre:euchre /app/bun.lock ./bun.lock
|
||||||
COPY --from=builder --chown=euchre:euchre /app/prisma ./prisma
|
COPY --from=builder --chown=euchre:euchre /app/prisma ./prisma
|
||||||
|
|
||||||
# Install only production dependencies
|
# Install only production dependencies
|
||||||
RUN npm ci --legacy-peer-deps --omit=dev
|
RUN bun install --production
|
||||||
|
|
||||||
# Generate Prisma client
|
# Generate Prisma client
|
||||||
# Note: We need to set DATABASE_URL even for generation because prisma.config.ts requires it
|
# Note: We need to set DATABASE_URL even for generation because prisma.config.ts requires it
|
||||||
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate
|
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" bun x prisma generate
|
||||||
|
|
||||||
# Switch to non-root user
|
# Switch to non-root user
|
||||||
USER euchre
|
USER euchre
|
||||||
|
|||||||
+3
-2
@@ -2,7 +2,7 @@
|
|||||||
# Used for Gitea Actions CI workflows
|
# Used for Gitea Actions CI workflows
|
||||||
# Uses Microsoft Playwright image as base (Ubuntu-based) with Bun added
|
# Uses Microsoft Playwright image as base (Ubuntu-based) with Bun added
|
||||||
|
|
||||||
FROM mcr.microsoft.com/playwright:v1.59.1-jammy AS base
|
FROM mcr.microsoft.com/playwright:v1.58.0-jammy AS base
|
||||||
|
|
||||||
# Install unzip (required for Bun installation) and other tools
|
# Install unzip (required for Bun installation) and other tools
|
||||||
RUN apt-get update && apt-get install -y unzip && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y unzip && rm -rf /var/lib/apt/lists/*
|
||||||
@@ -22,7 +22,8 @@ RUN echo "=== Bun Version ===" && bun --version && \
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Set default environment variables
|
# Set default environment variables
|
||||||
ENV DATABASE_PROVIDER=postgresql
|
ENV DATABASE_PROVIDER=sqlite
|
||||||
|
ENV DATABASE_URL=file:./prisma/ci.db
|
||||||
ENV BETTER_AUTH_SECRET=test-secret-key-for-ci-only
|
ENV BETTER_AUTH_SECRET=test-secret-key-for-ci-only
|
||||||
ENV NODE_ENV=test
|
ENV NODE_ENV=test
|
||||||
|
|
||||||
|
|||||||
@@ -294,8 +294,8 @@ npm run test
|
|||||||
# Run acceptance tests
|
# Run acceptance tests
|
||||||
npm run test:acceptance
|
npm run test:acceptance
|
||||||
|
|
||||||
# Run acceptance tests (CI-style, set DATABASE_URL in your shell)
|
# Run acceptance tests with SQLite (CI-style)
|
||||||
DATABASE_PROVIDER=postgresql DATABASE_URL="your_dev_db_url" npm run test:acceptance
|
DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance
|
||||||
```
|
```
|
||||||
|
|
||||||
### Database Commands
|
### Database Commands
|
||||||
@@ -400,8 +400,8 @@ The original attempt to use a pre-built CI runner image with pre-installed depen
|
|||||||
# Run unit tests (same as CI)
|
# Run unit tests (same as CI)
|
||||||
npm run test:run
|
npm run test:run
|
||||||
|
|
||||||
# Run acceptance tests (set DATABASE_URL in your shell)
|
# Run acceptance tests with SQLite
|
||||||
DATABASE_PROVIDER=postgresql DATABASE_URL="your_dev_db_url" npm run test:acceptance
|
DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance
|
||||||
```
|
```
|
||||||
|
|
||||||
## Docker Deployment
|
## Docker Deployment
|
||||||
|
|||||||
+8
-24
@@ -24,11 +24,11 @@
|
|||||||
- [x] Write TODO list to repository file
|
- [x] Write TODO list to repository file
|
||||||
- [x] Auto-create tournament when uploading matches without selecting one
|
- [x] Auto-create tournament when uploading matches without selecting one
|
||||||
|
|
||||||
### Completed ✅
|
### In Progress 🔄
|
||||||
- [x] Update API routes to handle new variant scoring fields
|
- [ ] Update API routes to handle new variant scoring fields
|
||||||
- [x] Update EditTournamentForm to add variant scoring controls
|
- [ ] Update EditTournamentForm to add variant scoring controls
|
||||||
- [x] Update MatchEditor to use tournament-specific target score
|
- [ ] Update MatchEditor to use tournament-specific target score
|
||||||
- [x] Run tests and verify variant scoring implementation
|
- [ ] Run tests and verify variant scoring implementation
|
||||||
|
|
||||||
### Recently Completed ✅
|
### Recently Completed ✅
|
||||||
- [x] Update CI/CD workflows to use Bun (PR, release)
|
- [x] Update CI/CD workflows to use Bun (PR, release)
|
||||||
@@ -59,27 +59,11 @@
|
|||||||
- [x] Create migration to add rating system tables (elo_ratings, glicko2_ratings, open_skill_ratings)
|
- [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
|
- [x] Add tabbed rankings page to display Elo, OpenSkill, and Glicko2 ratings
|
||||||
|
|
||||||
### Completed ✅
|
|
||||||
- [x] Add UI controls for variant scoring in tournament creation/edit
|
|
||||||
- [x] Test variant tournament functionality end-to-end (e2e/tournament-edit-allowTies.test.ts)
|
|
||||||
- [x] Add validation for tie scores based on tournament configuration (MatchEditor.tsx)
|
|
||||||
|
|
||||||
### Completed ✅ (CI/DB Infrastructure)
|
|
||||||
- [x] Fix PostgreSQL database ownership — each env owns its own DB
|
|
||||||
- [x] Fix role attributes — euchre_camp_dev gets CREATEDB, euchre_camp_ci loses SUPERUSER
|
|
||||||
- [x] Update .env.development to use euchre_camp_dev user
|
|
||||||
- [x] Update .env.development.local to use euchre_camp_dev user
|
|
||||||
- [x] Update CI docker-compose to use euchre_camp_ci user
|
|
||||||
- [x] Update dev docker-compose to use euchre_camp_dev user
|
|
||||||
- [x] Recreate dev and CI containers with correct credentials
|
|
||||||
- [x] Fix Playwright baseURL for CI (https://euchre-ci.notsosm.art)
|
|
||||||
- [x] Fix Navigation unit tests (RoleSwitcherProvider wrapper)
|
|
||||||
- [x] Fix secrets vs vars in PR workflow (secrets.CI_DATABASE_URL)
|
|
||||||
|
|
||||||
### Backlog 📋
|
### 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
|
- [ ] Document variant tournament features
|
||||||
- [ ] Update Gitea secret CI_DATABASE_URL to use euchre_camp_ci user
|
|
||||||
- [ ] Test isolation improvements for parallel CI execution
|
|
||||||
|
|
||||||
## Recently Completed (Detailed)
|
## Recently Completed (Detailed)
|
||||||
|
|
||||||
|
|||||||
@@ -1,343 +0,0 @@
|
|||||||
# Technical Findings: Next.js App Router Data Staleness in Production
|
|
||||||
|
|
||||||
## Issue Summary
|
|
||||||
|
|
||||||
**Problem**: Freshly generated database data (TournamentRound and BracketMatchup records) created via POST `/api/tournaments/[id]/schedule` fails to appear immediately after a browser refresh in production builds, despite the server component having `revalidate = 0` and `dynamic = "force-dynamic"`.
|
|
||||||
|
|
||||||
**Context**: The test suite `schedule-tab.test.ts` shows that data is created successfully in the database but the page refresh doesn't immediately display the new data in production builds.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Root Cause Analysis
|
|
||||||
|
|
||||||
### 1. Next.js Data Cache Behavior
|
|
||||||
|
|
||||||
**Finding**: Next.js App Router caches `fetch` responses by default in production. While `revalidate = 0` and `dynamic = "force-dynamic"` disable full-route caching, they do not automatically disable the Data Cache for individual `fetch` requests.
|
|
||||||
|
|
||||||
**Evidence from codebase**:
|
|
||||||
- `src/app/admin/tournaments/[id]/schedule/page.tsx` sets:
|
|
||||||
```typescript
|
|
||||||
export const dynamic = "force-dynamic"
|
|
||||||
export const revalidate = 0
|
|
||||||
```
|
|
||||||
- However, the page uses Prisma directly, not `fetch`. The page query `prisma.event.findUnique` is not subject to Next.js fetch caching, but the **browser/client router cache** may still cause issues.
|
|
||||||
|
|
||||||
**Relevant Code Locations**:
|
|
||||||
- `src/app/admin/tournaments/[id]/schedule/page.tsx:14-16`
|
|
||||||
- `src/app/api/tournaments/[id]/schedule/route.ts:191-222` (POST transaction)
|
|
||||||
|
|
||||||
### 2. Prisma Client and Transaction Isolation
|
|
||||||
|
|
||||||
**Finding**: The POST endpoint uses `prisma.$transaction` to create rounds and matchups. In production with PostgreSQL, transaction isolation levels and connection pooling can cause visibility delays.
|
|
||||||
|
|
||||||
**Evidence**:
|
|
||||||
```typescript
|
|
||||||
// src/app/api/tournaments/[id]/schedule/route.ts:191
|
|
||||||
const created = await prisma.$transaction(
|
|
||||||
schedule.map((round) =>
|
|
||||||
prisma.tournamentRound.create({...})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
**Potential Issues**:
|
|
||||||
- **Read Committed Isolation**: PostgreSQL's default `READ COMMITTED` isolation level ensures that once a transaction commits, subsequent queries see the new data. However, if the browser refresh happens immediately after the POST response, there might be a race condition.
|
|
||||||
- **Connection Pooling**: The Prisma client uses connection pooling. If the GET request (page load) uses a different connection than the POST request, and there's a replication delay (unlikely with SQLite/PostgreSQL single instance), it could see stale data.
|
|
||||||
|
|
||||||
**Evidence Locations**:
|
|
||||||
- `src/lib/prisma.ts:13-35` (Prisma client initialization)
|
|
||||||
- `src/app/api/tournaments/[id]/schedule/route.ts:191-222` (Transaction block)
|
|
||||||
|
|
||||||
### 3. Client-Side Router Cache
|
|
||||||
|
|
||||||
**Finding**: The Next.js App Router maintains a client-side cache for visited routes. Even when the server component revalidates, the client might serve a cached version from the client-side navigation cache.
|
|
||||||
|
|
||||||
**Evidence from research**:
|
|
||||||
- The GitHub discussion #51612 shows that `router.push` and browser refresh can still serve stale data due to client-side caching.
|
|
||||||
- The `ScheduleGenerator` component uses `fetch` to POST data but doesn't trigger a router refresh or invalidate the client cache.
|
|
||||||
|
|
||||||
**Code Locations**:
|
|
||||||
- `src/components/ScheduleGenerator.tsx:27-29` (POST request)
|
|
||||||
- `src/components/ScheduleGenerator.tsx:84` (Only calls `window.location.reload()` on DELETE, not POST)
|
|
||||||
|
|
||||||
### 4. Production vs Development Differences
|
|
||||||
|
|
||||||
**Finding**: Development mode (`next dev`) has more lenient caching behavior. Production builds (`next start`) aggressively cache by default.
|
|
||||||
|
|
||||||
**Evidence**:
|
|
||||||
- The test `schedule-tab.test.ts` passes in development but fails in production.
|
|
||||||
- The `ScheduleGenerator` component doesn't use `revalidatePath` or `revalidateTag` after successful POST.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Specific Technical Findings
|
|
||||||
|
|
||||||
### Finding 1: Missing Cache Invalidation After POST
|
|
||||||
|
|
||||||
**Location**: `src/components/ScheduleGenerator.tsx:43-49`
|
|
||||||
|
|
||||||
**Issue**: After a successful POST request, the component updates local state (`result`) but doesn't:
|
|
||||||
1. Call `revalidatePath` (requires Server Action)
|
|
||||||
2. Call `revalidateTag` (requires Server Action)
|
|
||||||
3. Trigger a router refresh
|
|
||||||
4. Force a page reload
|
|
||||||
|
|
||||||
**Current Behavior**:
|
|
||||||
```typescript
|
|
||||||
const handleGenerate = async () => {
|
|
||||||
// ... POST request ...
|
|
||||||
const data = await response.json()
|
|
||||||
setResult({
|
|
||||||
roundsCreated: data.roundsCreated,
|
|
||||||
matchupsCreated: data.matchupsCreated,
|
|
||||||
})
|
|
||||||
setIsGenerating(false)
|
|
||||||
// ❌ No cache invalidation
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Expected Behavior**: After POST, the page should re-fetch data to show newly created rounds.
|
|
||||||
|
|
||||||
### Finding 2: Prisma Client Singleton Pattern
|
|
||||||
|
|
||||||
**Location**: `src/lib/prisma.ts:37-39`
|
|
||||||
|
|
||||||
**Issue**: The Prisma client is a singleton, which is correct. However, in production with connection pooling, there might be delays in visibility across connections.
|
|
||||||
|
|
||||||
**Current Code**:
|
|
||||||
```typescript
|
|
||||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
|
|
||||||
|
|
||||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
|
||||||
```
|
|
||||||
|
|
||||||
**Note**: This is correct pattern, but production connection pooling behavior differs from development.
|
|
||||||
|
|
||||||
### Finding 3: Server Component Data Fetching
|
|
||||||
|
|
||||||
**Location**: `src/app/admin/tournaments/[id]/schedule/page.tsx:26-50`
|
|
||||||
|
|
||||||
**Issue**: The server component fetches data directly with Prisma. While `revalidate = 0` ensures the server re-renders on each request, the client might cache the response.
|
|
||||||
|
|
||||||
**Current Code**:
|
|
||||||
```typescript
|
|
||||||
export const dynamic = "force-dynamic"
|
|
||||||
export const revalidate = 0
|
|
||||||
|
|
||||||
export default async function TournamentSchedulePage({ params }: PageProps) {
|
|
||||||
const tournament = await prisma.event.findUnique({
|
|
||||||
where: { id: tournamentId },
|
|
||||||
include: { rounds: { ... } }
|
|
||||||
})
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Note**: This should work correctly, but client-side router cache might interfere.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Potential Fixes
|
|
||||||
|
|
||||||
### Fix 1: Implement Server Actions for Cache Invalidation
|
|
||||||
|
|
||||||
**Approach**: Convert the schedule generation to use Server Actions with `revalidatePath`.
|
|
||||||
|
|
||||||
**Implementation**:
|
|
||||||
```typescript
|
|
||||||
// src/app/actions/schedule.ts
|
|
||||||
'use server'
|
|
||||||
|
|
||||||
import { revalidatePath } from 'next/cache'
|
|
||||||
import { prisma } from '@/lib/prisma'
|
|
||||||
import { generateRoundRobin, /* ... */ } from '@/lib/schedule-generator'
|
|
||||||
|
|
||||||
export async function generateSchedule(tournamentId: number) {
|
|
||||||
// ... existing logic from route.ts ...
|
|
||||||
|
|
||||||
// After successful creation
|
|
||||||
await prisma.$transaction(/* ... */)
|
|
||||||
|
|
||||||
// Revalidate the schedule page
|
|
||||||
revalidatePath(`/admin/tournaments/${tournamentId}/schedule`)
|
|
||||||
revalidatePath(`/admin/tournaments/${tournamentId}`)
|
|
||||||
|
|
||||||
return { success: true, roundsCreated: created.length }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Update ScheduleGenerator component**:
|
|
||||||
```typescript
|
|
||||||
// src/components/ScheduleGenerator.tsx
|
|
||||||
import { generateSchedule } from '@/app/actions/schedule'
|
|
||||||
|
|
||||||
const handleGenerate = async () => {
|
|
||||||
const result = await generateSchedule(tournamentId)
|
|
||||||
if (result.success) {
|
|
||||||
setResult({
|
|
||||||
roundsCreated: result.roundsCreated,
|
|
||||||
matchupsCreated: /* calculate from result */,
|
|
||||||
})
|
|
||||||
// Router automatically revalidates due to revalidatePath
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Fix 2: Force Router Refresh After POST
|
|
||||||
|
|
||||||
**Approach**: Use `router.refresh()` after successful POST to invalidate client cache.
|
|
||||||
|
|
||||||
**Implementation**:
|
|
||||||
```typescript
|
|
||||||
// src/components/ScheduleGenerator.tsx
|
|
||||||
'use client'
|
|
||||||
|
|
||||||
import { useRouter } from 'next/navigation'
|
|
||||||
|
|
||||||
export function ScheduleGenerator({ tournamentId, /* ... */ }) {
|
|
||||||
const router = useRouter()
|
|
||||||
|
|
||||||
const handleGenerate = async () => {
|
|
||||||
// ... POST request ...
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
// Force router to re-fetch server component data
|
|
||||||
router.refresh()
|
|
||||||
|
|
||||||
// Or force full page reload as fallback
|
|
||||||
// window.location.reload()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Fix 3: Disable Fetch Caching Explicitly
|
|
||||||
|
|
||||||
**Approach**: Even though we use Prisma, ensure any internal fetches don't cache.
|
|
||||||
|
|
||||||
**Implementation**:
|
|
||||||
```typescript
|
|
||||||
// src/app/api/tournaments/[id]/schedule/route.ts
|
|
||||||
export async function GET(request: Request, { params }: RouteParams) {
|
|
||||||
// Add cache control headers
|
|
||||||
const response = NextResponse.json({ rounds: tournament.rounds })
|
|
||||||
response.headers.set('Cache-Control', 'no-store, max-age=0')
|
|
||||||
return response
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Fix 4: Add Delay/Retry Logic in Tests
|
|
||||||
|
|
||||||
**Approach**: For Playwright tests, add explicit wait for data visibility.
|
|
||||||
|
|
||||||
**Implementation**:
|
|
||||||
```typescript
|
|
||||||
// e2e/schedule-tab.test.ts
|
|
||||||
test('Schedule page displays generated rounds and matchups', async ({ page }) => {
|
|
||||||
// ... navigate to schedule page ...
|
|
||||||
|
|
||||||
// Wait for rounds to be visible with retry logic
|
|
||||||
await expect(page.locator('text=Round 1')).toBeVisible({ timeout: 10000 })
|
|
||||||
|
|
||||||
// Additional verification
|
|
||||||
await expect(page.locator('text=Alice + Bob')).toBeVisible()
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
### Fix 5: Database Transaction Optimization
|
|
||||||
|
|
||||||
**Approach**: Ensure transaction commits fully before returning response.
|
|
||||||
|
|
||||||
**Implementation**:
|
|
||||||
```typescript
|
|
||||||
// src/app/api/tournaments/[id]/schedule/route.ts
|
|
||||||
const created = await prisma.$transaction(
|
|
||||||
schedule.map((round) =>
|
|
||||||
prisma.tournamentRound.create({
|
|
||||||
data: { /* ... */ },
|
|
||||||
include: { /* ... */ } // Eager load to ensure data is available
|
|
||||||
})
|
|
||||||
),
|
|
||||||
{
|
|
||||||
isolationLevel: 'ReadCommitted', // Explicit isolation level
|
|
||||||
maxWait: 5000, // Increase wait time
|
|
||||||
timeout: 10000, // Increase timeout
|
|
||||||
}
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Recommended Solution
|
|
||||||
|
|
||||||
### Immediate Fix (Quick)
|
|
||||||
|
|
||||||
1. **Update `ScheduleGenerator.tsx`** to use `router.refresh()` after POST:
|
|
||||||
```typescript
|
|
||||||
import { useRouter } from 'next/navigation'
|
|
||||||
|
|
||||||
const router = useRouter()
|
|
||||||
|
|
||||||
const handleGenerate = async () => {
|
|
||||||
// ... POST logic ...
|
|
||||||
if (response.ok) {
|
|
||||||
router.refresh()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Add cache control headers** to the GET endpoint:
|
|
||||||
```typescript
|
|
||||||
// In GET handler
|
|
||||||
const response = NextResponse.json({ rounds: tournament.rounds })
|
|
||||||
response.headers.set('Cache-Control', 'no-store, max-age=0')
|
|
||||||
return response
|
|
||||||
```
|
|
||||||
|
|
||||||
### Long-term Fix (Recommended)
|
|
||||||
|
|
||||||
1. **Migrate to Server Actions** for schedule generation:
|
|
||||||
- Use `'use server'` directive
|
|
||||||
- Call `revalidatePath` after mutations
|
|
||||||
- Eliminate need for separate API route
|
|
||||||
|
|
||||||
2. **Implement proper cache tagging**:
|
|
||||||
- Tag fetch requests with `next: { tags: ['schedule'] }`
|
|
||||||
- Use `revalidateTag('schedule')` after mutations
|
|
||||||
|
|
||||||
3. **Update test patterns**:
|
|
||||||
- Ensure tests wait for server component revalidation
|
|
||||||
- Use `page.waitForLoadState('networkidle')` after mutations
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Verification Steps
|
|
||||||
|
|
||||||
1. **Test in production build**:
|
|
||||||
```bash
|
|
||||||
npm run build
|
|
||||||
npm run start
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Verify data flow**:
|
|
||||||
- Create schedule via UI
|
|
||||||
- Refresh page immediately
|
|
||||||
- Verify rounds display correctly
|
|
||||||
|
|
||||||
3. **Check server logs**:
|
|
||||||
- Look for revalidation messages
|
|
||||||
- Verify Prisma query execution
|
|
||||||
|
|
||||||
4. **Run acceptance tests**:
|
|
||||||
```bash
|
|
||||||
npm run test:acceptance
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
- Next.js App Router Caching: https://nextjs.org/docs/app/building-your-application/data-fetching/caching
|
|
||||||
- Server Actions: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
|
|
||||||
- GitHub Discussion #51612: https://github.com/vercel/next.js/discussions/51612
|
|
||||||
- Prisma Transactions: https://www.prisma.io/docs/orm/prisma-client/queries/transactions
|
|
||||||
@@ -10,8 +10,6 @@
|
|||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
|
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
// Generate unique test account credentials
|
// Generate unique test account credentials
|
||||||
function getTestCredentials() {
|
function getTestCredentials() {
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
@@ -54,14 +52,14 @@ test.describe.serial('Account Lifecycle API Acceptance Test', () => {
|
|||||||
console.log('Test 1 - testEmail:', testEmail);
|
console.log('Test 1 - testEmail:', testEmail);
|
||||||
|
|
||||||
// Register via API
|
// Register via API
|
||||||
const response = await request.post('/api/auth/sign-up/email', {
|
const response = await request.post('http://localhost:3000/api/auth/sign-up/email', {
|
||||||
data: {
|
data: {
|
||||||
email: testEmail,
|
email: testEmail,
|
||||||
password: testPassword,
|
password: testPassword,
|
||||||
name: testName
|
name: testName
|
||||||
},
|
},
|
||||||
headers: {
|
headers: {
|
||||||
'Origin': BASE_URL
|
'Origin': 'http://localhost:3000'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,13 +96,13 @@ test.describe.serial('Account Lifecycle API Acceptance Test', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Login via API
|
// Login via API
|
||||||
const response = await request.post('/api/auth/sign-in/email', {
|
const response = await request.post('http://localhost:3000/api/auth/sign-in/email', {
|
||||||
data: {
|
data: {
|
||||||
email: testEmail,
|
email: testEmail,
|
||||||
password: testPassword
|
password: testPassword
|
||||||
},
|
},
|
||||||
headers: {
|
headers: {
|
||||||
'Origin': BASE_URL
|
'Origin': 'http://localhost:3000'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ test.describe.serial('Account Lifecycle Acceptance Test', () => {
|
|||||||
await page.goto('/auth/register');
|
await page.goto('/auth/register');
|
||||||
|
|
||||||
// Wait for JavaScript to be ready
|
// Wait for JavaScript to be ready
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Wait for the form to be visible and the submit button to be enabled
|
// Wait for the form to be visible and the submit button to be enabled
|
||||||
await page.waitForSelector('form');
|
await page.waitForSelector('form');
|
||||||
@@ -74,7 +74,7 @@ test.describe.serial('Account Lifecycle Acceptance Test', () => {
|
|||||||
await page.waitForURL(/\/players\/\d+\/profile/, { timeout: 10000 });
|
await page.waitForURL(/\/players\/\d+\/profile/, { timeout: 10000 });
|
||||||
|
|
||||||
// Wait a moment for the user to be saved to database
|
// Wait a moment for the user to be saved to database
|
||||||
await page.waitForTimeout(200);
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
// Verify user was created in database
|
// Verify user was created in database
|
||||||
const user = await prisma.user.findUnique({
|
const user = await prisma.user.findUnique({
|
||||||
@@ -105,7 +105,7 @@ test.describe.serial('Account Lifecycle Acceptance Test', () => {
|
|||||||
|
|
||||||
// Reload to ensure session is loaded from cookies
|
// Reload to ensure session is loaded from cookies
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Wait for logout button to appear
|
// Wait for logout button to appear
|
||||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
import { test, expect } from '@playwright/test'
|
import { test, expect } from '@playwright/test'
|
||||||
import { prisma } from '@/lib/prisma'
|
import { prisma } from '@/lib/prisma'
|
||||||
|
|
||||||
test.describe.skip('Admin Features: Match and Player Management @chromium-admin', () => {
|
test.describe('Admin Features: Match and Player Management @chromium-admin', () => {
|
||||||
test.describe('Match Management', () => {
|
test.describe('Match Management', () => {
|
||||||
test('should access matches admin page', async ({ page }) => {
|
test('should access matches admin page', async ({ page }) => {
|
||||||
await page.goto('/admin/matches')
|
await page.goto('/admin/matches')
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
import { test, expect } from '@playwright/test'
|
|
||||||
|
|
||||||
test.describe.skip('Admin Smoke Test', () => {
|
|
||||||
test.describe('Admin Panel Navigation', () => {
|
|
||||||
test('should navigate to admin dashboard', async ({ page }) => {
|
|
||||||
await page.goto('/admin')
|
|
||||||
await expect(page.locator('text=Admin')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should navigate to matches admin page', async ({ page }) => {
|
|
||||||
await page.goto('/admin/matches')
|
|
||||||
await expect(page.locator('text=Match Management')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should navigate to players admin page', async ({ page }) => {
|
|
||||||
await page.goto('/admin/players')
|
|
||||||
await expect(page.locator('text=Player Management')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should navigate to users admin page', async ({ page }) => {
|
|
||||||
await page.goto('/admin/users')
|
|
||||||
await expect(page.locator('text=User Management')).toBeVisible()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test.describe('Match Management', () => {
|
|
||||||
test('should display matches page', async ({ page }) => {
|
|
||||||
await page.goto('/admin/matches')
|
|
||||||
await expect(page.locator('text=Match Management')).toBeVisible()
|
|
||||||
|
|
||||||
const hasTable = await page.locator('table').count().then(c => c > 0)
|
|
||||||
const hasEmptyState = await page.locator('text=/no matches|No matches/').count().then(c => c > 0)
|
|
||||||
|
|
||||||
expect(hasTable || hasEmptyState).toBeTruthy()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should have delete button for matches when matches exist', async ({ page }) => {
|
|
||||||
await page.goto('/admin/matches')
|
|
||||||
const deleteButtons = page.locator('button:has-text("Delete")')
|
|
||||||
const count = await deleteButtons.count()
|
|
||||||
if (count > 0) {
|
|
||||||
await expect(page.locator('text=Actions')).toBeVisible()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test.describe('Player Management', () => {
|
|
||||||
test('should display players table', async ({ page }) => {
|
|
||||||
await page.goto('/admin/players')
|
|
||||||
await expect(page.locator('table')).toBeVisible()
|
|
||||||
await expect(page.locator('text=Player Name')).toBeVisible()
|
|
||||||
await expect(page.locator('text=Current Elo')).toBeVisible()
|
|
||||||
await expect(page.locator('text=Actions')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should have edit and delete buttons for players', async ({ page }) => {
|
|
||||||
await page.goto('/admin/players')
|
|
||||||
await expect(page.locator('text=Actions')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should allow editing player name', async ({ page }) => {
|
|
||||||
await page.goto('/admin/players')
|
|
||||||
const editButton = page.locator('button:has-text("Edit")').first()
|
|
||||||
if (await editButton.isVisible()) {
|
|
||||||
await editButton.click()
|
|
||||||
|
|
||||||
await expect(page.locator('text=Edit Player Name')).toBeVisible()
|
|
||||||
|
|
||||||
await page.click('text=Cancel')
|
|
||||||
await expect(page.locator('text=Edit Player Name')).not.toBeVisible()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test.describe('User Management', () => {
|
|
||||||
test('should display users page', async ({ page }) => {
|
|
||||||
await page.goto('/admin/users')
|
|
||||||
const hasTable = await page.locator('table').isVisible().catch(() => false)
|
|
||||||
const hasNoUsers = await page.locator('text=No users found').isVisible().catch(() => false)
|
|
||||||
|
|
||||||
expect(hasTable || hasNoUsers).toBeTruthy()
|
|
||||||
|
|
||||||
await expect(page.locator('text=User Management')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should have create user link', async ({ page }) => {
|
|
||||||
await page.goto('/admin/users')
|
|
||||||
const createLink = page.locator('a.bg-green-600:has-text("Create User")')
|
|
||||||
await expect(createLink).toBeVisible()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -10,10 +10,9 @@ import fs from 'fs';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
|
|
||||||
test.describe.skip('CSV Upload Player Deduplication', () => {
|
test.describe('CSV Upload Player Deduplication', () => {
|
||||||
let testTournamentId: number;
|
let testTournamentId: number;
|
||||||
const testPlayerIds: number[] = [];
|
const testPlayerIds: number[] = [];
|
||||||
const ts = Date.now();
|
|
||||||
|
|
||||||
test.beforeAll(async () => {
|
test.beforeAll(async () => {
|
||||||
// Create a test tournament
|
// Create a test tournament
|
||||||
@@ -48,14 +47,12 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete test players (those with "Dedupe" or "Aggregate Test" in the name)
|
// Delete test players (those with "Dedupe" in the name)
|
||||||
await prisma.player.deleteMany({
|
await prisma.player.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
OR: [
|
name: {
|
||||||
{ name: { contains: 'Dedupe' } },
|
contains: 'Dedupe',
|
||||||
{ name: { contains: 'Aggregate Test' } },
|
},
|
||||||
{ name: { contains: 'Whitespace' } },
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -81,13 +78,10 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
|
|||||||
formData.append('csvFile', file);
|
formData.append('csvFile', file);
|
||||||
formData.append('eventId', testTournamentId.toString());
|
formData.append('eventId', testTournamentId.toString());
|
||||||
|
|
||||||
const response = await request.post('/api/matches/upload', {
|
const response = await request.post('http://localhost:3000/api/matches/upload', {
|
||||||
multipart: formData,
|
multipart: formData,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok()) {
|
|
||||||
console.log('CSV upload failed:', response.status(), await response.text());
|
|
||||||
}
|
|
||||||
expect(response.ok()).toBeTruthy();
|
expect(response.ok()).toBeTruthy();
|
||||||
|
|
||||||
// Check that only 4 unique players were created (not 8)
|
// Check that only 4 unique players were created (not 8)
|
||||||
@@ -138,13 +132,10 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
|
|||||||
formData.append('csvFile', file);
|
formData.append('csvFile', file);
|
||||||
formData.append('eventId', testTournamentId.toString());
|
formData.append('eventId', testTournamentId.toString());
|
||||||
|
|
||||||
const response = await request.post('/api/matches/upload', {
|
const response = await request.post('http://localhost:3000/api/matches/upload', {
|
||||||
multipart: formData,
|
multipart: formData,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok()) {
|
|
||||||
console.log('CSV upload failed:', response.status(), await response.text());
|
|
||||||
}
|
|
||||||
expect(response.ok()).toBeTruthy();
|
expect(response.ok()).toBeTruthy();
|
||||||
|
|
||||||
// Check that players were created without extra whitespace
|
// Check that players were created without extra whitespace
|
||||||
@@ -172,8 +163,8 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
|
|||||||
// First, create some players manually to simulate previous uploads
|
// First, create some players manually to simulate previous uploads
|
||||||
const player1 = await prisma.player.create({
|
const player1 = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: `Aggregate Test ${ts}`,
|
name: 'Aggregate Test',
|
||||||
normalizedName: `aggregate test ${ts}`,
|
normalizedName: 'aggregate test',
|
||||||
currentElo: 1050,
|
currentElo: 1050,
|
||||||
gamesPlayed: 5,
|
gamesPlayed: 5,
|
||||||
wins: 3,
|
wins: 3,
|
||||||
@@ -184,7 +175,7 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
|
|||||||
|
|
||||||
// Upload a CSV with the same player name
|
// Upload a CSV with the same player name
|
||||||
const csvContent = `Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points
|
const csvContent = `Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points
|
||||||
1,1,1,Aggregate Test ${ts},Test Player 1,5,Test Player 2,Test Player 3,3`;
|
1,1,1,Aggregate Test,Test Player 1,5,Test Player 2,Test Player 3,3`;
|
||||||
|
|
||||||
const csvPath = path.join(__dirname, 'temp-aggregate-test.csv');
|
const csvPath = path.join(__dirname, 'temp-aggregate-test.csv');
|
||||||
fs.writeFileSync(csvPath, csvContent);
|
fs.writeFileSync(csvPath, csvContent);
|
||||||
@@ -198,19 +189,16 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
|
|||||||
formData.append('csvFile', file);
|
formData.append('csvFile', file);
|
||||||
formData.append('eventId', testTournamentId.toString());
|
formData.append('eventId', testTournamentId.toString());
|
||||||
|
|
||||||
const response = await request.post('/api/matches/upload', {
|
const response = await request.post('http://localhost:3000/api/matches/upload', {
|
||||||
multipart: formData,
|
multipart: formData,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok()) {
|
|
||||||
console.log('CSV upload failed:', response.status(), await response.text());
|
|
||||||
}
|
|
||||||
expect(response.ok()).toBeTruthy();
|
expect(response.ok()).toBeTruthy();
|
||||||
|
|
||||||
// Check that the existing player was updated (not duplicated)
|
// Check that the existing player was updated (not duplicated)
|
||||||
const aggregatePlayers = await prisma.player.findMany({
|
const aggregatePlayers = await prisma.player.findMany({
|
||||||
where: {
|
where: {
|
||||||
name: `Aggregate Test ${ts}`,
|
name: 'Aggregate Test',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+39
-26
@@ -1,32 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* Bridge file to run Cucumber tests through Playwright's test runner
|
||||||
|
*
|
||||||
|
* This allows Cucumber tests to benefit from Playwright's:
|
||||||
|
* - Dev server management
|
||||||
|
* - Browser lifecycle management
|
||||||
|
* - Test reporting
|
||||||
|
* - CI/CD integration
|
||||||
|
*/
|
||||||
|
|
||||||
import { test } from '@playwright/test';
|
import { test } from '@playwright/test';
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
|
|
||||||
test.describe.skip('Cucumber E2E Tests', () => {
|
// This test file doesn't contain actual tests
|
||||||
|
// It just runs Cucumber CLI which executes the feature files
|
||||||
|
test.describe('Cucumber E2E Tests', () => {
|
||||||
test('Run all Cucumber feature files', async () => {
|
test('Run all Cucumber feature files', async () => {
|
||||||
const baseURL = process.env.CI
|
// This test is a placeholder that triggers Cucumber execution
|
||||||
? 'https://euchre-ci.notsosm.art'
|
// In practice, Cucumber should be run directly via CLI
|
||||||
: 'http://localhost:3000';
|
console.log('Cucumber tests should be run via: bun cucumber-js');
|
||||||
|
|
||||||
let result;
|
|
||||||
try {
|
|
||||||
result = execSync(
|
|
||||||
'npx cucumber-js --config e2e/cucumber/cucumber.config.ts',
|
|
||||||
{
|
|
||||||
encoding: 'utf-8',
|
|
||||||
stdio: 'pipe',
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
BASE_URL: baseURL,
|
|
||||||
},
|
|
||||||
cwd: process.cwd(),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error: any) {
|
|
||||||
console.log('Cucumber stderr:', error.stderr?.toString() || 'none');
|
|
||||||
console.log('Cucumber stdout:', error.stdout?.toString() || 'none');
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(result);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Alternative approach: Programmatic execution
|
||||||
|
*
|
||||||
|
* If you want to run Cucumber programmatically from within Playwright:
|
||||||
|
*/
|
||||||
|
/*
|
||||||
|
import { execSync } from 'child_process';
|
||||||
|
|
||||||
|
export default async function runCucumberTests() {
|
||||||
|
try {
|
||||||
|
const output = execSync(
|
||||||
|
'bun cucumber-js --config e2e/cucumber/cucumber.config.ts',
|
||||||
|
{ encoding: 'utf-8', stdio: 'inherit' }
|
||||||
|
);
|
||||||
|
console.log(output);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Cucumber tests failed:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ module.exports = {
|
|||||||
|
|
||||||
// Format options
|
// Format options
|
||||||
format: [
|
format: [
|
||||||
process.env.CI ? 'progress' : ['pretty', 'html:cucumber-report.html']
|
'progress-bar',
|
||||||
|
'pretty:cucumber-pretty'
|
||||||
],
|
],
|
||||||
|
|
||||||
// Output directory for reports
|
// Output directory for reports
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
Feature: Club Admin Dashboard
|
|
||||||
As a club admin
|
|
||||||
I want to view club-wide statistics and manage club operations
|
|
||||||
So that I can effectively oversee the club
|
|
||||||
|
|
||||||
@happy-path @admin @issue-11
|
|
||||||
Scenario: Club admin views dashboard with statistics
|
|
||||||
Given I am logged in as a club admin
|
|
||||||
When I go to the admin dashboard
|
|
||||||
Then I should see "Admin Dashboard"
|
|
||||||
And I should see total player count
|
|
||||||
And I should see active tournament count
|
|
||||||
|
|
||||||
@happy-path @admin @issue-11
|
|
||||||
Scenario: Club admin views recent activity feed
|
|
||||||
Given I am logged in as a club admin
|
|
||||||
And there are recent activities in the system
|
|
||||||
When I go to the admin dashboard
|
|
||||||
Then I should see the activity feed section
|
|
||||||
And I should see recent player registrations
|
|
||||||
|
|
||||||
@happy-path @admin @issue-11
|
|
||||||
Scenario: Club admin searches player directory
|
|
||||||
Given I am logged in as a club admin
|
|
||||||
And there are multiple players in the system
|
|
||||||
When I go to the player management page
|
|
||||||
And I search for "Player 1"
|
|
||||||
Then I should see search results
|
|
||||||
|
|
||||||
@happy-path @admin @issue-11
|
|
||||||
Scenario: Club admin updates club settings
|
|
||||||
Given I am logged in as a club admin
|
|
||||||
When I go to the club settings page
|
|
||||||
And I update the club name
|
|
||||||
And I save the settings
|
|
||||||
Then the settings should be saved successfully
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
Feature: Bracket Visualization
|
|
||||||
As a tournament admin
|
|
||||||
I want to see a visual bracket of the tournament schedule
|
|
||||||
So that I can track tournament progress at a glance
|
|
||||||
|
|
||||||
@happy-path @tournament @issue-8
|
|
||||||
Scenario: Tournament admin views bracket with a generated schedule
|
|
||||||
Given I am logged in as a tournament admin
|
|
||||||
And a tournament exists with 4 teams
|
|
||||||
When I go to the tournament schedule page
|
|
||||||
And I click the "Generate Schedule" button
|
|
||||||
Then I should see "Generated"
|
|
||||||
When I go to the tournament detail page
|
|
||||||
And I click the "Bracket" tab
|
|
||||||
Then I should see "Tournament Bracket"
|
|
||||||
And I should see "Round 1"
|
|
||||||
And I should see "Round 2"
|
|
||||||
And I should see "Round 3"
|
|
||||||
And I should see bracket matchup cards
|
|
||||||
|
|
||||||
@happy-path @tournament @issue-8
|
|
||||||
Scenario: Bracket shows team names in matchup cards
|
|
||||||
Given I am logged in as a tournament admin
|
|
||||||
And a tournament exists with 4 teams
|
|
||||||
When I go to the tournament schedule page
|
|
||||||
And I click the "Generate Schedule" button
|
|
||||||
Then I should see "Generated"
|
|
||||||
When I go to the tournament detail page
|
|
||||||
And I click the "Bracket" tab
|
|
||||||
Then I should see bracket matchup cards with team names
|
|
||||||
|
|
||||||
@happy-path @tournament @issue-8
|
|
||||||
Scenario: Bracket tab is not visible without a schedule
|
|
||||||
Given I am logged in as a tournament admin
|
|
||||||
And a tournament exists with 4 teams
|
|
||||||
When I go to the tournament detail page
|
|
||||||
Then I should not see the "Bracket" tab
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
Feature: Home Page
|
|
||||||
As a visitor
|
|
||||||
I want to see the home page
|
|
||||||
So that I can learn about the club and view player rankings
|
|
||||||
|
|
||||||
Background:
|
|
||||||
Given there are top players in the system
|
|
||||||
And there is a club president
|
|
||||||
And there is a recent tournament
|
|
||||||
|
|
||||||
@happy-path @public @home
|
|
||||||
Scenario: Home page displays Top 10 Players
|
|
||||||
Given I am on the home page
|
|
||||||
Then I should see "Top 10 Players"
|
|
||||||
And I should see a rankings table
|
|
||||||
|
|
||||||
@happy-path @public @home
|
|
||||||
Scenario: Home page displays club information
|
|
||||||
Given I am on the home page
|
|
||||||
Then I should see "Club Information"
|
|
||||||
And I should see "Club President"
|
|
||||||
|
|
||||||
@happy-path @public @home
|
|
||||||
Scenario: Home page displays most recent tournament
|
|
||||||
Given I am on the home page
|
|
||||||
Then I should see "Most Recent Tournament"
|
|
||||||
|
|
||||||
@happy-path @public @home
|
|
||||||
Scenario: Home page has sign in and create account links
|
|
||||||
Given I am on the home page
|
|
||||||
Then I should see "Sign In"
|
|
||||||
And I should see "Create Account"
|
|
||||||
@@ -9,7 +9,7 @@ Feature: Player Schedule
|
|||||||
When I go to my schedule page
|
When I go to my schedule page
|
||||||
Then I should see "No upcoming matches"
|
Then I should see "No upcoming matches"
|
||||||
|
|
||||||
@happy-path @player-features @issue-9
|
@happy-path @player-features @issue-9 @wip
|
||||||
Scenario: Player views schedule with upcoming matches
|
Scenario: Player views schedule with upcoming matches
|
||||||
Given I am logged in as a player
|
Given I am logged in as a player
|
||||||
And I have upcoming matches in my schedule
|
And I have upcoming matches in my schedule
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
Feature: Rankings Page
|
|
||||||
As a visitor
|
|
||||||
I want to view player rankings
|
|
||||||
So that I can see top players and their statistics
|
|
||||||
|
|
||||||
@happy-path @public @rankings
|
|
||||||
Scenario: Rankings page loads and displays rankings table
|
|
||||||
When I go to the rankings page
|
|
||||||
Then I should see "Player Rankings" in the page heading
|
|
||||||
And I should see a rankings table
|
|
||||||
|
|
||||||
@happy-path @public @rankings
|
|
||||||
Scenario: Rankings table displays player columns
|
|
||||||
When I go to the rankings page
|
|
||||||
Then I should see a rankings table with columns
|
|
||||||
And the table should have column headers
|
|
||||||
|
|
||||||
@happy-path @public @rankings
|
|
||||||
Scenario: Rankings page is publicly accessible (no login required)
|
|
||||||
Given I am not logged in
|
|
||||||
When I go to the rankings page
|
|
||||||
Then I should be on the rankings page
|
|
||||||
And I should see the rankings table
|
|
||||||
@@ -11,33 +11,29 @@ Feature: Tournament Schedule
|
|||||||
Then I should see "Schedule"
|
Then I should see "Schedule"
|
||||||
And I should see the "Generate Schedule" button
|
And I should see the "Generate Schedule" button
|
||||||
|
|
||||||
@happy-path @tournament @issue-7
|
@happy-path @tournament @issue-7 @wip
|
||||||
Scenario: Tournament admin generates round-robin schedule
|
Scenario: Tournament admin generates round-robin schedule
|
||||||
Given I am logged in as a tournament admin
|
Given I am logged in as a tournament admin
|
||||||
And a tournament exists with 4 teams
|
And a tournament exists with 4 teams
|
||||||
When I go to the tournament schedule page
|
When I go to the tournament schedule page
|
||||||
And I click the "Generate Schedule" button
|
And I click the "Generate Schedule" button
|
||||||
Then I should see "Generated"
|
Then I should see "Schedule generated successfully"
|
||||||
And I should see "rounds with"
|
And I should see round 1 matchups
|
||||||
Then I should see round 1 matchups
|
|
||||||
And I should see round 2 matchups
|
And I should see round 2 matchups
|
||||||
|
|
||||||
@happy-path @tournament @issue-7
|
@happy-path @tournament @issue-7 @wip
|
||||||
Scenario: Tournament admin views schedule with bye rounds
|
Scenario: Tournament admin views schedule with bye rounds
|
||||||
Given I am logged in as a tournament admin
|
Given I am logged in as a tournament admin
|
||||||
And a tournament exists with 5 teams
|
And a tournament exists with 5 teams
|
||||||
When I go to the tournament schedule page
|
When I go to the tournament schedule page
|
||||||
And I click the "Generate Schedule" button
|
And I click the "Generate Schedule" button
|
||||||
Then I should see "Generated"
|
Then I should see a bye round for one team
|
||||||
Then I should see 5 rounds
|
|
||||||
And each team should play every other team exactly once
|
And each team should play every other team exactly once
|
||||||
|
|
||||||
@happy-path @tournament @issue-7
|
@happy-path @tournament @issue-7 @wip
|
||||||
Scenario: Tournament admin clicks on a matchup to enter results
|
Scenario: Tournament admin clicks on a matchup to enter results
|
||||||
Given I am logged in as a tournament admin
|
Given I am logged in as a tournament admin
|
||||||
And a tournament exists with 4 teams
|
And a tournament has a generated schedule
|
||||||
When I go to the tournament schedule page
|
When I go to the tournament schedule page
|
||||||
And I click the "Generate Schedule" button
|
|
||||||
Then I should see "Generated"
|
|
||||||
And I click on a matchup
|
And I click on a matchup
|
||||||
Then I should be on the match result entry page
|
Then I should be on the match result entry page
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
Feature: View As Role
|
|
||||||
As a site admin
|
|
||||||
I want to temporarily view the site as a player or club admin
|
|
||||||
So that I can understand and improve the experience for each role
|
|
||||||
|
|
||||||
@happy-path @admin-features @issue-15
|
|
||||||
Scenario: Site admin sees role switcher in navigation
|
|
||||||
Given I am logged in as a site admin
|
|
||||||
When I view the navigation
|
|
||||||
Then I should see the role switcher dropdown
|
|
||||||
Then the role switcher should default to "Viewing as Site Admin"
|
|
||||||
|
|
||||||
@happy-path @admin-features @issue-15
|
|
||||||
Scenario: Site admin switches to player view
|
|
||||||
Given I am logged in as a site admin
|
|
||||||
When I select "View as Player" from the role switcher
|
|
||||||
Then I should see the player navigation links
|
|
||||||
And I should not see the "Admin" link
|
|
||||||
And I should not see the "Users" link
|
|
||||||
And I should see a banner indicating I am viewing as "Player"
|
|
||||||
|
|
||||||
@happy-path @admin-features @issue-15
|
|
||||||
Scenario: Site admin switches to tournament admin view
|
|
||||||
Given I am logged in as a site admin
|
|
||||||
When I select "View as Tournament Admin" from the role switcher
|
|
||||||
Then I should see the "Tournaments" link
|
|
||||||
And I should not see the "Admin" link
|
|
||||||
And I should not see the "Users" link
|
|
||||||
And I should see a banner indicating I am viewing as "Tournament Admin"
|
|
||||||
|
|
||||||
@happy-path @admin-features @issue-15
|
|
||||||
Scenario: Site admin switches to club admin view
|
|
||||||
Given I am logged in as a site admin
|
|
||||||
When I select "View as Club Admin" from the role switcher
|
|
||||||
Then I should see the "Admin" link
|
|
||||||
And I should see the "Users" link
|
|
||||||
And I should see a banner indicating I am viewing as "Club Admin"
|
|
||||||
|
|
||||||
@happy-path @admin-features @issue-15
|
|
||||||
Scenario: Site admin resets to site admin view
|
|
||||||
Given I am logged in as a site admin
|
|
||||||
When I select "View as Player" from the role switcher
|
|
||||||
And I click the "Reset to Site Admin" button
|
|
||||||
Then the role switcher should default to "Viewing as Site Admin"
|
|
||||||
And I should see the "Admin" link
|
|
||||||
And I should not see the viewing as banner
|
|
||||||
@@ -108,10 +108,16 @@ Given('I am logged in as a player', async function () {
|
|||||||
/**
|
/**
|
||||||
* Precondition: I am logged in as a tournament admin
|
* Precondition: I am logged in as a tournament admin
|
||||||
* Note: In the actual app, admin roles are assigned by club admins or via API.
|
* Note: In the actual app, admin roles are assigned by club admins or via API.
|
||||||
* For acceptance tests, we'll assign the tournament_admin role directly via Prisma.
|
* For acceptance tests, we'll use the default player role and test admin features
|
||||||
|
* as the dev site would handle them.
|
||||||
*/
|
*/
|
||||||
Given('I am logged in as a tournament admin', async function () {
|
Given('I am logged in as a tournament admin', async function () {
|
||||||
console.log('🌍 Creating and logging in as a tournament admin...');
|
console.log('🌍 Creating and logging in as a player (tournament admin role is assigned via UI/API)...');
|
||||||
|
// For now, use the same flow as player
|
||||||
|
// In real usage, the admin would either:
|
||||||
|
// 1. Be pre-created on the dev site
|
||||||
|
// 2. Have role assigned via API
|
||||||
|
// 3. Use the admin dashboard to manage users
|
||||||
|
|
||||||
const credentials = generateTestCredentials();
|
const credentials = generateTestCredentials();
|
||||||
world.user = credentials;
|
world.user = credentials;
|
||||||
@@ -124,174 +130,43 @@ Given('I am logged in as a tournament admin', async function () {
|
|||||||
await world.page.fill('input[name="password"]', credentials.password);
|
await world.page.fill('input[name="password"]', credentials.password);
|
||||||
|
|
||||||
await world.page.click('button[type="submit"]');
|
await world.page.click('button[type="submit"]');
|
||||||
|
// Wait for redirect
|
||||||
// Wait for any redirect away from register page
|
await world.page.waitForURL(/\/players\/\d+\/profile/, { timeout: 15000 });
|
||||||
await world.page.waitForURL((url) => !url.toString().includes('/auth/register'), { timeout: 15000 });
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(1000);
|
|
||||||
|
|
||||||
const currentUrl = world.page.url();
|
|
||||||
console.log(`🌍 After registration, URL: ${currentUrl}`);
|
|
||||||
|
|
||||||
// Try to extract player ID from URL
|
|
||||||
const match = currentUrl.match(/\/players\/(\d+)\/profile/);
|
|
||||||
if (match) {
|
|
||||||
world.playerId = match[1];
|
|
||||||
console.log(`🌍 Player ID from URL: ${world.playerId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the user ID from the database (works regardless of redirect destination)
|
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
console.log(`🌍 Looking up user by email: ${credentials.email}`);
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
where: { email: credentials.email },
|
|
||||||
include: { player: true }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (user) {
|
|
||||||
(world.user as any).id = user.id;
|
|
||||||
console.log(`🌍 User ID from DB: ${user.id}, role: ${user.role}, playerId: ${user.playerId}`);
|
|
||||||
|
|
||||||
if (user.player) {
|
|
||||||
world.playerId = user.player.id.toString();
|
|
||||||
console.log(`🌍 Player ID from DB: ${world.playerId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Assign tournament_admin role
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: user.id },
|
|
||||||
data: { role: 'tournament_admin' }
|
|
||||||
});
|
|
||||||
console.log(`🌍 Assigned tournament_admin role to user: ${user.id}`);
|
|
||||||
|
|
||||||
// Navigate to trigger a fresh role fetch
|
|
||||||
await world.page.goto(`${world.baseURL}/rankings`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(500);
|
|
||||||
} else {
|
|
||||||
console.log(`🌍 WARNING: User not found in DB by email. Trying to find latest user...`);
|
|
||||||
// Fallback: find the latest user (most recently created)
|
|
||||||
const latestUser = await prisma.user.findFirst({
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
include: { player: true }
|
|
||||||
});
|
|
||||||
if (latestUser) {
|
|
||||||
(world.user as any).id = latestUser.id;
|
|
||||||
world.playerId = latestUser.playerId?.toString() || latestUser.player?.id?.toString();
|
|
||||||
console.log(`🌍 Using latest user: ${latestUser.id} (${latestUser.email})`);
|
|
||||||
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: latestUser.id },
|
|
||||||
data: { role: 'tournament_admin' }
|
|
||||||
});
|
|
||||||
console.log(`🌍 Assigned tournament_admin role`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`🌍 User created: ${credentials.email}`);
|
console.log(`🌍 User created: ${credentials.email}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* Precondition: I am logged in as a site admin
|
|
||||||
* Creates a new user and assigns site_admin role via Prisma
|
|
||||||
*/
|
|
||||||
Given('I am logged in as a site admin', async function () {
|
|
||||||
console.log('🌍 Creating and logging in as a site admin...');
|
|
||||||
|
|
||||||
const credentials = generateTestCredentials();
|
|
||||||
world.user = credentials;
|
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/register`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
|
|
||||||
await world.page.fill('input[name="name"]', credentials.name);
|
|
||||||
await world.page.fill('input[name="email"]', credentials.email);
|
|
||||||
await world.page.fill('input[name="password"]', credentials.password);
|
|
||||||
|
|
||||||
await world.page.click('button[type="submit"]');
|
|
||||||
await world.page.waitForURL(/\/players\/\d+\/profile/, { timeout: 15000 });
|
|
||||||
|
|
||||||
const currentUrl = world.page.url();
|
|
||||||
const match = currentUrl.match(/\/players\/(\d+)\/profile/);
|
|
||||||
if (match) {
|
|
||||||
const playerId = match[1];
|
|
||||||
world.playerId = playerId;
|
|
||||||
|
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
const player = await prisma.player.findUnique({
|
|
||||||
where: { id: parseInt(playerId) },
|
|
||||||
include: { user: true }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (player && player.user) {
|
|
||||||
const userId = player.user.id;
|
|
||||||
(world.user as any).id = userId;
|
|
||||||
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: userId },
|
|
||||||
data: { role: 'site_admin' }
|
|
||||||
});
|
|
||||||
console.log(`🌍 Assigned site_admin role to user: ${userId}`);
|
|
||||||
|
|
||||||
// Navigate to home page to trigger Navigation re-mount with new role
|
|
||||||
await world.page.goto(`${world.baseURL}/`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(1000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`🌍 Site admin created: ${credentials.email}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Precondition: I am logged in as a club admin
|
* Precondition: I am logged in as a club admin
|
||||||
* Creates a new user via UI and assigns club_admin role via Prisma
|
* Uses a pre-existing admin user from the database
|
||||||
*/
|
*/
|
||||||
Given('I am logged in as a club admin', async function () {
|
Given('I am logged in as a club admin', async function () {
|
||||||
console.log('🌍 Creating and logging in as a club admin...');
|
console.log('🌍 Logging in as existing club admin...');
|
||||||
|
|
||||||
const credentials = generateTestCredentials();
|
// Use the admin user created by seed.js
|
||||||
world.user = credentials;
|
const adminEmail = 'david@dhg.lol';
|
||||||
|
const adminPassword = 'adminadmin';
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/register`);
|
world.user = {
|
||||||
|
email: adminEmail,
|
||||||
|
password: adminPassword,
|
||||||
|
name: 'David Admin',
|
||||||
|
};
|
||||||
|
|
||||||
|
await world.page.goto(`${world.baseURL}/auth/login`);
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('domcontentloaded');
|
||||||
|
|
||||||
await world.page.fill('input[name="name"]', credentials.name);
|
await world.page.fill('input[name="email"]', adminEmail);
|
||||||
await world.page.fill('input[name="email"]', credentials.email);
|
await world.page.fill('input[name="password"]', adminPassword);
|
||||||
await world.page.fill('input[name="password"]', credentials.password);
|
|
||||||
|
|
||||||
await world.page.click('button[type="submit"]');
|
await world.page.click('button[type="submit"]');
|
||||||
await world.page.waitForURL(/\/players\/\d+\/profile/, { timeout: 15000 });
|
|
||||||
|
|
||||||
const currentUrl = world.page.url();
|
// Wait for redirect after login
|
||||||
const match = currentUrl.match(/\/players\/(\d+)\/profile/);
|
try {
|
||||||
if (match) {
|
await world.page.waitForURL((url) => !url.toString().includes('/auth/login'), { timeout: 10000 });
|
||||||
const playerId = match[1];
|
console.log(`🌍 Club admin logged in: ${adminEmail}`);
|
||||||
world.playerId = playerId;
|
} catch (e) {
|
||||||
|
console.log('🌍 Login redirect timed out, current URL:', world.page.url());
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
const player = await prisma.player.findUnique({
|
|
||||||
where: { id: parseInt(playerId) },
|
|
||||||
include: { user: true }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (player && player.user) {
|
|
||||||
const userId = player.user.id;
|
|
||||||
(world.user as any).id = userId;
|
|
||||||
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: userId },
|
|
||||||
data: { role: 'club_admin' }
|
|
||||||
});
|
|
||||||
console.log(`🌍 Assigned club_admin role to user: ${userId}`);
|
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(1000);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`🌍 Club admin created: ${credentials.email}`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -302,7 +177,7 @@ When('I register with valid credentials', async function () {
|
|||||||
world.user = credentials;
|
world.user = credentials;
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/register`);
|
await world.page.goto(`${world.baseURL}/auth/register`);
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
await world.page.fill('input[name="name"]', credentials.name);
|
await world.page.fill('input[name="name"]', credentials.name);
|
||||||
await world.page.fill('input[name="email"]', credentials.email);
|
await world.page.fill('input[name="email"]', credentials.email);
|
||||||
@@ -319,7 +194,7 @@ When('I register with duplicate email', async function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/register`);
|
await world.page.goto(`${world.baseURL}/auth/register`);
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
await world.page.fill('input[name="name"]', world.user.name);
|
await world.page.fill('input[name="name"]', world.user.name);
|
||||||
await world.page.fill('input[name="email"]', world.user.email);
|
await world.page.fill('input[name="email"]', world.user.email);
|
||||||
@@ -345,7 +220,7 @@ When('I register with weak password', async function () {
|
|||||||
credentials.password = 'weak'; // Too short
|
credentials.password = 'weak'; // Too short
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/register`);
|
await world.page.goto(`${world.baseURL}/auth/register`);
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
await world.page.fill('input[name="name"]', credentials.name);
|
await world.page.fill('input[name="name"]', credentials.name);
|
||||||
await world.page.fill('input[name="email"]', credentials.email);
|
await world.page.fill('input[name="email"]', credentials.email);
|
||||||
@@ -365,7 +240,7 @@ When('I log in with valid credentials', async function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/login`);
|
await world.page.goto(`${world.baseURL}/auth/login`);
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
await world.page.fill('input[name="email"]', world.user.email);
|
await world.page.fill('input[name="email"]', world.user.email);
|
||||||
await world.page.fill('input[name="password"]', world.user.password);
|
await world.page.fill('input[name="password"]', world.user.password);
|
||||||
@@ -377,7 +252,7 @@ When('I log in with valid credentials', async function () {
|
|||||||
|
|
||||||
When('I log in with invalid credentials', async function () {
|
When('I log in with invalid credentials', async function () {
|
||||||
await world.page.goto(`${world.baseURL}/auth/login`);
|
await world.page.goto(`${world.baseURL}/auth/login`);
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
await world.page.fill('input[name="email"]', 'nonexistent@example.com');
|
await world.page.fill('input[name="email"]', 'nonexistent@example.com');
|
||||||
await world.page.fill('input[name="password"]', 'wrongpassword');
|
await world.page.fill('input[name="password"]', 'wrongpassword');
|
||||||
@@ -462,67 +337,16 @@ When('I go to my schedule page', async function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Given('I have upcoming matches in my schedule', async function () {
|
Given('I have upcoming matches in my schedule', async function () {
|
||||||
console.log('🌍 Setting up upcoming matches in schedule');
|
console.log('🌍 Note: This step requires database setup via API or UI');
|
||||||
const prisma = await world.getPrisma();
|
console.log('🌍 For acceptance tests, this would be set up before running the test');
|
||||||
const timestamp = Date.now();
|
// For true acceptance testing, we would:
|
||||||
|
// 1. Create a tournament
|
||||||
|
// 2. Add the player as a participant
|
||||||
|
// 3. Generate a schedule
|
||||||
|
// 4. The match would then appear in the player's schedule
|
||||||
|
|
||||||
// Get the current player
|
// For now, this is a placeholder that indicates data setup is needed
|
||||||
if (!world.playerId) {
|
// In a real test run, this data would already exist in the dev database
|
||||||
throw new Error('No player ID found. Make sure user is logged in as a player first.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentPlayerId = parseInt(world.playerId, 10);
|
|
||||||
|
|
||||||
// Create 3 other players for the match
|
|
||||||
const opponent1 = await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Opponent ${timestamp} 1`,
|
|
||||||
normalizedName: `opponent ${timestamp} 1`,
|
|
||||||
currentElo: 1000,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const opponent2 = await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Opponent ${timestamp} 2`,
|
|
||||||
normalizedName: `opponent ${timestamp} 2`,
|
|
||||||
currentElo: 1000,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const partner1 = await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Partner ${timestamp}`,
|
|
||||||
normalizedName: `partner ${timestamp}`,
|
|
||||||
currentElo: 1000,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create a tournament
|
|
||||||
const tournament = await prisma.event.create({
|
|
||||||
data: {
|
|
||||||
name: `Test Schedule Tournament ${timestamp}`,
|
|
||||||
eventDate: new Date(Date.now() + 86400000), // Tomorrow
|
|
||||||
status: 'planned',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create a match with the current player as player1P1 (played tomorrow)
|
|
||||||
await prisma.match.create({
|
|
||||||
data: {
|
|
||||||
eventId: tournament.id,
|
|
||||||
player1P1Id: currentPlayerId,
|
|
||||||
player1P2Id: partner1.id,
|
|
||||||
player2P1Id: opponent1.id,
|
|
||||||
player2P2Id: opponent2.id,
|
|
||||||
team1Score: 10,
|
|
||||||
team2Score: 5,
|
|
||||||
status: 'completed',
|
|
||||||
playedAt: new Date(Date.now() + 86400000), // Tomorrow
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`🌍 Created tournament "${tournament.name}" with 1 match for player ${currentPlayerId}`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -533,42 +357,19 @@ Given('a tournament exists with {int} teams', async function (teamCount: number)
|
|||||||
|
|
||||||
// Get Prisma client
|
// Get Prisma client
|
||||||
const prisma = await world.getPrisma();
|
const prisma = await world.getPrisma();
|
||||||
|
|
||||||
|
// Find or create a tournament
|
||||||
|
let tournament = await prisma.event.findFirst({
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!tournament) {
|
||||||
|
// Create a new tournament if none exists
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
|
tournament = await prisma.event.create({
|
||||||
// Get the current user ID for ownership
|
|
||||||
const userId = world.user?.id;
|
|
||||||
if (!userId) {
|
|
||||||
throw new Error('User ID not found. Ensure user is logged in before creating tournament.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always create a new tournament for test isolation
|
|
||||||
const tournament = await prisma.event.create({
|
|
||||||
data: {
|
data: {
|
||||||
name: `Test Tournament ${timestamp}`,
|
name: `Test Tournament ${timestamp}`,
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
ownerId: userId, // Set the owner to the current user
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Euchre is 2v2, so each team has 2 players
|
|
||||||
// Create teamCount * 2 players and add them as participants
|
|
||||||
const playerCount = teamCount * 2;
|
|
||||||
for (let i = 1; i <= playerCount; i++) {
|
|
||||||
const player = await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Tournament Player ${i} ${timestamp}`,
|
|
||||||
normalizedName: `tournament player ${i} ${timestamp}`,
|
|
||||||
currentElo: 1000,
|
|
||||||
gamesPlayed: 0,
|
|
||||||
wins: 0,
|
|
||||||
losses: 0,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await prisma.eventParticipant.create({
|
|
||||||
data: {
|
|
||||||
eventId: tournament.id,
|
|
||||||
playerId: player.id,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -576,138 +377,21 @@ Given('a tournament exists with {int} teams', async function (teamCount: number)
|
|||||||
world.tournament = tournament;
|
world.tournament = tournament;
|
||||||
world.tournamentTeamCount = teamCount;
|
world.tournamentTeamCount = teamCount;
|
||||||
|
|
||||||
console.log(`🌍 Created tournament: ${tournament.name} (ID: ${tournament.id}) with ${playerCount} players (${teamCount} teams)`);
|
console.log(`🌍 Using tournament: ${tournament.name} (ID: ${tournament.id})`);
|
||||||
});
|
});
|
||||||
|
|
||||||
When('I go to the tournament schedule page', async function () {
|
When('I go to the tournament schedule page', async function () {
|
||||||
console.log('🌍 Going to tournament schedule page');
|
console.log('🌍 Going to tournament schedule page');
|
||||||
const tournamentId = world.tournament?.id || 1;
|
const tournamentId = world.tournament?.id || 1;
|
||||||
const url = `${world.baseURL}/admin/tournaments/${tournamentId}/schedule?t=${Date.now()}`;
|
await world.page.goto(`${world.baseURL}/admin/tournaments/${tournamentId}/schedule`);
|
||||||
await world.page.goto(url);
|
await world.page.waitForLoadState('networkidle');
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
// Wait for ScheduleDisplay client component to hydrate
|
|
||||||
await world.page.waitForTimeout(2000);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Given('a tournament has a generated schedule', async function () {
|
Given('a tournament has a generated schedule', async function () {
|
||||||
console.log('🌍 Creating tournament with generated schedule');
|
console.log('🌍 Note: Tournament schedule requires generation via API or UI');
|
||||||
|
console.log('🌍 For acceptance tests, this would be created before running the test');
|
||||||
const prisma = await world.getPrisma();
|
// In a real test run, we would:
|
||||||
const timestamp = Date.now();
|
// 1. Create a tournament
|
||||||
|
// 2. Add teams/participants
|
||||||
// Get the current user ID for ownership
|
// 3. Generate schedule via API or UI
|
||||||
const userId = world.user?.id;
|
|
||||||
if (!userId) {
|
|
||||||
throw new Error('User ID not found. Ensure user is logged in before creating tournament.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a tournament
|
|
||||||
const tournament = await prisma.event.create({
|
|
||||||
data: {
|
|
||||||
name: `Test Schedule Tournament ${timestamp}`,
|
|
||||||
createdAt: new Date(),
|
|
||||||
ownerId: userId, // Set the owner to the current user
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create 4 players and add them as participants
|
|
||||||
const players = [];
|
|
||||||
for (let i = 1; i <= 4; i++) {
|
|
||||||
const player = await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Schedule Player ${i} ${timestamp}`,
|
|
||||||
normalizedName: `schedule player ${i} ${timestamp}`,
|
|
||||||
currentElo: 1000,
|
|
||||||
gamesPlayed: 0,
|
|
||||||
wins: 0,
|
|
||||||
losses: 0,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
players.push(player);
|
|
||||||
|
|
||||||
await prisma.eventParticipant.create({
|
|
||||||
data: {
|
|
||||||
eventId: tournament.id,
|
|
||||||
playerId: player.id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate schedule via API
|
|
||||||
const response = await fetch(`${world.baseURL}/api/tournaments/${tournament.id}/schedule`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
console.log('🌍 Failed to generate schedule:', response.status, response.statusText);
|
|
||||||
// Try to get error details
|
|
||||||
try {
|
|
||||||
const errorData = await response.json();
|
|
||||||
console.log('🌍 Error details:', errorData);
|
|
||||||
} catch {
|
|
||||||
// Ignore
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const data = await response.json();
|
|
||||||
console.log('🌍 Schedule generated:', data);
|
|
||||||
}
|
|
||||||
|
|
||||||
world.tournament = tournament;
|
|
||||||
world.tournamentTeamCount = 4;
|
|
||||||
console.log(`🌍 Tournament with schedule created: ${tournament.name} (ID: ${tournament.id})`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Given('there are recent activities in the system', async function () {
|
|
||||||
// Create test activities using the activity logger
|
|
||||||
const prisma = await world.getPrisma()
|
|
||||||
|
|
||||||
// Use timestamp to ensure unique names
|
|
||||||
const timestamp = Date.now()
|
|
||||||
|
|
||||||
// Create a test player first
|
|
||||||
const player = await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Test Activity Player ${timestamp}`,
|
|
||||||
normalizedName: `test activity player ${timestamp}`,
|
|
||||||
currentElo: 1000,
|
|
||||||
gamesPlayed: 0,
|
|
||||||
wins: 0,
|
|
||||||
losses: 0,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// Create an activity
|
|
||||||
await (prisma as any).activity.create({
|
|
||||||
data: {
|
|
||||||
type: 'player_registration',
|
|
||||||
description: `Test Activity Player ${timestamp} registered`,
|
|
||||||
playerId: player.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
console.log('🌍 Created test activity for player:', player.name)
|
|
||||||
})
|
|
||||||
|
|
||||||
Given('there are multiple players in the system', async function () {
|
|
||||||
const prisma = await world.getPrisma()
|
|
||||||
|
|
||||||
// Use timestamp to ensure unique names
|
|
||||||
const timestamp = Date.now()
|
|
||||||
|
|
||||||
// Create multiple test players
|
|
||||||
for (let i = 1; i <= 5; i++) {
|
|
||||||
await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Test Player ${i} ${timestamp}`,
|
|
||||||
normalizedName: `test player ${i} ${timestamp}`,
|
|
||||||
currentElo: 1000 + i * 10,
|
|
||||||
gamesPlayed: 0,
|
|
||||||
wins: 0,
|
|
||||||
losses: 0,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('🌍 Created 5 test players')
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -29,12 +29,6 @@ Given('I am on the login page', async function () {
|
|||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('domcontentloaded');
|
||||||
});
|
});
|
||||||
|
|
||||||
Given('I am on the password reset page', async function () {
|
|
||||||
console.log('🌍 Navigating to password reset page');
|
|
||||||
await world.page.goto(`${world.baseURL}/auth/password-reset`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
});
|
|
||||||
|
|
||||||
Given('I am on the {string} page', async function (pageName: string) {
|
Given('I am on the {string} page', async function (pageName: string) {
|
||||||
const pageUrls: Record<string, string> = {
|
const pageUrls: Record<string, string> = {
|
||||||
'home': '/',
|
'home': '/',
|
||||||
@@ -109,14 +103,8 @@ When('I go back', async function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
When('I refresh the page', async function () {
|
When('I refresh the page', async function () {
|
||||||
console.log('🌍 About to refresh page from URL:', world.page.url());
|
await world.page.reload();
|
||||||
await world.page.reload({ waitUntil: 'load' });
|
await world.page.waitForLoadState('domcontentloaded');
|
||||||
console.log('🌍 Page refreshed, new URL:', world.page.url());
|
|
||||||
// Wait extra time for full render
|
|
||||||
await world.page.waitForTimeout(2000);
|
|
||||||
const content = await world.page.content();
|
|
||||||
console.log('🌍 After refresh - has "Round":', content.includes('Round'));
|
|
||||||
console.log('🌍 After refresh - has "Generated":', content.includes('Generated'));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -173,7 +161,7 @@ When('I click the {string} button', async function (buttonText: string) {
|
|||||||
console.log(`🌍 URL did not change immediately after click`);
|
console.log(`🌍 URL did not change immediately after click`);
|
||||||
// Wait for potential network activity to settle
|
// Wait for potential network activity to settle
|
||||||
try {
|
try {
|
||||||
await world.page.waitForLoadState('domcontentloaded', { timeout: 3000 });
|
await world.page.waitForLoadState('networkidle', { timeout: 3000 });
|
||||||
} catch {
|
} catch {
|
||||||
console.log(`🌍 Network idle not reached, continuing anyway`);
|
console.log(`🌍 Network idle not reached, continuing anyway`);
|
||||||
}
|
}
|
||||||
@@ -186,18 +174,28 @@ When('I click the {string} link', async function (linkText: string) {
|
|||||||
const selector = `a:has-text("${linkText}")`;
|
const selector = `a:has-text("${linkText}")`;
|
||||||
console.log(`🌍 Clicking link: ${linkText}`);
|
console.log(`🌍 Clicking link: ${linkText}`);
|
||||||
|
|
||||||
|
// Get current URL
|
||||||
|
const currentUrl = world.page.url();
|
||||||
|
|
||||||
// Click the link
|
// Click the link
|
||||||
await world.page.click(selector);
|
await world.page.click(selector);
|
||||||
|
|
||||||
// Wait for navigation to complete
|
// Wait a bit for navigation to start
|
||||||
try {
|
await world.page.waitForTimeout(500);
|
||||||
await world.page.waitForLoadState('domcontentloaded', { timeout: 10000 });
|
|
||||||
} catch {
|
|
||||||
console.log(`🌍 Networkidle not reached, continuing`);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Check if URL changed
|
||||||
const newUrl = world.page.url();
|
const newUrl = world.page.url();
|
||||||
|
if (newUrl === currentUrl) {
|
||||||
|
console.log(`🌍 URL did not change immediately after link click`);
|
||||||
|
// Wait for any navigation to complete
|
||||||
|
try {
|
||||||
|
await world.page.waitForLoadState('domcontentloaded', { timeout: 5000 });
|
||||||
|
} catch {
|
||||||
|
console.log(`🌍 DOMContentLoaded not reached, continuing`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
console.log(`🌍 Page navigated to: ${newUrl}`);
|
console.log(`🌍 Page navigated to: ${newUrl}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
When('I click the {string} wordmark', async function (wordmarkText: string) {
|
When('I click the {string} wordmark', async function (wordmarkText: string) {
|
||||||
@@ -407,7 +405,7 @@ Then('I should see the {string} button', async function (buttonText: string) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Then('I should be redirected to {string}', async function (path: string) {
|
Then('I should be redirected to {string}', async function (path: string) {
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
const currentUrl = world.page.url();
|
const currentUrl = world.page.url();
|
||||||
|
|
||||||
console.log(`🌍 Checking redirect to: ${path}`);
|
console.log(`🌍 Checking redirect to: ${path}`);
|
||||||
@@ -438,7 +436,7 @@ When('I wait for {int} seconds', async function (seconds: number) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
When('I wait for the page to load', async function () {
|
When('I wait for the page to load', async function () {
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -451,7 +449,7 @@ Then('the URL should contain {string}', async function (expectedPath: string) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Then('I should be redirected to the login page', async function () {
|
Then('I should be redirected to the login page', async function () {
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
await world.page.waitForLoadState('networkidle');
|
||||||
const currentUrl = world.page.url();
|
const currentUrl = world.page.url();
|
||||||
|
|
||||||
console.log(`🌍 Checking redirect to login page. Current URL: ${currentUrl}`);
|
console.log(`🌍 Checking redirect to login page. Current URL: ${currentUrl}`);
|
||||||
@@ -477,312 +475,3 @@ Then('I should see {string} error', async function (errorMessage: string) {
|
|||||||
expect(content).toMatch(new RegExp(errorMessage, 'i'));
|
expect(content).toMatch(new RegExp(errorMessage, 'i'));
|
||||||
console.log(`🌍 Verified error message: ${errorMessage}`);
|
console.log(`🌍 Verified error message: ${errorMessage}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Admin Dashboard Steps
|
|
||||||
When('I go to the admin dashboard', async function () {
|
|
||||||
console.log('🌍 Going to admin dashboard');
|
|
||||||
await world.page.goto(`${world.baseURL}/admin`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see total player count', async function () {
|
|
||||||
await expect(world.page.locator('text=Total Players')).toBeVisible();
|
|
||||||
console.log('🌍 Verified total players section is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see active tournament count', async function () {
|
|
||||||
// Use more specific locator to find the stats card
|
|
||||||
await expect(world.page.locator('dt:has-text("Tournaments")').first()).toBeVisible();
|
|
||||||
console.log('🌍 Verified tournaments section is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see the activity feed section', async function () {
|
|
||||||
await expect(world.page.locator('text=Recent Activity')).toBeVisible();
|
|
||||||
console.log('🌍 Verified activity feed section is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see recent player registrations', async function () {
|
|
||||||
// Check if there are any activities in the feed
|
|
||||||
const activityItems = await world.page.locator('.divide-y.divide-gray-200 li').count();
|
|
||||||
console.log(`🌍 Found ${activityItems} activity items`);
|
|
||||||
|
|
||||||
// Also check for the activity text
|
|
||||||
const content = await world.page.content();
|
|
||||||
const hasActivityText = content.includes('Test Activity Player');
|
|
||||||
console.log(`🌍 Activity text found in page: ${hasActivityText}`);
|
|
||||||
|
|
||||||
expect(activityItems).toBeGreaterThan(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I go to the player management page', async function () {
|
|
||||||
console.log('🌍 Going to player management page');
|
|
||||||
await world.page.goto(`${world.baseURL}/admin/players`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I search for {string}', async function (searchTerm: string) {
|
|
||||||
console.log(`🌍 Searching for: ${searchTerm}`);
|
|
||||||
await world.page.fill('input[name="search"]', searchTerm);
|
|
||||||
await world.page.waitForTimeout(500); // Wait for search to execute
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see search results', async function () {
|
|
||||||
// Check if player table is visible
|
|
||||||
await expect(world.page.locator('table')).toBeVisible();
|
|
||||||
console.log('🌍 Verified search results are displayed');
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I go to the club settings page', async function () {
|
|
||||||
console.log('🌍 Going to club settings page');
|
|
||||||
await world.page.goto(`${world.baseURL}/admin/settings`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I update the club name', async function () {
|
|
||||||
console.log('🌍 Updating club name');
|
|
||||||
await world.page.fill('input[id="clubName"]', 'Test Club Updated');
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I save the settings', async function () {
|
|
||||||
console.log('🌍 Saving settings');
|
|
||||||
await world.page.click('button:has-text("Save Settings")');
|
|
||||||
await world.page.waitForTimeout(1000); // Wait for save to complete
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('the settings should be saved successfully', async function () {
|
|
||||||
await expect(world.page.locator('text=Settings saved successfully')).toBeVisible();
|
|
||||||
console.log('🌍 Verified settings were saved successfully');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Rankings Page Steps
|
|
||||||
When('I go to the rankings page', async function () {
|
|
||||||
console.log('🌍 Going to rankings page');
|
|
||||||
await world.page.goto(`${world.baseURL}/rankings`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see {string} in the page heading', async function (heading: string) {
|
|
||||||
// Use a more flexible selector that matches text content
|
|
||||||
await expect(world.page.locator(`text=${heading}`)).toBeVisible();
|
|
||||||
console.log(`🌍 Verified heading "${heading}" is visible`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see a rankings table', async function () {
|
|
||||||
await expect(world.page.locator('table')).toBeVisible();
|
|
||||||
console.log('🌍 Verified rankings table is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see a rankings table with columns', async function () {
|
|
||||||
const table = world.page.locator('table');
|
|
||||||
await expect(table).toBeVisible();
|
|
||||||
const headerCount = await world.page.locator('th').count();
|
|
||||||
expect(headerCount).toBeGreaterThan(0);
|
|
||||||
console.log(`🌍 Verified rankings table has ${headerCount} columns`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('the table should have column headers', async function () {
|
|
||||||
const headerCount = await world.page.locator('th').count();
|
|
||||||
expect(headerCount).toBeGreaterThan(0);
|
|
||||||
console.log(`🌍 Verified table has ${headerCount} column headers`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Given('I am not logged in', async function () {
|
|
||||||
// This is just a documentation step - the test environment starts fresh
|
|
||||||
console.log('🌍 User is not logged in (fresh session)');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should be on the rankings page', async function () {
|
|
||||||
const currentUrl = world.page.url();
|
|
||||||
console.log(`🌍 Checking current URL: ${currentUrl}`);
|
|
||||||
expect(currentUrl).toContain('/rankings');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see the rankings table', async function () {
|
|
||||||
await expect(world.page.locator('table')).toBeVisible();
|
|
||||||
console.log('🌍 Verified rankings table is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Player Schedule Steps
|
|
||||||
Then('I should see the match date', async function () {
|
|
||||||
const content = await world.page.content();
|
|
||||||
const hasDate = content.match(/\d{1,2}\/\d{1,2}\/\d{4}/) || content.match(/\w+ \d{1,2}, \d{4}/);
|
|
||||||
expect(hasDate).toBeTruthy();
|
|
||||||
console.log('🌍 Verified match date is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see my opponent\'s name', async function () {
|
|
||||||
const content = await world.page.content();
|
|
||||||
const hasOpponent = content.includes('Opponent');
|
|
||||||
expect(hasOpponent).toBe(true);
|
|
||||||
console.log('🌍 Verified opponent name is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see my partner\'s name', async function () {
|
|
||||||
const content = await world.page.content();
|
|
||||||
const hasPartner = content.includes('Partner');
|
|
||||||
expect(hasPartner).toBe(true);
|
|
||||||
console.log('🌍 Verified partner name is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see the tournament name', async function () {
|
|
||||||
const content = await world.page.content();
|
|
||||||
const hasTournament = content.includes('Test Schedule Tournament');
|
|
||||||
expect(hasTournament).toBe(true);
|
|
||||||
console.log('🌍 Verified tournament name is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I click on a match', async function () {
|
|
||||||
const matchLink = world.page.locator('a[href*="/matches/"]').first();
|
|
||||||
await matchLink.click();
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
console.log('🌍 Clicked on match');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should be on the match detail page', async function () {
|
|
||||||
const currentUrl = world.page.url();
|
|
||||||
console.log(`🌍 Checking current URL: ${currentUrl}`);
|
|
||||||
expect(currentUrl).toMatch(/\/matches\/\d+/);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Tournament Schedule Steps
|
|
||||||
Then('I should see round {int} matchups', async function (roundNumber: number) {
|
|
||||||
const roundText = `Round ${roundNumber}`;
|
|
||||||
const roundHeader = world.page.locator(`h3:has-text("${roundText}")`);
|
|
||||||
await expect(roundHeader).toBeVisible({ timeout: 30000 });
|
|
||||||
console.log(`🌍 Verified round ${roundNumber} matchups are visible`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see {int} rounds', async function (expectedRounds: number) {
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(2000);
|
|
||||||
const roundHeaders = await world.page.locator('h3:has-text("Round")').count();
|
|
||||||
expect(roundHeaders).toBe(expectedRounds);
|
|
||||||
console.log(`🌍 Verified ${expectedRounds} rounds are visible`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('each team should play every other team exactly once', async function () {
|
|
||||||
const content = await world.page.content();
|
|
||||||
expect(content).toMatch(/schedule|round|matchup/i);
|
|
||||||
console.log('🌍 Verified schedule exists with matchups');
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I click on a matchup', async function () {
|
|
||||||
const matchup = world.page.locator('[data-testid="matchup"]').first();
|
|
||||||
await matchup.waitFor({ state: 'visible', timeout: 15000 });
|
|
||||||
|
|
||||||
const href = await matchup.getAttribute('href');
|
|
||||||
console.log(`🌍 Matchup link href: ${href}`);
|
|
||||||
|
|
||||||
if (href) {
|
|
||||||
await world.page.goto(`${world.baseURL}${href}`);
|
|
||||||
} else {
|
|
||||||
await matchup.click();
|
|
||||||
}
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
console.log(`🌍 Navigated to: ${world.page.url()}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should be on the match result entry page', async function () {
|
|
||||||
const currentUrl = world.page.url();
|
|
||||||
console.log(`🌍 Checking current URL: ${currentUrl}`);
|
|
||||||
expect(currentUrl).toMatch(/\/matches\/|\/admin\/tournaments\/\d+\/(entry|results)/);
|
|
||||||
});
|
|
||||||
|
|
||||||
// View As Role Steps
|
|
||||||
When('I view the navigation', async function () {
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(1000);
|
|
||||||
console.log('🌍 Viewing navigation');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see the role switcher dropdown', async function () {
|
|
||||||
const switcher = world.page.locator('[data-testid="role-switcher"]');
|
|
||||||
await expect(switcher).toBeVisible({ timeout: 5000 });
|
|
||||||
console.log('🌍 Verified role switcher dropdown is visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('the role switcher should default to {string}', async function (expectedText: string) {
|
|
||||||
const switcher = world.page.locator('[data-testid="role-switcher"]');
|
|
||||||
const selectedValue = await switcher.inputValue();
|
|
||||||
const selectedText = await switcher.locator('option:checked').textContent();
|
|
||||||
console.log(`🌍 Dropdown selected text: "${selectedText}", value: "${selectedValue}"`);
|
|
||||||
expect(selectedText?.trim()).toBe(expectedText);
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I select {string} from the role switcher', async function (optionText: string) {
|
|
||||||
const switcher = world.page.locator('[data-testid="role-switcher"]');
|
|
||||||
await switcher.selectOption({ label: optionText });
|
|
||||||
await world.page.waitForTimeout(500);
|
|
||||||
console.log(`🌍 Selected "${optionText}" from role switcher`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see the player navigation links', async function () {
|
|
||||||
await expect(world.page.locator('nav a:has-text("Rankings")')).toBeVisible();
|
|
||||||
await expect(world.page.locator('nav a:has-text("Tournaments")')).toBeVisible();
|
|
||||||
console.log('🌍 Verified player navigation links are visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should not see the {string} link', async function (linkText: string) {
|
|
||||||
const link = world.page.locator(`nav a:has-text("${linkText}")`);
|
|
||||||
await expect(link).not.toBeVisible({ timeout: 3000 });
|
|
||||||
console.log(`🌍 Verified "${linkText}" nav link is not visible`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see the {string} link', async function (linkText: string) {
|
|
||||||
const link = world.page.locator(`nav a:has-text("${linkText}")`);
|
|
||||||
await expect(link).toBeVisible({ timeout: 5000 });
|
|
||||||
console.log(`🌍 Verified "${linkText}" nav link is visible`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see a banner indicating I am viewing as {string}', async function (roleName: string) {
|
|
||||||
const banner = world.page.locator(`text=Viewing as ${roleName}`);
|
|
||||||
await expect(banner).toBeVisible({ timeout: 5000 });
|
|
||||||
console.log(`🌍 Verified viewing as ${roleName} banner is visible`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should not see the viewing as banner', async function () {
|
|
||||||
const banner = world.page.locator('[data-testid="reset-view-as"]');
|
|
||||||
await expect(banner).not.toBeVisible({ timeout: 3000 });
|
|
||||||
console.log('🌍 Verified viewing as banner is not visible');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Bracket Visualization Steps
|
|
||||||
When('I go to the tournament detail page', async function () {
|
|
||||||
const tournamentId = world.tournament?.id || 1;
|
|
||||||
await world.page.goto(`${world.baseURL}/admin/tournaments/${tournamentId}`);
|
|
||||||
await world.page.waitForLoadState('domcontentloaded');
|
|
||||||
await world.page.waitForTimeout(500);
|
|
||||||
console.log(`🌍 Navigated to tournament detail page: ${tournamentId}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
When('I click the {string} tab', async function (tabName: string) {
|
|
||||||
const tab = world.page.locator(`button:has-text("${tabName}")`);
|
|
||||||
await tab.click();
|
|
||||||
await world.page.waitForTimeout(500);
|
|
||||||
console.log(`🌍 Clicked "${tabName}" tab`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see bracket matchup cards', async function () {
|
|
||||||
const cards = world.page.locator('[data-testid="bracket-matchup"]');
|
|
||||||
const count = await cards.count();
|
|
||||||
expect(count).toBeGreaterThan(0);
|
|
||||||
console.log(`🌍 Found ${count} bracket matchup cards`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should see bracket matchup cards with team names', async function () {
|
|
||||||
const cards = world.page.locator('[data-testid="bracket-matchup"]');
|
|
||||||
const count = await cards.count();
|
|
||||||
expect(count).toBeGreaterThan(0);
|
|
||||||
|
|
||||||
const firstCard = cards.first();
|
|
||||||
const text = await firstCard.textContent();
|
|
||||||
expect(text).toBeTruthy();
|
|
||||||
expect(text!.length).toBeGreaterThan(2);
|
|
||||||
console.log(`🌍 Verified bracket matchup cards have team names`);
|
|
||||||
});
|
|
||||||
|
|
||||||
Then('I should not see the {string} tab', async function (tabName: string) {
|
|
||||||
const tab = world.page.locator(`button:has-text("${tabName}")`);
|
|
||||||
await expect(tab).not.toBeVisible({ timeout: 3000 });
|
|
||||||
console.log(`🌍 Verified "${tabName}" tab is not visible`);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
import { Given, After } from '@cucumber/cucumber';
|
|
||||||
import { world } from '../support/world';
|
|
||||||
|
|
||||||
Given('there are top players in the system', async function () {
|
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
const timestamp = Date.now();
|
|
||||||
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
await prisma.player.create({
|
|
||||||
data: {
|
|
||||||
name: `Home Test Player ${timestamp} ${i + 1}`,
|
|
||||||
normalizedName: `home_test_player_${timestamp}_${i + 1}`.toLowerCase(),
|
|
||||||
currentElo: 2000 - i * 10,
|
|
||||||
gamesPlayed: 10,
|
|
||||||
wins: 7,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Given('there is a club president', async function () {
|
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
const timestamp = Date.now();
|
|
||||||
|
|
||||||
await prisma.user.create({
|
|
||||||
data: {
|
|
||||||
email: `president-${timestamp}@example.com`,
|
|
||||||
name: `Club President ${timestamp}`,
|
|
||||||
role: 'club_admin',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
Given('there is a recent tournament', async function () {
|
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
const timestamp = Date.now();
|
|
||||||
|
|
||||||
const tournament = await prisma.event.create({
|
|
||||||
data: {
|
|
||||||
name: `Recent Tournament ${timestamp}`,
|
|
||||||
eventType: 'tournament',
|
|
||||||
eventDate: new Date(Date.now() + 86400000),
|
|
||||||
status: 'completed',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const p1 = await prisma.player.create({
|
|
||||||
data: { name: `HP1 ${timestamp}`, normalizedName: `hp1_${timestamp}`.toLowerCase(), currentElo: 1500 },
|
|
||||||
});
|
|
||||||
const p2 = await prisma.player.create({
|
|
||||||
data: { name: `HP2 ${timestamp}`, normalizedName: `hp2_${timestamp}`.toLowerCase(), currentElo: 1480 },
|
|
||||||
});
|
|
||||||
const p3 = await prisma.player.create({
|
|
||||||
data: { name: `HP3 ${timestamp}`, normalizedName: `hp3_${timestamp}`.toLowerCase(), currentElo: 1450 },
|
|
||||||
});
|
|
||||||
const p4 = await prisma.player.create({
|
|
||||||
data: { name: `HP4 ${timestamp}`, normalizedName: `hp4_${timestamp}`.toLowerCase(), currentElo: 1420 },
|
|
||||||
});
|
|
||||||
|
|
||||||
await prisma.match.create({
|
|
||||||
data: {
|
|
||||||
eventId: tournament.id,
|
|
||||||
player1P1Id: p1.id,
|
|
||||||
player1P2Id: p2.id,
|
|
||||||
player2P1Id: p3.id,
|
|
||||||
player2P2Id: p4.id,
|
|
||||||
team1Score: 10,
|
|
||||||
team2Score: 5,
|
|
||||||
status: 'completed',
|
|
||||||
playedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -14,17 +14,22 @@ setDefaultTimeout(30000);
|
|||||||
// Global browser instance
|
// Global browser instance
|
||||||
let browser: Browser;
|
let browser: Browser;
|
||||||
|
|
||||||
// Load environment file (gitignored, contains dev database URL)
|
// Load environment files
|
||||||
|
const envPath = path.resolve(process.cwd(), '.env');
|
||||||
const envDevPath = path.resolve(process.cwd(), '.env.development');
|
const envDevPath = path.resolve(process.cwd(), '.env.development');
|
||||||
|
|
||||||
|
if (fs.existsSync(envPath)) {
|
||||||
|
require('dotenv').config({ path: envPath });
|
||||||
|
}
|
||||||
|
|
||||||
if (fs.existsSync(envDevPath)) {
|
if (fs.existsSync(envDevPath)) {
|
||||||
require('dotenv').config({ path: envDevPath });
|
require('dotenv').config({ path: envDevPath, override: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Database safety check - prevent tests from running against production
|
// Database safety check - prevent tests from running against production
|
||||||
function isProductionDatabase(): boolean {
|
function isProductionDatabase(): boolean {
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev') && !dbUrl.includes('_ci') && !dbUrl.includes('test');
|
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev') && !dbUrl.includes('test');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isProductionDatabase()) {
|
if (isProductionDatabase()) {
|
||||||
@@ -111,92 +116,11 @@ Before(async function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* After each scenario: Close page and clean up test data
|
* After each scenario: Close page
|
||||||
*/
|
*/
|
||||||
After(async function () {
|
After(async function () {
|
||||||
console.log('🌍 Cleaning up after scenario...');
|
console.log('🌍 Cleaning up after scenario...');
|
||||||
|
|
||||||
// Clean up test data from dev database
|
|
||||||
try {
|
|
||||||
const prisma = await world.getPrisma();
|
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
|
||||||
|
|
||||||
// Safety check: only clean up dev/test databases
|
|
||||||
if (dbUrl.includes('_dev') || dbUrl.includes('test') || dbUrl.includes('ci')) {
|
|
||||||
// Use Prisma API for cleanup instead of raw SQL to avoid column name issues
|
|
||||||
|
|
||||||
// Find test tournaments first
|
|
||||||
const testTournaments = await prisma.event.findMany({
|
|
||||||
where: {
|
|
||||||
OR: [
|
|
||||||
{ name: { startsWith: 'Test Tournament' } },
|
|
||||||
{ name: { startsWith: 'Test Schedule Tournament' } },
|
|
||||||
{ name: { startsWith: 'Recent Tournament' } },
|
|
||||||
]
|
|
||||||
},
|
|
||||||
select: { id: true }
|
|
||||||
});
|
|
||||||
|
|
||||||
const tournamentIds = testTournaments.map((t: { id: number }) => t.id);
|
|
||||||
|
|
||||||
if (tournamentIds.length > 0) {
|
|
||||||
// Delete bracket matchups via Prisma
|
|
||||||
await prisma.bracketMatchup.deleteMany({
|
|
||||||
where: {
|
|
||||||
round: {
|
|
||||||
eventId: { in: tournamentIds }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Delete rounds
|
|
||||||
await prisma.tournamentRound.deleteMany({
|
|
||||||
where: { eventId: { in: tournamentIds } }
|
|
||||||
});
|
|
||||||
|
|
||||||
// Delete event participants
|
|
||||||
await prisma.eventParticipant.deleteMany({
|
|
||||||
where: { eventId: { in: tournamentIds } }
|
|
||||||
});
|
|
||||||
|
|
||||||
// Delete tournaments
|
|
||||||
await prisma.event.deleteMany({
|
|
||||||
where: { id: { in: tournamentIds } }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete test players
|
|
||||||
await prisma.player.deleteMany({
|
|
||||||
where: {
|
|
||||||
OR: [
|
|
||||||
{ name: { startsWith: 'Tournament Player' } },
|
|
||||||
{ name: { startsWith: 'Schedule Player' } },
|
|
||||||
{ name: { startsWith: 'Test Player' } },
|
|
||||||
{ name: { startsWith: 'Test Activity Player' } },
|
|
||||||
{ name: { startsWith: 'Home Test Player' } },
|
|
||||||
{ name: { startsWith: 'HP' } },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Delete test users
|
|
||||||
await prisma.user.deleteMany({
|
|
||||||
where: {
|
|
||||||
OR: [
|
|
||||||
{ email: { startsWith: 'cucumber-' } },
|
|
||||||
{ email: { startsWith: 'president-' } },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('🌍 Test data cleaned up from dev database');
|
|
||||||
} else {
|
|
||||||
console.log('🌍 Skipping database cleanup (not a dev/test database)');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.log('🌍 Database cleanup error (non-critical):', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close page and context
|
// Close page and context
|
||||||
if (world.page) {
|
if (world.page) {
|
||||||
await world.page.close();
|
await world.page.close();
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ export interface WorldState {
|
|||||||
prisma: any; // Lazy-loaded PrismaClient
|
prisma: any; // Lazy-loaded PrismaClient
|
||||||
baseURL: string;
|
baseURL: string;
|
||||||
user?: {
|
user?: {
|
||||||
id?: string;
|
|
||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
password: string;
|
password: string;
|
||||||
@@ -33,7 +32,6 @@ export class World implements WorldState {
|
|||||||
prisma: any;
|
prisma: any;
|
||||||
baseURL: string;
|
baseURL: string;
|
||||||
user?: {
|
user?: {
|
||||||
id?: string;
|
|
||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
password: string;
|
password: string;
|
||||||
@@ -62,11 +60,14 @@ export class World implements WorldState {
|
|||||||
if (!process.env.DATABASE_URL) {
|
if (!process.env.DATABASE_URL) {
|
||||||
throw new Error('DATABASE_URL not set. Make sure .env.development exists and contains DATABASE_URL or set DATABASE_URL environment variable.');
|
throw new Error('DATABASE_URL not set. Make sure .env.development exists and contains DATABASE_URL or set DATABASE_URL environment variable.');
|
||||||
}
|
}
|
||||||
|
process.env.DATABASE_PROVIDER = process.env.DATABASE_PROVIDER || 'postgresql';
|
||||||
|
|
||||||
// Use the shared prisma instance from the app's lib
|
// Import PrismaClient AFTER setting environment variables
|
||||||
// This handles the adapter setup correctly
|
const { PrismaClient } = await import('@prisma/client');
|
||||||
const { prisma } = require('@/lib/prisma');
|
const { PrismaPg } = await import('@prisma/adapter-pg');
|
||||||
this.prisma = prisma;
|
|
||||||
|
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
||||||
|
this.prisma = new PrismaClient({ adapter });
|
||||||
}
|
}
|
||||||
return this.prisma;
|
return this.prisma;
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-63
@@ -10,87 +10,74 @@ import fs from 'fs';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
|
|
||||||
test.describe.skip('Elo Rating Updates', () => {
|
test.describe('Elo Rating Updates', () => {
|
||||||
test.beforeAll(async () => {
|
test.beforeAll(async () => {
|
||||||
// Clean up any existing test data
|
// Clean up any existing test data
|
||||||
const playerIds = await getEloTestPlayerIds();
|
|
||||||
|
|
||||||
// First delete matches that reference players
|
// First delete matches that reference players
|
||||||
await prisma.match.deleteMany({
|
await prisma.match.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
OR: [
|
OR: [
|
||||||
{ player1P1Id: { in: playerIds } },
|
{ player1P1Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player1P2Id: { in: playerIds } },
|
{ player1P2Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player2P1Id: { in: playerIds } },
|
{ player2P1Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player2P2Id: { in: playerIds } },
|
{ player2P2Id: { in: await getEloTestPlayerIds() } },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Then delete partnerships that reference players
|
// Then delete partnerships
|
||||||
await prisma.partnershipStat.deleteMany({
|
await prisma.partnershipStat.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
OR: [
|
OR: [
|
||||||
{ player1Id: { in: playerIds } },
|
{ player1Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player2Id: { in: playerIds } },
|
{ player2Id: { in: await getEloTestPlayerIds() } },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Then delete event participants that reference players
|
|
||||||
await prisma.eventParticipant.deleteMany({
|
|
||||||
where: {
|
|
||||||
playerId: { in: playerIds }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Finally delete players
|
// Finally delete players
|
||||||
await prisma.player.deleteMany({
|
await prisma.player.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
id: { in: playerIds }
|
name: {
|
||||||
|
startsWith: 'Elo Test'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test.afterAll(async () => {
|
test.afterAll(async () => {
|
||||||
// Clean up test data
|
// Clean up test data
|
||||||
const playerIds = await getEloTestPlayerIds();
|
|
||||||
|
|
||||||
// First delete matches that reference players
|
// First delete matches that reference players
|
||||||
await prisma.match.deleteMany({
|
await prisma.match.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
OR: [
|
OR: [
|
||||||
{ player1P1Id: { in: playerIds } },
|
{ player1P1Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player1P2Id: { in: playerIds } },
|
{ player1P2Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player2P1Id: { in: playerIds } },
|
{ player2P1Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player2P2Id: { in: playerIds } },
|
{ player2P2Id: { in: await getEloTestPlayerIds() } },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Then delete partnerships that reference players
|
// Then delete partnerships
|
||||||
await prisma.partnershipStat.deleteMany({
|
await prisma.partnershipStat.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
OR: [
|
OR: [
|
||||||
{ player1Id: { in: playerIds } },
|
{ player1Id: { in: await getEloTestPlayerIds() } },
|
||||||
{ player2Id: { in: playerIds } },
|
{ player2Id: { in: await getEloTestPlayerIds() } },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Then delete event participants that reference players
|
|
||||||
await prisma.eventParticipant.deleteMany({
|
|
||||||
where: {
|
|
||||||
playerId: { in: playerIds }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Finally delete players
|
// Finally delete players
|
||||||
await prisma.player.deleteMany({
|
await prisma.player.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
id: { in: playerIds }
|
name: {
|
||||||
|
startsWith: 'Elo Test'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
await prisma.$disconnect();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function getEloTestPlayerIds(): Promise<number[]> {
|
async function getEloTestPlayerIds(): Promise<number[]> {
|
||||||
@@ -107,11 +94,10 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
|
|
||||||
test('Elo rating updates after match upload', async ({ page }) => {
|
test('Elo rating updates after match upload', async ({ page }) => {
|
||||||
// Step 1: Create test players with known initial ratings
|
// Step 1: Create test players with known initial ratings
|
||||||
const ts = Date.now();
|
|
||||||
const player1 = await prisma.player.create({
|
const player1 = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: `Elo Test Player 1 ${ts}`,
|
name: 'Elo Test Player 1',
|
||||||
normalizedName: `elo_test_player_1_${ts}`,
|
normalizedName: 'elo test player 1',
|
||||||
currentElo: 1500,
|
currentElo: 1500,
|
||||||
gamesPlayed: 0,
|
gamesPlayed: 0,
|
||||||
wins: 0,
|
wins: 0,
|
||||||
@@ -121,8 +107,8 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
|
|
||||||
const player2 = await prisma.player.create({
|
const player2 = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: `Elo Test Player 2 ${ts}`,
|
name: 'Elo Test Player 2',
|
||||||
normalizedName: `elo_test_player_2_${ts}`,
|
normalizedName: 'elo test player 2',
|
||||||
currentElo: 1500,
|
currentElo: 1500,
|
||||||
gamesPlayed: 0,
|
gamesPlayed: 0,
|
||||||
wins: 0,
|
wins: 0,
|
||||||
@@ -132,8 +118,8 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
|
|
||||||
const player3 = await prisma.player.create({
|
const player3 = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: `Elo Test Player 3 ${ts}`,
|
name: 'Elo Test Player 3',
|
||||||
normalizedName: `elo_test_player_3_${ts}`,
|
normalizedName: 'elo test player 3',
|
||||||
currentElo: 1500,
|
currentElo: 1500,
|
||||||
gamesPlayed: 0,
|
gamesPlayed: 0,
|
||||||
wins: 0,
|
wins: 0,
|
||||||
@@ -143,8 +129,8 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
|
|
||||||
const player4 = await prisma.player.create({
|
const player4 = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: `Elo Test Player 4 ${ts}`,
|
name: 'Elo Test Player 4',
|
||||||
normalizedName: `elo_test_player_4_${ts}`,
|
normalizedName: 'elo test player 4',
|
||||||
currentElo: 1500,
|
currentElo: 1500,
|
||||||
gamesPlayed: 0,
|
gamesPlayed: 0,
|
||||||
wins: 0,
|
wins: 0,
|
||||||
@@ -205,7 +191,7 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Check if we're logged in
|
// Check if we're logged in
|
||||||
const content = await page.content();
|
const content = await page.content();
|
||||||
@@ -225,19 +211,19 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
console.log('Logging out and logging in as admin...');
|
console.log('Logging out and logging in as admin...');
|
||||||
await page.click('button:has-text("Sign out")');
|
await page.click('button:has-text("Sign out")');
|
||||||
await page.waitForURL('/auth/login');
|
await page.waitForURL('/auth/login');
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isLoggedIn || page.url().includes('/players/')) {
|
if (!isLoggedIn || page.url().includes('/players/')) {
|
||||||
// If not logged in or logged in as regular user, log in as admin
|
// If not logged in or logged in as regular user, log in as admin
|
||||||
console.log('Logging in as admin...');
|
console.log('Logging in as admin...');
|
||||||
await page.goto('/auth/login');
|
await page.goto('/auth/login');
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.fill('input[name="email"]', adminEmail);
|
await page.fill('input[name="email"]', adminEmail);
|
||||||
await page.fill('input[name="password"]', adminPassword);
|
await page.fill('input[name="password"]', adminPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify tournament ownership
|
// Verify tournament ownership
|
||||||
@@ -252,14 +238,14 @@ test.describe.skip('Elo Rating Updates', () => {
|
|||||||
await page.goto('/admin/matches/upload');
|
await page.goto('/admin/matches/upload');
|
||||||
|
|
||||||
// Wait for page to load and tournaments to be fetched
|
// Wait for page to load and tournaments to be fetched
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Wait for tournament dropdown to be ready
|
// Wait for tournament dropdown to be ready
|
||||||
await page.waitForSelector('select#tournament', { timeout: 3000 });
|
await page.waitForSelector('select#tournament', { timeout: 5000 });
|
||||||
|
|
||||||
// Wait a bit for tournaments to load
|
// Wait a bit for tournaments to load
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Select the tournament manually
|
// Select the tournament manually
|
||||||
const tournamentSelect = await page.locator('select#tournament');
|
const tournamentSelect = await page.locator('select#tournament');
|
||||||
@@ -315,7 +301,7 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
|
|||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// Wait for upload to complete
|
// Wait for upload to complete
|
||||||
await page.waitForTimeout(1000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
// Check for any error messages
|
// Check for any error messages
|
||||||
const uploadContentAfter = await page.content();
|
const uploadContentAfter = await page.content();
|
||||||
@@ -327,12 +313,12 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
|
|||||||
|
|
||||||
// Navigate back to upload page for second match
|
// Navigate back to upload page for second match
|
||||||
await page.goto('/admin/matches/upload');
|
await page.goto('/admin/matches/upload');
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Re-select the tournament for the second upload
|
// Re-select the tournament for the second upload
|
||||||
await page.waitForSelector('select#tournament', { timeout: 3000 });
|
await page.waitForSelector('select#tournament', { timeout: 5000 });
|
||||||
await page.waitForTimeout(200); // Wait for tournaments to load
|
await page.waitForTimeout(1000); // Wait for tournaments to load
|
||||||
|
|
||||||
const tournamentSelect2 = await page.locator('select#tournament');
|
const tournamentSelect2 = await page.locator('select#tournament');
|
||||||
const currentSelection = await tournamentSelect2.inputValue();
|
const currentSelection = await tournamentSelect2.inputValue();
|
||||||
@@ -351,10 +337,10 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
|
|||||||
await page.setInputFiles('input[type="file"]', tmpFile2);
|
await page.setInputFiles('input[type="file"]', tmpFile2);
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(500);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(2000);
|
||||||
fs.unlinkSync(tmpFile2);
|
fs.unlinkSync(tmpFile2);
|
||||||
|
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Verify ratings after multiple matches
|
// Verify ratings after multiple matches
|
||||||
const updatedPlayer1 = await prisma.player.findUnique({
|
const updatedPlayer1 = await prisma.player.findUnique({
|
||||||
@@ -383,11 +369,10 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
|
|||||||
|
|
||||||
test('Elo ratings are visible on player profile', async ({ page }) => {
|
test('Elo ratings are visible on player profile', async ({ page }) => {
|
||||||
// Create a test player
|
// Create a test player
|
||||||
const ts = Date.now();
|
|
||||||
const player = await prisma.player.create({
|
const player = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: `Elo Test Profile Player ${ts}`,
|
name: 'Elo Test Profile Player',
|
||||||
normalizedName: `elo_test_profile_player_${ts}`,
|
normalizedName: 'elo test profile player',
|
||||||
currentElo: 1750,
|
currentElo: 1750,
|
||||||
gamesPlayed: 50,
|
gamesPlayed: 50,
|
||||||
wins: 30,
|
wins: 30,
|
||||||
@@ -399,7 +384,7 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
|
|||||||
await page.goto(`/players/${player.id}/profile`);
|
await page.goto(`/players/${player.id}/profile`);
|
||||||
|
|
||||||
// Wait for page to load
|
// Wait for page to load
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Verify rating is displayed (from player.currentElo)
|
// Verify rating is displayed (from player.currentElo)
|
||||||
await expect(page.locator('text=1750')).toBeVisible();
|
await expect(page.locator('text=1750')).toBeVisible();
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
|
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
|
|
||||||
function getTestCredentials() {
|
function getTestCredentials() {
|
||||||
@@ -36,11 +35,11 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
testName = credentials.name;
|
testName = credentials.name;
|
||||||
|
|
||||||
// Create test user via API with proper origin header
|
// Create test user via API with proper origin header
|
||||||
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
|
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Origin': BASE_URL,
|
'Origin': 'http://localhost:3000',
|
||||||
'X-Requested-With': 'XMLHttpRequest'
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -93,10 +92,10 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
|
|
||||||
test('Logout button appears in navigation when logged in', async ({ page }) => {
|
test('Logout button appears in navigation when logged in', async ({ page }) => {
|
||||||
// Login first
|
// Login first
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
|
|
||||||
// Wait for page to load
|
// Wait for JavaScript to be ready
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForSelector('form');
|
await page.waitForSelector('form');
|
||||||
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
||||||
|
|
||||||
@@ -130,10 +129,10 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
// Navigate to home page to check navigation (session should persist)
|
// Navigate to home page to check navigation (session should persist)
|
||||||
// Use reload to ensure session is read from cookies
|
// Use reload to ensure session is read from cookies
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Wait a moment for the navigation component to update
|
// Wait a moment for the navigation component to update
|
||||||
await page.waitForTimeout(200);
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
// Debug: Check what's on the page
|
// Debug: Check what's on the page
|
||||||
const pageContent = await page.content();
|
const pageContent = await page.content();
|
||||||
@@ -157,7 +156,7 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
|
|
||||||
test('Logout clears session and redirects to home', async ({ page }) => {
|
test('Logout clears session and redirects to home', async ({ page }) => {
|
||||||
// Login first
|
// Login first
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
@@ -167,7 +166,7 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
|
|
||||||
// Navigate to home using reload to ensure session is loaded
|
// Navigate to home using reload to ensure session is loaded
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Wait for logout button to appear
|
// Wait for logout button to appear
|
||||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||||
@@ -181,7 +180,7 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
|
|
||||||
test('After logout, protected pages redirect to login', async ({ page }) => {
|
test('After logout, protected pages redirect to login', async ({ page }) => {
|
||||||
// Login first
|
// Login first
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
@@ -191,7 +190,7 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
|
|
||||||
// Navigate to home using reload to ensure session is loaded
|
// Navigate to home using reload to ensure session is loaded
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Wait for logout button to appear
|
// Wait for logout button to appear
|
||||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||||
@@ -201,7 +200,7 @@ test.describe.serial('Epic 1: User Logout', () => {
|
|||||||
await page.waitForURL('**/auth/login**', { timeout: 10000 });
|
await page.waitForURL('**/auth/login**', { timeout: 10000 });
|
||||||
|
|
||||||
// Try to access admin page
|
// Try to access admin page
|
||||||
await page.goto('/admin');
|
await page.goto('http://localhost:3000/admin');
|
||||||
|
|
||||||
// Should redirect to login
|
// Should redirect to login
|
||||||
await expect(page).toHaveURL(/.*auth\/login.*/);
|
await expect(page).toHaveURL(/.*auth\/login.*/);
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import { test, expect } from '@playwright/test';
|
|||||||
|
|
||||||
test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => {
|
test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => {
|
||||||
test('Forgot password link exists on login page', async ({ page }) => {
|
test('Forgot password link exists on login page', async ({ page }) => {
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
|
|
||||||
// Check for forgot password link
|
// Check for forgot password link
|
||||||
await expect(page.locator('a[href*="password-reset"]')).toBeVisible();
|
await expect(page.locator('a[href*="password-reset"]')).toBeVisible();
|
||||||
@@ -29,7 +29,7 @@ test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => {
|
|||||||
test('Password reset page exists but is not functional', async ({ page }) => {
|
test('Password reset page exists but is not functional', async ({ page }) => {
|
||||||
// Note: The link exists but the page may not be implemented
|
// Note: The link exists but the page may not be implemented
|
||||||
// This test documents the current state
|
// This test documents the current state
|
||||||
await page.goto('/auth/password-reset');
|
await page.goto('http://localhost:3000/auth/password-reset');
|
||||||
|
|
||||||
// Check if page loads (may show "not implemented" message)
|
// Check if page loads (may show "not implemented" message)
|
||||||
await expect(page.locator('body')).toBeVisible();
|
await expect(page.locator('body')).toBeVisible();
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ test.describe.serial('Epic 1: User Registration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('Registration page exists and loads', async ({ page }) => {
|
test('Registration page exists and loads', async ({ page }) => {
|
||||||
await page.goto('/auth/register');
|
await page.goto('http://localhost:3000/auth/register');
|
||||||
|
|
||||||
// Check for registration form elements
|
// Check for registration form elements
|
||||||
await expect(page.locator('input[name="name"]')).toBeVisible();
|
await expect(page.locator('input[name="name"]')).toBeVisible();
|
||||||
@@ -61,10 +61,10 @@ test.describe.serial('Epic 1: User Registration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('Registration with valid data creates account', async ({ page }) => {
|
test('Registration with valid data creates account', async ({ page }) => {
|
||||||
await page.goto('/auth/register');
|
await page.goto('http://localhost:3000/auth/register');
|
||||||
|
|
||||||
// Wait for page to load
|
// Wait for JavaScript to be ready
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForSelector('form');
|
await page.waitForSelector('form');
|
||||||
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ test.describe.serial('Epic 1: User Registration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Wait a moment for JavaScript to be ready
|
// Wait a moment for JavaScript to be ready
|
||||||
await page.waitForTimeout(200);
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
// Submit form
|
// Submit form
|
||||||
const [response] = await Promise.all([
|
const [response] = await Promise.all([
|
||||||
@@ -122,7 +122,7 @@ test.describe.serial('Epic 1: User Registration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('Registration with duplicate email fails', async ({ page }) => {
|
test('Registration with duplicate email fails', async ({ page }) => {
|
||||||
await page.goto('/auth/register');
|
await page.goto('http://localhost:3000/auth/register');
|
||||||
|
|
||||||
// Fill registration form with existing email
|
// Fill registration form with existing email
|
||||||
await page.fill('input[name="name"]', testName);
|
await page.fill('input[name="name"]', testName);
|
||||||
@@ -147,7 +147,7 @@ test.describe.serial('Epic 1: User Registration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('Registration with weak password fails', async ({ page }) => {
|
test('Registration with weak password fails', async ({ page }) => {
|
||||||
await page.goto('/auth/register');
|
await page.goto('http://localhost:3000/auth/register');
|
||||||
|
|
||||||
// Fill registration form with weak password
|
// Fill registration form with weak password
|
||||||
await page.fill('input[name="name"]', testName);
|
await page.fill('input[name="name"]', testName);
|
||||||
@@ -162,7 +162,7 @@ test.describe.serial('Epic 1: User Registration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('Auto-created player profile is linked to user', async ({ page }) => {
|
test('Auto-created player profile is linked to user', async ({ page }) => {
|
||||||
await page.goto('/auth/register');
|
await page.goto('http://localhost:3000/auth/register');
|
||||||
|
|
||||||
const profileEmail = `profile-${Date.now()}@example.com`;
|
const profileEmail = `profile-${Date.now()}@example.com`;
|
||||||
const profileName = 'Profile Test User';
|
const profileName = 'Profile Test User';
|
||||||
|
|||||||
@@ -15,17 +15,17 @@ import { test, expect } from '@playwright/test';
|
|||||||
|
|
||||||
test.describe('Epic 3: Rankings Page', () => {
|
test.describe('Epic 3: Rankings Page', () => {
|
||||||
test('Rankings page loads and displays rankings table', async ({ page }) => {
|
test('Rankings page loads and displays rankings table', async ({ page }) => {
|
||||||
await page.goto('/rankings');
|
await page.goto('http://localhost:3000/rankings');
|
||||||
|
|
||||||
// Check page title or heading - use .first() since page may have both h1 and h2
|
// Check page title or heading
|
||||||
await expect(page.locator('h1, h2').first()).toContainText(/rankings?/i);
|
await expect(page.locator('h1, h2')).toContainText(/rankings?/i);
|
||||||
|
|
||||||
// Check for rankings table
|
// Check for rankings table
|
||||||
await expect(page.locator('table')).toBeVisible();
|
await expect(page.locator('table')).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Rankings table displays player columns', async ({ page }) => {
|
test('Rankings table displays player columns', async ({ page }) => {
|
||||||
await page.goto('/rankings');
|
await page.goto('http://localhost:3000/rankings');
|
||||||
|
|
||||||
// Check for expected column headers
|
// Check for expected column headers
|
||||||
const table = page.locator('table');
|
const table = page.locator('table');
|
||||||
@@ -38,7 +38,7 @@ test.describe('Epic 3: Rankings Page', () => {
|
|||||||
|
|
||||||
test('Rankings page is publicly accessible (no login required)', async ({ page }) => {
|
test('Rankings page is publicly accessible (no login required)', async ({ page }) => {
|
||||||
// Navigate directly to rankings without logging in
|
// Navigate directly to rankings without logging in
|
||||||
await page.goto('/rankings');
|
await page.goto('http://localhost:3000/rankings');
|
||||||
|
|
||||||
// Page should load without redirecting to login
|
// Page should load without redirecting to login
|
||||||
await expect(page).toHaveURL(/.*rankings.*/);
|
await expect(page).toHaveURL(/.*rankings.*/);
|
||||||
|
|||||||
@@ -13,7 +13,6 @@
|
|||||||
|
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
|
|
||||||
function getTestCredentials() {
|
function getTestCredentials() {
|
||||||
@@ -25,7 +24,7 @@ function getTestCredentials() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
test.describe.skip('Epic 4: Tournament Creation', () => {
|
test.describe.serial('Epic 4: Tournament Creation', () => {
|
||||||
let testEmail: string;
|
let testEmail: string;
|
||||||
let testPassword: string;
|
let testPassword: string;
|
||||||
let testName: string;
|
let testName: string;
|
||||||
@@ -37,11 +36,11 @@ test.describe.skip('Epic 4: Tournament Creation', () => {
|
|||||||
testName = credentials.name;
|
testName = credentials.name;
|
||||||
|
|
||||||
// Create admin user via API
|
// Create admin user via API
|
||||||
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
|
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Origin': BASE_URL
|
'Origin': 'http://localhost:3000'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
email: testEmail,
|
email: testEmail,
|
||||||
@@ -83,16 +82,16 @@ test.describe.skip('Epic 4: Tournament Creation', () => {
|
|||||||
|
|
||||||
test('Tournament creation page exists and loads', async ({ page }) => {
|
test('Tournament creation page exists and loads', async ({ page }) => {
|
||||||
// Login first
|
// Login first
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// Wait for redirect to admin or player profile (indicates successful login)
|
// Wait for redirect to admin or player profile (indicates successful login)
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to new tournament page
|
// Navigate to new tournament page
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Check for form
|
// Check for form
|
||||||
await expect(page.locator('form')).toBeVisible();
|
await expect(page.locator('form')).toBeVisible();
|
||||||
@@ -100,44 +99,34 @@ test.describe.skip('Epic 4: Tournament Creation', () => {
|
|||||||
|
|
||||||
test('Tournament form has required fields', async ({ page }) => {
|
test('Tournament form has required fields', async ({ page }) => {
|
||||||
// Login first
|
// Login first
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// Wait for redirect to admin or player profile (indicates successful login)
|
// Wait for redirect to admin or player profile (indicates successful login)
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Wait for step 1 form to load
|
// Check for required fields
|
||||||
await page.waitForSelector('input[name="name"]', { timeout: 5000 });
|
|
||||||
|
|
||||||
// Check for required fields on Step 1
|
|
||||||
await expect(page.locator('input[name="name"]')).toBeVisible();
|
await expect(page.locator('input[name="name"]')).toBeVisible();
|
||||||
await expect(page.locator('select[name="format"]')).toBeVisible();
|
await expect(page.locator('select[name="format"]')).toBeVisible();
|
||||||
|
|
||||||
// Fill in the required name field first so Next actually advances
|
|
||||||
await page.fill('input[name="name"]', 'Test Tournament');
|
|
||||||
|
|
||||||
// Step through to Step 2 to check for submit button (only appears after clicking Next)
|
|
||||||
await page.click('button:has-text("Next")');
|
|
||||||
await page.waitForSelector('button[type="submit"]', { timeout: 5000 });
|
|
||||||
await expect(page.locator('button[type="submit"]')).toBeVisible();
|
await expect(page.locator('button[type="submit"]')).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Create tournament with valid data', async ({ page }) => {
|
test('Create tournament with valid data', async ({ page }) => {
|
||||||
// Login first
|
// Login first
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// Wait for redirect to admin or player profile (indicates successful login)
|
// Wait for redirect to admin or player profile (indicates successful login)
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to new tournament page
|
// Navigate to new tournament page
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
const tournamentName = `Test Tournament ${Date.now()}`;
|
const tournamentName = `Test Tournament ${Date.now()}`;
|
||||||
|
|
||||||
|
|||||||
+87
-65
@@ -4,28 +4,40 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { chromium, type FullConfig } from '@playwright/test';
|
import { chromium, type FullConfig } from '@playwright/test';
|
||||||
import { PrismaClient } from '@prisma/client';
|
import { prisma } from '@/lib/prisma';
|
||||||
import { PrismaPg } from '@prisma/adapter-pg';
|
import { cleanupAllTestData } from '@/__tests__/test-utils';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
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';
|
||||||
|
|
||||||
function isDatabase(url: string, name: string): boolean {
|
// Check if we're using the dev database
|
||||||
return url.includes(name);
|
function isDevDatabase(): boolean {
|
||||||
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
|
return dbUrl.includes('euchre_camp_dev');
|
||||||
}
|
}
|
||||||
|
|
||||||
function isProductionDatabase(): boolean {
|
function isProductionDatabase(): boolean {
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
return isDatabase(dbUrl, 'euchre_camp') && !isDatabase(dbUrl, '_dev') && !isDatabase(dbUrl, '_ci');
|
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev');
|
||||||
}
|
|
||||||
|
|
||||||
function isCIDatabase(): boolean {
|
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
|
||||||
return isDatabase(dbUrl, '_ci');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Strict check - fail if using production database
|
||||||
if (isProductionDatabase()) {
|
if (isProductionDatabase()) {
|
||||||
console.error('');
|
console.error('');
|
||||||
console.error('='.repeat(80));
|
console.error('='.repeat(80));
|
||||||
@@ -34,116 +46,121 @@ if (isProductionDatabase()) {
|
|||||||
console.error('');
|
console.error('');
|
||||||
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
|
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||||
console.error('');
|
console.error('');
|
||||||
console.error('Tests MUST run against development (euchre_camp_dev) or CI (euchre_camp_ci)');
|
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('');
|
||||||
console.error('Aborting test execution to prevent data corruption.');
|
console.error('Aborting test execution to prevent data corruption.');
|
||||||
console.error('');
|
console.error('');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createPrismaClient() {
|
if (!isDevDatabase()) {
|
||||||
const databaseUrl = process.env.DATABASE_URL;
|
console.warn('⚠️ WARNING: DATABASE_URL does not contain euchre_camp_dev');
|
||||||
if (!databaseUrl) throw new Error('DATABASE_URL is required');
|
console.warn(' Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||||
const adapter = new PrismaPg({ connectionString: databaseUrl });
|
|
||||||
return new PrismaClient({ adapter });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resetDatabaseSchema(prisma: PrismaClient) {
|
export default async function globalSetup(config: FullConfig) {
|
||||||
console.log('Resetting database schema...');
|
|
||||||
|
|
||||||
const tables = await prisma.$queryRaw<{ tablename: string }[]>`
|
|
||||||
SELECT tablename FROM pg_tables
|
|
||||||
WHERE schemaname = 'public' AND tablename NOT LIKE '_prisma_migrations'
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (tables.length > 0) {
|
|
||||||
await prisma.$executeRawUnsafe(`
|
|
||||||
DROP SCHEMA public CASCADE;
|
|
||||||
CREATE SCHEMA public;
|
|
||||||
`);
|
|
||||||
console.log(`Dropped ${tables.length} tables`);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Running migrations...');
|
|
||||||
const { execSync } = await import('child_process');
|
|
||||||
execSync('bunx prisma migrate deploy', { stdio: 'inherit' });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function createTestUsers(config: FullConfig) {
|
|
||||||
const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000';
|
const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000';
|
||||||
|
|
||||||
const browser = await chromium.launch();
|
const browser = await chromium.launch();
|
||||||
const context = await browser.newContext();
|
const context = await browser.newContext();
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
|
|
||||||
|
// Log all responses for debugging
|
||||||
page.on('response', response => {
|
page.on('response', response => {
|
||||||
if (response.url().includes('/api/auth')) {
|
if (response.url().includes('/api/auth')) {
|
||||||
console.log('API Response:', response.status(), response.url());
|
console.log('API Response:', response.status(), response.url());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Generate unique test credentials
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const testEmail = `setup-user-${timestamp}@example.com`;
|
const testEmail = `setup-user-${timestamp}@example.com`;
|
||||||
const testPassword = 'TestPassword1234!';
|
const testPassword = 'TestPassword1234!';
|
||||||
const testName = 'Setup User';
|
const testName = 'Setup User';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Navigate to registration page
|
||||||
console.log('Navigating to registration page...');
|
console.log('Navigating to registration page...');
|
||||||
await page.goto(`${baseURL}/auth/register`);
|
await page.goto(`${baseURL}/auth/register`);
|
||||||
|
|
||||||
|
// Fill in registration form
|
||||||
await page.fill('input[name="name"]', testName);
|
await page.fill('input[name="name"]', testName);
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
|
|
||||||
|
// Submit the form
|
||||||
console.log('Submitting registration form...');
|
console.log('Submitting registration form...');
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
try {
|
// Wait for the sign-up API call to complete
|
||||||
|
console.log('Waiting for sign-up API call...');
|
||||||
|
try {
|
||||||
await page.waitForResponse(response =>
|
await page.waitForResponse(response =>
|
||||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||||
{ timeout: 5000 }
|
{ timeout: 10000 }
|
||||||
);
|
);
|
||||||
console.log('Sign-up API call successful');
|
console.log('Sign-up API call successful');
|
||||||
} catch {
|
} catch {
|
||||||
console.log('Sign-up API call failed or timed out');
|
console.log('Sign-up API call failed or timed out');
|
||||||
}
|
}
|
||||||
|
|
||||||
await page.waitForTimeout(500);
|
// Wait a bit for session to be established
|
||||||
|
console.log('Waiting for session establishment...');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// Check if we're already authenticated
|
||||||
|
const currentUrl = page.url();
|
||||||
|
console.log('Current URL after registration:', currentUrl);
|
||||||
|
|
||||||
|
// Save the authentication state
|
||||||
await context.storageState({ path: authFile });
|
await context.storageState({ path: authFile });
|
||||||
|
|
||||||
console.log(`Created and authenticated test user: ${testEmail}`);
|
console.log(`Created and authenticated test user: ${testEmail}`);
|
||||||
|
|
||||||
// Clear session so admin registration doesn't get redirected
|
// Now create admin user
|
||||||
await context.clearCookies();
|
|
||||||
|
|
||||||
const adminTimestamp = timestamp + 1;
|
const adminTimestamp = timestamp + 1;
|
||||||
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
||||||
const adminPassword = 'AdminPassword123!';
|
const adminPassword = 'AdminPassword123!';
|
||||||
const adminName = 'Setup Admin';
|
const adminName = 'Setup Admin';
|
||||||
|
|
||||||
|
// Navigate to registration page again
|
||||||
console.log('Navigating to registration page for admin...');
|
console.log('Navigating to registration page for admin...');
|
||||||
await page.goto(`${baseURL}/auth/register`);
|
await page.goto(`${baseURL}/auth/register`);
|
||||||
|
|
||||||
|
// Fill in registration form
|
||||||
await page.fill('input[name="name"]', adminName);
|
await page.fill('input[name="name"]', adminName);
|
||||||
await page.fill('input[name="email"]', adminEmail);
|
await page.fill('input[name="email"]', adminEmail);
|
||||||
await page.fill('input[name="password"]', adminPassword);
|
await page.fill('input[name="password"]', adminPassword);
|
||||||
|
|
||||||
|
// Submit the form
|
||||||
console.log('Submitting admin registration form...');
|
console.log('Submitting admin registration form...');
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
|
// Wait for the sign-up API call to complete
|
||||||
|
console.log('Waiting for admin sign-up API call...');
|
||||||
try {
|
try {
|
||||||
await page.waitForResponse(response =>
|
await page.waitForResponse(response =>
|
||||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||||
{ timeout: 5000 }
|
{ timeout: 10000 }
|
||||||
);
|
);
|
||||||
console.log('Admin sign-up API call successful');
|
console.log('Admin sign-up API call successful');
|
||||||
} catch {
|
} catch {
|
||||||
console.log('Admin sign-up API call failed or timed out');
|
console.log('Admin sign-up API call failed or timed out');
|
||||||
}
|
}
|
||||||
|
|
||||||
await page.waitForTimeout(500);
|
// Wait a bit for session to be established
|
||||||
|
console.log('Waiting for admin session establishment...');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
const prisma = createPrismaClient();
|
// Update user role to admin via database
|
||||||
const user = await prisma.user.findUnique({ where: { email: adminEmail } });
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { email: adminEmail }
|
||||||
|
});
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
@@ -152,39 +169,44 @@ try {
|
|||||||
});
|
});
|
||||||
console.log('Updated user role to club_admin');
|
console.log('Updated user role to club_admin');
|
||||||
}
|
}
|
||||||
await prisma.$disconnect();
|
|
||||||
|
|
||||||
|
// Navigate to admin page to refresh session
|
||||||
console.log('Navigating to admin page for admin user...');
|
console.log('Navigating to admin page for admin user...');
|
||||||
await page.goto(`${baseURL}/admin`);
|
await page.goto(`${baseURL}/admin`);
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
console.log('Admin page loaded:', page.url());
|
console.log('Admin page loaded:', page.url());
|
||||||
|
|
||||||
await page.waitForTimeout(500);
|
// Wait a bit to ensure session is refreshed
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// Refresh the page to force session reload
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
console.log('Page reloaded');
|
console.log('Page reloaded');
|
||||||
|
|
||||||
|
// Save the authentication state
|
||||||
await context.storageState({ path: adminAuthFile });
|
await context.storageState({ path: adminAuthFile });
|
||||||
|
|
||||||
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Global setup error:', error);
|
||||||
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
await browser.close();
|
await browser.close();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
export default async function globalSetup(config: FullConfig) {
|
// Return teardown function
|
||||||
console.log('=== Global Setup ===');
|
return async () => {
|
||||||
console.log('DATABASE_URL:', process.env.DATABASE_URL);
|
console.log('\n=== Global Teardown ===');
|
||||||
|
|
||||||
if (isCIDatabase()) {
|
// Clean up all test data
|
||||||
console.log('CI environment detected - will reset database schema');
|
try {
|
||||||
const prisma = createPrismaClient();
|
await cleanupAllTestData();
|
||||||
await resetDatabaseSchema(prisma);
|
} catch (error) {
|
||||||
|
console.error('Error cleaning up test data:', error);
|
||||||
|
} finally {
|
||||||
await prisma.$disconnect();
|
await prisma.$disconnect();
|
||||||
} else if (!isProductionDatabase()) {
|
|
||||||
console.log('Development environment - preserving existing data');
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
await createTestUsers(config);
|
|
||||||
console.log('=== Global Setup Complete ===\n');
|
|
||||||
}
|
}
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
/**
|
|
||||||
* Global teardown for Playwright tests
|
|
||||||
* Handles cleanup based on environment:
|
|
||||||
* - CI: Full schema reset (database can be destroyed and recreated)
|
|
||||||
* - Dev: Selective cleanup of test records (preserve real data)
|
|
||||||
* - Prod: Selective cleanup of test records (preserve real data)
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { type FullConfig } from '@playwright/test';
|
|
||||||
import { PrismaClient } from '@prisma/client';
|
|
||||||
import { PrismaPg } from '@prisma/adapter-pg';
|
|
||||||
import { execSync } from 'child_process';
|
|
||||||
|
|
||||||
const TEST_PATTERNS = {
|
|
||||||
players: [
|
|
||||||
'%Test%',
|
|
||||||
'%Setup%',
|
|
||||||
'%Home Test%',
|
|
||||||
'%Home Match Player%',
|
|
||||||
'%Admin User%',
|
|
||||||
'%NinePart%',
|
|
||||||
'%Nine Part%',
|
|
||||||
'%Test Player%',
|
|
||||||
'%TestUser%',
|
|
||||||
'%Cucumber%',
|
|
||||||
'%Config Admin%',
|
|
||||||
'%Elo Test%',
|
|
||||||
'%Dedupe%',
|
|
||||||
'%Whitespace%',
|
|
||||||
'%Aggregate%',
|
|
||||||
'%Tournament Player%',
|
|
||||||
'%Schedule Player%',
|
|
||||||
'%Test Activity Player%',
|
|
||||||
'%HP%',
|
|
||||||
],
|
|
||||||
events: [
|
|
||||||
'%Test%',
|
|
||||||
'%Setup%',
|
|
||||||
'%Recent%',
|
|
||||||
'%Test Tournament%',
|
|
||||||
'%Cucumber%',
|
|
||||||
'%Elo Test%',
|
|
||||||
'%Schedule%',
|
|
||||||
],
|
|
||||||
users: [
|
|
||||||
'%test%',
|
|
||||||
'%setup%',
|
|
||||||
'%cucumber%',
|
|
||||||
'%TestUser%',
|
|
||||||
'%logout-test%',
|
|
||||||
'%admin-%',
|
|
||||||
'%config-admin%',
|
|
||||||
'%schedule-admin%',
|
|
||||||
'%nine-part-test%',
|
|
||||||
'%tour-admin-%',
|
|
||||||
'%president-%',
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
function isDatabase(url: string, name: string): boolean {
|
|
||||||
return url.includes(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isProductionDatabase(): boolean {
|
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
|
||||||
return isDatabase(dbUrl, 'euchre_camp') && !isDatabase(dbUrl, '_dev') && !isDatabase(dbUrl, '_ci');
|
|
||||||
}
|
|
||||||
|
|
||||||
function isCIDatabase(): boolean {
|
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
|
||||||
return isDatabase(dbUrl, '_ci');
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildLikeClause(patterns: string[]): string {
|
|
||||||
return patterns.map(p => `name LIKE '${p}'`).join(' OR ');
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildEmailLikeClause(patterns: string[]): string {
|
|
||||||
return patterns.map(p => `email LIKE '${p}'`).join(' OR ');
|
|
||||||
}
|
|
||||||
|
|
||||||
function createPrismaClient() {
|
|
||||||
const databaseUrl = process.env.DATABASE_URL;
|
|
||||||
if (!databaseUrl) throw new Error('DATABASE_URL is required');
|
|
||||||
const adapter = new PrismaPg({ connectionString: databaseUrl });
|
|
||||||
return new PrismaClient({ adapter });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function resetDatabaseSchema(prisma: PrismaClient) {
|
|
||||||
console.log('Resetting database schema...');
|
|
||||||
|
|
||||||
const tables = await prisma.$queryRaw<{ tablename: string }[]>`
|
|
||||||
SELECT tablename FROM pg_tables
|
|
||||||
WHERE schemaname = 'public' AND tablename NOT LIKE '_prisma_migrations'
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (tables.length > 0) {
|
|
||||||
await prisma.$executeRawUnsafe(`
|
|
||||||
DROP SCHEMA public CASCADE;
|
|
||||||
CREATE SCHEMA public;
|
|
||||||
`);
|
|
||||||
console.log(`Dropped ${tables.length} tables`);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Running migrations...');
|
|
||||||
execSync('bunx prisma migrate deploy', { stdio: 'inherit' });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cleanupTestRecords(prisma: PrismaClient) {
|
|
||||||
console.log('Cleaning up test records...');
|
|
||||||
|
|
||||||
const playerWhere = buildLikeClause(TEST_PATTERNS.players);
|
|
||||||
const eventWhere = buildLikeClause(TEST_PATTERNS.events);
|
|
||||||
const userWhere = buildEmailLikeClause(TEST_PATTERNS.users);
|
|
||||||
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM elo_snapshots WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM partnership_games WHERE "player1Id" IN (SELECT id FROM players WHERE (${playerWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM partnership_stats WHERE "player1Id" IN (SELECT id FROM players WHERE (${playerWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM event_participants WHERE "eventId" IN (SELECT id FROM events WHERE (${eventWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM tournament_rounds WHERE "eventId" IN (SELECT id FROM events WHERE (${eventWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM bracket_matchups WHERE "eventId" IN (SELECT id FROM events WHERE (${eventWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM events WHERE (${eventWhere});`);
|
|
||||||
console.log('Deleted test events');
|
|
||||||
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM elo_ratings WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM glicko2_ratings WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM open_skill_ratings WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM players WHERE (${playerWhere});`);
|
|
||||||
console.log('Deleted test players');
|
|
||||||
|
|
||||||
await prisma.$executeRawUnsafe(`DELETE FROM users WHERE (${userWhere}) AND "playerId" IS NULL;`);
|
|
||||||
console.log('Deleted test users (without player associations)');
|
|
||||||
|
|
||||||
await prisma.$disconnect();
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function globalTeardown(config: FullConfig) {
|
|
||||||
console.log('\n=== Global Teardown ===');
|
|
||||||
|
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
|
||||||
|
|
||||||
if (isCIDatabase()) {
|
|
||||||
console.log('CI environment - resetting database schema');
|
|
||||||
const prisma = createPrismaClient();
|
|
||||||
await resetDatabaseSchema(prisma);
|
|
||||||
await prisma.$disconnect();
|
|
||||||
} else if (isProductionDatabase()) {
|
|
||||||
console.log('Production environment - selective cleanup of test records');
|
|
||||||
const prisma = createPrismaClient();
|
|
||||||
await cleanupTestRecords(prisma);
|
|
||||||
} else {
|
|
||||||
console.log('Development environment - selective cleanup of test records');
|
|
||||||
const prisma = createPrismaClient();
|
|
||||||
await cleanupTestRecords(prisma);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('=== Global Teardown Complete ===\n');
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { test, expect } from '@playwright/test'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { createTestPlayer, cleanupTestRecords, getCreatedRecordCounts } from '@/__tests__/test-utils'
|
||||||
|
|
||||||
|
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 }) => {
|
||||||
|
// Create some test players with unique names and very high Elo to ensure they're in top 10
|
||||||
|
const timestamp = Date.now()
|
||||||
|
const players = []
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
const playerName = `Home Test Player ${timestamp} ${i + 1}`
|
||||||
|
const player = await createTestPlayer({
|
||||||
|
name: playerName,
|
||||||
|
currentElo: 2000 - i * 10,
|
||||||
|
})
|
||||||
|
players.push(player)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Navigate to home page
|
||||||
|
await page.goto('/')
|
||||||
|
|
||||||
|
// Check that the page loads
|
||||||
|
await expect(page.locator('text=Top 10 Players')).toBeVisible()
|
||||||
|
|
||||||
|
// Check that at least one of our test players is displayed
|
||||||
|
// Use a more specific locator to avoid multiple matches
|
||||||
|
await expect(
|
||||||
|
page.locator(`a:has-text("Home Test Player ${timestamp} 1")`)
|
||||||
|
).toBeVisible()
|
||||||
|
|
||||||
|
// Verify cleanup will work
|
||||||
|
const counts = getCreatedRecordCounts();
|
||||||
|
expect(counts.players).toBe(3);
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should display club president', async ({ page }) => {
|
||||||
|
const timestamp = Date.now()
|
||||||
|
// Create a club admin user
|
||||||
|
const clubAdmin = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
email: `president-${timestamp}@example.com`,
|
||||||
|
name: `Club President ${timestamp}`,
|
||||||
|
role: 'club_admin',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Navigate to home page
|
||||||
|
await page.goto('/')
|
||||||
|
|
||||||
|
// Check that the club president section is visible
|
||||||
|
await expect(page.locator('text=Club President')).toBeVisible()
|
||||||
|
|
||||||
|
// Clean up
|
||||||
|
await prisma.user.delete({ where: { id: clubAdmin.id } })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should display most recent tournament', async ({ page }) => {
|
||||||
|
const timestamp = Date.now()
|
||||||
|
// Create a tournament with a future date to ensure it's the most recent
|
||||||
|
const tournament = await prisma.event.create({
|
||||||
|
data: {
|
||||||
|
name: `Recent Tournament ${timestamp}`,
|
||||||
|
eventType: 'tournament',
|
||||||
|
eventDate: new Date(Date.now() + 86400000), // Tomorrow
|
||||||
|
status: 'completed',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Create players for the match
|
||||||
|
const player1Name = `Home Match Player 1 ${timestamp}`
|
||||||
|
const player1 = await prisma.player.create({
|
||||||
|
data: { name: player1Name, normalizedName: player1Name.toLowerCase(), currentElo: 1500 },
|
||||||
|
})
|
||||||
|
const player2Name = `Home Match Player 2 ${timestamp}`
|
||||||
|
const player2 = await prisma.player.create({
|
||||||
|
data: { name: player2Name, normalizedName: player2Name.toLowerCase(), currentElo: 1480 },
|
||||||
|
})
|
||||||
|
const player3Name = `Home Match Player 3 ${timestamp}`
|
||||||
|
const player3 = await prisma.player.create({
|
||||||
|
data: { name: player3Name, normalizedName: player3Name.toLowerCase(), currentElo: 1450 },
|
||||||
|
})
|
||||||
|
const player4Name = `Home Match Player 4 ${timestamp}`
|
||||||
|
const player4 = await prisma.player.create({
|
||||||
|
data: { name: player4Name, normalizedName: player4Name.toLowerCase(), currentElo: 1420 },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Create a match in the tournament
|
||||||
|
await prisma.match.create({
|
||||||
|
data: {
|
||||||
|
eventId: tournament.id,
|
||||||
|
player1P1Id: player1.id,
|
||||||
|
player1P2Id: player2.id,
|
||||||
|
player2P1Id: player3.id,
|
||||||
|
player2P2Id: player4.id,
|
||||||
|
team1Score: 10,
|
||||||
|
team2Score: 5,
|
||||||
|
status: 'completed',
|
||||||
|
playedAt: new Date(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Navigate to home page
|
||||||
|
await page.goto('/')
|
||||||
|
|
||||||
|
// Check that the tournament section is visible
|
||||||
|
await expect(page.locator('text=Most Recent Tournament')).toBeVisible()
|
||||||
|
await expect(page.locator(`text=Recent Tournament ${timestamp}`)).toBeVisible()
|
||||||
|
|
||||||
|
// Clean up
|
||||||
|
await prisma.match.deleteMany({ where: { eventId: tournament.id } })
|
||||||
|
await prisma.event.delete({ where: { id: tournament.id } })
|
||||||
|
await prisma.player.deleteMany({
|
||||||
|
where: { id: { in: [player1.id, player2.id, player3.id, player4.id] } },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
+21
-22
@@ -13,7 +13,6 @@
|
|||||||
|
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
function getTestCredentials() {
|
function getTestCredentials() {
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
@@ -24,7 +23,7 @@ function getTestCredentials() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
test.describe.skip('Issue #7: Schedule Tab', () => {
|
test.describe.serial('Issue #7: Schedule Tab', () => {
|
||||||
let testEmail: string;
|
let testEmail: string;
|
||||||
let testPassword: string;
|
let testPassword: string;
|
||||||
let tournamentId: number;
|
let tournamentId: number;
|
||||||
@@ -35,11 +34,11 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
|
|||||||
testPassword = credentials.password;
|
testPassword = credentials.password;
|
||||||
|
|
||||||
// Create admin user via API
|
// Create admin user via API
|
||||||
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
|
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Origin: BASE_URL,
|
Origin: 'http://localhost:3000',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
email: testEmail,
|
email: testEmail,
|
||||||
@@ -129,30 +128,30 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
|
|||||||
|
|
||||||
test('Schedule tab link exists on tournament detail page', async ({ page }) => {
|
test('Schedule tab link exists on tournament detail page', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to tournament detail
|
// Navigate to tournament detail
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}`);
|
||||||
|
|
||||||
// Check Schedule tab link exists - use button since page uses buttons for tabs
|
// Check Schedule tab link exists
|
||||||
const scheduleLink = page.locator('button', { hasText: 'Schedule' });
|
const scheduleLink = page.locator('a', { hasText: 'Schedule' });
|
||||||
await expect(scheduleLink).toBeVisible();
|
await expect(scheduleLink).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Schedule page loads with no schedule message', async ({ page }) => {
|
test('Schedule page loads with no schedule message', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to schedule page
|
// Navigate to schedule page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/schedule`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
|
||||||
|
|
||||||
// Check page content
|
// Check page content
|
||||||
await expect(page.locator('h1')).toContainText('Tournament Schedule');
|
await expect(page.locator('h1')).toContainText('Tournament Schedule');
|
||||||
@@ -162,20 +161,20 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
|
|||||||
|
|
||||||
test('Generate schedule creates rounds and matchups', async ({ page }) => {
|
test('Generate schedule creates rounds and matchups', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to schedule page
|
// Navigate to schedule page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/schedule`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
|
||||||
|
|
||||||
// Click generate schedule
|
// Click generate schedule
|
||||||
await page.click('button:has-text("Generate Schedule")');
|
await page.click('button:has-text("Generate Schedule")');
|
||||||
|
|
||||||
// Wait for success message or page reload
|
// Wait for success message or page reload
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
// Verify rounds were created in database
|
// Verify rounds were created in database
|
||||||
const rounds = await prisma.tournamentRound.findMany({
|
const rounds = await prisma.tournamentRound.findMany({
|
||||||
@@ -192,14 +191,14 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
|
|||||||
|
|
||||||
test('Schedule page displays generated rounds and matchups', async ({ page }) => {
|
test('Schedule page displays generated rounds and matchups', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to schedule page
|
// Navigate to schedule page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/schedule`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
|
||||||
|
|
||||||
// Check that rounds are displayed
|
// Check that rounds are displayed
|
||||||
await expect(page.locator('text=Round 1')).toBeVisible();
|
await expect(page.locator('text=Round 1')).toBeVisible();
|
||||||
@@ -214,15 +213,15 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
|
|||||||
|
|
||||||
test('Schedule API returns rounds with matchups', async ({ page }) => {
|
test('Schedule API returns rounds with matchups', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Call the schedule API
|
// Call the schedule API
|
||||||
const response = await page.request.get(
|
const response = await page.request.get(
|
||||||
`/api/tournaments/${tournamentId}/schedule`
|
`http://localhost:3000/api/tournaments/${tournamentId}/schedule`
|
||||||
);
|
);
|
||||||
expect(response.ok()).toBe(true);
|
expect(response.ok()).toBe(true);
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,109 @@
|
|||||||
import { test, expect } from '@playwright/test'
|
import { test, expect } from '@playwright/test'
|
||||||
|
|
||||||
test.describe('Smoke Test: EuchreCamp Application', () => {
|
test.describe('Smoke Test: EuchreCamp Application', () => {
|
||||||
|
test.describe('Admin Panel Navigation', () => {
|
||||||
|
test('should navigate to admin dashboard', async ({ page }) => {
|
||||||
|
await page.goto('/admin')
|
||||||
|
// Admin dashboard should be visible
|
||||||
|
await expect(page.locator('text=Admin')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should navigate to matches admin page', async ({ page }) => {
|
||||||
|
await page.goto('/admin/matches')
|
||||||
|
await expect(page.locator('text=Match Management')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should navigate to players admin page', async ({ page }) => {
|
||||||
|
await page.goto('/admin/players')
|
||||||
|
await expect(page.locator('text=Player Management')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should navigate to users admin page', async ({ page }) => {
|
||||||
|
await page.goto('/admin/users')
|
||||||
|
await expect(page.locator('text=User Management')).toBeVisible()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test.describe('Match Management', () => {
|
||||||
|
test('should display matches page', async ({ page }) => {
|
||||||
|
await page.goto('/admin/matches')
|
||||||
|
// Verify page header is visible
|
||||||
|
await expect(page.locator('text=Match Management')).toBeVisible()
|
||||||
|
|
||||||
|
// Page should load successfully - verify either table or empty state is present
|
||||||
|
const hasTable = await page.locator('table').count().then(c => c > 0)
|
||||||
|
const hasEmptyState = await page.locator('text=/no matches|No matches/').count().then(c => c > 0)
|
||||||
|
|
||||||
|
// At least one should be present
|
||||||
|
expect(hasTable || hasEmptyState).toBeTruthy()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should have delete button for matches when matches exist', async ({ page }) => {
|
||||||
|
await page.goto('/admin/matches')
|
||||||
|
// Check if delete buttons exist in the table
|
||||||
|
const deleteButtons = page.locator('button:has-text("Delete")')
|
||||||
|
const count = await deleteButtons.count()
|
||||||
|
// Table might be empty, but if there are matches, delete buttons should exist
|
||||||
|
if (count > 0) {
|
||||||
|
await expect(page.locator('text=Actions')).toBeVisible()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test.describe('Player Management', () => {
|
||||||
|
test('should display players table', async ({ page }) => {
|
||||||
|
await page.goto('/admin/players')
|
||||||
|
await expect(page.locator('table')).toBeVisible()
|
||||||
|
await expect(page.locator('text=Player Name')).toBeVisible()
|
||||||
|
await expect(page.locator('text=Current Elo')).toBeVisible()
|
||||||
|
await expect(page.locator('text=Actions')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should have edit and delete buttons for players', async ({ page }) => {
|
||||||
|
await page.goto('/admin/players')
|
||||||
|
// At minimum, verify the Actions column exists
|
||||||
|
await expect(page.locator('text=Actions')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should allow editing player name', async ({ page }) => {
|
||||||
|
await page.goto('/admin/players')
|
||||||
|
// Click edit on first player
|
||||||
|
const editButton = page.locator('button:has-text("Edit")').first()
|
||||||
|
if (await editButton.isVisible()) {
|
||||||
|
await editButton.click()
|
||||||
|
|
||||||
|
// Verify edit modal appears
|
||||||
|
await expect(page.locator('text=Edit Player Name')).toBeVisible()
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
await page.click('text=Cancel')
|
||||||
|
await expect(page.locator('text=Edit Player Name')).not.toBeVisible()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test.describe('User Management', () => {
|
||||||
|
test('should display users page', async ({ page }) => {
|
||||||
|
await page.goto('/admin/users')
|
||||||
|
// Page should load with either a table or "no users" message
|
||||||
|
const hasTable = await page.locator('table').isVisible().catch(() => false)
|
||||||
|
const hasNoUsers = await page.locator('text=No users found').isVisible().catch(() => false)
|
||||||
|
|
||||||
|
// At least one of these should be true
|
||||||
|
expect(hasTable || hasNoUsers).toBeTruthy()
|
||||||
|
|
||||||
|
// Verify page header is visible
|
||||||
|
await expect(page.locator('text=User Management')).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should have create user link', async ({ page }) => {
|
||||||
|
await page.goto('/admin/users')
|
||||||
|
// Check for the main create user link (with green button styling)
|
||||||
|
const createLink = page.locator('a.bg-green-600:has-text("Create User")')
|
||||||
|
await expect(createLink).toBeVisible()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
test.describe('Public Pages', () => {
|
test.describe('Public Pages', () => {
|
||||||
test('should display rankings page', async ({ page }) => {
|
test('should display rankings page', async ({ page }) => {
|
||||||
await page.goto('/rankings')
|
await page.goto('/rankings')
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
|
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
function getTestCredentials() {
|
function getTestCredentials() {
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
@@ -18,7 +17,7 @@ function getTestCredentials() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
test.describe.skip('Issue #22: Team Configuration', () => {
|
test.describe.serial('Issue #22: Team Configuration', () => {
|
||||||
let testEmail: string;
|
let testEmail: string;
|
||||||
let testPassword: string;
|
let testPassword: string;
|
||||||
let tournamentId: number;
|
let tournamentId: number;
|
||||||
@@ -29,11 +28,11 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
testPassword = credentials.password;
|
testPassword = credentials.password;
|
||||||
|
|
||||||
// Create admin user via API
|
// Create admin user via API
|
||||||
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
|
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Origin: BASE_URL,
|
Origin: 'http://localhost:3000',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
email: testEmail,
|
email: testEmail,
|
||||||
@@ -78,14 +77,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
|
|
||||||
test('Tournament creation form shows team configuration options', async ({ page }) => {
|
test('Tournament creation form shows team configuration options', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to tournament creation
|
// Navigate to tournament creation
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Select Round Robin format
|
// Select Round Robin format
|
||||||
await page.selectOption('select[name="format"]', 'round_robin');
|
await page.selectOption('select[name="format"]', 'round_robin');
|
||||||
@@ -101,14 +100,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
|
|
||||||
test('Create tournament with permanent teams', async ({ page }) => {
|
test('Create tournament with permanent teams', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to tournament creation
|
// Navigate to tournament creation
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Fill in tournament details
|
// Fill in tournament details
|
||||||
await page.fill('input[name="name"]', `Test Tournament ${Date.now()}`);
|
await page.fill('input[name="name"]', `Test Tournament ${Date.now()}`);
|
||||||
@@ -126,8 +125,7 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
const playerName3 = `Player ${Date.now() + 2}`;
|
const playerName3 = `Player ${Date.now() + 2}`;
|
||||||
const playerName4 = `Player ${Date.now() + 3}`;
|
const playerName4 = `Player ${Date.now() + 3}`;
|
||||||
|
|
||||||
// Create first player - wait for search input to appear first
|
// Create first player
|
||||||
await page.waitForSelector('input[placeholder*="Search"]', { timeout: 5000 });
|
|
||||||
await page.fill('input[placeholder*="Search"]', playerName1);
|
await page.fill('input[placeholder*="Search"]', playerName1);
|
||||||
await page.waitForTimeout(500);
|
await page.waitForTimeout(500);
|
||||||
await page.click(`text=+ Create "${playerName1}" as new player`);
|
await page.click(`text=+ Create "${playerName1}" as new player`);
|
||||||
@@ -177,14 +175,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
|
|
||||||
test('Create tournament with variable teams and partner rotation', async ({ page }) => {
|
test('Create tournament with variable teams and partner rotation', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to tournament creation
|
// Navigate to tournament creation
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Fill in tournament details
|
// Fill in tournament details
|
||||||
await page.fill('input[name="name"]', `Variable Teams Tournament ${Date.now()}`);
|
await page.fill('input[name="name"]', `Variable Teams Tournament ${Date.now()}`);
|
||||||
@@ -239,11 +237,11 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
|
|
||||||
test('Edit tournament team configuration', async ({ page }) => {
|
test('Edit tournament team configuration', async ({ page }) => {
|
||||||
// First create a tournament with default settings
|
// First create a tournament with default settings
|
||||||
const createResponse = await fetch(`${BASE_URL}/api/tournaments`, {
|
const createResponse = await fetch('http://localhost:3000/api/tournaments', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Origin: BASE_URL,
|
Origin: 'http://localhost:3000',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name: `Edit Test Tournament ${Date.now()}`,
|
name: `Edit Test Tournament ${Date.now()}`,
|
||||||
@@ -255,14 +253,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
|
|||||||
tournamentId = createData.tournament.id;
|
tournamentId = createData.tournament.id;
|
||||||
|
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to edit tournament page
|
// Navigate to edit tournament page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/edit`);
|
||||||
|
|
||||||
// Check that team configuration section is visible
|
// Check that team configuration section is visible
|
||||||
await expect(page.locator('text=Team Configuration')).toBeVisible();
|
await expect(page.locator('text=Team Configuration')).toBeVisible();
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
export const BASE_URL = process.env.BASE_URL || (process.env.CI
|
|
||||||
? 'https://euchre-ci.notsosm.art'
|
|
||||||
: 'http://localhost:3000');
|
|
||||||
@@ -18,7 +18,6 @@
|
|||||||
|
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
function getTestCredentials() {
|
function getTestCredentials() {
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
@@ -29,7 +28,7 @@ function getTestCredentials() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
test.describe.skip('Tournament with 10 Participants and Variable Team Durability', () => {
|
test.describe.serial('Tournament with 10 Participants and Variable Team Durability', () => {
|
||||||
let testEmail: string;
|
let testEmail: string;
|
||||||
let testPassword: string;
|
let testPassword: string;
|
||||||
let tournamentId: number;
|
let tournamentId: number;
|
||||||
@@ -42,11 +41,11 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
|
|
||||||
// Create admin user via API
|
// Create admin user via API
|
||||||
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
|
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Origin: BASE_URL,
|
Origin: 'http://localhost:3000',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
email: testEmail,
|
email: testEmail,
|
||||||
@@ -103,14 +102,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
|
|
||||||
test('Tournament creation form shows variable team durability options', async ({ page }) => {
|
test('Tournament creation form shows variable team durability options', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to tournament creation
|
// Navigate to tournament creation
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Select Round Robin format
|
// Select Round Robin format
|
||||||
await page.selectOption('select[name="format"]', 'round_robin');
|
await page.selectOption('select[name="format"]', 'round_robin');
|
||||||
@@ -133,14 +132,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
|
|
||||||
test('Create tournament with 10 participants, variable teams, and minimize_repeat', async ({ page }) => {
|
test('Create tournament with 10 participants, variable teams, and minimize_repeat', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to tournament creation
|
// Navigate to tournament creation
|
||||||
await page.goto('/admin/tournaments/new');
|
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||||
|
|
||||||
// Fill in tournament details
|
// Fill in tournament details
|
||||||
const tournamentName = `9 Participant Variable Tournament ${Date.now()}`;
|
const tournamentName = `9 Participant Variable Tournament ${Date.now()}`;
|
||||||
@@ -189,7 +188,7 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
await page.click('button:has-text("Add")');
|
await page.click('button:has-text("Add")');
|
||||||
|
|
||||||
// Wait for the player to be added and UI to update
|
// Wait for the player to be added and UI to update
|
||||||
await page.waitForTimeout(200);
|
await page.waitForTimeout(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify 10 players are added
|
// Verify 10 players are added
|
||||||
@@ -239,10 +238,10 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
test('Schedule generation for 10 participants creates correct number of matchups', async ({ page }) => {
|
test('Schedule generation for 10 participants creates correct number of matchups', async ({ page }) => {
|
||||||
// Navigate to Matchups tab (formerly Teams tab)
|
// Navigate to Matchups tab (formerly Teams tab)
|
||||||
// The test is already authenticated via the chromium-admin project
|
// The test is already authenticated via the chromium-admin project
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}`);
|
||||||
|
|
||||||
// Wait for page to load and data to be fetched
|
// Wait for page to load and data to be fetched
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
// Wait for the page content to appear (not just "Loading...")
|
// Wait for the page content to appear (not just "Loading...")
|
||||||
await expect(page.locator('text=Matchups')).toBeVisible({ timeout: 15000 });
|
await expect(page.locator('text=Matchups')).toBeVisible({ timeout: 15000 });
|
||||||
@@ -281,14 +280,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
|
|
||||||
test('Schedule displays correct matchups for 10 participants', async ({ page }) => {
|
test('Schedule displays correct matchups for 10 participants', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to Schedule tab
|
// Navigate to Schedule tab
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/schedule`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
|
||||||
|
|
||||||
// Verify rounds are displayed
|
// Verify rounds are displayed
|
||||||
await expect(page.locator('text=Round 1')).toBeVisible();
|
await expect(page.locator('text=Round 1')).toBeVisible();
|
||||||
@@ -305,14 +304,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
|
|||||||
|
|
||||||
test('Matchup generation with minimize_repeat creates varied partnerships', async ({ page }) => {
|
test('Matchup generation with minimize_repeat creates varied partnerships', async ({ page }) => {
|
||||||
// Login
|
// Login
|
||||||
await page.goto('/auth/login');
|
await page.goto('http://localhost:3000/auth/login');
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||||
|
|
||||||
// Navigate to Schedule tab
|
// Navigate to Schedule tab
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/schedule`);
|
await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
|
||||||
|
|
||||||
// Get all matchups from the database to verify partnership variety
|
// Get all matchups from the database to verify partnership variety
|
||||||
const matchups = await prisma.bracketMatchup.findMany({
|
const matchups = await prisma.bracketMatchup.findMany({
|
||||||
|
|||||||
+6
-76
@@ -11,54 +11,11 @@
|
|||||||
|
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
|
|
||||||
|
|
||||||
function getTestCredentials() {
|
test.describe('Tournament Edit - allowTies functionality', () => {
|
||||||
const timestamp = Date.now();
|
|
||||||
return {
|
|
||||||
email: `allowties-admin-${timestamp}@example.com`,
|
|
||||||
password: 'AdminPassword123!',
|
|
||||||
name: `AllowTies Admin ${timestamp}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
test.describe.skip('Tournament Edit - allowTies functionality', () => {
|
|
||||||
let tournamentId: number;
|
let tournamentId: number;
|
||||||
let testEmail: string;
|
|
||||||
let testPassword: string;
|
|
||||||
|
|
||||||
test.beforeAll(async () => {
|
test.beforeAll(async () => {
|
||||||
// Create admin user via API
|
|
||||||
const credentials = getTestCredentials();
|
|
||||||
testEmail = credentials.email;
|
|
||||||
testPassword = credentials.password;
|
|
||||||
|
|
||||||
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Origin: BASE_URL,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
email: testEmail,
|
|
||||||
password: testPassword,
|
|
||||||
name: credentials.name,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('allowTies test user creation response:', response.status);
|
|
||||||
|
|
||||||
// Update user to club_admin role
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
where: { email: testEmail },
|
|
||||||
});
|
|
||||||
if (user) {
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: user.id },
|
|
||||||
data: { role: 'club_admin' },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a test tournament for editing
|
// Create a test tournament for editing
|
||||||
const tournament = await prisma.event.create({
|
const tournament = await prisma.event.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -68,7 +25,6 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
|
|||||||
status: 'planned',
|
status: 'planned',
|
||||||
allowTies: false,
|
allowTies: false,
|
||||||
targetScore: 5,
|
targetScore: 5,
|
||||||
ownerId: user?.id,
|
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
},
|
},
|
||||||
@@ -81,28 +37,16 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
|
|||||||
if (tournamentId) {
|
if (tournamentId) {
|
||||||
await prisma.event.delete({
|
await prisma.event.delete({
|
||||||
where: { id: tournamentId },
|
where: { id: tournamentId },
|
||||||
}).catch(() => {});
|
});
|
||||||
}
|
|
||||||
// Clean up user
|
|
||||||
const user = await prisma.user.findUnique({ where: { email: testEmail } });
|
|
||||||
if (user) {
|
|
||||||
await prisma.user.delete({ where: { id: user.id } });
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should display allowTies checkbox on edit form @chromium-admin', async ({ page }) => {
|
test('should display allowTies checkbox on edit form @chromium-admin', async ({ page }) => {
|
||||||
// Login first
|
|
||||||
await page.goto('/auth/login');
|
|
||||||
await page.fill('input[name="email"]', testEmail);
|
|
||||||
await page.fill('input[name="password"]', testPassword);
|
|
||||||
await page.click('button[type="submit"]');
|
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
|
||||||
|
|
||||||
// Navigate to tournament edit page
|
// Navigate to tournament edit page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
||||||
|
|
||||||
// Wait for form to load - edit page shows "Edit Tournament" heading
|
// Wait for form to load
|
||||||
await expect(page.locator('text=Edit Tournament')).toBeVisible({ timeout: 5000 });
|
await expect(page.locator('text=Tournament Name')).toBeVisible();
|
||||||
|
|
||||||
// Check that allowTies checkbox exists
|
// Check that allowTies checkbox exists
|
||||||
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
|
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
|
||||||
@@ -111,18 +55,11 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('should save allowTies when toggled to true @chromium-admin', async ({ page }) => {
|
test('should save allowTies when toggled to true @chromium-admin', async ({ page }) => {
|
||||||
// Login first
|
|
||||||
await page.goto('/auth/login');
|
|
||||||
await page.fill('input[name="email"]', testEmail);
|
|
||||||
await page.fill('input[name="password"]', testPassword);
|
|
||||||
await page.click('button[type="submit"]');
|
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
|
||||||
|
|
||||||
// Navigate to tournament edit page
|
// Navigate to tournament edit page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
||||||
|
|
||||||
// Wait for form to load
|
// Wait for form to load
|
||||||
await expect(page.locator('text=Edit Tournament')).toBeVisible({ timeout: 5000 });
|
await expect(page.locator('text=Tournament Name')).toBeVisible();
|
||||||
|
|
||||||
// Toggle allowTies checkbox
|
// Toggle allowTies checkbox
|
||||||
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
|
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
|
||||||
@@ -150,18 +87,11 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
|
|||||||
data: { allowTies: true },
|
data: { allowTies: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Login first
|
|
||||||
await page.goto('/auth/login');
|
|
||||||
await page.fill('input[name="email"]', testEmail);
|
|
||||||
await page.fill('input[name="password"]', testPassword);
|
|
||||||
await page.click('button[type="submit"]');
|
|
||||||
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
|
|
||||||
|
|
||||||
// Navigate to tournament edit page
|
// Navigate to tournament edit page
|
||||||
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
await page.goto(`/admin/tournaments/${tournamentId}/edit`);
|
||||||
|
|
||||||
// Wait for form to load
|
// Wait for form to load
|
||||||
await expect(page.locator('text=Edit Tournament')).toBeVisible({ timeout: 5000 });
|
await expect(page.locator('text=Tournament Name')).toBeVisible();
|
||||||
|
|
||||||
// Verify checkbox is checked
|
// Verify checkbox is checked
|
||||||
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
|
const allowTiesCheckbox = page.locator('input[name="allowTies"]');
|
||||||
@@ -22,7 +22,8 @@ IMAGE_TAG_COMMIT := `git rev-parse --short HEAD`
|
|||||||
# --- Variables ---
|
# --- Variables ---
|
||||||
# Database
|
# Database
|
||||||
DB_CONTAINER := "euchre-camp-postgres"
|
DB_CONTAINER := "euchre-camp-postgres"
|
||||||
DATABASE_URL := env_var_or_default("DATABASE_URL", "")
|
DATABASE_PROVIDER := env_var_or_default("DATABASE_PROVIDER", "sqlite")
|
||||||
|
DATABASE_URL := env_var_or_default("DATABASE_URL", "file:./prisma/dev.db")
|
||||||
|
|
||||||
# --- Setup & Installation ---
|
# --- Setup & Installation ---
|
||||||
|
|
||||||
@@ -31,7 +32,7 @@ setup:
|
|||||||
@echo "Installing dependencies..."
|
@echo "Installing dependencies..."
|
||||||
npm install
|
npm install
|
||||||
@echo "Setting up database..."
|
@echo "Setting up database..."
|
||||||
npm run db:setup-dev
|
npm run db:setup-postgres
|
||||||
@echo "Generating Prisma client..."
|
@echo "Generating Prisma client..."
|
||||||
npx prisma generate
|
npx prisma generate
|
||||||
|
|
||||||
@@ -55,29 +56,46 @@ format:
|
|||||||
|
|
||||||
# --- Testing ---
|
# --- Testing ---
|
||||||
|
|
||||||
# Run all tests (unit + acceptance)
|
# Run all tests (unit + acceptance with SQLite)
|
||||||
test: test-unit test-acceptance
|
# Note: Uses Docker containers for consistent environment
|
||||||
|
test: test-unit test-acceptance-sqlite
|
||||||
|
|
||||||
# Run unit tests
|
# Run all tests with PostgreSQL (Docker)
|
||||||
|
test-pg: test-unit test-acceptance-postgres
|
||||||
|
|
||||||
|
# Run unit tests (Vitest)
|
||||||
test-unit:
|
test-unit:
|
||||||
npm run test:run
|
npm run test:run
|
||||||
|
|
||||||
# Run acceptance tests (Playwright)
|
# Run acceptance tests with SQLite (fast, no Docker needed)
|
||||||
test-acceptance:
|
test-acceptance-sqlite:
|
||||||
|
@echo "Running acceptance tests with SQLite..."
|
||||||
|
DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db BETTER_AUTH_SECRET=test-secret-key npm run test:acceptance
|
||||||
|
|
||||||
|
# Run acceptance tests with PostgreSQL (Docker)
|
||||||
|
test-acceptance-postgres:
|
||||||
|
@echo "Starting Docker containers for acceptance tests..."
|
||||||
|
docker compose up -d
|
||||||
|
@echo "Waiting for services to be ready..."
|
||||||
|
sleep 10
|
||||||
@echo "Running acceptance tests..."
|
@echo "Running acceptance tests..."
|
||||||
npm run test:acceptance
|
npm run test:acceptance
|
||||||
|
@echo "Stopping Docker containers..."
|
||||||
|
docker compose down
|
||||||
|
|
||||||
# Run Cucumber e2e tests
|
# Run Cucumber e2e tests with SQLite
|
||||||
test-cucumber:
|
test-cucumber-sqlite:
|
||||||
@echo "Clearing Next.js cache..."
|
@echo "Running Cucumber e2e tests with SQLite..."
|
||||||
rm -rf .next/
|
DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance:cucumber
|
||||||
@echo "Running Cucumber e2e tests..."
|
|
||||||
|
# Run Cucumber e2e tests with PostgreSQL (uses .env.development)
|
||||||
|
test-cucumber-postgres:
|
||||||
|
@echo "Running Cucumber e2e tests with PostgreSQL..."
|
||||||
npm run test:acceptance:cucumber
|
npm run test:acceptance:cucumber
|
||||||
|
|
||||||
# Run Cucumber e2e tests against production build
|
# Run Cucumber e2e tests with PostgreSQL against production build
|
||||||
test-cucumber-prod:
|
# This is more reliable than dev server (no HMR, faster API responses)
|
||||||
@echo "Clearing Next.js cache..."
|
test-cucumber-postgres-prod:
|
||||||
rm -rf .next/
|
|
||||||
@echo "Building application for production..."
|
@echo "Building application for production..."
|
||||||
bun run build
|
bun run build
|
||||||
@echo "Starting production server in background..."
|
@echo "Starting production server in background..."
|
||||||
@@ -91,6 +109,9 @@ test-cucumber-prod:
|
|||||||
kill $$SERVER_PID 2>/dev/null || true
|
kill $$SERVER_PID 2>/dev/null || true
|
||||||
@echo "Tests completed."
|
@echo "Tests completed."
|
||||||
|
|
||||||
|
# Run all e2e tests (both Playwright and Cucumber)
|
||||||
|
test-e2e: test-acceptance-sqlite test-cucumber-sqlite
|
||||||
|
|
||||||
# Run database migrations (Prisma)
|
# Run database migrations (Prisma)
|
||||||
migrate:
|
migrate:
|
||||||
npx prisma migrate dev
|
npx prisma migrate dev
|
||||||
@@ -99,6 +120,13 @@ migrate:
|
|||||||
seed:
|
seed:
|
||||||
npm run db:seed
|
npm run db:seed
|
||||||
|
|
||||||
|
# Switch database provider
|
||||||
|
db-switch-sqlite:
|
||||||
|
npm run db:switch sqlite
|
||||||
|
|
||||||
|
db-switch-postgres:
|
||||||
|
npm run db:switch postgresql
|
||||||
|
|
||||||
# --- Docker ---
|
# --- Docker ---
|
||||||
|
|
||||||
# Build the Docker image (standard build)
|
# Build the Docker image (standard build)
|
||||||
@@ -114,6 +142,7 @@ docker-build-commit:
|
|||||||
docker-build-full: docker-build docker-build-commit
|
docker-build-full: docker-build docker-build-commit
|
||||||
|
|
||||||
# Fast rebuild using Docker BuildKit cache
|
# Fast rebuild using Docker BuildKit cache
|
||||||
|
# Uses build cache to speed up rebuilds when only code changes
|
||||||
docker-rebuild-fast:
|
docker-rebuild-fast:
|
||||||
@echo "Fast rebuilding Docker image {{PROJECT}}:{{IMAGE_TAG}}..."
|
@echo "Fast rebuilding Docker image {{PROJECT}}:{{IMAGE_TAG}}..."
|
||||||
DOCKER_BUILDKIT=1 docker build \
|
DOCKER_BUILDKIT=1 docker build \
|
||||||
@@ -160,14 +189,19 @@ docker-push: docker-build-full
|
|||||||
|
|
||||||
# --- CI/CD Pipeline Simulation ---
|
# --- CI/CD Pipeline Simulation ---
|
||||||
|
|
||||||
# Run full CI pipeline locally (lint, test, build)
|
# Run full CI pipeline locally (lint, test, build, push)
|
||||||
ci: lint typecheck test-unit test-acceptance docker-build
|
# Matches the Gitea Actions workflow
|
||||||
|
ci: lint typecheck test-unit test-acceptance-sqlite docker-build
|
||||||
@echo "CI Pipeline completed successfully!"
|
@echo "CI Pipeline completed successfully!"
|
||||||
|
|
||||||
# PR validation (what runs on pull requests)
|
# PR validation (what runs on pull requests)
|
||||||
pr-validate: lint typecheck test-unit test-acceptance
|
pr-validate: lint typecheck test-unit test-acceptance-sqlite
|
||||||
@echo "PR validation completed successfully!"
|
@echo "PR validation completed successfully!"
|
||||||
|
|
||||||
|
# Run CI with PostgreSQL (for release workflow simulation)
|
||||||
|
ci-postgres: lint typecheck test-unit test-acceptance-postgres docker-build
|
||||||
|
@echo "CI Pipeline with PostgreSQL completed successfully!"
|
||||||
|
|
||||||
# --- Utilities ---
|
# --- Utilities ---
|
||||||
|
|
||||||
# Show help information
|
# Show help information
|
||||||
@@ -177,7 +211,9 @@ help:
|
|||||||
# Clean up project (remove node_modules, build artifacts)
|
# Clean up project (remove node_modules, build artifacts)
|
||||||
clean:
|
clean:
|
||||||
@echo "Cleaning project..."
|
@echo "Cleaning project..."
|
||||||
rm -rf node_modules .next dist .turbo
|
rm -rf node_modules .next dist
|
||||||
|
@echo "Cleaning Docker artifacts..."
|
||||||
|
docker system prune -f
|
||||||
|
|
||||||
# Generate Prisma client
|
# Generate Prisma client
|
||||||
prisma-generate:
|
prisma-generate:
|
||||||
@@ -239,72 +275,13 @@ workflow-status:
|
|||||||
@echo "PR Workflow: Runs unit + acceptance tests on pull requests"
|
@echo "PR Workflow: Runs unit + acceptance tests on pull requests"
|
||||||
@echo "Test Workflow: Runs unit tests on all branch pushes"
|
@echo "Test Workflow: Runs unit tests on all branch pushes"
|
||||||
@echo "Release Workflow: Runs on main branch pushes (version bump + Docker build)"
|
@echo "Release Workflow: Runs on main branch pushes (version bump + Docker build)"
|
||||||
|
|
||||||
# --- Production Deployment ---
|
|
||||||
|
|
||||||
# Deploy a specific version to production (human gate)
|
|
||||||
# Usage: just deploy-prod v0.1.21
|
|
||||||
deploy-prod version:
|
|
||||||
@echo "Deploying {{version}} to production..."
|
|
||||||
@echo "This requires the image to already be pushed to the registry."
|
|
||||||
@echo ""
|
@echo ""
|
||||||
@read -p "Have you verified this version works in dev? (y/N) " confirm; \
|
@echo "Note: CI image approach deprecated due to Gitea Actions workspace mounting"
|
||||||
if [ "$$confirm" != "y" ]; then \
|
|
||||||
echo "Cancelled. Please verify in dev first."; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
cd /apps/youthful_simon && \
|
|
||||||
sed -i "s|image: docker.notsosm.art/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:{{version}}|" docker-compose.yml && \
|
|
||||||
sed -i "s|image: euchre-camp/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:{{version}}|" docker-compose.yml && \
|
|
||||||
docker compose pull app && \
|
|
||||||
docker compose up -d app && \
|
|
||||||
echo "Waiting for production site to be healthy..." && \
|
|
||||||
for i in {1..6}; do \
|
|
||||||
if curl -sf https://euchre.notsosm.art/api/health > /dev/null 2>&1; then \
|
|
||||||
echo "✅ Production successfully deployed with version {{version}}"; \
|
|
||||||
exit 0; \
|
|
||||||
fi; \
|
|
||||||
sleep 15; \
|
|
||||||
done && \
|
|
||||||
echo "❌ Production deployment failed - health check timed out"; \
|
|
||||||
docker compose logs app; \
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
# Show current deployment status across all environments
|
# Check current database provider
|
||||||
status:
|
db-status:
|
||||||
@echo "=== EuchreCamp Deployment Status ==="
|
@echo "Database Provider: ${DATABASE_PROVIDER}"
|
||||||
|
@echo "Database URL: ${DATABASE_URL}"
|
||||||
@echo ""
|
@echo ""
|
||||||
@echo "CI Site (euchre-camp-ci):"
|
@echo "Current schema.prisma provider:"
|
||||||
@grep "image:" /apps/euchre_camp_ci/docker-compose.yml | head -1
|
grep -A 2 "datasource db" prisma/schema.prisma | head -3
|
||||||
@echo ""
|
|
||||||
@echo "Dev Site (euchre-camp-dev):"
|
|
||||||
@grep "image:" /apps/intelligent_silasak/docker-compose.yml | head -1
|
|
||||||
@echo ""
|
|
||||||
@echo "Prod Site (euchre-camp):"
|
|
||||||
@grep "image:" /apps/youthful_simon/docker-compose.yml | head -1
|
|
||||||
@echo ""
|
|
||||||
|
|
||||||
# --- SDLC Database Operations ---
|
|
||||||
|
|
||||||
# Sync production data to development database (manual operation)
|
|
||||||
sync-dev:
|
|
||||||
@echo "Syncing production data to development database..."
|
|
||||||
node scripts/sync-prod-to-dev.js
|
|
||||||
|
|
||||||
# Run acceptance tests against production database (opt-in, manual)
|
|
||||||
test-prod:
|
|
||||||
@echo "⚠️ WARNING: This will run tests against the PRODUCTION database!"
|
|
||||||
@echo " All test records will be cleaned up after the run."
|
|
||||||
@echo ""
|
|
||||||
@read -p "Are you sure you want to continue? (y/N) " confirm; \
|
|
||||||
if [ "$$confirm" != "y" ]; then \
|
|
||||||
echo "Cancelled."; \
|
|
||||||
else \
|
|
||||||
DATABASE_URL="$$PROD_DATABASE_URL" bun test:acceptance; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Reset CI database (for local CI testing)
|
|
||||||
reset-ci-db:
|
|
||||||
@echo "Resetting CI database..."
|
|
||||||
psql "$CI_DATABASE_URL" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
|
|
||||||
bunx prisma migrate deploy
|
|
||||||
|
|||||||
Generated
+2125
-2758
File diff suppressed because it is too large
Load Diff
+24
-20
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "euchre_camp",
|
"name": "euchre_camp",
|
||||||
"version": "0.1.21",
|
"version": "0.1.6",
|
||||||
"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",
|
||||||
@@ -17,10 +17,14 @@
|
|||||||
"test:acceptance:headed": "bun x playwright test e2e/ --headed",
|
"test:acceptance:headed": "bun x playwright test e2e/ --headed",
|
||||||
"test:acceptance:cucumber": "DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"') DATABASE_PROVIDER=postgresql bun cucumber-js --config e2e/cucumber/cucumber.config.ts",
|
"test:acceptance:cucumber": "DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"') DATABASE_PROVIDER=postgresql bun cucumber-js --config e2e/cucumber/cucumber.config.ts",
|
||||||
"test:acceptance:cucumber:pretty": "DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"') DATABASE_PROVIDER=postgresql bun cucumber-js --config e2e/cucumber/cucumber.config.ts --format pretty:cucumber-pretty",
|
"test:acceptance:cucumber:pretty": "DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"') DATABASE_PROVIDER=postgresql bun cucumber-js --config e2e/cucumber/cucumber.config.ts --format pretty:cucumber-pretty",
|
||||||
"test:acceptance:cucumber:prod": "bun run build && (trap 'kill $(jobs -p) 2>/dev/null || true' EXIT; DATABASE_URL=${DATABASE_URL:-$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"')} DATABASE_PROVIDER=${DATABASE_PROVIDER:-postgresql} bun run start & echo 'Waiting for server to start...'; for i in {1..30}; do if curl -s http://localhost:3000 > /dev/null 2>&1; then echo 'Server ready!'; break; fi; sleep 1; done; npm run test:acceptance:cucumber)",
|
"test:acceptance:cucumber:prod": "bun run build && (DATABASE_URL=${DATABASE_URL:-$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"')} DATABASE_PROVIDER=${DATABASE_PROVIDER:-postgresql} bun run start & SERVER_PID=$! && sleep 15 && npm run test:acceptance:cucumber; kill $SERVER_PID 2>/dev/null || true)",
|
||||||
"cucumber": "DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"') DATABASE_PROVIDER=postgresql bun cucumber-js --config e2e/cucumber/cucumber.config.ts",
|
"cucumber": "DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '\"') DATABASE_PROVIDER=postgresql bun cucumber-js --config e2e/cucumber/cucumber.config.ts",
|
||||||
|
"db:switch": "bun run scripts/switch-database.js",
|
||||||
|
"db:setup-postgres": "bun run scripts/setup-postgres.js",
|
||||||
"db:setup-dev": "bun run scripts/setup-postgres.js",
|
"db:setup-dev": "bun run scripts/setup-postgres.js",
|
||||||
"db:setup-dev:clean": "bun run scripts/setup-postgres.js --drop",
|
"db:setup-dev:clean": "bun run scripts/setup-postgres.js --drop",
|
||||||
|
"db:reset-dev": "bun run scripts/reset-dev-db.js",
|
||||||
|
"db:use-dev": "bun run scripts/use-dev-db.js",
|
||||||
"db:cleanup-prod": "bun run scripts/cleanup-prod-db.js",
|
"db:cleanup-prod": "bun run scripts/cleanup-prod-db.js",
|
||||||
"db:check-prod": "bun run scripts/check-test-records.js",
|
"db:check-prod": "bun run scripts/check-test-records.js",
|
||||||
"db:seed": "bun run scripts/seed.js",
|
"db:seed": "bun run scripts/seed.js",
|
||||||
@@ -40,35 +44,35 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "^5.2.2",
|
"@hookform/resolvers": "^5.2.2",
|
||||||
"@prisma/adapter-pg": "^7.8.0",
|
"@prisma/adapter-pg": "^7.6.0",
|
||||||
"@prisma/client": "^7.8.0",
|
"@prisma/client": "^7.6.0",
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"better-auth": "^1.6.9",
|
"better-auth": "^1.5.6",
|
||||||
"glicko2": "^1.2.1",
|
"glicko2": "^1.2.1",
|
||||||
"jose": "^6.2.2",
|
"jose": "^6.2.2",
|
||||||
"next": "^16.2.4",
|
"next": "^16.2.1",
|
||||||
"openskill": "^4.1.1",
|
"openskill": "^4.1.1",
|
||||||
"papaparse": "^5.5.3",
|
"papaparse": "^5.5.3",
|
||||||
"pg": "^8.20.0",
|
"pg": "^8.20.0",
|
||||||
"prisma": "^7.8.0",
|
"prisma": "^7.6.0",
|
||||||
"react": "^19.2.5",
|
"react": "^19.2.4",
|
||||||
"react-dom": "^19.2.5",
|
"react-dom": "^19.2.4",
|
||||||
"react-hook-form": "^7.74.0",
|
"react-hook-form": "^7.72.0",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cucumber/cucumber": "^12.8.2",
|
"@cucumber/cucumber": "^12.8.2",
|
||||||
"@playwright/test": "^1.59.1",
|
"@playwright/test": "^1.58.2",
|
||||||
"@tailwindcss/postcss": "^4.2.4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@testing-library/jest-dom": "^6.9.1",
|
"@testing-library/jest-dom": "^6.9.1",
|
||||||
"@testing-library/react": "^16.3.2",
|
"@testing-library/react": "^16.3.2",
|
||||||
"@testing-library/user-event": "^14.6.1",
|
"@testing-library/user-event": "^14.6.1",
|
||||||
"@types/bcrypt": "^6.0.0",
|
"@types/bcrypt": "^6.0.0",
|
||||||
"@types/bun": "^1.3.13",
|
"@types/bun": "^1.3.11",
|
||||||
"@types/jsdom": "^28.0.1",
|
"@types/jsdom": "^28.0.1",
|
||||||
"@types/node": "^20.19.39",
|
"@types/node": "^20",
|
||||||
"@types/papaparse": "^5.5.2",
|
"@types/papaparse": "^5.5.2",
|
||||||
"@types/pg": "^8.20.0",
|
"@types/pg": "^8.20.0",
|
||||||
"@types/react": "^19.2.14",
|
"@types/react": "^19.2.14",
|
||||||
@@ -76,12 +80,12 @@
|
|||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
"argon2": "^0.44.0",
|
"argon2": "^0.44.0",
|
||||||
"cucumber-pretty": "^6.0.1",
|
"cucumber-pretty": "^6.0.1",
|
||||||
"eslint": "^8.57.1",
|
"eslint": "^8.57.0",
|
||||||
"eslint-config-next": "^16.2.4",
|
"eslint-config-next": "^16.2.1",
|
||||||
"jsdom": "^29.1.0",
|
"jsdom": "^29.0.1",
|
||||||
"tailwindcss": "^4.2.4",
|
"tailwindcss": "^4",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5",
|
||||||
"vitest": "^4.1.5"
|
"vitest": "^4.1.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-11
@@ -4,20 +4,23 @@ export default defineConfig({
|
|||||||
testDir: './e2e',
|
testDir: './e2e',
|
||||||
timeout: 30000,
|
timeout: 30000,
|
||||||
expect: {
|
expect: {
|
||||||
timeout: 2000
|
timeout: 5000
|
||||||
},
|
},
|
||||||
// Run tests in parallel for speed - database isolation is per-test via unique data
|
// Run tests sequentially to avoid database conflicts with SQLite
|
||||||
fullyParallel: true,
|
fullyParallel: false,
|
||||||
// Use multiple workers in CI to speed up test execution
|
// Fail the build on CI if you accidentally left test.only in the source code.
|
||||||
workers: process.env.CI ? 10 : 1,
|
forbidOnly: !!process.env.CI,
|
||||||
|
// Retry on CI only.
|
||||||
|
retries: process.env.CI ? 2 : 0,
|
||||||
|
// Always run with 1 worker to avoid database conflicts with SQLite
|
||||||
|
workers: 1,
|
||||||
// Reporter to use
|
// Reporter to use
|
||||||
reporter: 'html',
|
reporter: 'html',
|
||||||
// Global setup and teardown
|
// Global setup and teardown
|
||||||
globalSetup: require.resolve('./e2e/global.setup'),
|
globalSetup: require.resolve('./e2e/global.setup'),
|
||||||
globalTeardown: require.resolve('./e2e/global.teardown'),
|
|
||||||
// Use base URL for relative navigation
|
// Use base URL for relative navigation
|
||||||
use: {
|
use: {
|
||||||
baseURL: process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000',
|
baseURL: 'http://localhost:3000',
|
||||||
// Collect trace when retrying the failed test.
|
// Collect trace when retrying the failed test.
|
||||||
trace: 'on-first-retry',
|
trace: 'on-first-retry',
|
||||||
// Capture screenshot only on failure
|
// Capture screenshot only on failure
|
||||||
@@ -39,7 +42,6 @@ export default defineConfig({
|
|||||||
storageState: 'playwright/.auth/user.json',
|
storageState: 'playwright/.auth/user.json',
|
||||||
},
|
},
|
||||||
dependencies: ['setup'],
|
dependencies: ['setup'],
|
||||||
testIgnore: ['**/admin-*.test.ts'],
|
|
||||||
},
|
},
|
||||||
// Admin user project
|
// Admin user project
|
||||||
{
|
{
|
||||||
@@ -60,12 +62,11 @@ export default defineConfig({
|
|||||||
storageState: undefined,
|
storageState: undefined,
|
||||||
},
|
},
|
||||||
dependencies: ['setup'],
|
dependencies: ['setup'],
|
||||||
testIgnore: ['**/admin-*.test.ts'],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
// Run your local dev server before starting the tests
|
// Run your local dev server before starting the tests
|
||||||
webServer: process.env.CI ? undefined : {
|
webServer: {
|
||||||
command: 'bun run dev',
|
command: 'npm run dev',
|
||||||
url: 'http://localhost:3000',
|
url: 'http://localhost:3000',
|
||||||
timeout: 120000,
|
timeout: 120000,
|
||||||
reuseExistingServer: !process.env.CI,
|
reuseExistingServer: !process.env.CI,
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
-- DropForeignKey
|
|
||||||
ALTER TABLE "matches" DROP CONSTRAINT "matches_player1P1Id_fkey";
|
|
||||||
|
|
||||||
-- DropForeignKey
|
|
||||||
ALTER TABLE "matches" DROP CONSTRAINT "matches_player1P2Id_fkey";
|
|
||||||
|
|
||||||
-- DropForeignKey
|
|
||||||
ALTER TABLE "matches" DROP CONSTRAINT "matches_player2P1Id_fkey";
|
|
||||||
|
|
||||||
-- DropForeignKey
|
|
||||||
ALTER TABLE "matches" DROP CONSTRAINT "matches_player2P2Id_fkey";
|
|
||||||
|
|
||||||
-- CreateTable
|
|
||||||
CREATE TABLE "activities" (
|
|
||||||
"id" SERIAL NOT NULL,
|
|
||||||
"type" TEXT NOT NULL,
|
|
||||||
"description" TEXT NOT NULL,
|
|
||||||
"userId" TEXT,
|
|
||||||
"playerId" INTEGER,
|
|
||||||
"eventId" INTEGER,
|
|
||||||
"matchId" INTEGER,
|
|
||||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
|
|
||||||
CONSTRAINT "activities_pkey" PRIMARY KEY ("id")
|
|
||||||
);
|
|
||||||
|
|
||||||
-- CreateTable
|
|
||||||
CREATE TABLE "club_settings" (
|
|
||||||
"id" SERIAL NOT NULL,
|
|
||||||
"clubName" TEXT NOT NULL DEFAULT 'Euchre Club',
|
|
||||||
"defaultEloRating" INTEGER NOT NULL DEFAULT 1200,
|
|
||||||
"partnershipEnabled" BOOLEAN NOT NULL DEFAULT true,
|
|
||||||
"notificationsEnabled" BOOLEAN NOT NULL DEFAULT true,
|
|
||||||
"matchVerification" BOOLEAN NOT NULL DEFAULT false,
|
|
||||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
||||||
|
|
||||||
CONSTRAINT "club_settings_pkey" PRIMARY KEY ("id")
|
|
||||||
);
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "matches" ADD CONSTRAINT "matches_player1P1Id_fkey" FOREIGN KEY ("player1P1Id") REFERENCES "players"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "matches" ADD CONSTRAINT "matches_player1P2Id_fkey" FOREIGN KEY ("player1P2Id") REFERENCES "players"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "matches" ADD CONSTRAINT "matches_player2P1Id_fkey" FOREIGN KEY ("player2P1Id") REFERENCES "players"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "matches" ADD CONSTRAINT "matches_player2P2Id_fkey" FOREIGN KEY ("player2P2Id") REFERENCES "players"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "activities" ADD CONSTRAINT "activities_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "activities" ADD CONSTRAINT "activities_playerId_fkey" FOREIGN KEY ("playerId") REFERENCES "players"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "activities" ADD CONSTRAINT "activities_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "events"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "activities" ADD CONSTRAINT "activities_matchId_fkey" FOREIGN KEY ("matchId") REFERENCES "matches"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
|
||||||
@@ -27,7 +27,6 @@ model Player {
|
|||||||
partnershipGames2 PartnershipGame[] @relation("PartnershipPlayer2")
|
partnershipGames2 PartnershipGame[] @relation("PartnershipPlayer2")
|
||||||
partnershipStats PartnershipStat[] @relation("StatPlayer1")
|
partnershipStats PartnershipStat[] @relation("StatPlayer1")
|
||||||
partnershipStats2 PartnershipStat[] @relation("StatPlayer2")
|
partnershipStats2 PartnershipStat[] @relation("StatPlayer2")
|
||||||
activities Activity[]
|
|
||||||
user User?
|
user User?
|
||||||
eloRating EloRating?
|
eloRating EloRating?
|
||||||
glicko2Rating Glicko2Rating?
|
glicko2Rating Glicko2Rating?
|
||||||
@@ -54,7 +53,6 @@ model User {
|
|||||||
ownedTournaments Event[] @relation("TournamentOwner")
|
ownedTournaments Event[] @relation("TournamentOwner")
|
||||||
createdMatches Match[] @relation("MatchCreator")
|
createdMatches Match[] @relation("MatchCreator")
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
activities Activity[]
|
|
||||||
player Player? @relation(fields: [playerId], references: [id])
|
player Player? @relation(fields: [playerId], references: [id])
|
||||||
|
|
||||||
@@map("users")
|
@@map("users")
|
||||||
@@ -81,7 +79,6 @@ model Event {
|
|||||||
owner User? @relation("TournamentOwner", fields: [ownerId], references: [id])
|
owner User? @relation("TournamentOwner", fields: [ownerId], references: [id])
|
||||||
matches Match[]
|
matches Match[]
|
||||||
rounds TournamentRound[]
|
rounds TournamentRound[]
|
||||||
activities Activity[]
|
|
||||||
|
|
||||||
// Team configuration fields
|
// Team configuration fields
|
||||||
teamDurability String @default("permanent") // permanent, variable, per_round
|
teamDurability String @default("permanent") // permanent, variable, per_round
|
||||||
@@ -170,7 +167,6 @@ model Match {
|
|||||||
isCasual Boolean @default(false)
|
isCasual Boolean @default(false)
|
||||||
bracketMatchups BracketMatchup[]
|
bracketMatchups BracketMatchup[]
|
||||||
eloSnapshots EloSnapshot[]
|
eloSnapshots EloSnapshot[]
|
||||||
activities Activity[]
|
|
||||||
createdBy User? @relation("MatchCreator", fields: [createdById], references: [id])
|
createdBy User? @relation("MatchCreator", fields: [createdById], references: [id])
|
||||||
event Event? @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
event Event? @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||||
player1P1 Player? @relation("MatchPlayer1", fields: [player1P1Id], references: [id])
|
player1P1 Player? @relation("MatchPlayer1", fields: [player1P1Id], references: [id])
|
||||||
@@ -329,34 +325,3 @@ model OpenSkillRating {
|
|||||||
|
|
||||||
@@map("open_skill_ratings")
|
@@map("open_skill_ratings")
|
||||||
}
|
}
|
||||||
|
|
||||||
model Activity {
|
|
||||||
id Int @id @default(autoincrement())
|
|
||||||
type String // "player_registration", "tournament_created", "match_completed", "partnership_recorded"
|
|
||||||
description String
|
|
||||||
userId String?
|
|
||||||
playerId Int?
|
|
||||||
eventId Int?
|
|
||||||
matchId Int?
|
|
||||||
createdAt DateTime @default(now())
|
|
||||||
|
|
||||||
user User? @relation(fields: [userId], references: [id])
|
|
||||||
player Player? @relation(fields: [playerId], references: [id])
|
|
||||||
event Event? @relation(fields: [eventId], references: [id])
|
|
||||||
match Match? @relation(fields: [matchId], references: [id])
|
|
||||||
|
|
||||||
@@map("activities")
|
|
||||||
}
|
|
||||||
|
|
||||||
model ClubSettings {
|
|
||||||
id Int @id @default(autoincrement())
|
|
||||||
clubName String @default("Euchre Club")
|
|
||||||
defaultEloRating Int @default(1200)
|
|
||||||
partnershipEnabled Boolean @default(true)
|
|
||||||
notificationsEnabled Boolean @default(true)
|
|
||||||
matchVerification Boolean @default(false)
|
|
||||||
createdAt DateTime @default(now())
|
|
||||||
updatedAt DateTime @updatedAt
|
|
||||||
|
|
||||||
@@map("club_settings")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Generate 100+ games to test ELO rating calculations
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import random
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
DB_PATH = "prisma/prisma/dev.db"
|
||||||
|
|
||||||
|
|
||||||
|
def get_players():
|
||||||
|
"""Get all players from the database"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("SELECT id, name, currentElo FROM players")
|
||||||
|
players = cursor.fetchall()
|
||||||
|
conn.close()
|
||||||
|
return players
|
||||||
|
|
||||||
|
|
||||||
|
def generate_game(players, game_num, base_date):
|
||||||
|
"""Generate a single game with random players and scores"""
|
||||||
|
# Randomly select 4 different players
|
||||||
|
selected_players = random.sample(players, 4)
|
||||||
|
p1, p2, p3, p4 = selected_players
|
||||||
|
|
||||||
|
# Randomly assign teams (Team 1 vs Team 2)
|
||||||
|
team1_p1 = p1
|
||||||
|
team1_p2 = p2
|
||||||
|
team2_p1 = p3
|
||||||
|
team2_p2 = p4
|
||||||
|
|
||||||
|
# Generate realistic scores (Euchre games typically 10 points max)
|
||||||
|
# Team 1 wins 60% of the time for variety
|
||||||
|
team1_wins = random.random() < 0.6
|
||||||
|
if team1_wins:
|
||||||
|
# Team 1 wins - generate scores
|
||||||
|
team1_score = random.randint(10, 15)
|
||||||
|
team2_score = random.randint(0, 9)
|
||||||
|
else:
|
||||||
|
# Team 2 wins - generate scores
|
||||||
|
team2_score = random.randint(10, 15)
|
||||||
|
team1_score = random.randint(0, 9)
|
||||||
|
|
||||||
|
# Generate random date in the past 30 days
|
||||||
|
days_ago = random.randint(0, 30)
|
||||||
|
game_date = base_date - timedelta(
|
||||||
|
days=days_ago, hours=random.randint(0, 23), minutes=random.randint(0, 59)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"team1P1Id": team1_p1[0],
|
||||||
|
"team1P2Id": team1_p2[0],
|
||||||
|
"team2P1Id": team2_p1[0],
|
||||||
|
"team2P2Id": team2_p2[0],
|
||||||
|
"team1Score": team1_score,
|
||||||
|
"team2Score": team2_score,
|
||||||
|
"playedAt": game_date.isoformat() + "Z",
|
||||||
|
"status": "completed",
|
||||||
|
"eventId": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def insert_games(games):
|
||||||
|
"""Insert games into the database"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
for game in games:
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO matches
|
||||||
|
(team1P1Id, team1P2Id, team2P1Id, team2P2Id, team1Score, team2Score, playedAt, status, eventId, createdAt, updatedAt)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
game["team1P1Id"],
|
||||||
|
game["team1P2Id"],
|
||||||
|
game["team2P1Id"],
|
||||||
|
game["team2P2Id"],
|
||||||
|
game["team1Score"],
|
||||||
|
game["team2Score"],
|
||||||
|
game["playedAt"],
|
||||||
|
game["status"],
|
||||||
|
game["eventId"],
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Generating 150 games to test ELO ratings...")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
players = get_players()
|
||||||
|
print(f"Found {len(players)} players in database")
|
||||||
|
|
||||||
|
# Generate 150 games
|
||||||
|
num_games = 150
|
||||||
|
base_date = datetime.now()
|
||||||
|
|
||||||
|
games = []
|
||||||
|
for i in range(num_games):
|
||||||
|
game = generate_game(players, i, base_date)
|
||||||
|
games.append(game)
|
||||||
|
|
||||||
|
print(f"Generated {len(games)} games")
|
||||||
|
|
||||||
|
# Insert games into database
|
||||||
|
print("Inserting games into database...")
|
||||||
|
insert_games(games)
|
||||||
|
print("Games inserted successfully!")
|
||||||
|
|
||||||
|
# Show sample games
|
||||||
|
print("\nSample games:")
|
||||||
|
print("-" * 80)
|
||||||
|
for i, game in enumerate(games[:3]):
|
||||||
|
print(
|
||||||
|
f"Game {i + 1}: Team 1 ({game['team1Score']}) vs Team 2 ({game['team2Score']})"
|
||||||
|
)
|
||||||
|
print(f" Team 1: Player {game['team1P1Id']} + Player {game['team1P2Id']}")
|
||||||
|
print(f" Team 2: Player {game['team2P1Id']} + Player {game['team2P2Id']}")
|
||||||
|
print(f" Date: {game['playedAt']}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
print("=" * 60)
|
||||||
|
print(f"Total games generated: {num_games}")
|
||||||
|
print("Now check the ELO ratings by running the application!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Update partnership statistics based on matches in the database
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import math
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
DB_PATH = "prisma/prisma/dev.db"
|
||||||
|
K_FACTOR = 32
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_matches():
|
||||||
|
"""Get all matches from the database"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, team1P1Id, team1P2Id, team2P1Id, team2P2Id,
|
||||||
|
team1Score, team2Score, playedAt
|
||||||
|
FROM matches
|
||||||
|
ORDER BY playedAt
|
||||||
|
""")
|
||||||
|
matches = cursor.fetchall()
|
||||||
|
conn.close()
|
||||||
|
return matches
|
||||||
|
|
||||||
|
|
||||||
|
def get_or_create_partnership(player1_id, player2_id):
|
||||||
|
"""Get or create a partnership record"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Sort IDs to ensure consistent partnership lookup
|
||||||
|
p1 = min(player1_id, player2_id)
|
||||||
|
p2 = max(player1_id, player2_id)
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, gamesPlayed, wins, losses, totalEloChange
|
||||||
|
FROM partnership_stats
|
||||||
|
WHERE player1Id = ? AND player2Id = ?
|
||||||
|
""",
|
||||||
|
(p1, p2),
|
||||||
|
)
|
||||||
|
|
||||||
|
result = cursor.fetchone()
|
||||||
|
if result:
|
||||||
|
conn.close()
|
||||||
|
return result
|
||||||
|
|
||||||
|
# Create new partnership record
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO partnership_stats (player1Id, player2Id, gamesPlayed, wins, losses, totalEloChange, lastPlayed, createdAt, updatedAt)
|
||||||
|
VALUES (?, ?, 0, 0, 0, 0, NULL, ?, ?)
|
||||||
|
""",
|
||||||
|
(p1, p2, datetime.now().isoformat() + "Z", datetime.now().isoformat() + "Z"),
|
||||||
|
)
|
||||||
|
|
||||||
|
partnership_id = cursor.lastrowid
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return (partnership_id, 0, 0, 0, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def update_partnership_stats(player1_id, player2_id, won, elo_change):
|
||||||
|
"""Update partnership statistics"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Sort IDs to ensure consistent partnership lookup
|
||||||
|
p1 = min(player1_id, player2_id)
|
||||||
|
p2 = max(player1_id, player2_id)
|
||||||
|
|
||||||
|
# Get current partnership stats
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, gamesPlayed, wins, losses, totalEloChange
|
||||||
|
FROM partnership_stats
|
||||||
|
WHERE player1Id = ? AND player2Id = ?
|
||||||
|
""",
|
||||||
|
(p1, p2),
|
||||||
|
)
|
||||||
|
|
||||||
|
result = cursor.fetchone()
|
||||||
|
if not result:
|
||||||
|
# Create new partnership record
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO partnership_stats (player1Id, player2Id, gamesPlayed, wins, losses, totalEloChange, lastPlayed, createdAt, updatedAt)
|
||||||
|
VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
p1,
|
||||||
|
p2,
|
||||||
|
1 if won else 0,
|
||||||
|
0 if won else 1,
|
||||||
|
elo_change,
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
partnership_id, games_played, wins, losses, total_elo_change = result
|
||||||
|
|
||||||
|
# Update partnership stats
|
||||||
|
new_games = games_played + 1
|
||||||
|
new_wins = wins + 1 if won else wins
|
||||||
|
new_losses = losses if won else losses + 1
|
||||||
|
new_total_elo_change = total_elo_change + elo_change
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
UPDATE partnership_stats
|
||||||
|
SET gamesPlayed = ?, wins = ?, losses = ?, totalEloChange = ?, lastPlayed = ?, updatedAt = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
new_games,
|
||||||
|
new_wins,
|
||||||
|
new_losses,
|
||||||
|
new_total_elo_change,
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
datetime.now().isoformat() + "Z",
|
||||||
|
partnership_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Updating partnership statistics based on matches...")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Get all matches
|
||||||
|
matches = get_all_matches()
|
||||||
|
print(f"Found {len(matches)} matches in database")
|
||||||
|
|
||||||
|
# Reset partnership stats
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("DELETE FROM partnership_stats")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
print("Reset all partnership statistics")
|
||||||
|
|
||||||
|
# Process each match
|
||||||
|
match_count = 0
|
||||||
|
for (
|
||||||
|
match_id,
|
||||||
|
team1_p1,
|
||||||
|
team1_p2,
|
||||||
|
team2_p1,
|
||||||
|
team2_p2,
|
||||||
|
team1_score,
|
||||||
|
team2_score,
|
||||||
|
played_at,
|
||||||
|
) in matches:
|
||||||
|
# Determine winners
|
||||||
|
team1_won = team1_score > team2_score
|
||||||
|
team2_won = team2_score > team1_score
|
||||||
|
|
||||||
|
# Update partnership stats for Team 1
|
||||||
|
if team1_won:
|
||||||
|
update_partnership_stats(
|
||||||
|
team1_p1, team1_p2, True, 0
|
||||||
|
) # Elo change will be calculated separately
|
||||||
|
else:
|
||||||
|
update_partnership_stats(team1_p1, team1_p2, False, 0)
|
||||||
|
|
||||||
|
# Update partnership stats for Team 2
|
||||||
|
if team2_won:
|
||||||
|
update_partnership_stats(team2_p1, team2_p2, True, 0)
|
||||||
|
else:
|
||||||
|
update_partnership_stats(team2_p1, team2_p2, False, 0)
|
||||||
|
|
||||||
|
match_count += 1
|
||||||
|
if match_count % 20 == 0:
|
||||||
|
print(f"Processed {match_count}/{len(matches)} matches...")
|
||||||
|
|
||||||
|
print(f"Processed {match_count} matches")
|
||||||
|
|
||||||
|
# Display partnership stats for top players
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("Partnership Stats for Top Players:")
|
||||||
|
print("-" * 60)
|
||||||
|
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Get top players by ELO
|
||||||
|
cursor.execute("SELECT id, name FROM players ORDER BY currentElo DESC LIMIT 5")
|
||||||
|
top_players = cursor.fetchall()
|
||||||
|
|
||||||
|
for player_id, player_name in top_players:
|
||||||
|
print(f"\n{player_name}:")
|
||||||
|
|
||||||
|
# Get partnership stats for this player
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
CASE
|
||||||
|
WHEN player1Id = ? THEN (SELECT name FROM players WHERE id = player2Id)
|
||||||
|
ELSE (SELECT name FROM players WHERE id = player1Id)
|
||||||
|
END as partner_name,
|
||||||
|
gamesPlayed, wins, losses, totalEloChange
|
||||||
|
FROM partnership_stats
|
||||||
|
WHERE player1Id = ? OR player2Id = ?
|
||||||
|
ORDER BY gamesPlayed DESC
|
||||||
|
LIMIT 3
|
||||||
|
""",
|
||||||
|
(player_id, player_id, player_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
partnerships = cursor.fetchall()
|
||||||
|
for partner_name, games, wins, losses, elo_change in partnerships:
|
||||||
|
win_rate = (wins / games * 100) if games > 0 else 0
|
||||||
|
print(
|
||||||
|
f" - with {partner_name}: {games} games, {wins}/{losses} ({win_rate:.1f}%) ELO: {elo_change:+d}"
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("Partnership statistics updated successfully!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Update player statistics (ELO, gamesPlayed, wins, losses) based on matches in the database
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import math
|
||||||
|
|
||||||
|
DB_PATH = "prisma/prisma/dev.db"
|
||||||
|
K_FACTOR = 32 # Standard K-factor for Elo calculations
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_matches():
|
||||||
|
"""Get all matches from the database"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, team1P1Id, team1P2Id, team2P1Id, team2P2Id,
|
||||||
|
team1Score, team2Score, playedAt
|
||||||
|
FROM matches
|
||||||
|
ORDER BY playedAt
|
||||||
|
""")
|
||||||
|
matches = cursor.fetchall()
|
||||||
|
conn.close()
|
||||||
|
return matches
|
||||||
|
|
||||||
|
|
||||||
|
def get_player(player_id):
|
||||||
|
"""Get a player by ID"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT id, name, currentElo, gamesPlayed, wins, losses FROM players WHERE id = ?",
|
||||||
|
(player_id,),
|
||||||
|
)
|
||||||
|
player = cursor.fetchone()
|
||||||
|
conn.close()
|
||||||
|
return player
|
||||||
|
|
||||||
|
|
||||||
|
def update_player(player_id, current_elo, games_played, wins, losses):
|
||||||
|
"""Update a player's statistics"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
UPDATE players
|
||||||
|
SET currentElo = ?, gamesPlayed = ?, wins = ?, losses = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(current_elo, games_played, wins, losses, player_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_elo_change(rating_a, rating_b, score_a, score_b):
|
||||||
|
"""Calculate Elo change for a match"""
|
||||||
|
# Calculate expected scores
|
||||||
|
expected_a = 1 / (1 + math.pow(10, (rating_b - rating_a) / 400))
|
||||||
|
expected_b = 1 - expected_a
|
||||||
|
|
||||||
|
# Actual scores (1 for win, 0.5 for tie, 0 for loss)
|
||||||
|
actual_a = 0.5 if score_a == score_b else (1 if score_a > score_b else 0)
|
||||||
|
actual_b = 0.5 if score_a == score_b else (1 if score_b > score_a else 0)
|
||||||
|
|
||||||
|
# Calculate Elo change
|
||||||
|
elo_change_a = K_FACTOR * (actual_a - expected_a)
|
||||||
|
elo_change_b = K_FACTOR * (actual_b - expected_b)
|
||||||
|
|
||||||
|
return elo_change_a, elo_change_b
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Updating player statistics based on matches in database...")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Get all matches
|
||||||
|
matches = get_all_matches()
|
||||||
|
print(f"Found {len(matches)} matches in database")
|
||||||
|
|
||||||
|
# Reset all player stats to 0 before recalculating
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE players SET currentElo = 1000, gamesPlayed = 0, wins = 0, losses = 0"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
print("Reset all player statistics to initial values (ELO: 1000, games: 0)")
|
||||||
|
|
||||||
|
# Process each match
|
||||||
|
match_count = 0
|
||||||
|
for (
|
||||||
|
match_id,
|
||||||
|
team1_p1,
|
||||||
|
team1_p2,
|
||||||
|
team2_p1,
|
||||||
|
team2_p2,
|
||||||
|
team1_score,
|
||||||
|
team2_score,
|
||||||
|
played_at,
|
||||||
|
) in matches:
|
||||||
|
# Get player data
|
||||||
|
p1 = get_player(team1_p1)
|
||||||
|
p2 = get_player(team1_p2)
|
||||||
|
p3 = get_player(team2_p1)
|
||||||
|
p4 = get_player(team2_p2)
|
||||||
|
|
||||||
|
if not all([p1, p2, p3, p4]):
|
||||||
|
print(f"Warning: Could not find all players for match {match_id}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Calculate team ratings
|
||||||
|
team1_rating = (p1[2] + p2[2]) / 2 # currentElo
|
||||||
|
team2_rating = (p3[2] + p4[2]) / 2 # currentElo
|
||||||
|
|
||||||
|
# Calculate Elo changes
|
||||||
|
team1_elo_change, team2_elo_change = calculate_elo_change(
|
||||||
|
team1_rating, team2_rating, team1_score, team2_score
|
||||||
|
)
|
||||||
|
|
||||||
|
# Individual Elo changes (split evenly between team members)
|
||||||
|
p1_elo_change = team1_elo_change / 2
|
||||||
|
p2_elo_change = team1_elo_change / 2
|
||||||
|
p3_elo_change = team2_elo_change / 2
|
||||||
|
p4_elo_change = team2_elo_change / 2
|
||||||
|
|
||||||
|
# Determine winners
|
||||||
|
team1_won = team1_score > team2_score
|
||||||
|
team2_won = team2_score > team1_score
|
||||||
|
|
||||||
|
# Update player 1 stats
|
||||||
|
p1_new_elo = int(p1[2] + p1_elo_change)
|
||||||
|
p1_new_games = p1[3] + 1
|
||||||
|
p1_new_wins = p1[4] + 1 if team1_won else p1[4]
|
||||||
|
p1_new_losses = p1[5] if team1_won else p1[5] + 1
|
||||||
|
update_player(p1[0], p1_new_elo, p1_new_games, p1_new_wins, p1_new_losses)
|
||||||
|
|
||||||
|
# Update player 2 stats
|
||||||
|
p2_new_elo = int(p2[2] + p2_elo_change)
|
||||||
|
p2_new_games = p2[3] + 1
|
||||||
|
p2_new_wins = p2[4] + 1 if team1_won else p2[4]
|
||||||
|
p2_new_losses = p2[5] if team1_won else p2[5] + 1
|
||||||
|
update_player(p2[0], p2_new_elo, p2_new_games, p2_new_wins, p2_new_losses)
|
||||||
|
|
||||||
|
# Update player 3 stats
|
||||||
|
p3_new_elo = int(p3[2] + p3_elo_change)
|
||||||
|
p3_new_games = p3[3] + 1
|
||||||
|
p3_new_wins = p3[4] + 1 if team2_won else p3[4]
|
||||||
|
p3_new_losses = p3[5] if team2_won else p3[5] + 1
|
||||||
|
update_player(p3[0], p3_new_elo, p3_new_games, p3_new_wins, p3_new_losses)
|
||||||
|
|
||||||
|
# Update player 4 stats
|
||||||
|
p4_new_elo = int(p4[2] + p4_elo_change)
|
||||||
|
p4_new_games = p4[3] + 1
|
||||||
|
p4_new_wins = p4[4] + 1 if team2_won else p4[4]
|
||||||
|
p4_new_losses = p4[5] if team2_won else p4[5] + 1
|
||||||
|
update_player(p4[0], p4_new_elo, p4_new_games, p4_new_wins, p4_new_losses)
|
||||||
|
|
||||||
|
match_count += 1
|
||||||
|
if match_count % 20 == 0:
|
||||||
|
print(f"Processed {match_count}/{len(matches)} matches...")
|
||||||
|
|
||||||
|
print(f"Processed {match_count} matches")
|
||||||
|
|
||||||
|
# Display updated player rankings
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("Top 10 Players by ELO Rating:")
|
||||||
|
print("-" * 60)
|
||||||
|
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, name, currentElo, gamesPlayed, wins, losses
|
||||||
|
FROM players
|
||||||
|
ORDER BY currentElo DESC
|
||||||
|
LIMIT 10
|
||||||
|
""")
|
||||||
|
top_players = cursor.fetchall()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
for rank, (player_id, name, elo, games, wins, losses) in enumerate(top_players, 1):
|
||||||
|
win_rate = (wins / games * 100) if games > 0 else 0
|
||||||
|
print(
|
||||||
|
f"{rank:2}. {name:15} | ELO: {elo:4} | Games: {games:3} | W/L: {wins}/{losses} ({win_rate:.1f}%)"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("Player statistics updated successfully!")
|
||||||
|
print("Now run the application to see updated rankings.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Executable
+108
@@ -0,0 +1,108 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Script to switch between SQLite and PostgreSQL databases
|
||||||
|
* Usage: node scripts/switch-database.js [sqlite|postgres]
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const envFile = '.env';
|
||||||
|
const envExampleFile = '.env.example';
|
||||||
|
|
||||||
|
function updateEnvFile(provider) {
|
||||||
|
const envPath = path.join(process.cwd(), envFile);
|
||||||
|
|
||||||
|
// Read current .env file or create from example
|
||||||
|
let envContent = '';
|
||||||
|
if (fs.existsSync(envPath)) {
|
||||||
|
envContent = fs.readFileSync(envPath, 'utf8');
|
||||||
|
} else if (fs.existsSync(envExampleFile)) {
|
||||||
|
envContent = fs.readFileSync(envExampleFile, 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update DATABASE_PROVIDER (note: this is for reference only, not used by Prisma)
|
||||||
|
const providerRegex = /^DATABASE_PROVIDER=.*$/m;
|
||||||
|
if (providerRegex.test(envContent)) {
|
||||||
|
envContent = envContent.replace(providerRegex, `DATABASE_PROVIDER=${provider}`);
|
||||||
|
} else {
|
||||||
|
envContent += `\nDATABASE_PROVIDER=${provider}\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update DATABASE_URL based on provider
|
||||||
|
if (provider === 'sqlite') {
|
||||||
|
const sqliteUrl = 'DATABASE_URL="file:./prisma/dev.db"';
|
||||||
|
const urlRegex = /^DATABASE_URL=.*$/m;
|
||||||
|
if (urlRegex.test(envContent)) {
|
||||||
|
envContent = envContent.replace(urlRegex, sqliteUrl);
|
||||||
|
} else {
|
||||||
|
envContent += `${sqliteUrl}\n`;
|
||||||
|
}
|
||||||
|
} else if (provider === 'postgresql') {
|
||||||
|
const pgUrl = 'DATABASE_URL="postgresql://username:password@localhost:5432/euchre_camp"';
|
||||||
|
const urlRegex = /^DATABASE_URL=.*$/m;
|
||||||
|
if (urlRegex.test(envContent)) {
|
||||||
|
envContent = envContent.replace(urlRegex, pgUrl);
|
||||||
|
} else {
|
||||||
|
envContent += `${pgUrl}\n`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write updated content
|
||||||
|
fs.writeFileSync(envPath, envContent);
|
||||||
|
console.log(`✅ Updated ${envFile} to use ${provider} database`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateSchemaFile(provider) {
|
||||||
|
const schemaPath = path.join(process.cwd(), 'prisma', 'schema.prisma');
|
||||||
|
|
||||||
|
if (!fs.existsSync(schemaPath)) {
|
||||||
|
console.error(`❌ Schema file not found: ${schemaPath}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let schemaContent = fs.readFileSync(schemaPath, 'utf8');
|
||||||
|
|
||||||
|
// Update the provider in the datasource block
|
||||||
|
const providerRegex = /(datasource db\s*\{[^}]*provider\s*=\s*)"[^"]+"/;
|
||||||
|
if (providerRegex.test(schemaContent)) {
|
||||||
|
schemaContent = schemaContent.replace(
|
||||||
|
providerRegex,
|
||||||
|
`$1"${provider}"`
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(schemaPath, schemaContent);
|
||||||
|
console.log(`✅ Updated schema.prisma to use ${provider} provider`);
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
console.error(`❌ Could not find provider declaration in schema.prisma`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const provider = args[0];
|
||||||
|
|
||||||
|
if (!provider) {
|
||||||
|
console.error('❌ Usage: node scripts/switch-database.js [sqlite|postgres]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!['sqlite', 'postgres', 'postgresql'].includes(provider)) {
|
||||||
|
console.error(`❌ Invalid provider: ${provider}. Must be 'sqlite' or 'postgres'`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedProvider = provider === 'postgres' ? 'postgresql' : provider;
|
||||||
|
updateEnvFile(normalizedProvider);
|
||||||
|
updateSchemaFile(normalizedProvider);
|
||||||
|
|
||||||
|
console.log('\nNext steps:');
|
||||||
|
console.log('1. Run: npx prisma generate');
|
||||||
|
console.log('2. Run: npx prisma migrate deploy');
|
||||||
|
console.log('3. Restart your development server');
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sync production data to development database
|
|
||||||
*
|
|
||||||
* This script copies real data from production to development, filtering out
|
|
||||||
* test records to keep the dev database clean for testing.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const { execSync } = require('child_process');
|
|
||||||
const fs = require('fs');
|
|
||||||
const os = require('os');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
const PROD_DB_URL = process.env.PROD_DATABASE_URL;
|
|
||||||
const DEV_DB_URL = process.env.DEV_DATABASE_URL;
|
|
||||||
|
|
||||||
if (!PROD_DB_URL || !DEV_DB_URL) {
|
|
||||||
console.error('❌ Missing environment variables');
|
|
||||||
console.error('Please set PROD_DATABASE_URL and DEV_DATABASE_URL');
|
|
||||||
console.error('');
|
|
||||||
console.error('Example:');
|
|
||||||
console.error(' PROD_DATABASE_URL="postgresql://user:pass@host:5432/euchre_camp" \\');
|
|
||||||
console.error(' DEV_DATABASE_URL="postgresql://user:pass@host:5432/euchre_camp_dev" \\');
|
|
||||||
console.error(' node scripts/sync-prod-to-dev.js');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (PROD_DB_URL.includes('_dev') || PROD_DB_URL.includes('_ci')) {
|
|
||||||
console.error('❌ PROD_DATABASE_URL appears to be a non-production database!');
|
|
||||||
console.error(' This script should only be used with the production database.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const TEST_PATTERNS = {
|
|
||||||
players: [
|
|
||||||
'%Test%',
|
|
||||||
'%Setup%',
|
|
||||||
'%Home Test%',
|
|
||||||
'%Home Match Player%',
|
|
||||||
'%Admin User%',
|
|
||||||
'%NinePart%',
|
|
||||||
'%Nine Part%',
|
|
||||||
'%Test Player%',
|
|
||||||
'%TestUser%',
|
|
||||||
'%Cucumber%',
|
|
||||||
'%Config Admin%',
|
|
||||||
],
|
|
||||||
events: [
|
|
||||||
'%Test%',
|
|
||||||
'%Setup%',
|
|
||||||
'%Recent%',
|
|
||||||
'%Test Tournament%',
|
|
||||||
'%Cucumber%',
|
|
||||||
],
|
|
||||||
users: [
|
|
||||||
'%test%',
|
|
||||||
'%setup%',
|
|
||||||
'%cucumber%',
|
|
||||||
'%TestUser%',
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
function buildLikeClause(patterns) {
|
|
||||||
return patterns.map(p => `name LIKE '${p}'`).join(' OR ');
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildEmailLikeClause(patterns) {
|
|
||||||
return patterns.map(p => `email LIKE '${p}'`).join(' OR ');
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
console.log('🔄 Syncing production data to development database');
|
|
||||||
console.log('====================================================\n');
|
|
||||||
|
|
||||||
const readline = require('readline');
|
|
||||||
const rl = readline.createInterface({
|
|
||||||
input: process.stdin,
|
|
||||||
output: process.stdout
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('⚠️ WARNING: This will OVERWRITE the development database!');
|
|
||||||
console.log(' Production data will be copied, with test records excluded.');
|
|
||||||
console.log('');
|
|
||||||
console.log('Source:', PROD_DB_URL.replace(/:[^:@]+@/, ':***@'));
|
|
||||||
console.log('Target:', DEV_DB_URL.replace(/:[^:@]+@/, ':***@'));
|
|
||||||
console.log('');
|
|
||||||
|
|
||||||
rl.question('Type "sync" to confirm: ', async (answer) => {
|
|
||||||
if (answer !== 'sync') {
|
|
||||||
console.log('❌ Cancelled');
|
|
||||||
rl.close();
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
rl.close();
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log('\n📦 Dumping production data...');
|
|
||||||
|
|
||||||
const dumpFile = path.join(os.tmpdir(), `prod_dump_${Date.now()}.sql`);
|
|
||||||
|
|
||||||
execSync(`pg_dump "${PROD_DB_URL}" -f "${dumpFile}" --no-owner --no-acl`, {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
console.log('✅ Dump created');
|
|
||||||
|
|
||||||
console.log('\n🗑️ Clearing development database...');
|
|
||||||
execSync(`psql "${DEV_DB_URL}" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"`, {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
console.log('✅ Development database cleared');
|
|
||||||
|
|
||||||
console.log('\n📥 Restoring to development database...');
|
|
||||||
execSync(`psql "${DEV_DB_URL}" -f "${dumpFile}"`, {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
console.log('✅ Data restored');
|
|
||||||
|
|
||||||
console.log('\n🧹 Cleaning up test records in dev database...');
|
|
||||||
|
|
||||||
const playerWhere = buildLikeClause(TEST_PATTERNS.players);
|
|
||||||
const eventWhere = buildLikeClause(TEST_PATTERNS.events);
|
|
||||||
const userWhere = buildEmailLikeClause(TEST_PATTERNS.users);
|
|
||||||
|
|
||||||
execSync(`psql "${DEV_DB_URL}" -c "DELETE FROM events WHERE (${eventWhere});"`, {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
console.log(' Deleted test events');
|
|
||||||
|
|
||||||
execSync(`psql "${DEV_DB_URL}" -c "DELETE FROM players WHERE (${playerWhere});"`, {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
console.log(' Deleted test players');
|
|
||||||
|
|
||||||
execSync(`psql "${DEV_DB_URL}" -c "DELETE FROM users WHERE (${userWhere}) AND \"playerId\" IS NULL;"`, {
|
|
||||||
stdio: 'inherit'
|
|
||||||
});
|
|
||||||
console.log(' Deleted test users');
|
|
||||||
|
|
||||||
fs.unlinkSync(dumpFile);
|
|
||||||
console.log('\n🧹 Cleaned up temporary dump file');
|
|
||||||
|
|
||||||
console.log('\n✅ Sync complete!');
|
|
||||||
console.log('\n📊 Summary:');
|
|
||||||
console.log(' - Production data copied to development');
|
|
||||||
console.log(' - Test records filtered out');
|
|
||||||
console.log(' - Development database is now a mirror of production (minus test data)');
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('\n❌ Sync failed:', error.message);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
main();
|
|
||||||
Executable
+49
@@ -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');
|
||||||
@@ -8,7 +8,6 @@
|
|||||||
import { describe, it, expect, mock, beforeEach, afterEach } from 'bun:test'
|
import { describe, it, expect, mock, beforeEach, afterEach } from 'bun:test'
|
||||||
import { render, screen, waitFor } from '@testing-library/react'
|
import { render, screen, waitFor } from '@testing-library/react'
|
||||||
import Navigation from '@/components/Navigation'
|
import Navigation from '@/components/Navigation'
|
||||||
import { RoleSwitcherProvider } from '@/components/RoleSwitcher'
|
|
||||||
|
|
||||||
// Mock next/link
|
// Mock next/link
|
||||||
mock.module('next/link', () => ({
|
mock.module('next/link', () => ({
|
||||||
@@ -32,14 +31,6 @@ mock.module('@/lib/auth-client', () => ({
|
|||||||
// Mock fetch for role API call
|
// Mock fetch for role API call
|
||||||
global.fetch = mock(async () => new Response()) as any
|
global.fetch = mock(async () => new Response()) as any
|
||||||
|
|
||||||
function renderNavigation() {
|
|
||||||
return render(
|
|
||||||
<RoleSwitcherProvider>
|
|
||||||
<Navigation />
|
|
||||||
</RoleSwitcherProvider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
import { useSession as useSessionOriginal } from '@/components/SessionProvider'
|
import { useSession as useSessionOriginal } from '@/components/SessionProvider'
|
||||||
const useSession = useSessionOriginal as any
|
const useSession = useSessionOriginal as any
|
||||||
|
|
||||||
@@ -70,7 +61,7 @@ describe('Epic 1: Navigation Component', () => {
|
|||||||
refreshSession: mock(() => {}),
|
refreshSession: mock(() => {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
renderNavigation()
|
render(<Navigation />)
|
||||||
|
|
||||||
expect(screen.getByText('EuchreCamp')).toBeInTheDocument()
|
expect(screen.getByText('EuchreCamp')).toBeInTheDocument()
|
||||||
expect(screen.getByText('Rankings')).toBeInTheDocument()
|
expect(screen.getByText('Rankings')).toBeInTheDocument()
|
||||||
@@ -93,7 +84,7 @@ describe('Epic 1: Navigation Component', () => {
|
|||||||
refreshSession: mock(() => {}),
|
refreshSession: mock(() => {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
renderNavigation()
|
render(<Navigation />)
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(screen.getByText('Test User')).toBeInTheDocument()
|
expect(screen.getByText('Test User')).toBeInTheDocument()
|
||||||
@@ -118,7 +109,7 @@ describe('Epic 1: Navigation Component', () => {
|
|||||||
refreshSession: mock(() => {}),
|
refreshSession: mock(() => {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
renderNavigation()
|
render(<Navigation />)
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||||
@@ -151,7 +142,7 @@ describe('Epic 1: Navigation Component', () => {
|
|||||||
return new Response(JSON.stringify({}), { status: 200 })
|
return new Response(JSON.stringify({}), { status: 200 })
|
||||||
})
|
})
|
||||||
|
|
||||||
renderNavigation()
|
render(<Navigation />)
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(screen.getByText('Admin')).toBeInTheDocument()
|
expect(screen.getByText('Admin')).toBeInTheDocument()
|
||||||
@@ -186,7 +177,7 @@ describe('Epic 1: Navigation Component', () => {
|
|||||||
} as Response
|
} as Response
|
||||||
})
|
})
|
||||||
|
|
||||||
renderNavigation()
|
render(<Navigation />)
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||||
@@ -201,7 +192,7 @@ describe('Epic 1: Navigation Component', () => {
|
|||||||
refreshSession: mock(() => {}),
|
refreshSession: mock(() => {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
renderNavigation()
|
render(<Navigation />)
|
||||||
|
|
||||||
expect(screen.getByText('Loading...')).toBeInTheDocument()
|
expect(screen.getByText('Loading...')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import { describe, test, expect, mock, beforeEach } from 'bun:test';
|
import { describe, test, expect, mock, beforeEach } from 'bun:test';
|
||||||
import { hasRole, canManageTournament, canCreateTournaments } from '@/lib/permissions';
|
import { hasRole, canManageTournament, canCreateTournaments } from '@/lib/permissions';
|
||||||
import { getSession } from '@/lib/auth-simple';
|
import { getSession } from '@/lib/auth-simple';
|
||||||
|
import { prisma } from '@/lib/prisma';
|
||||||
import type { User } from '@prisma/client';
|
import type { User } from '@prisma/client';
|
||||||
|
|
||||||
// Create mock functions at module level
|
// Create mock functions at module level
|
||||||
|
|||||||
@@ -8,32 +8,12 @@ import { describe, it, expect, mock, beforeEach,} from 'bun:test';
|
|||||||
// Create mock functions at module level
|
// Create mock functions at module level
|
||||||
const eventFindUniqueMock = mock(async () => ({}));
|
const eventFindUniqueMock = mock(async () => ({}));
|
||||||
const eventUpdateMock = mock(async () => ({}));
|
const eventUpdateMock = mock(async () => ({}));
|
||||||
const userFindUniqueMock = mock(async () => ({
|
const canManageTournamentMock = mock(async () => ({ allowed: true }));
|
||||||
id: 'admin-1',
|
const canDeleteTournamentMock = mock(async () => ({ allowed: true }));
|
||||||
email: 'admin@example.com',
|
|
||||||
role: 'club_admin',
|
|
||||||
emailVerified: false,
|
|
||||||
name: null,
|
|
||||||
image: null,
|
|
||||||
playerId: null,
|
|
||||||
createdAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock auth-simple to return a valid session
|
// Mock prisma first
|
||||||
mock.module('@/lib/auth-simple', () => ({
|
|
||||||
getSession: mock(async () => ({
|
|
||||||
user: { id: 'admin-1', email: 'admin@example.com' },
|
|
||||||
session: { token: 'test', expiresAt: new Date() }
|
|
||||||
})),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock prisma with user and event
|
|
||||||
mock.module('@/lib/prisma', () => ({
|
mock.module('@/lib/prisma', () => ({
|
||||||
prisma: {
|
prisma: {
|
||||||
user: {
|
|
||||||
findUnique: userFindUniqueMock,
|
|
||||||
},
|
|
||||||
event: {
|
event: {
|
||||||
findUnique: eventFindUniqueMock,
|
findUnique: eventFindUniqueMock,
|
||||||
update: eventUpdateMock,
|
update: eventUpdateMock,
|
||||||
@@ -41,6 +21,12 @@ mock.module('@/lib/prisma', () => ({
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock the permissions module
|
||||||
|
mock.module('@/lib/permissions', () => ({
|
||||||
|
canManageTournament: canManageTournamentMock,
|
||||||
|
canDeleteTournament: canDeleteTournamentMock,
|
||||||
|
}));
|
||||||
|
|
||||||
// Import the route handler after mocking
|
// Import the route handler after mocking
|
||||||
import { PUT } from '@/app/api/tournaments/[id]/route';
|
import { PUT } from '@/app/api/tournaments/[id]/route';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
@@ -50,7 +36,8 @@ describe('Tournament Update API', () => {
|
|||||||
// Clear all mock history before each test
|
// Clear all mock history before each test
|
||||||
eventFindUniqueMock.mockClear();
|
eventFindUniqueMock.mockClear();
|
||||||
eventUpdateMock.mockClear();
|
eventUpdateMock.mockClear();
|
||||||
userFindUniqueMock.mockClear();
|
canManageTournamentMock.mockClear();
|
||||||
|
canDeleteTournamentMock.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update allowTies field when provided', async () => {
|
it('should update allowTies field when provided', async () => {
|
||||||
|
|||||||
@@ -59,17 +59,6 @@ export default async function AdminDashboard() {
|
|||||||
}),
|
}),
|
||||||
]) as [number, number, number, EventModel[]]
|
]) as [number, number, number, EventModel[]]
|
||||||
|
|
||||||
// Get recent activities (using any type to bypass TypeScript error for now)
|
|
||||||
const recentActivities = await (prisma as any).activity.findMany({
|
|
||||||
take: 10,
|
|
||||||
orderBy: { createdAt: "desc" },
|
|
||||||
include: {
|
|
||||||
user: { select: { name: true } },
|
|
||||||
player: { select: { name: true } },
|
|
||||||
event: { select: { name: true } },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
<Navigation />
|
<Navigation />
|
||||||
@@ -242,41 +231,6 @@ export default async function AdminDashboard() {
|
|||||||
</Link> in the rankings page.
|
</Link> in the rankings page.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Recent Activity Feed */}
|
|
||||||
<div className="bg-white shadow rounded-lg p-6 mt-6">
|
|
||||||
<div className="flex justify-between items-center mb-4">
|
|
||||||
<h2 className="text-lg font-medium text-gray-900">Recent Activity</h2>
|
|
||||||
<Link
|
|
||||||
href="/admin/activity"
|
|
||||||
className="text-green-600 hover:text-green-900 text-sm font-medium"
|
|
||||||
>
|
|
||||||
View All
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
{recentActivities.length > 0 ? (
|
|
||||||
<ul className="divide-y divide-gray-200">
|
|
||||||
{recentActivities.map((activity: any) => (
|
|
||||||
<li key={activity.id} className="py-3">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm text-gray-900">{activity.description}</p>
|
|
||||||
<p className="text-xs text-gray-500">
|
|
||||||
{new Date(activity.createdAt).toLocaleDateString()} at{' '}
|
|
||||||
{new Date(activity.createdAt).toLocaleTimeString()}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
|
|
||||||
{activity.type}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
) : (
|
|
||||||
<p className="text-gray-500">No recent activities.</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -231,34 +231,8 @@ export default function AdminPlayersPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Search and Filter Controls */}
|
|
||||||
<div className="bg-white shadow rounded-lg p-4 mb-4">
|
|
||||||
<div className="flex items-center space-x-4">
|
|
||||||
<div className="flex-1">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
name="search"
|
|
||||||
placeholder="Search players by name..."
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
|
|
||||||
onChange={async (e) => {
|
|
||||||
const search = e.target.value
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/api/players?search=${encodeURIComponent(search)}`)
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json()
|
|
||||||
setPlayers(data)
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Search failed:', err)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Player Table */}
|
{/* Player Table */}
|
||||||
<div className="bg-white shadow rounded-lg overflow-x-auto">
|
<div className="bg-white shadow rounded-lg overflow-hidden">
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
<table className="min-w-full divide-y divide-gray-200">
|
||||||
<thead className="bg-gray-50">
|
<thead className="bg-gray-50">
|
||||||
<tr>
|
<tr>
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useState, useEffect } from "react"
|
|
||||||
import Navigation from "@/components/Navigation"
|
|
||||||
import { redirect } from "next/navigation"
|
|
||||||
import { getSession } from "@/lib/auth-simple"
|
|
||||||
|
|
||||||
interface ClubSettings {
|
|
||||||
id: number
|
|
||||||
clubName: string
|
|
||||||
defaultEloRating: number
|
|
||||||
partnershipEnabled: boolean
|
|
||||||
notificationsEnabled: boolean
|
|
||||||
matchVerification: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ClubSettingsPage() {
|
|
||||||
const [settings, setSettings] = useState<ClubSettings | null>(null)
|
|
||||||
const [loading, setLoading] = useState(true)
|
|
||||||
const [saving, setSaving] = useState(false)
|
|
||||||
const [error, setError] = useState("")
|
|
||||||
const [success, setSuccess] = useState("")
|
|
||||||
|
|
||||||
const [formSettings, setFormSettings] = useState<Partial<ClubSettings>>({})
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchSettings()
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const fetchSettings = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/admin/settings")
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error("Failed to fetch settings")
|
|
||||||
}
|
|
||||||
const data = await response.json()
|
|
||||||
setSettings(data)
|
|
||||||
setFormSettings(data || {})
|
|
||||||
} catch (err: unknown) {
|
|
||||||
setError(err instanceof Error ? err.message : "Failed to fetch settings")
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
setSaving(true)
|
|
||||||
setError("")
|
|
||||||
setSuccess("")
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/admin/settings", {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(formSettings),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json()
|
|
||||||
throw new Error(errorData.error || "Failed to save settings")
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedSettings = await response.json()
|
|
||||||
setSettings(updatedSettings)
|
|
||||||
setSuccess("Settings saved successfully!")
|
|
||||||
} catch (err: unknown) {
|
|
||||||
setError(err instanceof Error ? err.message : "Failed to save settings")
|
|
||||||
} finally {
|
|
||||||
setSaving(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50">
|
|
||||||
<Navigation />
|
|
||||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
|
||||||
<div className="px-4 py-6 sm:px-0">
|
|
||||||
<p className="text-gray-500">Loading settings...</p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50">
|
|
||||||
<Navigation />
|
|
||||||
|
|
||||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
|
||||||
<div className="px-4 py-6 sm:px-0">
|
|
||||||
{/* Page Header */}
|
|
||||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Club Settings</h1>
|
|
||||||
<p className="text-gray-500 mt-1">
|
|
||||||
Configure your club's default settings and preferences.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Settings Form */}
|
|
||||||
<div className="bg-white shadow rounded-lg p-6">
|
|
||||||
{error && (
|
|
||||||
<div className="mb-4 p-4 bg-red-100 text-red-700 rounded">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{success && (
|
|
||||||
<div className="mb-4 p-4 bg-green-100 text-green-700 rounded">
|
|
||||||
{success}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Club Name */}
|
|
||||||
<div>
|
|
||||||
<label htmlFor="clubName" className="block text-sm font-medium text-gray-700 mb-2">
|
|
||||||
Club Name
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="clubName"
|
|
||||||
value={formSettings.clubName || ""}
|
|
||||||
onChange={(e) => setFormSettings({ ...formSettings, clubName: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Default Elo Rating */}
|
|
||||||
<div>
|
|
||||||
<label htmlFor="defaultEloRating" className="block text-sm font-medium text-gray-700 mb-2">
|
|
||||||
Default Elo Rating
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
id="defaultEloRating"
|
|
||||||
value={formSettings.defaultEloRating || 1000}
|
|
||||||
onChange={(e) => setFormSettings({ ...formSettings, defaultEloRating: parseInt(e.target.value) })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Partnership Tracking */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<label className="text-sm font-medium text-gray-700">Partnership Tracking</label>
|
|
||||||
<p className="text-sm text-gray-500">Enable partnership performance analytics</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setFormSettings({ ...formSettings, partnershipEnabled: !formSettings.partnershipEnabled })}
|
|
||||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 ${
|
|
||||||
formSettings.partnershipEnabled ? 'bg-green-600' : 'bg-gray-200'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
|
|
||||||
formSettings.partnershipEnabled ? 'translate-x-5' : 'translate-x-0'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Notifications */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<label className="text-sm font-medium text-gray-700">Notifications</label>
|
|
||||||
<p className="text-sm text-gray-500">Send email notifications for updates</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setFormSettings({ ...formSettings, notificationsEnabled: !formSettings.notificationsEnabled })}
|
|
||||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 ${
|
|
||||||
formSettings.notificationsEnabled ? 'bg-green-600' : 'bg-gray-200'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
|
|
||||||
formSettings.notificationsEnabled ? 'translate-x-5' : 'translate-x-0'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Match Verification */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<label className="text-sm font-medium text-gray-700">Match Verification</label>
|
|
||||||
<p className="text-sm text-gray-500">Require admin verification for match results</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setFormSettings({ ...formSettings, matchVerification: !formSettings.matchVerification })}
|
|
||||||
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 ${
|
|
||||||
formSettings.matchVerification ? 'bg-green-600' : 'bg-gray-200'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
|
|
||||||
formSettings.matchVerification ? 'translate-x-5' : 'translate-x-0'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Save Button */}
|
|
||||||
<div className="mt-8 flex justify-end">
|
|
||||||
<button
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={saving}
|
|
||||||
className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{saving ? 'Saving...' : 'Save Settings'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -73,7 +73,7 @@ export default function TournamentEntryPage({ params }: { params: Promise<{ id:
|
|||||||
const [team1Score, setTeam1Score] = useState("")
|
const [team1Score, setTeam1Score] = useState("")
|
||||||
const [team2Score, setTeam2Score] = useState("")
|
const [team2Score, setTeam2Score] = useState("")
|
||||||
|
|
||||||
// Parse params and validate tournamentId, check for matchup query param
|
// Parse params and validate tournamentId
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function parseParams() {
|
async function parseParams() {
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
@@ -87,26 +87,6 @@ export default function TournamentEntryPage({ params }: { params: Promise<{ id:
|
|||||||
parseParams()
|
parseParams()
|
||||||
}, [params, router])
|
}, [params, router])
|
||||||
|
|
||||||
// Handle pre-selection of matchup from query param
|
|
||||||
useEffect(() => {
|
|
||||||
if (schedule && selectedMatchupId === null) {
|
|
||||||
const searchParams = new URLSearchParams(window.location.search)
|
|
||||||
const matchupIdParam = searchParams.get('matchup')
|
|
||||||
if (matchupIdParam) {
|
|
||||||
const matchupId = parseInt(matchupIdParam, 10)
|
|
||||||
// Find which round contains this matchup
|
|
||||||
for (const round of schedule.rounds) {
|
|
||||||
const matchup = round.matchups.find(m => m.id === matchupId)
|
|
||||||
if (matchup) {
|
|
||||||
setSelectedRoundId(round.id)
|
|
||||||
setSelectedMatchupId(matchupId)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [schedule, selectedMatchupId])
|
|
||||||
|
|
||||||
// Load tournament, schedule, and matches
|
// Load tournament, schedule, and matches
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (tournamentId) {
|
if (tournamentId) {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import Navigation from "@/components/Navigation"
|
|||||||
import TeamsSection from "@/components/TeamsSection"
|
import TeamsSection from "@/components/TeamsSection"
|
||||||
import { DeleteTournamentButton } from "@/components/DeleteTournamentButton"
|
import { DeleteTournamentButton } from "@/components/DeleteTournamentButton"
|
||||||
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
|
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
|
||||||
import { BracketVisualization } from "@/components/BracketVisualization"
|
|
||||||
import MatchEditor from "@/components/MatchEditor"
|
import MatchEditor from "@/components/MatchEditor"
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
@@ -421,11 +420,6 @@ export default function TournamentDetailPage({ params }: PageProps) {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
||||||
case "bracket":
|
|
||||||
return (
|
|
||||||
<BracketVisualization rounds={rounds} />
|
|
||||||
)
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -561,18 +555,6 @@ export default function TournamentDetailPage({ params }: PageProps) {
|
|||||||
>
|
>
|
||||||
Results
|
Results
|
||||||
</button>
|
</button>
|
||||||
{hasSchedule && (
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveTab("bracket")}
|
|
||||||
className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
|
|
||||||
activeTab === "bracket"
|
|
||||||
? "border-green-500 text-green-600"
|
|
||||||
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Bracket
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<span className="border-transparent text-gray-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm cursor-not-allowed">
|
<span className="border-transparent text-gray-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm cursor-not-allowed">
|
||||||
Analytics
|
Analytics
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ import { prisma } from "@/lib/prisma"
|
|||||||
import Navigation from "@/components/Navigation"
|
import Navigation from "@/components/Navigation"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { notFound } from "next/navigation"
|
import { notFound } from "next/navigation"
|
||||||
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
|
|
||||||
import { ScheduleDisplay } from "@/components/ScheduleDisplay"
|
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: Promise<{
|
params: Promise<{
|
||||||
@@ -11,9 +9,7 @@ interface PageProps {
|
|||||||
}>
|
}>
|
||||||
}
|
}
|
||||||
|
|
||||||
// Force dynamic rendering and revalidate on each request
|
|
||||||
export const dynamic = "force-dynamic"
|
export const dynamic = "force-dynamic"
|
||||||
export const revalidate = 0
|
|
||||||
|
|
||||||
export default async function TournamentSchedulePage({ params }: PageProps) {
|
export default async function TournamentSchedulePage({ params }: PageProps) {
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
@@ -23,7 +19,6 @@ export default async function TournamentSchedulePage({ params }: PageProps) {
|
|||||||
notFound()
|
notFound()
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[Schedule Page] Fetching tournament ${tournamentId}`);
|
|
||||||
const tournament = await prisma.event.findUnique({
|
const tournament = await prisma.event.findUnique({
|
||||||
where: { id: tournamentId },
|
where: { id: tournamentId },
|
||||||
include: {
|
include: {
|
||||||
@@ -32,35 +27,13 @@ export default async function TournamentSchedulePage({ params }: PageProps) {
|
|||||||
player: true,
|
player: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
rounds: {
|
|
||||||
orderBy: { roundNumber: "asc" },
|
|
||||||
include: {
|
|
||||||
bracketMatchups: {
|
|
||||||
orderBy: { bracketPosition: "asc" },
|
|
||||||
include: {
|
|
||||||
player1P1: true,
|
|
||||||
player1P2: true,
|
|
||||||
player2P1: true,
|
|
||||||
player2P2: true,
|
|
||||||
match: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
console.log(`[Schedule Page] Tournament ${tournamentId} has ${tournament?.rounds?.length || 0} rounds`);
|
|
||||||
if (tournament?.rounds && tournament.rounds.length > 0) {
|
|
||||||
console.log(`[Schedule Page] First round:`, JSON.stringify(tournament.rounds[0]));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tournament) {
|
if (!tournament) {
|
||||||
notFound()
|
notFound()
|
||||||
}
|
}
|
||||||
|
|
||||||
const teamCount = tournament.participants.length
|
|
||||||
const existingRounds = tournament.rounds.length
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
<Navigation />
|
<Navigation />
|
||||||
@@ -80,30 +53,19 @@ export default async function TournamentSchedulePage({ params }: PageProps) {
|
|||||||
Schedule - {tournament.name}
|
Schedule - {tournament.name}
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
<div className="bg-white shadow rounded-lg p-6">
|
||||||
<div className="flex justify-between items-center mb-6">
|
<div className="flex justify-between items-center mb-6">
|
||||||
<h2 className="text-xl font-bold text-gray-900">
|
<h2 className="text-xl font-bold text-gray-900">
|
||||||
Tournament Schedule
|
Tournament Schedule
|
||||||
</h2>
|
</h2>
|
||||||
|
<button className="bg-green-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-green-700">
|
||||||
|
Generate Schedule
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="schedule-display">
|
<p className="text-gray-500">
|
||||||
{existingRounds > 0 ? (
|
|
||||||
<ScheduleDisplay rounds={tournament.rounds} tournamentId={tournamentId} />
|
|
||||||
) : (
|
|
||||||
<p className="text-gray-500 mb-6">
|
|
||||||
No schedule has been generated yet. Click "Generate Schedule" to create round matchups.
|
No schedule has been generated yet. Click "Generate Schedule" to create round matchups.
|
||||||
</p>
|
</p>
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-6 pt-6 border-t border-gray-200">
|
|
||||||
<ScheduleGenerator
|
|
||||||
tournamentId={tournamentId}
|
|
||||||
teamCount={teamCount}
|
|
||||||
existingRounds={existingRounds}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { prisma } from '@/lib/prisma'
|
|
||||||
import { getSession } from '@/lib/auth-simple'
|
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
|
||||||
const session = await getSession()
|
|
||||||
if (!session) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { searchParams } = new URL(request.url)
|
|
||||||
const limit = parseInt(searchParams.get('limit') || '20')
|
|
||||||
const offset = parseInt(searchParams.get('offset') || '0')
|
|
||||||
const type = searchParams.get('type')
|
|
||||||
|
|
||||||
const where: any = {}
|
|
||||||
if (type) {
|
|
||||||
where.type = type
|
|
||||||
}
|
|
||||||
|
|
||||||
const activities = await prisma.activity.findMany({
|
|
||||||
where,
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
take: limit,
|
|
||||||
skip: offset,
|
|
||||||
include: {
|
|
||||||
user: { select: { name: true } },
|
|
||||||
player: { select: { name: true } },
|
|
||||||
event: { select: { name: true } },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return NextResponse.json(activities)
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { prisma } from '@/lib/prisma'
|
|
||||||
import { getSession } from '@/lib/auth-simple'
|
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
const session = await getSession()
|
|
||||||
if (!session) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const settings = await (prisma as any).clubSettings.findFirst()
|
|
||||||
return NextResponse.json(settings)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function PATCH(request: NextRequest) {
|
|
||||||
const session = await getSession()
|
|
||||||
if (!session) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await request.json()
|
|
||||||
|
|
||||||
// Get the existing settings record (should be id: 1 or first record)
|
|
||||||
let settings = await (prisma as any).clubSettings.findFirst()
|
|
||||||
|
|
||||||
if (!settings) {
|
|
||||||
// Create default settings if none exist
|
|
||||||
settings = await (prisma as any).clubSettings.create({
|
|
||||||
data: {
|
|
||||||
clubName: 'Euchre Club',
|
|
||||||
defaultEloRating: 1200,
|
|
||||||
partnershipEnabled: true,
|
|
||||||
notificationsEnabled: true,
|
|
||||||
matchVerification: false,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update the settings
|
|
||||||
const updatedSettings = await (prisma as any).clubSettings.update({
|
|
||||||
where: { id: settings.id },
|
|
||||||
data,
|
|
||||||
})
|
|
||||||
|
|
||||||
return NextResponse.json(updatedSettings)
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
import { prisma } from "@/lib/prisma";
|
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
|
||||||
try {
|
|
||||||
const body = await request.json();
|
|
||||||
const { email } = body;
|
|
||||||
|
|
||||||
if (!email) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Email is required" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
where: { email: email.toLowerCase() },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "If an account exists with that email, a password reset link will be sent" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
message: "If an account exists with that email, a password reset link will be sent"
|
|
||||||
});
|
|
||||||
} catch (error: unknown) {
|
|
||||||
console.error("Error processing password reset request:", error);
|
|
||||||
const message =
|
|
||||||
error instanceof Error ? error.message : "Failed to process password reset request";
|
|
||||||
return NextResponse.json({ error: message }, { status: 500 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -6,22 +6,10 @@ import { prisma } from "@/lib/prisma";
|
|||||||
*
|
*
|
||||||
* Get all players with their user associations
|
* Get all players with their user associations
|
||||||
* This is a public endpoint (no authentication required)
|
* This is a public endpoint (no authentication required)
|
||||||
* Supports search query parameter
|
|
||||||
*/
|
*/
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const { searchParams } = new URL(request.url)
|
|
||||||
const search = searchParams.get('search') || ''
|
|
||||||
const limit = parseInt(searchParams.get('limit') || '50')
|
|
||||||
const offset = parseInt(searchParams.get('offset') || '0')
|
|
||||||
|
|
||||||
const where: any = {}
|
|
||||||
if (search) {
|
|
||||||
where.name = { contains: search, mode: 'insensitive' }
|
|
||||||
}
|
|
||||||
|
|
||||||
const players = await prisma.player.findMany({
|
const players = await prisma.player.findMany({
|
||||||
where,
|
|
||||||
include: {
|
include: {
|
||||||
user: {
|
user: {
|
||||||
select: {
|
select: {
|
||||||
@@ -29,9 +17,7 @@ export async function GET(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
orderBy: { currentElo: 'desc' },
|
orderBy: { name: "asc" },
|
||||||
take: limit,
|
|
||||||
skip: offset,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(players);
|
return NextResponse.json(players);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { canManageTournament } from "@/lib/permissions";
|
import { canManageTournament } from "@/lib/permissions";
|
||||||
import { generateRoundRobin, validateScheduleInput, generateVariableRoundRobin, expectedRounds } from "@/lib/schedule-generator";
|
import { generateRoundRobin, validateScheduleInput, generateVariableRoundRobin, expectedRounds } from "@/lib/schedule-generator";
|
||||||
@@ -79,15 +78,11 @@ export async function GET(_request: Request, { params }: RouteParams) {
|
|||||||
* Creates TournamentRound and BracketMatchup records.
|
* Creates TournamentRound and BracketMatchup records.
|
||||||
*/
|
*/
|
||||||
export async function POST(_request: Request, { params }: RouteParams) {
|
export async function POST(_request: Request, { params }: RouteParams) {
|
||||||
console.log(`[Schedule API] POST handler started`);
|
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const tournamentId = parseInt(id);
|
const tournamentId = parseInt(id);
|
||||||
|
|
||||||
console.log(`[Schedule API] POST /api/tournaments/${tournamentId}/schedule`);
|
|
||||||
|
|
||||||
if (isNaN(tournamentId)) {
|
if (isNaN(tournamentId)) {
|
||||||
console.log(`[Schedule API] Invalid tournament ID: ${id}`);
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Invalid tournament ID" },
|
{ error: "Invalid tournament ID" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
@@ -95,7 +90,6 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const permission = await canManageTournament(tournamentId);
|
const permission = await canManageTournament(tournamentId);
|
||||||
console.log(`[Schedule API] Permission check: ${permission.allowed}, reason: ${permission.reason}`);
|
|
||||||
if (!permission.allowed) {
|
if (!permission.allowed) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: permission.reason || "Not authorized to manage this tournament" },
|
{ error: permission.reason || "Not authorized to manage this tournament" },
|
||||||
@@ -104,7 +98,6 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check tournament exists
|
// Check tournament exists
|
||||||
console.log(`[Schedule API] Looking up tournament ${tournamentId}`);
|
|
||||||
const tournament = await prisma.event.findUnique({
|
const tournament = await prisma.event.findUnique({
|
||||||
where: { id: tournamentId },
|
where: { id: tournamentId },
|
||||||
include: {
|
include: {
|
||||||
@@ -118,17 +111,14 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!tournament) {
|
if (!tournament) {
|
||||||
console.log(`[Schedule API] Tournament ${tournamentId} not found`);
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Tournament not found" },
|
{ error: "Tournament not found" },
|
||||||
{ status: 404 }
|
{ status: 404 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
console.log(`[Schedule API] Found tournament ${tournamentId} with ${tournament.participants.length} participants and ${tournament.rounds.length} existing rounds`);
|
|
||||||
|
|
||||||
// Check if schedule already exists and delete it
|
// Check if schedule already exists and delete it
|
||||||
if (tournament.rounds.length > 0) {
|
if (tournament.rounds.length > 0) {
|
||||||
console.log(`[Schedule API] Deleting ${tournament.rounds.length} existing rounds`);
|
|
||||||
// Delete existing rounds and matchups before regenerating
|
// Delete existing rounds and matchups before regenerating
|
||||||
await prisma.bracketMatchup.deleteMany({
|
await prisma.bracketMatchup.deleteMany({
|
||||||
where: { eventId: tournamentId },
|
where: { eventId: tournamentId },
|
||||||
@@ -145,8 +135,6 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
currentElo: p.player.currentElo,
|
currentElo: p.player.currentElo,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
console.log(`[Schedule API] Got ${participants.length} participants`);
|
|
||||||
|
|
||||||
// Check minimum participants
|
// Check minimum participants
|
||||||
if (participants.length < 2) {
|
if (participants.length < 2) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -159,24 +147,20 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
const teamDurability = tournament.teamDurability || "permanent";
|
const teamDurability = tournament.teamDurability || "permanent";
|
||||||
const partnerRotation = (tournament.partnerRotation || "none") as 'none' | 'minimize_repeat' | 'maximize_even' | 'elo_based';
|
const partnerRotation = (tournament.partnerRotation || "none") as 'none' | 'minimize_repeat' | 'maximize_even' | 'elo_based';
|
||||||
const allowByes = tournament.allowByes ?? true;
|
const allowByes = tournament.allowByes ?? true;
|
||||||
console.log(`[Schedule API] Team durability: ${teamDurability}, partner rotation: ${partnerRotation}, allow byes: ${allowByes}`);
|
|
||||||
|
|
||||||
// Determine number of teams from participants
|
// Determine number of teams from participants
|
||||||
const tempResult = generateTeams(participants, partnerRotation, allowByes);
|
const tempResult = generateTeams(participants, partnerRotation, allowByes);
|
||||||
const teamCount = tempResult.teams.length;
|
const teamCount = tempResult.teams.length;
|
||||||
console.log(`[Schedule API] Generated ${teamCount} teams from ${participants.length} participants`);
|
|
||||||
|
|
||||||
if (teamCount < 2) {
|
if (teamCount < 2) {
|
||||||
console.log(`[Schedule API] Not enough teams: ${teamCount}`);
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "At least 2 teams are required to generate a schedule" },
|
{ error: "At least 2 teams (4 players) are required to generate a schedule" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate expected rounds
|
// Calculate number of rounds needed
|
||||||
const numRounds = expectedRounds(teamCount);
|
const numRounds = expectedRounds(teamCount);
|
||||||
console.log(`[Schedule API] Expected rounds: ${numRounds}`);
|
|
||||||
|
|
||||||
if (teamDurability === "permanent") {
|
if (teamDurability === "permanent") {
|
||||||
// ============================================
|
// ============================================
|
||||||
@@ -202,14 +186,11 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
|
|
||||||
// Generate schedule using fixed teams
|
// Generate schedule using fixed teams
|
||||||
const schedule = generateRoundRobin(teamPairings);
|
const schedule = generateRoundRobin(teamPairings);
|
||||||
console.log(`[Schedule API] Generated ${schedule.length} rounds for ${teamCount} teams (fixed)`);
|
|
||||||
|
|
||||||
// Create rounds and matchups in a transaction
|
// Create rounds and matchups in a transaction
|
||||||
console.log(`[Schedule API] About to create ${schedule.length} rounds in transaction`);
|
|
||||||
const created = await prisma.$transaction(
|
const created = await prisma.$transaction(
|
||||||
schedule.map((round) => {
|
schedule.map((round) =>
|
||||||
console.log(`[Schedule API] Creating round ${round.roundNumber} with ${round.matchups.length} matchups`);
|
prisma.tournamentRound.create({
|
||||||
return prisma.tournamentRound.create({
|
|
||||||
data: {
|
data: {
|
||||||
eventId: tournamentId,
|
eventId: tournamentId,
|
||||||
roundNumber: round.roundNumber,
|
roundNumber: round.roundNumber,
|
||||||
@@ -237,18 +218,9 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
})
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(`[Schedule API] Transaction complete. Created ${created.length} rounds`);
|
|
||||||
console.log(`[Schedule API] Verifying in database:`);
|
|
||||||
for (const round of created) {
|
|
||||||
console.log(`[Schedule API] Round ${round.roundNumber}: id=${round.id}, eventId=${round.eventId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
revalidatePath(`/admin/tournaments/${tournamentId}/schedule`);
|
|
||||||
console.log(`[Schedule API] revalidatePath called for /admin/tournaments/${tournamentId}/schedule`);
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
roundsCreated: created.length,
|
roundsCreated: created.length,
|
||||||
@@ -323,8 +295,6 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
revalidatePath(`/admin/tournaments/${tournamentId}/schedule`);
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
roundsCreated: created.length,
|
roundsCreated: created.length,
|
||||||
|
|||||||
@@ -15,22 +15,6 @@ export default function PasswordResetPage() {
|
|||||||
setError("")
|
setError("")
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/auth/password-reset", {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ email }),
|
|
||||||
})
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
setError(data.error || "Failed to send reset link")
|
|
||||||
setLoading(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setSent(true)
|
setSent(true)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Password reset error:", err)
|
console.error("Password reset error:", err)
|
||||||
|
|||||||
+1
-4
@@ -1,7 +1,6 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { SessionProvider } from "@/components/SessionProvider";
|
import { SessionProvider } from "@/components/SessionProvider";
|
||||||
import { RoleSwitcherProvider } from "@/components/RoleSwitcher";
|
|
||||||
import Footer from "@/components/Footer";
|
import Footer from "@/components/Footer";
|
||||||
|
|
||||||
const inter = {
|
const inter = {
|
||||||
@@ -23,12 +22,10 @@ export default function RootLayout({
|
|||||||
lang="en"
|
lang="en"
|
||||||
className={`${inter.variable} h-full antialiased`}
|
className={`${inter.variable} h-full antialiased`}
|
||||||
>
|
>
|
||||||
<body className="min-h-full flex flex-col overflow-x-hidden">
|
<body className="min-h-full flex flex-col">
|
||||||
<SessionProvider>
|
<SessionProvider>
|
||||||
<RoleSwitcherProvider>
|
|
||||||
{children}
|
{children}
|
||||||
<Footer />
|
<Footer />
|
||||||
</RoleSwitcherProvider>
|
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -128,10 +128,9 @@ export default async function PlayerSchedulePage({ params }: PageProps) {
|
|||||||
].filter(Boolean).join(" + ")
|
].filter(Boolean).join(" + ")
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<div
|
||||||
href={`/matches/${match.id}`}
|
|
||||||
key={match.id}
|
key={match.id}
|
||||||
className="block border border-gray-200 rounded-lg p-4 hover:bg-gray-50 cursor-pointer"
|
className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50"
|
||||||
>
|
>
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
@@ -148,7 +147,7 @@ export default async function PlayerSchedulePage({ params }: PageProps) {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</div>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ export default function RankingsClient({ players }: { players: PlayerWithRatings
|
|||||||
|
|
||||||
{/* Elo Rating Tab */}
|
{/* Elo Rating Tab */}
|
||||||
{activeTab === "elo" && (
|
{activeTab === "elo" && (
|
||||||
<div className="bg-white shadow overflow-x-auto sm:rounded-lg">
|
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
|
||||||
<h2 className="text-xl font-semibold text-gray-900 px-6 py-4 border-b">
|
<h2 className="text-xl font-semibold text-gray-900 px-6 py-4 border-b">
|
||||||
Elo Rating Rankings
|
Elo Rating Rankings
|
||||||
</h2>
|
</h2>
|
||||||
@@ -117,7 +117,7 @@ export default function RankingsClient({ players }: { players: PlayerWithRatings
|
|||||||
|
|
||||||
{/* OpenSkill Rating Tab */}
|
{/* OpenSkill Rating Tab */}
|
||||||
{activeTab === "openskill" && (
|
{activeTab === "openskill" && (
|
||||||
<div className="bg-white shadow overflow-x-auto sm:rounded-lg">
|
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
|
||||||
<h2 className="text-xl font-semibold text-gray-900 px-6 py-4 border-b">
|
<h2 className="text-xl font-semibold text-gray-900 px-6 py-4 border-b">
|
||||||
OpenSkill Rating Rankings
|
OpenSkill Rating Rankings
|
||||||
</h2>
|
</h2>
|
||||||
@@ -178,7 +178,7 @@ export default function RankingsClient({ players }: { players: PlayerWithRatings
|
|||||||
|
|
||||||
{/* Glicko2 Rating Tab */}
|
{/* Glicko2 Rating Tab */}
|
||||||
{activeTab === "glicko2" && (
|
{activeTab === "glicko2" && (
|
||||||
<div className="bg-white shadow overflow-x-auto sm:rounded-lg">
|
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
|
||||||
<h2 className="text-xl font-semibold text-gray-900 px-6 py-4 border-b">
|
<h2 className="text-xl font-semibold text-gray-900 px-6 py-4 border-b">
|
||||||
Glicko2 Rating Rankings
|
Glicko2 Rating Rankings
|
||||||
</h2>
|
</h2>
|
||||||
|
|||||||
@@ -1,168 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
interface Player {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BracketMatchup {
|
|
||||||
id: number
|
|
||||||
roundId: number
|
|
||||||
player1P1: Player | null
|
|
||||||
player1P2: Player | null
|
|
||||||
player2P1: Player | null
|
|
||||||
player2P2: Player | null
|
|
||||||
match: { id: number; team1Score: number; team2Score: number } | null
|
|
||||||
bracketPosition: number | null
|
|
||||||
status: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TournamentRound {
|
|
||||||
id: number
|
|
||||||
roundNumber: number
|
|
||||||
status: string
|
|
||||||
bracketMatchups: BracketMatchup[]
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BracketVisualizationProps {
|
|
||||||
rounds: TournamentRound[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function BracketVisualization({ rounds }: BracketVisualizationProps) {
|
|
||||||
if (rounds.length === 0) {
|
|
||||||
return (
|
|
||||||
<div className="bg-white shadow rounded-lg p-6">
|
|
||||||
<p className="text-gray-500">No schedule generated yet. Generate a schedule to see the bracket.</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentRoundIdx = rounds.findIndex(r => r.status === "in_progress")
|
|
||||||
const completedRounds = rounds.filter(r => r.status === "completed").length
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="bg-white shadow rounded-lg p-6">
|
|
||||||
<div className="flex items-center justify-between mb-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900">Tournament Bracket</h2>
|
|
||||||
<div className="flex items-center space-x-4 text-sm text-gray-500">
|
|
||||||
<span>{rounds.length} rounds</span>
|
|
||||||
<span>{completedRounds} completed</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="overflow-x-auto pb-4">
|
|
||||||
<div
|
|
||||||
className="inline-grid gap-4"
|
|
||||||
style={{
|
|
||||||
gridTemplateColumns: `repeat(${rounds.length}, minmax(200px, 1fr))`,
|
|
||||||
minWidth: `${rounds.length * 220}px`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{rounds.map((round, roundIdx) => {
|
|
||||||
const isCurrent = roundIdx === currentRoundIdx
|
|
||||||
const isCompleted = round.status === "completed"
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div key={round.id} className="flex flex-col">
|
|
||||||
{/* Round Header */}
|
|
||||||
<div
|
|
||||||
className={`text-center py-2 px-3 rounded-t-lg font-medium text-sm ${
|
|
||||||
isCurrent
|
|
||||||
? "bg-green-100 text-green-800 border border-green-300"
|
|
||||||
: isCompleted
|
|
||||||
? "bg-gray-100 text-gray-600 border border-gray-200"
|
|
||||||
: "bg-gray-50 text-gray-500 border border-gray-200"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Round {round.roundNumber}
|
|
||||||
{isCurrent && (
|
|
||||||
<span className="ml-1 text-xs">(current)</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Matchups */}
|
|
||||||
<div className="flex flex-col gap-2 mt-2">
|
|
||||||
{round.bracketMatchups
|
|
||||||
.sort((a, b) => (a.bracketPosition || 0) - (b.bracketPosition || 0))
|
|
||||||
.map((matchup) => (
|
|
||||||
<MatchupCard key={matchup.id} matchup={matchup} isCurrentRound={isCurrent} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function MatchupCard({ matchup, isCurrentRound }: { matchup: BracketMatchup; isCurrentRound: boolean }) {
|
|
||||||
const team1Name = matchup.player1P1 && matchup.player1P2
|
|
||||||
? `${matchup.player1P1.name.split(" ").pop()} & ${matchup.player1P2.name.split(" ").pop()}`
|
|
||||||
: "TBD"
|
|
||||||
const team2Name = matchup.player2P1 && matchup.player2P2
|
|
||||||
? `${matchup.player2P1.name.split(" ").pop()} & ${matchup.player2P2.name.split(" ").pop()}`
|
|
||||||
: "TBD"
|
|
||||||
|
|
||||||
const hasResult = matchup.match !== null
|
|
||||||
const team1Won = hasResult && matchup.match!.team1Score > matchup.match!.team2Score
|
|
||||||
const team2Won = hasResult && matchup.match!.team2Score > matchup.match!.team1Score
|
|
||||||
|
|
||||||
const borderColor = isCurrentRound
|
|
||||||
? "border-green-400"
|
|
||||||
: hasResult
|
|
||||||
? "border-gray-300"
|
|
||||||
: "border-gray-200"
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={`border rounded-md p-2 text-xs transition-colors ${borderColor} ${
|
|
||||||
isCurrentRound ? "shadow-sm" : ""
|
|
||||||
}`}
|
|
||||||
data-testid="bracket-matchup"
|
|
||||||
>
|
|
||||||
{/* Team 1 */}
|
|
||||||
<div
|
|
||||||
className={`flex justify-between items-center py-1 px-1 ${
|
|
||||||
team1Won ? "font-semibold" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span className={`truncate ${team1Won ? "text-green-700" : "text-gray-700"}`}>
|
|
||||||
{team1Name}
|
|
||||||
</span>
|
|
||||||
{hasResult && (
|
|
||||||
<span className={`ml-1 font-mono ${team1Won ? "text-green-700" : "text-gray-500"}`}>
|
|
||||||
{matchup.match!.team1Score}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Divider */}
|
|
||||||
<div className="border-t border-gray-200 my-0.5" />
|
|
||||||
|
|
||||||
{/* Team 2 */}
|
|
||||||
<div
|
|
||||||
className={`flex justify-between items-center py-1 px-1 ${
|
|
||||||
team2Won ? "font-semibold" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span className={`truncate ${team2Won ? "text-green-700" : "text-gray-700"}`}>
|
|
||||||
{team2Name}
|
|
||||||
</span>
|
|
||||||
{hasResult && (
|
|
||||||
<span className={`ml-1 font-mono ${team2Won ? "text-green-700" : "text-gray-500"}`}>
|
|
||||||
{matchup.match!.team2Score}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Status indicator */}
|
|
||||||
{!hasResult && matchup.status === "pending" && (
|
|
||||||
<div className="text-center text-gray-400 text-[10px] mt-1">
|
|
||||||
pending
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
import type { Player, Match } from "@prisma/client"
|
import type { Player, Match } from "@prisma/client"
|
||||||
|
|
||||||
interface MatchEditorProps {
|
interface MatchEditorProps {
|
||||||
@@ -41,7 +40,6 @@ export default function MatchEditor({
|
|||||||
prefilledP4,
|
prefilledP4,
|
||||||
prefilledRound,
|
prefilledRound,
|
||||||
}: MatchEditorProps) {
|
}: MatchEditorProps) {
|
||||||
const router = useRouter()
|
|
||||||
// Check if players are prefilled from URL params
|
// Check if players are prefilled from URL params
|
||||||
const hasPrefilledPlayers = prefilledP1 && prefilledP2 && prefilledP3 && prefilledP4;
|
const hasPrefilledPlayers = prefilledP1 && prefilledP2 && prefilledP3 && prefilledP4;
|
||||||
|
|
||||||
@@ -172,9 +170,9 @@ export default function MatchEditor({
|
|||||||
isCasual: false,
|
isCasual: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Refresh the page to show updated matches
|
// Reload the page to show updated matches
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
router.refresh()
|
window.location.reload()
|
||||||
}, 1000)
|
}, 1000)
|
||||||
} catch {
|
} catch {
|
||||||
setError("An error occurred. Please try again.")
|
setError("An error occurred. Please try again.")
|
||||||
|
|||||||
@@ -4,13 +4,12 @@ import Link from "next/link"
|
|||||||
import { useSession } from "./SessionProvider"
|
import { useSession } from "./SessionProvider"
|
||||||
import { authClient } from "@/lib/auth-client"
|
import { authClient } from "@/lib/auth-client"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { useRoleSwitcher } from "./RoleSwitcher"
|
|
||||||
|
|
||||||
export default function Navigation() {
|
export default function Navigation() {
|
||||||
const { session, loading } = useSession()
|
const { session, loading } = useSession()
|
||||||
const [userRole, setUserRole] = useState<string | null>(null)
|
const [userRole, setUserRole] = useState<string | null>(null)
|
||||||
const { viewAsRole, setViewAsRole, effectiveRole } = useRoleSwitcher()
|
|
||||||
|
|
||||||
|
// Fetch user role whenever session changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchUserRole = async () => {
|
const fetchUserRole = async () => {
|
||||||
const userId = (session?.user as { id?: string })?.id
|
const userId = (session?.user as { id?: string })?.id
|
||||||
@@ -35,57 +34,30 @@ export default function Navigation() {
|
|||||||
}, [session])
|
}, [session])
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
setViewAsRole(null)
|
|
||||||
await authClient.signOut()
|
await authClient.signOut()
|
||||||
window.location.href = '/auth/login'
|
window.location.href = '/auth/login'
|
||||||
}
|
}
|
||||||
|
|
||||||
const displayRole = effectiveRole || userRole
|
// Determine wordmark href based on session and role
|
||||||
const isSiteAdmin = userRole === "site_admin"
|
// If session exists but role is not yet loaded, use /rankings as default for players
|
||||||
|
|
||||||
const wordmarkHref = session
|
const wordmarkHref = session
|
||||||
? (displayRole === "club_admin" || displayRole === "site_admin")
|
? (userRole === "club_admin" || userRole === "site_admin")
|
||||||
? "/admin"
|
? "/admin"
|
||||||
: "/rankings"
|
: "/rankings"
|
||||||
: "/"
|
: "/";
|
||||||
|
|
||||||
const roleLabels: Record<string, string> = {
|
|
||||||
player: "Player",
|
|
||||||
tournament_admin: "Tournament Admin",
|
|
||||||
club_admin: "Club Admin",
|
|
||||||
site_admin: "Site Admin",
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
{viewAsRole && (
|
|
||||||
<div className="bg-yellow-50 border-b border-yellow-200 px-4 py-2">
|
|
||||||
<div className="max-w-7xl mx-auto flex items-center justify-between">
|
|
||||||
<p className="text-sm text-yellow-800">
|
|
||||||
<span className="font-medium">Viewing as {roleLabels[viewAsRole]}</span>
|
|
||||||
{" "}— you are seeing what a {roleLabels[viewAsRole]?.toLowerCase()} would see.
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
onClick={() => setViewAsRole(null)}
|
|
||||||
className="text-sm font-medium text-yellow-800 hover:text-yellow-900 underline"
|
|
||||||
data-testid="reset-view-as"
|
|
||||||
>
|
|
||||||
Reset to Site Admin
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<nav className="bg-white shadow-sm">
|
<nav className="bg-white shadow-sm">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
<div className="flex justify-between h-16">
|
<div className="flex justify-between h-16">
|
||||||
<div className="flex items-center min-w-0 overflow-hidden">
|
<div className="flex items-center">
|
||||||
<Link
|
<Link
|
||||||
href="/"
|
href="/wordmark-redirect"
|
||||||
className="text-xl font-bold text-gray-900 no-underline flex-shrink-0"
|
className="text-xl font-bold text-gray-900 no-underline"
|
||||||
>
|
>
|
||||||
EuchreCamp
|
EuchreCamp
|
||||||
</Link>
|
</Link>
|
||||||
<div className="hidden md:ml-6 md:flex md:space-x-8 min-w-0 overflow-hidden">
|
<div className="hidden md:ml-6 md:flex md:space-x-8">
|
||||||
<Link
|
<Link
|
||||||
href="/rankings"
|
href="/rankings"
|
||||||
className="border-transparent text-gray-500 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
|
className="border-transparent text-gray-500 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
|
||||||
@@ -100,7 +72,7 @@ export default function Navigation() {
|
|||||||
>
|
>
|
||||||
Tournaments
|
Tournaments
|
||||||
</Link>
|
</Link>
|
||||||
{(displayRole === "club_admin" || displayRole === "site_admin") && (
|
{(userRole === "club_admin" || userRole === "site_admin") && (
|
||||||
<>
|
<>
|
||||||
<Link
|
<Link
|
||||||
href="/admin"
|
href="/admin"
|
||||||
@@ -138,20 +110,7 @@ export default function Navigation() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center min-w-0 overflow-hidden space-x-4">
|
<div className="flex items-center">
|
||||||
{isSiteAdmin && (
|
|
||||||
<select
|
|
||||||
value={viewAsRole || ""}
|
|
||||||
onChange={(e) => setViewAsRole(e.target.value ? e.target.value as "player" | "tournament_admin" | "club_admin" : null)}
|
|
||||||
className="text-sm border border-gray-300 rounded-md px-2 py-1 bg-white text-gray-700 focus:outline-none focus:ring-green-500 focus:border-green-500"
|
|
||||||
data-testid="role-switcher"
|
|
||||||
>
|
|
||||||
<option value="">Viewing as Site Admin</option>
|
|
||||||
<option value="player">View as Player</option>
|
|
||||||
<option value="tournament_admin">View as Tournament Admin</option>
|
|
||||||
<option value="club_admin">View as Club Admin</option>
|
|
||||||
</select>
|
|
||||||
)}
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="text-gray-500">Loading...</div>
|
<div className="text-gray-500">Loading...</div>
|
||||||
) : session ? (
|
) : session ? (
|
||||||
@@ -187,6 +146,5 @@ export default function Navigation() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
|
|
||||||
export function RecalculateEloButton() {
|
export function RecalculateEloButton() {
|
||||||
const router = useRouter()
|
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
|
||||||
const handleClick = async () => {
|
const handleClick = async () => {
|
||||||
@@ -35,7 +33,7 @@ export function RecalculateEloButton() {
|
|||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
alert(`Recalculation completed: ${JSON.stringify(data.data)}`)
|
alert(`Recalculation completed: ${JSON.stringify(data.data)}`)
|
||||||
router.refresh()
|
window.location.reload()
|
||||||
} else {
|
} else {
|
||||||
alert(`Error: ${data.error}`)
|
alert(`Error: ${data.error}`)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { createContext, useContext, useState, useCallback, ReactNode } from "react"
|
|
||||||
|
|
||||||
type ViewAsRole = "player" | "tournament_admin" | "club_admin" | null
|
|
||||||
|
|
||||||
interface RoleSwitcherContextType {
|
|
||||||
viewAsRole: ViewAsRole
|
|
||||||
setViewAsRole: (role: ViewAsRole) => void
|
|
||||||
effectiveRole: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
const RoleSwitcherContext = createContext<RoleSwitcherContextType | undefined>(undefined)
|
|
||||||
|
|
||||||
export function RoleSwitcherProvider({ children }: { children: ReactNode }) {
|
|
||||||
const [viewAsRole, setViewAsRole] = useState<ViewAsRole>(null)
|
|
||||||
|
|
||||||
const value = {
|
|
||||||
viewAsRole,
|
|
||||||
setViewAsRole: useCallback((role: ViewAsRole) => setViewAsRole(role), []),
|
|
||||||
effectiveRole: viewAsRole,
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<RoleSwitcherContext.Provider value={value}>
|
|
||||||
{children}
|
|
||||||
</RoleSwitcherContext.Provider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useRoleSwitcher() {
|
|
||||||
const context = useContext(RoleSwitcherContext)
|
|
||||||
if (!context) {
|
|
||||||
throw new Error("useRoleSwitcher must be used within RoleSwitcherProvider")
|
|
||||||
}
|
|
||||||
return context
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import Link from "next/link"
|
|
||||||
|
|
||||||
interface Player {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BracketMatchup {
|
|
||||||
id: number
|
|
||||||
player1P1: Player | null
|
|
||||||
player1P2: Player | null
|
|
||||||
player2P1: Player | null
|
|
||||||
player2P2: Player | null
|
|
||||||
match: { id: number } | null
|
|
||||||
bracketPosition: number | null
|
|
||||||
status: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TournamentRound {
|
|
||||||
id: number
|
|
||||||
roundNumber: number
|
|
||||||
status: string
|
|
||||||
bracketMatchups: BracketMatchup[]
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ScheduleDisplayProps {
|
|
||||||
rounds: TournamentRound[]
|
|
||||||
tournamentId: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ScheduleDisplay({ rounds, tournamentId }: ScheduleDisplayProps) {
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
{rounds.map((round) => (
|
|
||||||
<div key={round.id} className="bg-white rounded-lg shadow p-4">
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<h3 className="text-lg font-semibold">Round {round.roundNumber}</h3>
|
|
||||||
<span className={`text-sm px-2 py-1 rounded ${
|
|
||||||
round.status === 'completed' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
|
|
||||||
}`}>
|
|
||||||
{round.status}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{round.bracketMatchups.map((matchup) => {
|
|
||||||
const content = (
|
|
||||||
<div className="p-3 border border-gray-200 rounded hover:border-green-500 transition-colors">
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-sm text-gray-500">
|
|
||||||
Match {matchup.bracketPosition || matchup.id}
|
|
||||||
</p>
|
|
||||||
<p className="font-medium">
|
|
||||||
{matchup.player1P1?.name || 'TBD'} & {matchup.player1P2?.name || 'TBD'}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-gray-500">vs</p>
|
|
||||||
<p className="font-medium">
|
|
||||||
{matchup.player2P1?.name || 'TBD'} & {matchup.player2P2?.name || 'TBD'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
{matchup.match ? (
|
|
||||||
<span className="text-sm text-green-600">Completed</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-sm text-gray-400">Pending</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link
|
|
||||||
key={matchup.id}
|
|
||||||
href={`/admin/tournaments/${tournamentId}/entry?matchup=${matchup.id}`}
|
|
||||||
className="block hover:bg-gray-100 rounded-md transition-colors"
|
|
||||||
data-testid="matchup"
|
|
||||||
>
|
|
||||||
{content}
|
|
||||||
</Link>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
|
|
||||||
interface ScheduleGeneratorProps {
|
interface ScheduleGeneratorProps {
|
||||||
tournamentId: number
|
tournamentId: number
|
||||||
@@ -10,7 +9,6 @@ interface ScheduleGeneratorProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ScheduleGenerator({ tournamentId, teamCount, existingRounds }: ScheduleGeneratorProps) {
|
export function ScheduleGenerator({ tournamentId, teamCount, existingRounds }: ScheduleGeneratorProps) {
|
||||||
const router = useRouter()
|
|
||||||
const [isGenerating, setIsGenerating] = useState(false)
|
const [isGenerating, setIsGenerating] = useState(false)
|
||||||
const [error, setError] = useState("")
|
const [error, setError] = useState("")
|
||||||
const [result, setResult] = useState<{
|
const [result, setResult] = useState<{
|
||||||
@@ -50,8 +48,10 @@ export function ScheduleGenerator({ tournamentId, teamCount, existingRounds }: S
|
|||||||
})
|
})
|
||||||
setIsGenerating(false)
|
setIsGenerating(false)
|
||||||
|
|
||||||
// Re-fetch the schedule data from the server
|
// Reload to show the schedule
|
||||||
router.refresh()
|
setTimeout(() => {
|
||||||
|
window.location.reload()
|
||||||
|
}, 1500)
|
||||||
} catch {
|
} catch {
|
||||||
setError("An error occurred. Please try again.")
|
setError("An error occurred. Please try again.")
|
||||||
setIsGenerating(false)
|
setIsGenerating(false)
|
||||||
@@ -86,7 +86,7 @@ export function ScheduleGenerator({ tournamentId, teamCount, existingRounds }: S
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
router.refresh()
|
window.location.reload()
|
||||||
} catch {
|
} catch {
|
||||||
setError("An error occurred. Please try again.")
|
setError("An error occurred. Please try again.")
|
||||||
setIsGenerating(false)
|
setIsGenerating(false)
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
import { prisma } from './prisma'
|
|
||||||
|
|
||||||
export type ActivityType =
|
|
||||||
| 'player_registration'
|
|
||||||
| 'tournament_created'
|
|
||||||
| 'match_completed'
|
|
||||||
| 'partnership_recorded'
|
|
||||||
|
|
||||||
export interface ActivityData {
|
|
||||||
type: ActivityType
|
|
||||||
description: string
|
|
||||||
userId?: string
|
|
||||||
playerId?: number
|
|
||||||
eventId?: number
|
|
||||||
matchId?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function logActivity(data: ActivityData) {
|
|
||||||
return prisma.activity.create({
|
|
||||||
data: {
|
|
||||||
type: data.type,
|
|
||||||
description: data.description,
|
|
||||||
userId: data.userId,
|
|
||||||
playerId: data.playerId,
|
|
||||||
eventId: data.eventId,
|
|
||||||
matchId: data.matchId,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
+20
-6
@@ -3,34 +3,42 @@ import { prismaAdapter } from "better-auth/adapters/prisma";
|
|||||||
import { prisma } from "./prisma";
|
import { prisma } from "./prisma";
|
||||||
import { testUtils } from "better-auth/plugins";
|
import { testUtils } from "better-auth/plugins";
|
||||||
|
|
||||||
|
// Detect database provider from environment
|
||||||
|
const databaseProvider = process.env.DATABASE_PROVIDER || "sqlite";
|
||||||
|
|
||||||
export const auth = betterAuth({
|
export const auth = betterAuth({
|
||||||
database: prismaAdapter(prisma, {
|
database: prismaAdapter(prisma, {
|
||||||
provider: "postgresql",
|
provider: databaseProvider as "sqlite" | "postgresql",
|
||||||
}),
|
}),
|
||||||
emailAndPassword: {
|
emailAndPassword: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
autoSignIn: true,
|
autoSignIn: true, // Automatically sign in after registration
|
||||||
requireEmailVerification: false,
|
requireEmailVerification: false, // Don't require email verification for tests
|
||||||
minPasswordLength: 8,
|
minPasswordLength: 8, // Set minimum password length
|
||||||
maxPasswordLength: 128,
|
maxPasswordLength: 128, // Set maximum password length
|
||||||
},
|
},
|
||||||
secret: process.env.BETTER_AUTH_SECRET || process.env.NEXTAUTH_SECRET,
|
secret: process.env.BETTER_AUTH_SECRET || process.env.NEXTAUTH_SECRET,
|
||||||
baseURL: process.env.BETTER_AUTH_URL || process.env.NEXTAUTH_URL || "http://localhost:3000/api/auth",
|
baseURL: process.env.BETTER_AUTH_URL || process.env.NEXTAUTH_URL || "http://localhost:3000/api/auth",
|
||||||
|
// Configure trusted origins - parse from environment or use defaults
|
||||||
trustedOrigins: (() => {
|
trustedOrigins: (() => {
|
||||||
const origins = [];
|
const origins = [];
|
||||||
|
|
||||||
|
// Add environment-specified origins
|
||||||
if (process.env.TRUSTED_ORIGINS) {
|
if (process.env.TRUSTED_ORIGINS) {
|
||||||
origins.push(...process.env.TRUSTED_ORIGINS.split(',').map(o => o.trim()));
|
origins.push(...process.env.TRUSTED_ORIGINS.split(',').map(o => o.trim()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add BETTER_AUTH_URL if set
|
||||||
if (process.env.BETTER_AUTH_URL) {
|
if (process.env.BETTER_AUTH_URL) {
|
||||||
origins.push(process.env.BETTER_AUTH_URL);
|
origins.push(process.env.BETTER_AUTH_URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add NEXTAUTH_URL if set
|
||||||
if (process.env.NEXTAUTH_URL) {
|
if (process.env.NEXTAUTH_URL) {
|
||||||
origins.push(process.env.NEXTAUTH_URL);
|
origins.push(process.env.NEXTAUTH_URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add defaults
|
||||||
origins.push(
|
origins.push(
|
||||||
"https://euchre.notsosm.art",
|
"https://euchre.notsosm.art",
|
||||||
"http://euchre.notsosm.art",
|
"http://euchre.notsosm.art",
|
||||||
@@ -40,13 +48,16 @@ export const auth = betterAuth({
|
|||||||
"http://0.0.0.0:3000"
|
"http://0.0.0.0:3000"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Remove duplicates and empty strings
|
||||||
return [...new Set(origins.filter(o => o))];
|
return [...new Set(origins.filter(o => o))];
|
||||||
})(),
|
})(),
|
||||||
session: {
|
session: {
|
||||||
cookieCache: {
|
cookieCache: {
|
||||||
enabled: false,
|
enabled: false, // Disable cookie cache to avoid session cache issues
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
// Configure rate limiting - disable for test environment
|
||||||
|
// Note: Rate limiting is disabled for all environments to ensure test reliability
|
||||||
rateLimit: {
|
rateLimit: {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
},
|
},
|
||||||
@@ -55,11 +66,13 @@ export const auth = betterAuth({
|
|||||||
user: {
|
user: {
|
||||||
create: {
|
create: {
|
||||||
async after(user) {
|
async after(user) {
|
||||||
|
// Generate a unique player name using timestamp and random string
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const randomId = Math.random().toString(36).substring(2, 8);
|
const randomId = Math.random().toString(36).substring(2, 8);
|
||||||
const baseName = user.name || user.email.split('@')[0];
|
const baseName = user.name || user.email.split('@')[0];
|
||||||
const uniqueName = `${baseName}-${timestamp}-${randomId}`;
|
const uniqueName = `${baseName}-${timestamp}-${randomId}`;
|
||||||
|
|
||||||
|
// Create a Player record for the new user
|
||||||
const newPlayer = await prisma.player.create({
|
const newPlayer = await prisma.player.create({
|
||||||
data: {
|
data: {
|
||||||
name: uniqueName,
|
name: uniqueName,
|
||||||
@@ -67,6 +80,7 @@ export const auth = betterAuth({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Update the User with the playerId
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
where: { id: user.id },
|
where: { id: user.id },
|
||||||
data: { playerId: newPlayer.id },
|
data: { playerId: newPlayer.id },
|
||||||
|
|||||||
+24
-6
@@ -1,19 +1,37 @@
|
|||||||
import { PrismaClient } from '@prisma/client'
|
import { PrismaClient } from '@prisma/client'
|
||||||
import { PrismaPg } from '@prisma/adapter-pg'
|
|
||||||
|
|
||||||
const globalForPrisma = globalThis as unknown as {
|
const globalForPrisma = globalThis as unknown as {
|
||||||
prisma: PrismaClient | undefined
|
prisma: PrismaClient | undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Detect database provider from environment (default to sqlite for local development)
|
||||||
|
// Next.js automatically loads environment variables from .env, .env.development, .env.production
|
||||||
|
const databaseProvider = process.env.DATABASE_PROVIDER || 'sqlite'
|
||||||
const databaseUrl = process.env.DATABASE_URL
|
const databaseUrl = process.env.DATABASE_URL
|
||||||
|
|
||||||
if (!databaseUrl) {
|
// Create PrismaClient with appropriate adapter
|
||||||
throw new Error('DATABASE_URL environment variable is required.')
|
|
||||||
}
|
|
||||||
|
|
||||||
const createPrismaClient = () => {
|
const createPrismaClient = () => {
|
||||||
|
let client: PrismaClient
|
||||||
|
|
||||||
|
if (databaseProvider === 'postgresql') {
|
||||||
|
// Validate DATABASE_URL is present for PostgreSQL
|
||||||
|
if (!databaseUrl) {
|
||||||
|
throw new Error(
|
||||||
|
'DATABASE_URL environment variable is required when DATABASE_PROVIDER is set to postgresql. ' +
|
||||||
|
'Current DATABASE_PROVIDER: ' + databaseProvider
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use PrismaPg adapter for PostgreSQL
|
||||||
|
const { PrismaPg } = require('@prisma/adapter-pg')
|
||||||
const adapter = new PrismaPg({ connectionString: databaseUrl })
|
const adapter = new PrismaPg({ connectionString: databaseUrl })
|
||||||
return new PrismaClient({ adapter })
|
client = new PrismaClient({ adapter })
|
||||||
|
} else {
|
||||||
|
// No adapter needed for SQLite
|
||||||
|
client = new PrismaClient()
|
||||||
|
}
|
||||||
|
|
||||||
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
|
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
|
||||||
|
|||||||
Reference in New Issue
Block a user