Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56a56e590e | |||
| 9a6188b2ae | |||
| fea0585a75 | |||
| 820b1d8d84 | |||
| 48b524ef84 | |||
| e602e83642 | |||
| ac8562ea51 | |||
| b1c4e9a0ce | |||
| 413ebaeaee | |||
| f27efebd82 | |||
| 30ea4e4e86 | |||
| 75cb6ed29d | |||
| fa13ed86c9 | |||
| 66e574d5ec | |||
| a9138cfbe4 | |||
| 1489848b77 | |||
| 49865cd9c3 | |||
| c8e89b17ac | |||
| e1b43c0702 | |||
| e4874c3438 | |||
| d9d759a06f | |||
| c796b89fb6 | |||
| 3c071b856d | |||
| adac558b5c | |||
| 5673ec14aa | |||
| f0a6d62246 | |||
| 20565df5a1 | |||
| 28fecdfaad | |||
| 79dd9be11e | |||
| 08152fba51 | |||
| 9bfb890143 |
+26
-32
@@ -1,54 +1,48 @@
|
||||
# EuchreCamp Environment Configuration
|
||||
# Copy this file to .env and fill in your values
|
||||
# ============================================
|
||||
# Copy this file to .env (for local dev) or use
|
||||
# .env.development / .env.ci for specific environments
|
||||
|
||||
# ============================================
|
||||
# Database Configuration
|
||||
# ============================================
|
||||
# PostgreSQL connection string
|
||||
# Format: postgresql://username:password@host:port/database
|
||||
DATABASE_URL=postgresql://euchre:euchrepassword@localhost:5432/euchre_camp
|
||||
# IMPORTANT: Use the appropriate DATABASE_URL for your environment:
|
||||
#
|
||||
# - Development (ephemeral, synced from prod): euchre_camp_dev
|
||||
# - CI/Testing (reset before each run): euchre_camp_ci
|
||||
# - Production (DO NOT USE FOR TESTS): euchre_camp
|
||||
#
|
||||
# The .credentials file in the project root contains
|
||||
# the actual connection strings - DO NOT commit .credentials
|
||||
|
||||
# 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
|
||||
|
||||
# ============================================
|
||||
# Better Auth Configuration
|
||||
# ============================================
|
||||
# Secret key for session encryption (generate a strong random string)
|
||||
# Run: openssl rand -base64 32
|
||||
BETTER_AUTH_SECRET=your-secret-key-change-in-production
|
||||
# Generate a new secret with: openssl rand -base64 32
|
||||
BETTER_AUTH_SECRET=generate-new-secret-in-production
|
||||
|
||||
# Base URL for authentication callbacks
|
||||
# For production: https://your-domain.com
|
||||
# Base URL - update for production
|
||||
BETTER_AUTH_URL=http://localhost:3000
|
||||
|
||||
# ============================================
|
||||
# Application Configuration
|
||||
# ============================================
|
||||
# Environment: development, production, test
|
||||
NODE_ENV=production
|
||||
NODE_ENV=development
|
||||
|
||||
# Trusted origins for CORS and authentication
|
||||
# Add your domain(s) for production
|
||||
# Comma-separated list of trusted origins
|
||||
TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||
|
||||
# ============================================
|
||||
# Optional: External Services
|
||||
# Environment-Specific Overrides
|
||||
# ============================================
|
||||
# If using external database (e.g., Supabase, Railway)
|
||||
# DATABASE_URL=postgresql://user:pass@host:port/db
|
||||
|
||||
# If using external auth provider
|
||||
# BETTER_AUTH_URL=https://your-app.com
|
||||
|
||||
# ============================================
|
||||
# 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)
|
||||
# For development (.env.development):
|
||||
# DATABASE_URL from .credentials (euchre_camp_dev)
|
||||
# NODE_ENV=development
|
||||
# BETTER_AUTH_URL=http://localhost:3000
|
||||
#
|
||||
# For CI (.env.ci):
|
||||
# DATABASE_URL from .credentials (euchre_camp_ci)
|
||||
# NODE_ENV=test
|
||||
# BETTER_AUTH_URL=http://localhost:3000
|
||||
@@ -5,13 +5,13 @@ on:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'Dockerfile.ci-base'
|
||||
- 'package.json'
|
||||
- 'bun.lock'
|
||||
- '.gitea/workflows/build-ci-images.yml'
|
||||
- "Dockerfile.ci-base"
|
||||
- "package.json"
|
||||
- "bun.lock"
|
||||
- ".gitea/workflows/build-ci-images.yml"
|
||||
schedule:
|
||||
# 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
|
||||
|
||||
env:
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
id: meta
|
||||
run: |
|
||||
# Get Playwright version from package.json
|
||||
PLAYWRIGHT_VERSION=$(grep -o '"@playwright/test": "[^"]*"' package.json | cut -d'"' -f4)
|
||||
PLAYWRIGHT_VERSION=$(grep -o '"@playwright/test": "[^"]*"' package.json | cut -d'"' -f4 | sed 's/^\^//')
|
||||
echo "playwright_version=${PLAYWRIGHT_VERSION}" >> $GITHUB_OUTPUT
|
||||
|
||||
# Get Bun version (latest)
|
||||
@@ -52,20 +52,17 @@ jobs:
|
||||
|
||||
- name: Build and push CI base image
|
||||
run: |
|
||||
WORKSPACE_DIR="$GITHUB_WORKSPACE"
|
||||
# Build with multiple tags
|
||||
docker build \
|
||||
--file Dockerfile.ci-base \
|
||||
--context "$WORKSPACE_DIR" \
|
||||
--file "$WORKSPACE_DIR/Dockerfile.ci-base" \
|
||||
--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:${{ github.sha }} \
|
||||
.
|
||||
|
||||
# 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
|
||||
if: always()
|
||||
run: |
|
||||
docker logout ${{ env.REGISTRY }}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
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..30}; 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 0.5
|
||||
done
|
||||
echo "❌ Production deployment failed"
|
||||
docker compose logs app
|
||||
exit 1
|
||||
+58
-12
@@ -5,6 +5,10 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
env:
|
||||
REGISTRY: docker.notsosm.art
|
||||
IMAGE_NAME: euchre-camp
|
||||
|
||||
jobs:
|
||||
unit-tests:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -16,9 +20,6 @@ jobs:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Clear Bun cache
|
||||
run: bun pm cache rm || true
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
@@ -30,7 +31,7 @@ jobs:
|
||||
- name: Run unit tests
|
||||
run: bun test src/__tests__/unit/ src/__tests__/*.test.tsx src/__tests__/auth-simple.test.ts
|
||||
|
||||
e2e-tests:
|
||||
build-and-deploy-ci:
|
||||
runs-on: ubuntu-latest
|
||||
needs: unit-tests
|
||||
container:
|
||||
@@ -41,9 +42,6 @@ jobs:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Clear Bun cache
|
||||
run: bun pm cache rm || true
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
@@ -52,15 +50,63 @@ jobs:
|
||||
env:
|
||||
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
|
||||
|
||||
- name: Run E2E tests
|
||||
run: npm run test:acceptance:cucumber:prod
|
||||
- name: Extract PR number and commit info
|
||||
id: info
|
||||
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: |
|
||||
WORKSPACE_DIR="$GITHUB_WORKSPACE"
|
||||
IMAGE_TAG="pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }}"
|
||||
docker build \
|
||||
--context "$WORKSPACE_DIR" \
|
||||
--file "$WORKSPACE_DIR/Dockerfile" \
|
||||
--target runner \
|
||||
--build-arg GIT_COMMIT=$GITHUB_SHA \
|
||||
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${IMAGE_TAG} \
|
||||
"$WORKSPACE_DIR"
|
||||
|
||||
- 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}
|
||||
|
||||
# Pull the new image and restart the CI stack
|
||||
cd /apps/euchre_camp_ci
|
||||
docker compose pull app
|
||||
docker compose up -d app
|
||||
|
||||
- name: Wait for CI site to be healthy
|
||||
run: |
|
||||
for i in {1..30}; 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 0.5
|
||||
done
|
||||
echo "CI site failed to become healthy after 15 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 }}" bun test:acceptance
|
||||
env:
|
||||
DATABASE_URL: postgresql://euchre_camp:${{ secrets.DB_PASSWORD }}@dhg.lol:5432/euchre_camp_dev
|
||||
DATABASE_PROVIDER: postgresql
|
||||
CI: true
|
||||
|
||||
- name: Cleanup PR images
|
||||
if: always()
|
||||
run: |
|
||||
docker rmi ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }} || true
|
||||
|
||||
analyze-bump-type:
|
||||
runs-on: ubuntu-latest
|
||||
needs: e2e-tests
|
||||
needs: unit-tests
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
|
||||
@@ -110,11 +110,14 @@ jobs:
|
||||
- name: Build test-capable image
|
||||
if: steps.commit.outputs.committed == 'true'
|
||||
run: |
|
||||
WORKSPACE_DIR="$GITHUB_WORKSPACE"
|
||||
docker build \
|
||||
--context "$WORKSPACE_DIR" \
|
||||
--file "$WORKSPACE_DIR/Dockerfile" \
|
||||
--target test-runner \
|
||||
--build-arg GIT_COMMIT=${{ github.sha }} \
|
||||
-t ${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \
|
||||
.
|
||||
"$WORKSPACE_DIR"
|
||||
|
||||
- name: Run tests inside test-capable container
|
||||
if: steps.commit.outputs.committed == 'true'
|
||||
@@ -127,12 +130,15 @@ jobs:
|
||||
- name: Build production image
|
||||
if: steps.commit.outputs.committed == 'true'
|
||||
run: |
|
||||
WORKSPACE_DIR="$GITHUB_WORKSPACE"
|
||||
docker build \
|
||||
--context "$WORKSPACE_DIR" \
|
||||
--file "$WORKSPACE_DIR/Dockerfile" \
|
||||
--target runner \
|
||||
--build-arg GIT_COMMIT=${{ github.sha }} \
|
||||
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.new_version }} \
|
||||
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \
|
||||
.
|
||||
"$WORKSPACE_DIR"
|
||||
|
||||
- name: Push Docker images
|
||||
if: steps.commit.outputs.committed == 'true'
|
||||
@@ -164,31 +170,25 @@ jobs:
|
||||
run: |
|
||||
echo "Deploying version ${{ steps.version.outputs.new_version }} to dev environment..."
|
||||
|
||||
# Update docker-compose.yml with new image tag using full registry path
|
||||
# The registry is docker.notsosm.art and image is euchre-camp
|
||||
# Update dev compose file with new image tag
|
||||
IMAGE_TAG="${{ steps.version.outputs.new_version }}"
|
||||
sed -i "s|image: docker.notsosm.art/euchre-camp:[0-9.]*|image: docker.notsosm.art/euchre-camp:${IMAGE_TAG}|" docker-compose.yml
|
||||
|
||||
# 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
|
||||
COMPOSE_FILE="/apps/intelligent_silasak/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}
|
||||
|
||||
# Pull and restart the dev container
|
||||
cd /home/euchre_camp
|
||||
docker-compose pull app
|
||||
docker-compose up -d app
|
||||
cd /apps/intelligent_silasak
|
||||
docker compose pull app
|
||||
docker compose up -d app
|
||||
|
||||
# Wait for container to be healthy
|
||||
echo "Waiting for container to start..."
|
||||
sleep 10
|
||||
|
||||
# Check if container is running
|
||||
if docker ps --filter "name=euchre-camp-app" --format "{{.Status}}" | grep -q "Up"; then
|
||||
echo "Waiting for dev site to be healthy..."
|
||||
for i in {1..30}; do
|
||||
if curl -sf https://euchre-dev.notsosm.art/api/health > /dev/null 2>&1; then
|
||||
echo "✅ Dev environment successfully deployed with version ${{ steps.version.outputs.new_version }}"
|
||||
else
|
||||
echo "❌ Dev environment deployment failed"
|
||||
docker-compose logs app
|
||||
exit 1
|
||||
exit 0
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "❌ Dev environment deployment failed"
|
||||
docker compose logs app
|
||||
exit 1
|
||||
|
||||
+3
-4
@@ -15,6 +15,8 @@
|
||||
/playwright/.auth/
|
||||
/test-results
|
||||
/cookies.txt
|
||||
.env.test
|
||||
prisma/ci.db
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
@@ -53,13 +55,10 @@ next-env.d.ts
|
||||
/src/generated/prisma
|
||||
|
||||
# database
|
||||
*.db
|
||||
*.db-journal
|
||||
prisma/dev.db*
|
||||
prisma/prisma/dev.db*
|
||||
playwright-report/
|
||||
.env.development
|
||||
.env.dev
|
||||
|
||||
cucumber-pretty
|
||||
.env.production
|
||||
.credentials
|
||||
|
||||
@@ -1,3 +1,39 @@
|
||||
## [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
|
||||
|
||||
+1
-2
@@ -22,8 +22,7 @@ RUN echo "=== Bun Version ===" && bun --version && \
|
||||
WORKDIR /app
|
||||
|
||||
# Set default environment variables
|
||||
ENV DATABASE_PROVIDER=sqlite
|
||||
ENV DATABASE_URL=file:./prisma/ci.db
|
||||
ENV DATABASE_PROVIDER=postgresql
|
||||
ENV BETTER_AUTH_SECRET=test-secret-key-for-ci-only
|
||||
ENV NODE_ENV=test
|
||||
|
||||
|
||||
+24
-8
@@ -24,11 +24,11 @@
|
||||
- [x] Write TODO list to repository file
|
||||
- [x] Auto-create tournament when uploading matches without selecting one
|
||||
|
||||
### In Progress 🔄
|
||||
- [ ] Update API routes to handle new variant scoring fields
|
||||
- [ ] Update EditTournamentForm to add variant scoring controls
|
||||
- [ ] Update MatchEditor to use tournament-specific target score
|
||||
- [ ] Run tests and verify variant scoring implementation
|
||||
### Completed ✅
|
||||
- [x] Update API routes to handle new variant scoring fields
|
||||
- [x] Update EditTournamentForm to add variant scoring controls
|
||||
- [x] Update MatchEditor to use tournament-specific target score
|
||||
- [x] Run tests and verify variant scoring implementation
|
||||
|
||||
### Recently Completed ✅
|
||||
- [x] Update CI/CD workflows to use Bun (PR, release)
|
||||
@@ -59,11 +59,27 @@
|
||||
- [x] Create migration to add rating system tables (elo_ratings, glicko2_ratings, open_skill_ratings)
|
||||
- [x] Add tabbed rankings page to display Elo, OpenSkill, and Glicko2 ratings
|
||||
|
||||
### Completed ✅
|
||||
- [x] 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 📋
|
||||
- [ ] 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
|
||||
- [ ] Update Gitea secret CI_DATABASE_URL to use euchre_camp_ci user
|
||||
- [ ] Test isolation improvements for parallel CI execution
|
||||
|
||||
## Recently Completed (Detailed)
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
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
|
||||
@@ -19,8 +19,6 @@ Feature: Tournament Schedule
|
||||
And I click the "Generate Schedule" button
|
||||
Then I should see "Generated"
|
||||
And I should see "rounds with"
|
||||
# Navigate away and back to verify schedule persisted (avoids HMR caching issues)
|
||||
When I go to the tournament schedule page
|
||||
Then I should see round 1 matchups
|
||||
And I should see round 2 matchups
|
||||
|
||||
@@ -31,8 +29,6 @@ Feature: Tournament Schedule
|
||||
When I go to the tournament schedule page
|
||||
And I click the "Generate Schedule" button
|
||||
Then I should see "Generated"
|
||||
# Navigate away and back to verify schedule persisted
|
||||
When I go to the tournament schedule page
|
||||
Then I should see 5 rounds
|
||||
And each team should play every other team exactly once
|
||||
|
||||
@@ -43,7 +39,5 @@ Feature: Tournament Schedule
|
||||
When I go to the tournament schedule page
|
||||
And I click the "Generate Schedule" button
|
||||
Then I should see "Generated"
|
||||
# Navigate away and back to ensure schedule data is loaded
|
||||
When I go to the tournament schedule page
|
||||
And I click on a matchup
|
||||
Then I should be on the match result entry page
|
||||
|
||||
@@ -124,34 +124,67 @@ Given('I am logged in as a tournament admin', async function () {
|
||||
await world.page.fill('input[name="password"]', credentials.password);
|
||||
|
||||
await world.page.click('button[type="submit"]');
|
||||
// Wait for redirect
|
||||
await world.page.waitForURL(/\/players\/\d+\/profile/, { timeout: 15000 });
|
||||
|
||||
// Extract user ID from the URL (e.g., /players/2147/profile)
|
||||
// Wait for any redirect away from register page
|
||||
await world.page.waitForURL((url) => !url.toString().includes('/auth/register'), { timeout: 15000 });
|
||||
await world.page.waitForLoadState('networkidle');
|
||||
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) {
|
||||
const playerId = match[1];
|
||||
world.playerId = playerId;
|
||||
world.playerId = match[1];
|
||||
console.log(`🌍 Player ID from URL: ${world.playerId}`);
|
||||
}
|
||||
|
||||
// Get the user ID from the database
|
||||
// Get the user ID from the database (works regardless of redirect destination)
|
||||
const prisma = await world.getPrisma();
|
||||
const player = await prisma.player.findUnique({
|
||||
where: { id: parseInt(playerId) },
|
||||
include: { user: true }
|
||||
console.log(`🌍 Looking up user by email: ${credentials.email}`);
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email },
|
||||
include: { player: true }
|
||||
});
|
||||
|
||||
if (player && player.user) {
|
||||
const userId = player.user.id;
|
||||
(world.user as any).id = userId;
|
||||
console.log(`🌍 User ID extracted: ${userId}`);
|
||||
if (user) {
|
||||
(world.user as any).id = user.id;
|
||||
console.log(`🌍 User ID from DB: ${user.id}, role: ${user.role}, playerId: ${user.playerId}`);
|
||||
|
||||
// Assign tournament_admin role to the user
|
||||
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: userId },
|
||||
where: { id: user.id },
|
||||
data: { role: 'tournament_admin' }
|
||||
});
|
||||
console.log(`🌍 Assigned tournament_admin role to user: ${userId}`);
|
||||
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('networkidle');
|
||||
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`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,10 +564,11 @@ Given('a tournament exists with {int} teams', async function (teamCount: number)
|
||||
When('I go to the tournament schedule page', async function () {
|
||||
console.log('🌍 Going to tournament schedule page');
|
||||
const tournamentId = world.tournament?.id || 1;
|
||||
await world.page.goto(`${world.baseURL}/admin/tournaments/${tournamentId}/schedule`);
|
||||
await world.page.waitForLoadState('load');
|
||||
// Wait for client components to hydrate
|
||||
await world.page.waitForTimeout(1000);
|
||||
const url = `${world.baseURL}/admin/tournaments/${tournamentId}/schedule?t=${Date.now()}`;
|
||||
await world.page.goto(url);
|
||||
await world.page.waitForLoadState('networkidle');
|
||||
// Wait for ScheduleDisplay client component to hydrate
|
||||
await world.page.waitForTimeout(2000);
|
||||
});
|
||||
|
||||
Given('a tournament has a generated schedule', async function () {
|
||||
|
||||
@@ -647,17 +647,14 @@ Then('I should be on the match detail page', async function () {
|
||||
// Tournament Schedule Steps
|
||||
Then('I should see round {int} matchups', async function (roundNumber: number) {
|
||||
const roundText = `Round ${roundNumber}`;
|
||||
await world.page.waitForTimeout(2000);
|
||||
const content = await world.page.content();
|
||||
console.log(`🌍 Page URL: ${world.page.url()}`);
|
||||
console.log(`🌍 Page has "Round ${roundNumber}": ${content.includes(`Round ${roundNumber}`)}`);
|
||||
console.log(`🌍 Page has "Generated": ${content.includes('Generated')}`);
|
||||
|
||||
await expect(world.page.locator(`text=${roundText}`)).toBeVisible({ timeout: 10000 });
|
||||
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('networkidle');
|
||||
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`);
|
||||
@@ -748,3 +745,44 @@ Then('I should not see the viewing as banner', async function () {
|
||||
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('networkidle');
|
||||
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`);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Epic 3: Rankings & Public Data
|
||||
* Acceptance Test: Player Rankings Page
|
||||
*
|
||||
* User Story: As a visitor, I want to view player rankings so that I can see top players
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - Sortable rankings table
|
||||
* - Columns: Rank, Name, Elo, Win Rate, Games Played
|
||||
* - Search/filter functionality
|
||||
* - Pagination
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Epic 3: Rankings Page', () => {
|
||||
test('Rankings page loads and displays rankings table', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Check page title or heading
|
||||
await expect(page.locator('h1, h2')).toContainText(/rankings?/i);
|
||||
|
||||
// Check for rankings table
|
||||
await expect(page.locator('table')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Rankings table displays player columns', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Check for expected column headers
|
||||
const table = page.locator('table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// Check for column headers (may vary based on implementation)
|
||||
const headerCount = await page.locator('th').count();
|
||||
expect(headerCount).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('Rankings page is publicly accessible (no login required)', async ({ page }) => {
|
||||
// Navigate directly to rankings without logging in
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Page should load without redirecting to login
|
||||
await expect(page).toHaveURL(/.*rankings.*/);
|
||||
await expect(page.locator('body')).toBeVisible();
|
||||
});
|
||||
});
|
||||
+58
-83
@@ -4,40 +4,28 @@
|
||||
*/
|
||||
|
||||
import { chromium, type FullConfig } from '@playwright/test';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { cleanupAllTestData } from '@/__tests__/test-utils';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
// Load .env file first, then .env.development (which will override .env)
|
||||
const envPath = path.resolve(process.cwd(), '.env');
|
||||
const envDevPath = path.resolve(process.cwd(), '.env.development');
|
||||
|
||||
// Load base .env file
|
||||
if (fs.existsSync(envPath)) {
|
||||
require('dotenv').config({ path: envPath });
|
||||
}
|
||||
|
||||
// Load .env.development file (will override .env settings)
|
||||
if (fs.existsSync(envDevPath)) {
|
||||
require('dotenv').config({ path: envDevPath, override: true });
|
||||
}
|
||||
|
||||
const authFile = 'playwright/.auth/user.json';
|
||||
const adminAuthFile = 'playwright/.auth/admin.json';
|
||||
|
||||
// Check if we're using the dev database
|
||||
function isDevDatabase(): boolean {
|
||||
const dbUrl = process.env.DATABASE_URL || '';
|
||||
return dbUrl.includes('euchre_camp_dev');
|
||||
function isDatabase(url: string, name: string): boolean {
|
||||
return url.includes(name);
|
||||
}
|
||||
|
||||
function isProductionDatabase(): boolean {
|
||||
const dbUrl = process.env.DATABASE_URL || '';
|
||||
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev');
|
||||
return isDatabase(dbUrl, 'euchre_camp') && !isDatabase(dbUrl, '_dev') && !isDatabase(dbUrl, '_ci');
|
||||
}
|
||||
|
||||
function isCIDatabase(): boolean {
|
||||
const dbUrl = process.env.DATABASE_URL || '';
|
||||
return isDatabase(dbUrl, '_ci');
|
||||
}
|
||||
|
||||
// Strict check - fail if using production database
|
||||
if (isProductionDatabase()) {
|
||||
console.error('');
|
||||
console.error('='.repeat(80));
|
||||
@@ -46,59 +34,70 @@ if (isProductionDatabase()) {
|
||||
console.error('');
|
||||
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||
console.error('');
|
||||
console.error('Tests MUST run against the development database (euchre_camp_dev)');
|
||||
console.error('');
|
||||
console.error('To fix this:');
|
||||
console.error(' 1. Run: npm run test:acceptance');
|
||||
console.error(' 2. Or set: DATABASE_URL environment variable to dev database URL');
|
||||
console.error(' 3. Or load .env.development: source .env.development && npm run test:acceptance');
|
||||
console.error('Tests MUST run against development (euchre_camp_dev) or CI (euchre_camp_ci)');
|
||||
console.error('');
|
||||
console.error('Aborting test execution to prevent data corruption.');
|
||||
console.error('');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!isDevDatabase()) {
|
||||
console.warn('⚠️ WARNING: DATABASE_URL does not contain euchre_camp_dev');
|
||||
console.warn(' Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||
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 });
|
||||
}
|
||||
|
||||
export default async function globalSetup(config: FullConfig) {
|
||||
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...');
|
||||
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 browser = await chromium.launch();
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Log all responses for debugging
|
||||
page.on('response', response => {
|
||||
if (response.url().includes('/api/auth')) {
|
||||
console.log('API Response:', response.status(), response.url());
|
||||
}
|
||||
});
|
||||
|
||||
// Generate unique test credentials
|
||||
const timestamp = Date.now();
|
||||
const testEmail = `setup-user-${timestamp}@example.com`;
|
||||
const testPassword = 'TestPassword1234!';
|
||||
const testName = 'Setup User';
|
||||
|
||||
try {
|
||||
// Navigate to registration page
|
||||
console.log('Navigating to registration page...');
|
||||
await page.goto(`${baseURL}/auth/register`);
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Submit the form
|
||||
console.log('Submitting registration form...');
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for the sign-up API call to complete
|
||||
console.log('Waiting for sign-up API call...');
|
||||
try {
|
||||
await page.waitForResponse(response =>
|
||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||
@@ -109,40 +108,25 @@ export default async function globalSetup(config: FullConfig) {
|
||||
console.log('Sign-up API call failed or timed out');
|
||||
}
|
||||
|
||||
// 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 });
|
||||
|
||||
console.log(`Created and authenticated test user: ${testEmail}`);
|
||||
|
||||
// Now create admin user
|
||||
const adminTimestamp = timestamp + 1;
|
||||
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
||||
const adminPassword = 'AdminPassword123!';
|
||||
const adminName = 'Setup Admin';
|
||||
|
||||
// Navigate to registration page again
|
||||
console.log('Navigating to registration page for admin...');
|
||||
await page.goto(`${baseURL}/auth/register`);
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', adminName);
|
||||
await page.fill('input[name="email"]', adminEmail);
|
||||
await page.fill('input[name="password"]', adminPassword);
|
||||
|
||||
// Submit the form
|
||||
console.log('Submitting admin registration form...');
|
||||
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 {
|
||||
await page.waitForResponse(response =>
|
||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||
@@ -153,14 +137,10 @@ export default async function globalSetup(config: FullConfig) {
|
||||
console.log('Admin sign-up API call failed or timed out');
|
||||
}
|
||||
|
||||
// Wait a bit for session to be established
|
||||
console.log('Waiting for admin session establishment...');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Update user role to admin via database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: adminEmail }
|
||||
});
|
||||
const prisma = createPrismaClient();
|
||||
const user = await prisma.user.findUnique({ where: { email: adminEmail } });
|
||||
|
||||
if (user) {
|
||||
await prisma.user.update({
|
||||
@@ -169,44 +149,39 @@ export default async function globalSetup(config: FullConfig) {
|
||||
});
|
||||
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...');
|
||||
await page.goto(`${baseURL}/admin`);
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
console.log('Admin page loaded:', page.url());
|
||||
|
||||
// Wait a bit to ensure session is refreshed
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Refresh the page to force session reload
|
||||
await page.reload();
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
console.log('Page reloaded');
|
||||
|
||||
// Save the authentication state
|
||||
await context.storageState({ path: adminAuthFile });
|
||||
|
||||
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Global setup error:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
// Return teardown function
|
||||
return async () => {
|
||||
console.log('\n=== Global Teardown ===');
|
||||
|
||||
// Clean up all test data
|
||||
try {
|
||||
await cleanupAllTestData();
|
||||
} catch (error) {
|
||||
console.error('Error cleaning up test data:', error);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default async function globalSetup(config: FullConfig) {
|
||||
console.log('=== Global Setup ===');
|
||||
console.log('DATABASE_URL:', process.env.DATABASE_URL);
|
||||
|
||||
if (isCIDatabase()) {
|
||||
console.log('CI environment detected - will reset database schema');
|
||||
const prisma = createPrismaClient();
|
||||
await resetDatabaseSchema(prisma);
|
||||
await prisma.$disconnect();
|
||||
} else if (!isProductionDatabase()) {
|
||||
console.log('Development environment - preserving existing data');
|
||||
}
|
||||
|
||||
await createTestUsers(config);
|
||||
console.log('=== Global Setup Complete ===\n');
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* 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%',
|
||||
],
|
||||
events: [
|
||||
'%Test%',
|
||||
'%Setup%',
|
||||
'%Recent%',
|
||||
'%Test Tournament%',
|
||||
'%Cucumber%',
|
||||
],
|
||||
users: [
|
||||
'%test%',
|
||||
'%setup%',
|
||||
'%cucumber%',
|
||||
'%TestUser%',
|
||||
]
|
||||
};
|
||||
|
||||
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 events WHERE (${eventWhere});`);
|
||||
console.log('Deleted test events');
|
||||
|
||||
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,110 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
test.describe('Home Page', () => {
|
||||
const createdIds = {
|
||||
players: [] as number[],
|
||||
events: [] as number[],
|
||||
matches: [] as number[],
|
||||
users: [] as string[],
|
||||
}
|
||||
|
||||
test.afterEach(async () => {
|
||||
await prisma.match.deleteMany({ where: { id: { in: createdIds.matches } } })
|
||||
await prisma.event.deleteMany({ where: { id: { in: createdIds.events } } })
|
||||
await prisma.player.deleteMany({ id: { in: createdIds.players } })
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdIds.users } } })
|
||||
createdIds.players = []
|
||||
createdIds.events = []
|
||||
createdIds.matches = []
|
||||
createdIds.users = []
|
||||
})
|
||||
|
||||
test('displays top 10 players section', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const player = 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,
|
||||
},
|
||||
})
|
||||
createdIds.players.push(player.id)
|
||||
}
|
||||
|
||||
await page.goto('/')
|
||||
|
||||
await expect(page.locator('text=Top 10 Players')).toBeVisible()
|
||||
await expect(
|
||||
page.locator(`a:has-text("Home Test Player ${timestamp} 1")`)
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
test('displays club president section', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email: `president-${timestamp}@example.com`,
|
||||
name: `Club President ${timestamp}`,
|
||||
role: 'club_admin',
|
||||
},
|
||||
})
|
||||
createdIds.users.push(user.id)
|
||||
|
||||
await page.goto('/')
|
||||
|
||||
await expect(page.locator('text=Club President')).toBeVisible()
|
||||
})
|
||||
|
||||
test('displays most recent tournament section', async ({ page }) => {
|
||||
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',
|
||||
},
|
||||
})
|
||||
createdIds.events.push(tournament.id)
|
||||
|
||||
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 },
|
||||
})
|
||||
createdIds.players.push(p1.id, p2.id, p3.id, p4.id)
|
||||
|
||||
const match = 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(),
|
||||
},
|
||||
})
|
||||
createdIds.matches.push(match.id)
|
||||
|
||||
await page.goto('/')
|
||||
|
||||
await expect(page.locator('text=Most Recent Tournament')).toBeVisible()
|
||||
await expect(page.locator(`text=Recent Tournament ${timestamp}`)).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -22,8 +22,7 @@ IMAGE_TAG_COMMIT := `git rev-parse --short HEAD`
|
||||
# --- Variables ---
|
||||
# Database
|
||||
DB_CONTAINER := "euchre-camp-postgres"
|
||||
DATABASE_PROVIDER := env_var_or_default("DATABASE_PROVIDER", "sqlite")
|
||||
DATABASE_URL := env_var_or_default("DATABASE_URL", "file:./prisma/dev.db")
|
||||
DATABASE_URL := env_var_or_default("DATABASE_URL", "")
|
||||
|
||||
# --- Setup & Installation ---
|
||||
|
||||
@@ -32,7 +31,7 @@ setup:
|
||||
@echo "Installing dependencies..."
|
||||
npm install
|
||||
@echo "Setting up database..."
|
||||
npm run db:setup-postgres
|
||||
npm run db:setup-dev
|
||||
@echo "Generating Prisma client..."
|
||||
npx prisma generate
|
||||
|
||||
@@ -56,56 +55,33 @@ format:
|
||||
|
||||
# --- Testing ---
|
||||
|
||||
# Run all tests (unit + acceptance with SQLite)
|
||||
# Note: Uses Docker containers for consistent environment
|
||||
test: test-unit test-acceptance-sqlite
|
||||
# Run all tests (unit + acceptance)
|
||||
test: test-unit test-acceptance
|
||||
|
||||
# Run all tests with PostgreSQL (Docker)
|
||||
test-pg: test-unit test-acceptance-postgres
|
||||
|
||||
# Run unit tests (Vitest)
|
||||
# Run unit tests
|
||||
test-unit:
|
||||
npm run test:run
|
||||
|
||||
# Run acceptance tests with SQLite (fast, no Docker needed)
|
||||
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
|
||||
# Run acceptance tests (Playwright)
|
||||
test-acceptance:
|
||||
@echo "Running acceptance tests..."
|
||||
npm run test:acceptance
|
||||
@echo "Stopping Docker containers..."
|
||||
docker compose down
|
||||
|
||||
# Run Cucumber e2e tests with SQLite
|
||||
test-cucumber-sqlite:
|
||||
# Run Cucumber e2e tests
|
||||
test-cucumber:
|
||||
@echo "Clearing Next.js cache..."
|
||||
rm -rf .next/
|
||||
@echo "Running Cucumber e2e tests with SQLite..."
|
||||
DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance:cucumber
|
||||
|
||||
# Run Cucumber e2e tests with PostgreSQL (uses .env.development)
|
||||
test-cucumber-postgres:
|
||||
@echo "Clearing Next.js cache..."
|
||||
rm -rf .next/
|
||||
@echo "Running Cucumber e2e tests with PostgreSQL..."
|
||||
@echo "Running Cucumber e2e tests..."
|
||||
npm run test:acceptance:cucumber
|
||||
|
||||
# Run Cucumber e2e tests with PostgreSQL against production build
|
||||
# This is more reliable than dev server (no HMR, faster API responses)
|
||||
test-cucumber-postgres-prod:
|
||||
# Run Cucumber e2e tests against production build
|
||||
test-cucumber-prod:
|
||||
@echo "Clearing Next.js cache..."
|
||||
rm -rf .next/
|
||||
@echo "Building application for production..."
|
||||
bun run build
|
||||
@echo "Starting production server in background..."
|
||||
DATABASE_URL=$(grep DATABASE_URL .env.development | cut -d'=' -f2 | tr -d '"') DATABASE_PROVIDER=postgresql bun run start > /tmp/next-prod.log 2>&1 &
|
||||
bun run start > /tmp/next-prod.log 2>&1 &
|
||||
SERVER_PID=$$!
|
||||
@echo "Waiting for server to be ready..."
|
||||
sleep 15
|
||||
@@ -115,9 +91,6 @@ test-cucumber-postgres-prod:
|
||||
kill $$SERVER_PID 2>/dev/null || true
|
||||
@echo "Tests completed."
|
||||
|
||||
# Run all e2e tests (both Playwright and Cucumber)
|
||||
test-e2e: test-acceptance-sqlite test-cucumber-sqlite
|
||||
|
||||
# Run database migrations (Prisma)
|
||||
migrate:
|
||||
npx prisma migrate dev
|
||||
@@ -126,13 +99,6 @@ migrate:
|
||||
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 ---
|
||||
|
||||
# Build the Docker image (standard build)
|
||||
@@ -148,7 +114,6 @@ docker-build-commit:
|
||||
docker-build-full: docker-build docker-build-commit
|
||||
|
||||
# Fast rebuild using Docker BuildKit cache
|
||||
# Uses build cache to speed up rebuilds when only code changes
|
||||
docker-rebuild-fast:
|
||||
@echo "Fast rebuilding Docker image {{PROJECT}}:{{IMAGE_TAG}}..."
|
||||
DOCKER_BUILDKIT=1 docker build \
|
||||
@@ -195,19 +160,14 @@ docker-push: docker-build-full
|
||||
|
||||
# --- CI/CD Pipeline Simulation ---
|
||||
|
||||
# Run full CI pipeline locally (lint, test, build, push)
|
||||
# Matches the Gitea Actions workflow
|
||||
ci: lint typecheck test-unit test-acceptance-sqlite docker-build
|
||||
# Run full CI pipeline locally (lint, test, build)
|
||||
ci: lint typecheck test-unit test-acceptance docker-build
|
||||
@echo "CI Pipeline completed successfully!"
|
||||
|
||||
# PR validation (what runs on pull requests)
|
||||
pr-validate: lint typecheck test-unit test-acceptance-sqlite
|
||||
pr-validate: lint typecheck test-unit test-acceptance
|
||||
@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 ---
|
||||
|
||||
# Show help information
|
||||
@@ -279,13 +239,72 @@ workflow-status:
|
||||
@echo "PR Workflow: Runs unit + acceptance tests on pull requests"
|
||||
@echo "Test Workflow: Runs unit tests on all branch pushes"
|
||||
@echo "Release Workflow: Runs on main branch pushes (version bump + Docker build)"
|
||||
@echo ""
|
||||
@echo "Note: CI image approach deprecated due to Gitea Actions workspace mounting"
|
||||
|
||||
# Check current database provider
|
||||
db-status:
|
||||
@echo "Database Provider: ${DATABASE_PROVIDER}"
|
||||
@echo "Database URL: ${DATABASE_URL}"
|
||||
# --- 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 "Current schema.prisma provider:"
|
||||
grep -A 2 "datasource db" prisma/schema.prisma | head -3
|
||||
@read -p "Have you verified this version works in dev? (y/N) " confirm; \
|
||||
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..30}; 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 0.5; \
|
||||
done && \
|
||||
echo "❌ Production deployment failed - health check timed out"; \
|
||||
docker compose logs app; \
|
||||
exit 1
|
||||
|
||||
# Show current deployment status across all environments
|
||||
status:
|
||||
@echo "=== EuchreCamp Deployment Status ==="
|
||||
@echo ""
|
||||
@echo "CI Site (euchre-camp-ci):"
|
||||
@grep "image:" /apps/euchre_camp_ci/docker-compose.yml | head -1
|
||||
@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
|
||||
|
||||
+1
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "euchre_camp",
|
||||
"version": "0.1.15",
|
||||
"version": "0.1.20",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "NEXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) next dev",
|
||||
@@ -19,12 +19,8 @@
|
||||
"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)",
|
||||
"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: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:check-prod": "bun run scripts/check-test-records.js",
|
||||
"db:seed": "bun run scripts/seed.js",
|
||||
|
||||
@@ -6,21 +6,22 @@ export default defineConfig({
|
||||
expect: {
|
||||
timeout: 5000
|
||||
},
|
||||
// Run tests sequentially to avoid database conflicts with SQLite
|
||||
// Run tests sequentially to avoid database conflicts
|
||||
fullyParallel: false,
|
||||
// Fail the build on CI if you accidentally left test.only in the source code.
|
||||
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,
|
||||
retries: process.env.CI ? 1 : 0,
|
||||
// Use 2 workers in CI for parallel project execution; 1 locally
|
||||
workers: process.env.CI ? 2 : 1,
|
||||
// Reporter to use
|
||||
reporter: 'html',
|
||||
// Global setup and teardown
|
||||
globalSetup: require.resolve('./e2e/global.setup'),
|
||||
globalTeardown: require.resolve('./e2e/global.teardown'),
|
||||
// Use base URL for relative navigation
|
||||
use: {
|
||||
baseURL: 'http://localhost:3000',
|
||||
baseURL: process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000',
|
||||
// Collect trace when retrying the failed test.
|
||||
trace: 'on-first-retry',
|
||||
// Capture screenshot only on failure
|
||||
@@ -65,8 +66,8 @@ export default defineConfig({
|
||||
},
|
||||
],
|
||||
// Run your local dev server before starting the tests
|
||||
webServer: {
|
||||
command: 'npm run dev',
|
||||
webServer: process.env.CI ? undefined : {
|
||||
command: 'bun run dev',
|
||||
url: 'http://localhost:3000',
|
||||
timeout: 120000,
|
||||
reuseExistingServer: !process.env.CI,
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
#!/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()
|
||||
@@ -1,234 +0,0 @@
|
||||
#!/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()
|
||||
@@ -1,195 +0,0 @@
|
||||
#!/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()
|
||||
@@ -1,108 +0,0 @@
|
||||
#!/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();
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/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();
|
||||
@@ -1,49 +0,0 @@
|
||||
#!/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,6 +8,7 @@
|
||||
import { describe, it, expect, mock, beforeEach, afterEach } from 'bun:test'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import Navigation from '@/components/Navigation'
|
||||
import { RoleSwitcherProvider } from '@/components/RoleSwitcher'
|
||||
|
||||
// Mock next/link
|
||||
mock.module('next/link', () => ({
|
||||
@@ -31,6 +32,14 @@ mock.module('@/lib/auth-client', () => ({
|
||||
// Mock fetch for role API call
|
||||
global.fetch = mock(async () => new Response()) as any
|
||||
|
||||
function renderNavigation() {
|
||||
return render(
|
||||
<RoleSwitcherProvider>
|
||||
<Navigation />
|
||||
</RoleSwitcherProvider>
|
||||
)
|
||||
}
|
||||
|
||||
import { useSession as useSessionOriginal } from '@/components/SessionProvider'
|
||||
const useSession = useSessionOriginal as any
|
||||
|
||||
@@ -61,7 +70,7 @@ describe('Epic 1: Navigation Component', () => {
|
||||
refreshSession: mock(() => {}),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
renderNavigation()
|
||||
|
||||
expect(screen.getByText('EuchreCamp')).toBeInTheDocument()
|
||||
expect(screen.getByText('Rankings')).toBeInTheDocument()
|
||||
@@ -84,7 +93,7 @@ describe('Epic 1: Navigation Component', () => {
|
||||
refreshSession: mock(() => {}),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
renderNavigation()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test User')).toBeInTheDocument()
|
||||
@@ -109,7 +118,7 @@ describe('Epic 1: Navigation Component', () => {
|
||||
refreshSession: mock(() => {}),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
renderNavigation()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||
@@ -142,7 +151,7 @@ describe('Epic 1: Navigation Component', () => {
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
renderNavigation()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Admin')).toBeInTheDocument()
|
||||
@@ -177,7 +186,7 @@ describe('Epic 1: Navigation Component', () => {
|
||||
} as Response
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
renderNavigation()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||
@@ -192,7 +201,7 @@ describe('Epic 1: Navigation Component', () => {
|
||||
refreshSession: mock(() => {}),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
renderNavigation()
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -47,7 +47,9 @@ describe('getSession', () => {
|
||||
})
|
||||
|
||||
it('returns null when an error occurs', async () => {
|
||||
mockFetch.mockRejectedValue(new Error('Network error'))
|
||||
mockFetch.mockImplementation(async () => {
|
||||
throw new Error('Network error')
|
||||
})
|
||||
|
||||
const result = await getSession()
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
import { describe, test, expect, mock, beforeEach } from 'bun:test';
|
||||
import { hasRole, canManageTournament, canCreateTournaments } from '@/lib/permissions';
|
||||
import { getSession } from '@/lib/auth-simple';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import type { User } from '@prisma/client';
|
||||
|
||||
// Create mock functions at module level
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Tests the allowTies field is properly saved when updating tournaments
|
||||
*/
|
||||
|
||||
import { describe, it, expect, mock, beforeEach,} from 'bun:test';
|
||||
import { describe, it, expect, mock, beforeEach, afterAll } from 'bun:test';
|
||||
|
||||
// Create mock functions at module level
|
||||
const eventFindUniqueMock = mock(async () => ({}));
|
||||
@@ -27,6 +27,11 @@ mock.module('@/lib/permissions', () => ({
|
||||
canDeleteTournament: canDeleteTournamentMock,
|
||||
}));
|
||||
|
||||
// Cleanup after all tests in this file
|
||||
afterAll(() => {
|
||||
mock.restore('module');
|
||||
});
|
||||
|
||||
// Import the route handler after mocking
|
||||
import { PUT } from '@/app/api/tournaments/[id]/route';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
|
||||
@@ -7,6 +7,7 @@ import Navigation from "@/components/Navigation"
|
||||
import TeamsSection from "@/components/TeamsSection"
|
||||
import { DeleteTournamentButton } from "@/components/DeleteTournamentButton"
|
||||
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
|
||||
import { BracketVisualization } from "@/components/BracketVisualization"
|
||||
import MatchEditor from "@/components/MatchEditor"
|
||||
|
||||
interface PageProps {
|
||||
@@ -420,6 +421,11 @@ export default function TournamentDetailPage({ params }: PageProps) {
|
||||
</div>
|
||||
)
|
||||
|
||||
case "bracket":
|
||||
return (
|
||||
<BracketVisualization rounds={rounds} />
|
||||
)
|
||||
|
||||
default:
|
||||
return null
|
||||
}
|
||||
@@ -555,6 +561,18 @@ export default function TournamentDetailPage({ params }: PageProps) {
|
||||
>
|
||||
Results
|
||||
</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">
|
||||
Analytics
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"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>
|
||||
)
|
||||
}
|
||||
+6
-20
@@ -3,42 +3,34 @@ import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||
import { prisma } from "./prisma";
|
||||
import { testUtils } from "better-auth/plugins";
|
||||
|
||||
// Detect database provider from environment
|
||||
const databaseProvider = process.env.DATABASE_PROVIDER || "sqlite";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: databaseProvider as "sqlite" | "postgresql",
|
||||
provider: "postgresql",
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
autoSignIn: true, // Automatically sign in after registration
|
||||
requireEmailVerification: false, // Don't require email verification for tests
|
||||
minPasswordLength: 8, // Set minimum password length
|
||||
maxPasswordLength: 128, // Set maximum password length
|
||||
autoSignIn: true,
|
||||
requireEmailVerification: false,
|
||||
minPasswordLength: 8,
|
||||
maxPasswordLength: 128,
|
||||
},
|
||||
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",
|
||||
// Configure trusted origins - parse from environment or use defaults
|
||||
trustedOrigins: (() => {
|
||||
const origins = [];
|
||||
|
||||
// Add environment-specified origins
|
||||
if (process.env.TRUSTED_ORIGINS) {
|
||||
origins.push(...process.env.TRUSTED_ORIGINS.split(',').map(o => o.trim()));
|
||||
}
|
||||
|
||||
// Add BETTER_AUTH_URL if set
|
||||
if (process.env.BETTER_AUTH_URL) {
|
||||
origins.push(process.env.BETTER_AUTH_URL);
|
||||
}
|
||||
|
||||
// Add NEXTAUTH_URL if set
|
||||
if (process.env.NEXTAUTH_URL) {
|
||||
origins.push(process.env.NEXTAUTH_URL);
|
||||
}
|
||||
|
||||
// Add defaults
|
||||
origins.push(
|
||||
"https://euchre.notsosm.art",
|
||||
"http://euchre.notsosm.art",
|
||||
@@ -48,16 +40,13 @@ export const auth = betterAuth({
|
||||
"http://0.0.0.0:3000"
|
||||
);
|
||||
|
||||
// Remove duplicates and empty strings
|
||||
return [...new Set(origins.filter(o => o))];
|
||||
})(),
|
||||
session: {
|
||||
cookieCache: {
|
||||
enabled: false, // Disable cookie cache to avoid session cache issues
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
// Configure rate limiting - disable for test environment
|
||||
// Note: Rate limiting is disabled for all environments to ensure test reliability
|
||||
rateLimit: {
|
||||
enabled: false,
|
||||
},
|
||||
@@ -66,13 +55,11 @@ export const auth = betterAuth({
|
||||
user: {
|
||||
create: {
|
||||
async after(user) {
|
||||
// Generate a unique player name using timestamp and random string
|
||||
const timestamp = Date.now();
|
||||
const randomId = Math.random().toString(36).substring(2, 8);
|
||||
const baseName = user.name || user.email.split('@')[0];
|
||||
const uniqueName = `${baseName}-${timestamp}-${randomId}`;
|
||||
|
||||
// Create a Player record for the new user
|
||||
const newPlayer = await prisma.player.create({
|
||||
data: {
|
||||
name: uniqueName,
|
||||
@@ -80,7 +67,6 @@ export const auth = betterAuth({
|
||||
},
|
||||
});
|
||||
|
||||
// Update the User with the playerId
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { playerId: newPlayer.id },
|
||||
|
||||
+6
-24
@@ -1,37 +1,19 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
import { PrismaPg } from '@prisma/adapter-pg'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
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
|
||||
|
||||
// Create PrismaClient with appropriate adapter
|
||||
if (!databaseUrl) {
|
||||
throw new Error('DATABASE_URL environment variable is required.')
|
||||
}
|
||||
|
||||
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 })
|
||||
client = new PrismaClient({ adapter })
|
||||
} else {
|
||||
// No adapter needed for SQLite
|
||||
client = new PrismaClient()
|
||||
}
|
||||
|
||||
return client
|
||||
return new PrismaClient({ adapter })
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
|
||||
|
||||
Reference in New Issue
Block a user