36 Commits
Author SHA1 Message Date
jonny 00f6c6576a UPdate device tracking cookie 2025-11-16 12:47:19 +08:00
jonny 0cf8cf7fc0 Add deadline and refactor squad pages 2025-10-22 21:57:18 +08:00
jonny c199979eb9 Fix historical squads 2025-10-13 22:56:49 +08:00
jonny 6a50c9fe90 Add voting deadline function 2025-10-13 22:30:15 +08:00
jonny afd5ecd89a Update values 2025-10-10 21:10:53 +08:00
jonny 6886f94888 Add helm chart 2025-10-09 22:59:26 +08:00
jonny 09d5c79e8d Push latest fixes 2025-10-09 18:18:20 +08:00
jonny a6febae8a8 Refactoring fixes and adding functionality back 2025-10-07 22:03:36 +08:00
jonny d5350aa4cb Refactored pages 2025-10-06 23:32:53 +08:00
jonny a08897c5c2 Merge pull request 'identifier' (#2) from identifier into master
Reviewed-on: #2
2025-10-06 14:38:49 +00:00
jonny 0bf5f1a29c Fix S3 permissions and things 2025-10-06 22:28:27 +08:00
jonny 85858d33bd VArious admin fixes 2025-10-04 21:13:25 +08:00
jonny 83fe4b9013 VArious admin fixes 2025-10-04 21:05:01 +08:00
jonny a993767dc0 Add admin profile 2025-10-04 17:04:55 +08:00
jonny 0c60a4b4d8 Add extra DB functions 2025-10-04 16:47:40 +08:00
jonny 131f17947c Fix up voting and start adding club logos 2025-10-03 00:13:09 +08:00
jonny 7f0d171e21 Latest updates to use postgres 2025-10-01 23:25:05 +08:00
jonny acb88ae785 Latest updates 2025-09-29 22:50:42 +08:00
jonny aabc01382c Updated code to populate database 2025-09-29 22:39:57 +08:00
jonny 1b36a283d5 Add datbase setup 2025-09-29 20:25:10 +08:00
jonny 538e9bc27b Separate Containerfile for motm app 2025-09-29 20:10:27 +08:00
jonny e354caa03f Add Containerfle 2025-09-29 20:06:07 +08:00
jonny fa37916440 Fix flask table error 2025-09-29 12:31:47 +08:00
jonny 2cf4e923f3 Fix more errors 2025-09-29 12:30:02 +08:00
jonny 7f6ee28d7c Fix wtforms error 2025-09-29 12:28:47 +08:00
jonny 3d769837d4 Update to support py venv 2025-09-29 12:21:58 +08:00
jonny d3eb5567b6 Separate MotM app out 2025-09-29 10:43:48 +08:00
git-admin 5638b0af76 Fixed MotM URL 2021-10-10 16:13:03 +08:00
git-admin c0d01cca3f Removed unnecessary files 2021-09-19 22:56:07 +08:00
git-admin 58d39a464d Fixed DB name to use 2021-09-19 22:46:28 +08:00
git-admin 3d21364152 Fixed DB location 2021-09-19 22:13:15 +08:00
git-admin e7f914e503 Changed DB to use internal name 2021-09-19 21:52:43 +08:00
git-admin a368826ce4 Bumped to 2021/22 season 2021-09-11 15:33:38 +08:00
Jonathan Ervine 83a427c712 Merge branch 'master' of ssh://git.ervine.org/jonny/gcp-hockey-results
Removed auth
2020-11-25 20:46:57 +08:00
Jonathan Ervine 43561c926a Removed authentication 2020-11-25 20:46:47 +08:00
jonny c1ecfecbac Merge pull request 'dev' (#1) from dev into master
Reviewed-on: #1
2020-11-20 06:00:00 +00:00
162 changed files with 22287 additions and 81 deletions
+133
View File
@@ -0,0 +1,133 @@
# Git
.git
.gitignore
.gitattributes
# Documentation
README.md
*.md
docs/
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual environments
venv/
env/
ENV/
env.bak/
venv.bak/
.venv/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
*.log
logs/
# Database files (will be created in container)
*.db
*.sqlite
*.sqlite3
# Data directories
data/
temp/
tmp/
# Docker
Dockerfile*
docker-compose*.yml
.dockerignore
# Environment files
.env
.env.local
.env.production
.env.development
# Node modules (if any)
node_modules/
# Coverage reports
htmlcov/
.coverage
.coverage.*
coverage.xml
# Testing
.pytest_cache/
.tox/
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# pipenv
Pipfile.lock
# PEP 582
__pypackages__/
# Celery
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
+76
View File
@@ -0,0 +1,76 @@
# Multi-stage Containerfile for Hockey Results Application
# Supports multiple database backends (PostgreSQL, MariaDB, SQLite)
# Stage 1: Build stage
FROM python:3.11-slim as builder
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
# Install system dependencies for building Python packages
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
default-libmysqlclient-dev \
pkg-config \
&& rm -rf /var/lib/apt/lists/*
# Create and activate virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
# Copy requirements and install Python dependencies
COPY requirements.txt motm_app/requirements.txt ./
RUN pip install --upgrade pip && \
pip install -r requirements.txt && \
pip install -r motm_app/requirements.txt
# Stage 2: Runtime stage
FROM python:3.11-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PATH="/opt/venv/bin:$PATH" \
DATABASE_TYPE=sqlite \
FLASK_ENV=production \
FLASK_APP=motm_app/main.py
# Install runtime dependencies
RUN apt-get update && apt-get install -y \
libpq5 \
default-mysql-client \
curl \
&& rm -rf /var/lib/apt/lists/*
# Copy virtual environment from builder stage
COPY --from=builder /opt/venv /opt/venv
# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
# Create application directory
WORKDIR /app
# Copy application code
COPY --chown=appuser:appuser . .
# Create directories for data and logs
RUN mkdir -p /app/data /app/logs && \
chown -R appuser:appuser /app/data /app/logs
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 5000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:5000/ || exit 1
# Default command
CMD ["python", "motm_app/main.py"]
+362
View File
@@ -0,0 +1,362 @@
# Docker Containerization Guide
This guide explains how to run the Hockey Results Application using Docker containers with support for multiple database backends.
## 🏒 Quick Start
### Using Docker Compose (Recommended)
```bash
# Start with PostgreSQL (default)
docker-compose up -d
# Start with MariaDB
docker-compose --profile mariadb up -d
# Start with SQLite (no database container needed)
DATABASE_TYPE=sqlite docker-compose up -d
```
### Using Docker Commands
```bash
# Build the image
./docker/build.sh
# Run with SQLite
./docker/run.sh
# Run with PostgreSQL
./docker/run.sh -d postgresql
# Run with MariaDB
./docker/run.sh -d mysql
```
## 🗄️ Database Options
### 1. SQLite (Default)
- **Pros**: No external dependencies, perfect for development
- **Cons**: Not suitable for production with multiple users
- **Use case**: Development, testing, single-user deployments
```bash
# Using docker-compose
DATABASE_TYPE=sqlite docker-compose up -d
# Using docker run
./docker/run.sh -d sqlite
```
### 2. PostgreSQL (Recommended for Production)
- **Pros**: Robust, ACID compliant, excellent performance
- **Cons**: Requires external database container
- **Use case**: Production deployments, multi-user applications
```bash
# Using docker-compose (default)
docker-compose up -d
# Using docker run (requires external PostgreSQL)
./docker/run.sh -d postgresql
```
### 3. MariaDB/MySQL
- **Pros**: Widely supported, good performance
- **Cons**: Requires external database container
- **Use case**: Legacy systems, specific MySQL requirements
```bash
# Using docker-compose
docker-compose --profile mariadb up -d
# Using docker run (requires external MariaDB)
./docker/run.sh -d mysql
```
## 🚀 Deployment Options
### Development Environment
```bash
# Clone the repository
git clone <repository-url>
cd gcp-hockey-results
# Start with SQLite for development
./docker/run.sh -d sqlite -p 5000:5000
# Access the application
open http://localhost:5000
```
### Production Environment
#### Option 1: Docker Compose (Single Server)
```bash
# Set production environment variables
export SECRET_KEY="your-production-secret-key"
export BASIC_AUTH_PASSWORD="strong-production-password"
export POSTGRES_PASSWORD="strong-database-password"
# Start production stack
docker-compose up -d
# Scale the application (optional)
docker-compose up -d --scale hockey-app=3
```
#### Option 2: Kubernetes (Multi-Server)
```yaml
# kubernetes/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: hockey-app
spec:
replicas: 3
selector:
matchLabels:
app: hockey-app
template:
metadata:
labels:
app: hockey-app
spec:
containers:
- name: hockey-app
image: hockey-results:latest
ports:
- containerPort: 5000
env:
- name: DATABASE_TYPE
value: "postgresql"
- name: POSTGRES_HOST
value: "postgres-service"
```
#### Option 3: Cloud Platforms
**Google Cloud Run:**
```bash
# Build and push to Google Container Registry
./docker/build.sh --registry gcr.io/your-project-id --push
# Deploy to Cloud Run
gcloud run deploy hockey-app \
--image gcr.io/your-project-id/hockey-results:latest \
--platform managed \
--region us-central1 \
--set-env-vars DATABASE_TYPE=postgresql
```
**AWS ECS:**
```bash
# Build and push to ECR
./docker/build.sh --registry your-account.dkr.ecr.region.amazonaws.com --push
# Create ECS task definition with the image
```
## 🔧 Configuration
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `DATABASE_TYPE` | `sqlite` | Database type: sqlite, postgresql, mysql |
| `SECRET_KEY` | `your-secret-key-change-in-production` | Flask secret key |
| `FLASK_ENV` | `production` | Flask environment |
| `BASIC_AUTH_USERNAME` | `admin` | Basic auth username |
| `BASIC_AUTH_PASSWORD` | `letmein` | Basic auth password |
### PostgreSQL Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `POSTGRES_HOST` | `postgres` | PostgreSQL host |
| `POSTGRES_PORT` | `5432` | PostgreSQL port |
| `POSTGRES_DATABASE` | `hockey_results` | Database name |
| `POSTGRES_USER` | `hockey_user` | Database user |
| `POSTGRES_PASSWORD` | `hockey_password` | Database password |
### MySQL/MariaDB Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `MYSQL_HOST` | `mariadb` | MySQL host |
| `MYSQL_PORT` | `3306` | MySQL port |
| `MYSQL_DATABASE` | `hockey_results` | Database name |
| `MYSQL_USER` | `hockey_user` | Database user |
| `MYSQL_PASSWORD` | `hockey_password` | Database password |
## 📊 Monitoring and Logs
### View Logs
```bash
# Docker Compose
docker-compose logs -f hockey-app
# Docker Run
docker logs -f hockey-results-app
```
### Health Checks
```bash
# Check container health
docker ps
# Manual health check
curl -f http://localhost:5000/ || echo "Application is not healthy"
```
### Database Connection Test
```bash
# Test PostgreSQL connection
docker exec hockey-results-app python -c "
from motm_app.database import db_config
print('Database URL:', db_config.database_url)
"
# Test application database initialization
docker exec hockey-results-app python -c "
from motm_app.database import init_database
init_database()
print('Database initialized successfully')
"
```
## 🛠️ Development
### Local Development with Docker
```bash
# Build development image
./docker/build.sh -t dev
# Run with volume mount for live code changes
docker run -it --rm \
-p 5000:5000 \
-v $(pwd):/app \
-e FLASK_ENV=development \
-e FLASK_DEBUG=true \
hockey-results:dev
```
### Database Migrations
```bash
# Run migrations inside container
docker exec hockey-results-app python -c "
from motm_app.database import init_database
init_database()
"
```
### Backup and Restore
```bash
# Backup PostgreSQL data
docker exec hockey-postgres pg_dump -U hockey_user hockey_results > backup.sql
# Restore PostgreSQL data
docker exec -i hockey-postgres psql -U hockey_user hockey_results < backup.sql
# Backup SQLite data
docker cp hockey-results-app:/app/data/hockey_results.db ./backup.db
```
## 🔒 Security Considerations
### Production Security
1. **Change default passwords**:
```bash
export SECRET_KEY="$(openssl rand -hex 32)"
export BASIC_AUTH_PASSWORD="$(openssl rand -base64 32)"
export POSTGRES_PASSWORD="$(openssl rand -base64 32)"
```
2. **Use secrets management**:
```yaml
# docker-compose.prod.yml
services:
hockey-app:
environment:
- SECRET_KEY_FILE=/run/secrets/secret_key
secrets:
- secret_key
secrets:
secret_key:
file: ./secrets/secret_key.txt
```
3. **Network security**:
```yaml
# Use custom networks
networks:
hockey-network:
driver: bridge
ipam:
config:
- subnet: 172.20.0.0/16
```
## 🚨 Troubleshooting
### Common Issues
**Container won't start:**
```bash
# Check logs
docker logs hockey-results-app
# Check if port is already in use
netstat -tlnp | grep :5000
```
**Database connection issues:**
```bash
# Check database container status
docker-compose ps
# Test database connectivity
docker exec hockey-results-app python -c "
import psycopg2
conn = psycopg2.connect(host='postgres', port=5432, database='hockey_results', user='hockey_user', password='hockey_password')
print('Database connected successfully')
"
```
**Permission issues:**
```bash
# Fix file permissions
sudo chown -R $USER:$USER ./data
chmod -R 755 ./data
```
### Performance Tuning
**Database Optimization:**
```bash
# PostgreSQL tuning
docker exec hockey-postgres psql -U hockey_user hockey_results -c "
ALTER SYSTEM SET shared_buffers = '256MB';
ALTER SYSTEM SET effective_cache_size = '1GB';
SELECT pg_reload_conf();
"
```
**Application Scaling:**
```bash
# Scale application containers
docker-compose up -d --scale hockey-app=3
# Use load balancer
docker-compose --profile nginx up -d
```
## 📚 Additional Resources
- [Docker Documentation](https://docs.docker.com/)
- [Docker Compose Documentation](https://docs.docker.com/compose/)
- [PostgreSQL Docker Image](https://hub.docker.com/_/postgres)
- [MariaDB Docker Image](https://hub.docker.com/_/mariadb)
- [SQLAlchemy Documentation](https://docs.sqlalchemy.org/)
+6 -5
View File
@@ -6,6 +6,7 @@ import json
# These environment variables are configured in app.yaml. # These environment variables are configured in app.yaml.
CLOUDSQL_CONNECTION_NAME = "hk-hockey:asia-east2:hk-hockey-sql" CLOUDSQL_CONNECTION_NAME = "hk-hockey:asia-east2:hk-hockey-sql"
LOCAL_DB_SERVER = "mariadb.db.svc.cluster.local"
CLOUDSQL_USER = "root" CLOUDSQL_USER = "root"
CLOUDSQL_WRITE_USER = "hockeyWrite" CLOUDSQL_WRITE_USER = "hockeyWrite"
CLOUDSQL_READ_USER = "hockeyRead" CLOUDSQL_READ_USER = "hockeyRead"
@@ -13,7 +14,7 @@ CLOUDSQL_PASSWORD = "P8P1YopMlwg8TxhE"
CLOUDSQL_WRITE_PASSWORD = "1URYcxXXlQ6xOWgj" CLOUDSQL_WRITE_PASSWORD = "1URYcxXXlQ6xOWgj"
CLOUDSQL_READ_PASSWORD = "o4GWrbbkBKy3oR6u" CLOUDSQL_READ_PASSWORD = "o4GWrbbkBKy3oR6u"
CLOUDSQL_DATABASE = "20209_hockeyResults" CLOUDSQL_DATABASE = "20209_hockeyResults"
LOCAL_DATABASE = "hockeyResults2020" LOCAL_DATABASE = "hockeyResults2021"
CLOUDSQL_DATABASE_STATIC = "hockeyResults" CLOUDSQL_DATABASE_STATIC = "hockeyResults"
CLOUDSQL_CHARSET = "utf8" CLOUDSQL_CHARSET = "utf8"
@@ -37,7 +38,7 @@ def write_cloudsql():
# #
else: else:
# db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE, charset=CLOUDSQL_CHARSET) # db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE, charset=CLOUDSQL_CHARSET)
db = pymysql.connect(host='db.ipa.champion', user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=LOCAL_DATABASE, charset=CLOUDSQL_CHARSET) db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=LOCAL_DATABASE, charset=CLOUDSQL_CHARSET)
return db return db
def write_cloudsql_static(): def write_cloudsql_static():
@@ -59,7 +60,7 @@ def write_cloudsql_static():
# #
else: else:
# db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET) # db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
db = pymysql.connect(host='db.ipa.champion', user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET) db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
return db return db
def read_cloudsql(): def read_cloudsql():
@@ -81,7 +82,7 @@ def read_cloudsql():
# #
else: else:
# db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE, charset=CLOUDSQL_CHARSET) # db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE, charset=CLOUDSQL_CHARSET)
db = pymysql.connect(host='db.ipa.champion', user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=LOCAL_DATABASE, charset=CLOUDSQL_CHARSET) db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=LOCAL_DATABASE, charset=CLOUDSQL_CHARSET)
return db return db
def read_cloudsql_static(): def read_cloudsql_static():
@@ -103,7 +104,7 @@ def read_cloudsql_static():
# #
else: else:
# db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET) # db = MySQLdb.connect(host='db.ipa.champion', user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
db = pymysql.connect(host='db.ipa.champion', user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET) db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
return db return db
def sql_write(sql_cmd): def sql_write(sql_cmd):
+125
View File
@@ -0,0 +1,125 @@
version: '3.8'
services:
# Hockey Results Application
hockey-app:
build:
context: .
dockerfile: Containerfile
container_name: hockey-results-app
ports:
- "5000:5000"
environment:
- DATABASE_TYPE=postgresql
- POSTGRES_HOST=postgres
- POSTGRES_PORT=5432
- POSTGRES_DATABASE=hockey_results
- POSTGRES_USER=hockey_user
- POSTGRES_PASSWORD=hockey_password
- FLASK_ENV=production
- SECRET_KEY=your-secret-key-change-in-production
- BASIC_AUTH_USERNAME=admin
- BASIC_AUTH_PASSWORD=letmein
volumes:
- ./data:/app/data
- ./logs:/app/logs
depends_on:
postgres:
condition: service_healthy
restart: unless-stopped
networks:
- hockey-network
# PostgreSQL Database
postgres:
image: postgres:15-alpine
container_name: hockey-postgres
environment:
- POSTGRES_DB=hockey_results
- POSTGRES_USER=hockey_user
- POSTGRES_PASSWORD=hockey_password
- POSTGRES_INITDB_ARGS=--encoding=UTF-8 --lc-collate=C --lc-ctype=C
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init-scripts:/docker-entrypoint-initdb.d
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U hockey_user -d hockey_results"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
networks:
- hockey-network
# MariaDB Database (Alternative)
mariadb:
image: mariadb:10.11
container_name: hockey-mariadb
environment:
- MYSQL_ROOT_PASSWORD=root_password
- MYSQL_DATABASE=hockey_results
- MYSQL_USER=hockey_user
- MYSQL_PASSWORD=hockey_password
- MYSQL_CHARSET=utf8mb4
- MYSQL_COLLATION=utf8mb4_unicode_ci
volumes:
- mariadb_data:/var/lib/mysql
- ./init-scripts:/docker-entrypoint-initdb.d
ports:
- "3306:3306"
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "hockey_user", "-p$$MYSQL_PASSWORD"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
networks:
- hockey-network
profiles:
- mariadb
# Redis for caching (optional)
redis:
image: redis:7-alpine
container_name: hockey-redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
networks:
- hockey-network
profiles:
- redis
# Nginx reverse proxy (optional)
nginx:
image: nginx:alpine
container_name: hockey-nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- hockey-app
restart: unless-stopped
networks:
- hockey-network
profiles:
- nginx
volumes:
postgres_data:
driver: local
mariadb_data:
driver: local
redis_data:
driver: local
networks:
hockey-network:
driver: bridge
+127
View File
@@ -0,0 +1,127 @@
#!/bin/bash
# Docker build script for Hockey Results Application
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Configuration
IMAGE_NAME="hockey-results"
IMAGE_TAG="latest"
FULL_IMAGE_NAME="${IMAGE_NAME}:${IMAGE_TAG}"
echo -e "${BLUE}🏒 Building Hockey Results Application Docker Image${NC}"
echo -e "${BLUE}================================================${NC}"
# Function to display usage
usage() {
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -t, --tag TAG Set image tag (default: latest)"
echo " -n, --name NAME Set image name (default: hockey-results)"
echo " --no-cache Build without cache"
echo " --push Push image to registry after build"
echo " -h, --help Show this help message"
echo ""
echo "Examples:"
echo " $0 # Build with default settings"
echo " $0 -t v1.0.0 # Build with specific tag"
echo " $0 --no-cache # Build without cache"
echo " $0 -t v1.0.0 --push # Build and push to registry"
}
# Parse command line arguments
PUSH_IMAGE=false
NO_CACHE=""
REGISTRY=""
while [[ $# -gt 0 ]]; do
case $1 in
-t|--tag)
IMAGE_TAG="$2"
FULL_IMAGE_NAME="${IMAGE_NAME}:${IMAGE_TAG}"
shift 2
;;
-n|--name)
IMAGE_NAME="$2"
FULL_IMAGE_NAME="${IMAGE_NAME}:${IMAGE_TAG}"
shift 2
;;
--no-cache)
NO_CACHE="--no-cache"
shift
;;
--push)
PUSH_IMAGE=true
shift
;;
--registry)
REGISTRY="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo -e "${RED}Unknown option: $1${NC}"
usage
exit 1
;;
esac
done
echo -e "${YELLOW}📋 Build Configuration:${NC}"
echo -e " Image Name: ${GREEN}${FULL_IMAGE_NAME}${NC}"
echo -e " No Cache: ${GREEN}${NO_CACHE:-false}${NC}"
echo -e " Push Image: ${GREEN}${PUSH_IMAGE}${NC}"
echo ""
# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
echo -e "${RED}❌ Docker is not running. Please start Docker and try again.${NC}"
exit 1
fi
# Build the image
echo -e "${BLUE}🔨 Building Docker image...${NC}"
if docker build $NO_CACHE -t "$FULL_IMAGE_NAME" .; then
echo -e "${GREEN}✅ Docker image built successfully: ${FULL_IMAGE_NAME}${NC}"
else
echo -e "${RED}❌ Docker build failed${NC}"
exit 1
fi
# Show image information
echo -e "${BLUE}📊 Image Information:${NC}"
docker images "$FULL_IMAGE_NAME"
# Push image if requested
if [ "$PUSH_IMAGE" = true ]; then
echo -e "${BLUE}📤 Pushing image to registry...${NC}"
if [ -n "$REGISTRY" ]; then
FULL_REGISTRY_NAME="${REGISTRY}/${FULL_IMAGE_NAME}"
docker tag "$FULL_IMAGE_NAME" "$FULL_REGISTRY_NAME"
docker push "$FULL_REGISTRY_NAME"
echo -e "${GREEN}✅ Image pushed to registry: ${FULL_REGISTRY_NAME}${NC}"
else
docker push "$FULL_IMAGE_NAME"
echo -e "${GREEN}✅ Image pushed to registry: ${FULL_IMAGE_NAME}${NC}"
fi
fi
echo -e "${GREEN}🎉 Build process completed successfully!${NC}"
# Show next steps
echo -e "${YELLOW}📝 Next Steps:${NC}"
echo -e " To run the container: ${BLUE}docker run -p 5000:5000 ${FULL_IMAGE_NAME}${NC}"
echo -e " To run with docker-compose: ${BLUE}docker-compose up${NC}"
echo -e " To run with PostgreSQL: ${BLUE}docker-compose --profile postgres up${NC}"
echo -e " To run with MariaDB: ${BLUE}docker-compose --profile mariadb up${NC}"
+192
View File
@@ -0,0 +1,192 @@
#!/bin/bash
# Docker run script for Hockey Results Application
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default configuration
IMAGE_NAME="hockey-results:latest"
CONTAINER_NAME="hockey-results-app"
PORT="5000:5000"
DATABASE_TYPE="sqlite"
VOLUME_MOUNT=""
# Function to display usage
usage() {
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -i, --image IMAGE Docker image name (default: hockey-results:latest)"
echo " -c, --container NAME Container name (default: hockey-results-app)"
echo " -p, --port PORT Port mapping (default: 5000:5000)"
echo " -d, --database TYPE Database type: sqlite, postgresql, mysql (default: sqlite)"
echo " -v, --volume PATH Mount volume for data persistence"
echo " --detach Run container in background"
echo " --rm Remove container when it exits"
echo " --env KEY=VALUE Set environment variable"
echo " -h, --help Show this help message"
echo ""
echo "Database Types:"
echo " sqlite Use SQLite database (default, no external dependencies)"
echo " postgresql Use PostgreSQL database"
echo " mysql Use MySQL/MariaDB database"
echo ""
echo "Examples:"
echo " $0 # Run with SQLite"
echo " $0 -d postgresql # Run with PostgreSQL"
echo " $0 -v ./data:/app/data # Run with data persistence"
echo " $0 -p 8080:5000 # Run on different port"
echo " $0 --detach # Run in background"
}
# Parse command line arguments
DETACH=""
REMOVE=""
ENV_VARS=""
while [[ $# -gt 0 ]]; do
case $1 in
-i|--image)
IMAGE_NAME="$2"
shift 2
;;
-c|--container)
CONTAINER_NAME="$2"
shift 2
;;
-p|--port)
PORT="$2"
shift 2
;;
-d|--database)
DATABASE_TYPE="$2"
shift 2
;;
-v|--volume)
VOLUME_MOUNT="-v $2"
shift 2
;;
--detach)
DETACH="-d"
shift
;;
--rm)
REMOVE="--rm"
shift
;;
--env)
ENV_VARS="$ENV_VARS -e $2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo -e "${RED}Unknown option: $1${NC}"
usage
exit 1
;;
esac
done
echo -e "${BLUE}🏒 Running Hockey Results Application${NC}"
echo -e "${BLUE}====================================${NC}"
# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
echo -e "${RED}❌ Docker is not running. Please start Docker and try again.${NC}"
exit 1
fi
# Check if image exists
if ! docker images -q "$IMAGE_NAME" | grep -q .; then
echo -e "${YELLOW}⚠️ Image $IMAGE_NAME not found. Building it first...${NC}"
./docker/build.sh -n "$(echo $IMAGE_NAME | cut -d':' -f1)" -t "$(echo $IMAGE_NAME | cut -d':' -f2)"
fi
# Stop existing container if running
if docker ps -q -f name="$CONTAINER_NAME" | grep -q .; then
echo -e "${YELLOW}🛑 Stopping existing container...${NC}"
docker stop "$CONTAINER_NAME"
fi
# Remove existing container if it exists
if docker ps -aq -f name="$CONTAINER_NAME" | grep -q .; then
echo -e "${YELLOW}🗑️ Removing existing container...${NC}"
docker rm "$CONTAINER_NAME"
fi
# Set environment variables based on database type
case $DATABASE_TYPE in
"postgresql")
ENV_VARS="$ENV_VARS -e DATABASE_TYPE=postgresql"
ENV_VARS="$ENV_VARS -e POSTGRES_HOST=host.docker.internal"
ENV_VARS="$ENV_VARS -e POSTGRES_PORT=5432"
ENV_VARS="$ENV_VARS -e POSTGRES_DATABASE=hockey_results"
ENV_VARS="$ENV_VARS -e POSTGRES_USER=hockey_user"
ENV_VARS="$ENV_VARS -e POSTGRES_PASSWORD=hockey_password"
echo -e "${YELLOW}📊 Using PostgreSQL database${NC}"
;;
"mysql")
ENV_VARS="$ENV_VARS -e DATABASE_TYPE=mysql"
ENV_VARS="$ENV_VARS -e MYSQL_HOST=host.docker.internal"
ENV_VARS="$ENV_VARS -e MYSQL_PORT=3306"
ENV_VARS="$ENV_VARS -e MYSQL_DATABASE=hockey_results"
ENV_VARS="$ENV_VARS -e MYSQL_USER=hockey_user"
ENV_VARS="$ENV_VARS -e MYSQL_PASSWORD=hockey_password"
echo -e "${YELLOW}📊 Using MySQL/MariaDB database${NC}"
;;
"sqlite")
ENV_VARS="$ENV_VARS -e DATABASE_TYPE=sqlite"
ENV_VARS="$ENV_VARS -e SQLITE_DATABASE_PATH=/app/data/hockey_results.db"
VOLUME_MOUNT="$VOLUME_MOUNT -v $(pwd)/data:/app/data"
echo -e "${YELLOW}📊 Using SQLite database${NC}"
;;
*)
echo -e "${RED}❌ Unsupported database type: $DATABASE_TYPE${NC}"
echo -e "Supported types: sqlite, postgresql, mysql"
exit 1
;;
esac
echo -e "${BLUE}🚀 Starting container...${NC}"
echo -e " Image: ${GREEN}$IMAGE_NAME${NC}"
echo -e " Container: ${GREEN}$CONTAINER_NAME${NC}"
echo -e " Port: ${GREEN}$PORT${NC}"
echo -e " Database: ${GREEN}$DATABASE_TYPE${NC}"
# Run the container
docker run \
$DETACH \
$REMOVE \
--name "$CONTAINER_NAME" \
-p "$PORT" \
$VOLUME_MOUNT \
$ENV_VARS \
"$IMAGE_NAME"
if [ $? -eq 0 ]; then
if [ -n "$DETACH" ]; then
echo -e "${GREEN}✅ Container started successfully in background${NC}"
echo -e "${BLUE}📝 Container Information:${NC}"
docker ps -f name="$CONTAINER_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
echo ""
echo -e "${YELLOW}📋 Useful Commands:${NC}"
echo -e " View logs: ${BLUE}docker logs $CONTAINER_NAME${NC}"
echo -e " Stop container: ${BLUE}docker stop $CONTAINER_NAME${NC}"
echo -e " Remove container: ${BLUE}docker rm $CONTAINER_NAME${NC}"
echo -e " Access shell: ${BLUE}docker exec -it $CONTAINER_NAME /bin/bash${NC}"
else
echo -e "${GREEN}✅ Container finished${NC}"
fi
else
echo -e "${RED}❌ Failed to start container${NC}"
exit 1
fi
+68
View File
@@ -0,0 +1,68 @@
#!/bin/bash
# Docker startup script for Hockey Results Application
set -e
echo "🏒 Starting Hockey Results Application..."
# Function to wait for database
wait_for_database() {
local db_type=$1
local max_attempts=30
local attempt=1
echo "⏳ Waiting for $db_type database to be ready..."
case $db_type in
"postgresql")
while [ $attempt -le $max_attempts ]; do
if python -c "import psycopg2; psycopg2.connect(host='$POSTGRES_HOST', port='$POSTGRES_PORT', database='$POSTGRES_DATABASE', user='$POSTGRES_USER', password='$POSTGRES_PASSWORD')" 2>/dev/null; then
echo "✅ PostgreSQL database is ready!"
return 0
fi
echo "Attempt $attempt/$max_attempts: Database not ready, waiting..."
sleep 2
attempt=$((attempt + 1))
done
;;
"mysql"|"mariadb")
while [ $attempt -le $max_attempts ]; do
if python -c "import pymysql; pymysql.connect(host='$MYSQL_HOST', port='$MYSQL_PORT', database='$MYSQL_DATABASE', user='$MYSQL_USER', password='$MYSQL_PASSWORD')" 2>/dev/null; then
echo "✅ MySQL/MariaDB database is ready!"
return 0
fi
echo "Attempt $attempt/$max_attempts: Database not ready, waiting..."
sleep 2
attempt=$((attempt + 1))
done
;;
esac
echo "❌ Database connection timeout after $max_attempts attempts"
exit 1
}
# Initialize database if needed
init_database() {
echo "🔧 Initializing database..."
python -c "
from motm_app.database import init_database
try:
init_database()
print('✅ Database initialized successfully')
except Exception as e:
print(f'⚠️ Database initialization warning: {e}')
"
}
# Wait for database if not using SQLite
if [ "$DATABASE_TYPE" != "sqlite" ]; then
wait_for_database "$DATABASE_TYPE"
fi
# Initialize database
init_database
# Start the application
echo "🚀 Starting Flask application..."
exec python motm_app/main.py
+15 -47
View File
@@ -3,8 +3,7 @@ import pymysql
import os import os
from app import app from app import app
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, PasswordField, TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField from wtforms import BooleanField, StringField, PasswordField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField, DateField
from wtforms.fields.html5 import DateField
from wtforms_components import read_only from wtforms_components import read_only
from wtforms import validators, ValidationError from wtforms import validators, ValidationError
from wtforms.validators import InputRequired, Email, Length from wtforms.validators import InputRequired, Email, Length
@@ -27,24 +26,24 @@ class RegisterForm(FlaskForm):
class addPlayerForm(FlaskForm): class addPlayerForm(FlaskForm):
playerClub = SelectField('Club:', choices=[]) playerClub = SelectField('Club:', choices=[])
playerTeam = SelectField('Team:', choices=[]) playerTeam = SelectField('Team:', choices=[])
playerForenames = TextField('Forenames:') playerForenames = StringField('Forenames:')
playerSurnames = TextField('Surname:') playerSurnames = StringField('Surname:')
playerNickname = TextField('Nickname') playerNickname = StringField('Nickname')
playerChineseName = TextField('Chinese Name:') playerChineseName = StringField('Chinese Name:')
playerEmailAddress = TextField('Email Address:') playerEmailAddress = StringField('Email Address:')
playerDob = DateField('Date of Birth:', default=datetime.today, format='%Y-%m-%d') playerDob = DateField('Date of Birth:', default=datetime.today, format='%Y-%m-%d')
playerHkid = TextField('HKID Number:') playerHkid = StringField('HKID Number:')
playerNumber = TextField('Shirt Number:') playerNumber = StringField('Shirt Number:')
playerTelNumber = TextField('Player Contact Number:') playerTelNumber = StringField('Player Contact Number:')
submit = SubmitField('Submit') submit = SubmitField('Submit')
class addTeamForm(FlaskForm): class addTeamForm(FlaskForm):
clubName = SelectField("Club of team entry to create", coerce=str) clubName = SelectField("Club of team entry to create", coerce=str)
teamName = TextField("Team table to create (e.g. A, B, C, etc.)", validators=[InputRequired(), Length(max=1)]) teamName = StringField("Team table to create (e.g. A, B, C, etc.)", validators=[InputRequired(), Length(max=1)])
submit = SubmitField("Submit") submit = SubmitField("Submit")
class addClubForm(FlaskForm): class addClubForm(FlaskForm):
clubName = TextField("Name of the Hockey Club to add") clubName = StringField("Name of the Hockey Club to add")
submit = SubmitField("Submit") submit = SubmitField("Submit")
class playerDbCreateForm(FlaskForm): class playerDbCreateForm(FlaskForm):
@@ -54,7 +53,7 @@ class playerDbCreateForm(FlaskForm):
class searchForm(FlaskForm): class searchForm(FlaskForm):
seasonStart = datetime.strptime('2018-09-01', '%Y-%m-%d') seasonStart = datetime.strptime('2018-09-01', '%Y-%m-%d')
season = SelectField('Season data to search', choices=[('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')]) season = SelectField('Season data to search', choices=[('2021', '2021/22'), ('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')])
clubName = SelectField("Club to search", choices=[], coerce=str) clubName = SelectField("Club to search", choices=[], coerce=str)
teamName = SelectField("Select a Team", choices=[]) teamName = SelectField("Select a Team", choices=[])
startDate = DateField('DatePicker', format='%Y-%m-%d', default=seasonStart) startDate = DateField('DatePicker', format='%Y-%m-%d', default=seasonStart)
@@ -62,29 +61,22 @@ class searchForm(FlaskForm):
submitButton = SubmitField("Submit") submitButton = SubmitField("Submit")
class playerRecordsForm(FlaskForm): class playerRecordsForm(FlaskForm):
season = SelectField('Season data to search', choices=[('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')]) season = SelectField('Season data to search', choices=[('2021', '2021/22'), ('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')])
clubName = SelectField("Club to search", choices=[], coerce=str) clubName = SelectField("Club to search", choices=[], coerce=str)
teamName = SelectField("Select a Team", choices=[]) teamName = SelectField("Select a Team", choices=[])
submitButton = SubmitField("Submit") submitButton = SubmitField("Submit")
class teamRecordsForm(FlaskForm): class teamRecordsForm(FlaskForm):
season = SelectField('Season data to search', choices=[('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')]) season = SelectField('Season data to search', choices=[('2021', '2021/22'), ('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')])
clubName = SelectField("Club to search", choices=[], coerce=str) clubName = SelectField("Club to search", choices=[], coerce=str)
teamName = SelectField("Select a Team", choices=[]) teamName = SelectField("Select a Team", choices=[])
submitButton = SubmitField("Submit") submitButton = SubmitField("Submit")
class clubPlayingRecordsForm(FlaskForm): class clubPlayingRecordsForm(FlaskForm):
season = SelectField('Season data to search', choices=[('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')]) season = SelectField('Season data to search', choices=[('2021', '2021/22'), ('2020', '2020/21'), ('2019', '2019/20'), ('2018', '2018/19'), ('2017', '2017/18'), ('2016', '2016/17'), ('2015', '2015/16'), ('2014', '2014/15'), ('2013', '2013/14')])
clubName = SelectField("Club to search", choices=[], coerce=str) clubName = SelectField("Club to search", choices=[], coerce=str)
submitButton = SubmitField("Submit") submitButton = SubmitField("Submit")
class motmForm(FlaskForm):
startDate = DateField('DatePicker', format='%d-%m-%Y')
endDate = DateField('DatePicker', format='%d-%m-%Y')
class motmAdminForm(FlaskForm):
startDate = DateField('DatePicker', format='%d-%m-%Y')
endDate = DateField('DatePicker', format='%d-%m-%Y')
class squadListForm(FlaskForm): class squadListForm(FlaskForm):
teamName = SelectField("HKFC team to display") teamName = SelectField("HKFC team to display")
@@ -99,28 +91,4 @@ class adminSettingsForm(FlaskForm):
saveButton = SubmitField('Save Settings') saveButton = SubmitField('Save Settings')
activateButton = SubmitField('Activate MotM Vote') activateButton = SubmitField('Activate MotM Vote')
class goalsAssistsForm(FlaskForm):
fixtureNumber = TextField('Fixture Number')
match = SelectField('Fixture')
homeTeam = TextField('Home Team')
awayTeam = TextField('Away Team')
playerNumber = TextField('Player Number')
playerName = TextField('Player Name')
assists = SelectField('Assists:', choices=[(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4')])
goals = SelectField('Goals:', choices=[(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4')])
submit = SubmitField('Submit')
# def __init__(self, *args, **kwargs):
# super(goalsAssistsForm, self).__init__(*args, **kwargs)
# read_only(self.homeTeam)
# read_only(self.awayTeam)
class adminSettingsForm2(FlaskForm):
nextMatch = SelectField('Fixture', choices=[], default=mySettings('match'))
nextOppoClub = TextField('Next Opposition Club:', default=mySettings('club'))
nextOppoTeam = TextField("Next Opposition Team:")
currMotM = SelectField('Current Man of the Match:', choices=[], default=mySettings('motm'))
currDotD = SelectField('Current Dick of the Day:', choices=[], default=mySettings('dotd'))
saveButton = SubmitField('Save Settings')
activateButton = SubmitField('Activate MotM Vote')
+2 -15
View File
@@ -11,7 +11,7 @@ from flask import Flask, flash, render_template, request, redirect, url_for
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from flask_bootstrap import Bootstrap from flask_bootstrap import Bootstrap
from wtforms import StringField, PasswordField, BooleanField from wtforms import StringField, PasswordField, BooleanField
from wtforms.fields.html5 import DateField from wtforms import DateField
from wtforms.validators import InputRequired, Email, Length from wtforms.validators import InputRequired, Email, Length
from forms import LoginForm, RegisterForm from forms import LoginForm, RegisterForm
from dbWrite import sql_write, sql_write_static, sql_read, sql_read_static from dbWrite import sql_write, sql_write_static, sql_read, sql_read_static
@@ -20,19 +20,6 @@ from routes import *
app.register_blueprint(routes) app.register_blueprint(routes)
@app.route('/hkfc-d/vote-chart', methods=['GET', 'POST'])
def hkfc_d_vote_chart():
form = LoginForm()
print('Here we are')
if form.validate_on_submit():
sql = "SELECT username FROM hockeyUsers WHERE (username= '" + form.username.data + "')"
print(sql)
rows = sql_read(sql)
print(rows)
return redirect(url_for('/hkfc-d/voting'))
# return '<h1>Something went wrong there</h1>'
return render_template('hkfc-d/login-vote.html', form=form)
@app.route('/login', methods=['GET', 'POST']) @app.route('/login', methods=['GET', 'POST'])
def login(): def login():
@@ -44,7 +31,7 @@ def login():
rows = sql_write(sql) rows = sql_write(sql)
print(rows) print(rows)
print(rows[0]) print(rows[0])
return redirect(url_for('/hkfc-d/voting')) return redirect(url_for('dashboard'))
else: else:
return 'Something went wrong' return 'Something went wrong'
# return '<h1>Something went wrong there</h1>' # return '<h1>Something went wrong there</h1>'
+80
View File
@@ -0,0 +1,80 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual environments
venv/
env/
ENV/
env.bak/
venv.bak/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Database files
*.db
*.sqlite
*.sqlite3
# Logs
*.log
logs/
# Temporary files
*.tmp
*.temp
# Git
.git/
.gitignore
# Documentation
*.md
docs/
# Scripts and configs not needed in container
activate_motm.bat
activate_motm.sh
run_motm.bat
run_motm.sh
setup_venv_windows.bat
setup_venv.ps1
setup_venv.py
deploy.py
test_app.py
# Development files
app.yaml
database_config.ini
POSTGRESQL_SETUP.md
SETUP_GUIDE.md
VIRTUAL_ENV_GUIDE.md
README.md
+150
View File
@@ -0,0 +1,150 @@
# Virtual Environment
venv/
env/
ENV/
.venv/
.env/
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
Pipfile.lock
# PEP 582
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Application specific
*.db
*.sqlite
config.py
.env.local
.env.production
+3
View File
@@ -0,0 +1,3 @@
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: gunicorn in /home/jonny/.local/lib/python3.13/site-packages (21.2.0)
Requirement already satisfied: packaging in /usr/lib/python3.13/site-packages (from gunicorn) (24.2)
+261
View File
@@ -0,0 +1,261 @@
# Comments Management Feature
## Overview
Added a comprehensive comments management interface to the MOTM application, providing admin users with the ability to view, edit, delete, and manage match comments, similar to the existing MOTM management functionality.
## Features Implemented
### 1. View All Comments
- Display all comments in a card-based interface
- Show comment ID, match date, and full comment text
- Display statistics: total comments, unique match dates, and average comments per match
### 2. Edit Comments
- Inline edit functionality for each comment
- Click "Edit" to show an editable textarea
- Save or cancel changes without page reload
- Comments are properly escaped to handle special characters
### 3. Delete Comments
- **Individual Comment Deletion**: Delete specific comments one at a time
- **Match Date Deletion**: Delete all comments for a specific match date
- **Bulk Deletion**: Delete all comments in the database at once
- All deletions require confirmation dialogs for safety
### 4. Column Management
- View all columns in the `_motmcomments` table
- Drop unwanted columns (similar to MOTM management)
- Protected columns (`matchDate`, `comment`, `rowid`, `id`) cannot be dropped
### 5. Statistics Dashboard
- Total comment count
- Number of unique match dates with comments
- Average comments per match
## Files Modified/Created
### New Files
1. **`templates/comments_management.html`**
- Bootstrap 5-based responsive interface
- Card-based comment display
- Inline editing functionality
- Bulk operation controls
- Statistics dashboard
### Modified Files
1. **`main.py`**
- Added `/admin/comments/manage` route (lines 1385-1481)
- Handles GET and POST requests for all comment operations
- Actions supported:
- `delete_comment`: Delete individual comment
- `edit_comment`: Update comment text
- `delete_match_comments`: Delete all comments for a match
- `delete_all_comments`: Delete all comments
- `drop_column`: Drop a column from the table
2. **`templates/admin_dashboard.html`**
- Added "Comments Management" button (lines 68-76)
- Styled with yellow/warning theme (`btn-outline-warning`)
- Includes comments icon
## Usage
### Accessing Comments Management
1. Log in to the admin dashboard
2. Click the "Comments Management" button in the Quick Actions section
3. The page will display all match comments with management controls
### Managing Comments
#### Edit a Comment
1. Click the "Edit" button on any comment card
2. Modify the text in the textarea
3. Click "Save" to update or "Cancel" to discard changes
#### Delete a Comment
1. Click the "Delete" button on any comment card
2. Confirm the deletion in the dialog
3. Comment will be removed from the database
#### Delete Match Comments
1. In the "Bulk Operations" section, select a match date
2. Click "Delete Match Comments"
3. Confirm the deletion
4. All comments for that match will be removed
#### Delete All Comments
1. In the "Bulk Operations" section, click "Delete All Comments"
2. Confirm the deletion (requires explicit confirmation)
3. All comments in the database will be removed
#### Drop a Column
1. In the "Column Management" section, select a column
2. Click "Drop Column"
3. Confirm the action
4. The column will be removed from the table schema
## Database Compatibility
The implementation handles different database types:
### SQLite
- Uses `rowid` as the unique identifier for comments
- Fallback to `id` column if available
### PostgreSQL/MySQL
- Uses `information_schema` to query column names
- Uses `id` or `rowid` for unique identification
- Fallback logic ensures compatibility
## Security Features
1. **Authentication Required**: All routes require `@basic_auth.required`
2. **Confirmation Dialogs**: All destructive operations require user confirmation
3. **Protected Columns**: Core columns (`matchDate`, `comment`) are protected from dropping
4. **SQL Injection Prevention**: Uses parameterized queries with SQLAlchemy `text()`
5. **Special Character Handling**: Properly escapes single quotes in comments
## Technical Implementation
### Backend Route Pattern
```python
@app.route('/admin/comments/manage', methods=['GET', 'POST'])
@basic_auth.required
def comments_management():
# Handle POST actions (edit, delete, drop)
# Query database for comments and metadata
# Render template with data
```
### Key Query Examples
**Get all comments:**
```sql
SELECT rowid, matchDate, comment
FROM _motmcomments
ORDER BY matchDate DESC, rowid DESC
```
**Delete a comment:**
```sql
DELETE FROM _motmcomments
WHERE rowid = :comment_id
```
**Update a comment:**
```sql
UPDATE _motmcomments
SET comment = :comment
WHERE rowid = :comment_id
```
**Drop a column:**
```sql
ALTER TABLE _motmcomments
DROP COLUMN {column_name}
```
## UI/UX Features
### Responsive Design
- Bootstrap 5 grid system
- Mobile-friendly card layout
- Touch-friendly buttons and controls
### Visual Indicators
- Color-coded badges for match dates
- Card-based layout with left border accent
- FontAwesome icons for actions
- Success/error flash messages
### Interactive Elements
- Inline editing with JavaScript
- Confirmation dialogs for destructive actions
- Collapsible edit forms
- Real-time form validation
## Future Enhancements
Potential improvements for future versions:
1. **Search and Filter**
- Search comments by text
- Filter by match date range
- Sort by date, length, or other criteria
2. **Batch Operations**
- Select multiple comments for deletion
- Bulk edit with find/replace
3. **Comment Moderation**
- Flag inappropriate comments
- Approve/reject comments before display
4. **Export Functionality**
- Export comments to CSV/JSON
- Generate match reports with comments
5. **Pagination**
- Handle large numbers of comments efficiently
- Load more/infinite scroll
## Testing
To test the comments management feature:
1. **Setup**:
```bash
cd /home/jonny/Projects/gcp-hockey-results/motm_app
python main.py # or your preferred method
```
2. **Access**: Navigate to `/admin` and click "Comments Management"
3. **Test Cases**:
- View comments (should display all comments)
- Edit a comment (verify text updates correctly)
- Delete a comment (verify it's removed)
- Delete match comments (verify all for that date are removed)
- Try dropping a non-essential column (if any exist)
- Check statistics are calculated correctly
## Troubleshooting
### "No comments found"
- Ensure users have submitted comments during voting
- Check the `_motmcomments` table has data
### "Error deleting comment"
- Verify database permissions
- Check `rowid` or `id` column exists
- Review error message for specifics
### "Error dropping column"
- Ensure column name is correct
- Verify database supports `ALTER TABLE DROP COLUMN`
- SQLite has limitations on dropping columns
## Related Files
- `/admin/motm/manage` - Similar management interface for MOTM data
- `templates/motm_management.html` - Reference implementation
- `database.py` - Database models and configuration
- `db_setup.py` - Database initialization
## Comparison with MOTM Management
| Feature | MOTM Management | Comments Management |
|---------|----------------|---------------------|
| View Data | ✓ Table format | ✓ Card format |
| Edit Items | ✓ Reset counts | ✓ Edit text |
| Delete Items | ✓ Reset fixtures | ✓ Delete comments |
| Drop Columns | ✓ Yes | ✓ Yes |
| Bulk Operations | ✓ Reset all | ✓ Delete all |
| Statistics | ✓ Totals | ✓ Counts & averages |
## Conclusion
The Comments Management feature provides a complete administrative interface for managing match comments, matching the functionality pattern established by the MOTM Management system while being tailored to the specific needs of comment data.
+190
View File
@@ -0,0 +1,190 @@
# MOTM Application - Container Deployment
This document provides instructions for deploying the MOTM (Man of the Match) application using Docker containers.
## Quick Start
### Using Docker Compose (Recommended)
1. **Clone the repository and navigate to the project directory**
```bash
cd motm_app
```
2. **Start the application with PostgreSQL**
```bash
docker-compose up -d
```
3. **Access the application**
- Main page: http://localhost:5000
- Admin dashboard: http://localhost:5000/admin (username: `admin`, password: `letmein`)
### Using Docker Build
1. **Build the container**
```bash
docker build -f Containerfile -t motm-app .
```
2. **Run with external PostgreSQL**
```bash
docker run -d \
--name motm-app \
-p 5000:5000 \
-e DATABASE_TYPE=postgresql \
-e DB_HOST=your-postgres-host \
-e DB_PORT=5432 \
-e DB_NAME=motm_db \
-e DB_USER=motm_user \
-e DB_PASSWORD=motm_password \
motm-app
```
## Configuration
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `DATABASE_TYPE` | `postgresql` | Database type (postgresql/sqlite) |
| `DB_HOST` | `postgres` | Database host (use `postgres` for docker-compose) |
| `DB_PORT` | `5432` | Database port |
| `DB_NAME` | `motm_db` | Database name |
| `DB_USER` | `motm_user` | Database username |
| `DB_PASSWORD` | `motm_password` | Database password |
| `FLASK_ENV` | `production` | Flask environment |
| `FLASK_RUN_HOST` | `0.0.0.0` | Flask host |
| `FLASK_RUN_PORT` | `5000` | Flask port |
| `SECRET_KEY` | `your-secret-key-change-this-in-production` | Flask secret key |
### Production Security
**Important**: Before deploying to production, change the following:
1. **Database credentials** in `docker-compose.yml`
2. **Secret key** in environment variables
3. **Admin password** (use the admin profile page after first login)
## Container Features
### Multi-stage Build
- **Builder stage**: Installs dependencies and builds Python packages
- **Runtime stage**: Minimal image with only runtime dependencies
### Security
- Runs as non-root user (`appuser`)
- Minimal attack surface with slim base image
- Health checks for container monitoring
### Database Integration
- Automatic database connection waiting
- Database initialization support
- PostgreSQL optimized configuration
## Monitoring
### Health Checks
- Application health check: `curl -f http://localhost:5000/`
- Database health check: `pg_isready`
### Logs
```bash
# View application logs
docker-compose logs motm-app
# View database logs
docker-compose logs postgres
# Follow logs in real-time
docker-compose logs -f motm-app
```
## Maintenance
### Backup Database
```bash
# Create backup
docker exec motm-postgres pg_dump -U motm_user motm_db > backup.sql
# Restore backup
docker exec -i motm-postgres psql -U motm_user motm_db < backup.sql
```
### Update Application
```bash
# Pull latest changes
git pull
# Rebuild and restart
docker-compose down
docker-compose up -d --build
```
### Reset Database
```bash
# Stop services
docker-compose down
# Remove database volume
docker volume rm motm_app_postgres_data
# Start fresh
docker-compose up -d
```
## Troubleshooting
### Common Issues
1. **Database connection errors**
- Check if PostgreSQL container is running: `docker-compose ps`
- Verify database credentials in environment variables
- Check database logs: `docker-compose logs postgres`
2. **Application won't start**
- Check application logs: `docker-compose logs motm-app`
- Verify all environment variables are set correctly
- Ensure database is healthy before application starts
3. **Port conflicts**
- Change port mapping in `docker-compose.yml`
- Example: `"8080:5000"` to use port 8080 instead of 5000
### Debug Mode
```bash
# Run container in interactive mode for debugging
docker run -it --rm \
-p 5000:5000 \
-e DATABASE_TYPE=postgresql \
-e DB_HOST=your-postgres-host \
-e DB_PORT=5432 \
-e DB_NAME=motm_db \
-e DB_USER=motm_user \
-e DB_PASSWORD=motm_password \
motm-app /bin/bash
```
## File Structure
```
motm_app/
├── Containerfile # Docker container definition
├── docker-compose.yml # Multi-service orchestration
├── .dockerignore # Files to exclude from build
├── init.sql # Database initialization script
├── requirements.txt # Python dependencies
├── main.py # Main application file
├── static/ # Static assets (CSS, JS, images)
├── templates/ # HTML templates
└── data/ # Persistent data directory
```
## Support
For issues or questions about container deployment, please check:
1. Application logs: `docker-compose logs motm-app`
2. Database logs: `docker-compose logs postgres`
3. Container status: `docker-compose ps`
+96
View File
@@ -0,0 +1,96 @@
# Containerfile for MOTM (Man of the Match) Application
# Flask-based voting system for hockey matches
# Stage 1: Build stage
FROM python:3.11-slim as builder
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
# Install system dependencies for building Python packages
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
default-libmysqlclient-dev \
pkg-config \
&& rm -rf /var/lib/apt/lists/*
# Create and activate virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
# Copy requirements and install Python dependencies
COPY requirements.txt ./
RUN pip install --upgrade pip && \
pip install -r requirements.txt
# Stage 2: Runtime stage
FROM python:3.11-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PATH="/opt/venv/bin:$PATH" \
DATABASE_TYPE=postgresql \
FLASK_ENV=production \
FLASK_APP=main.py \
FLASK_RUN_HOST=0.0.0.0 \
FLASK_RUN_PORT=5000
# Install runtime dependencies
RUN apt-get update && apt-get install -y \
libpq5 \
default-mysql-client \
curl \
&& rm -rf /var/lib/apt/lists/*
# Copy virtual environment from builder stage
COPY --from=builder /opt/venv /opt/venv
# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
# Create application directory
WORKDIR /app
# Copy application code
COPY --chown=appuser:appuser . .
# Create directories for data and logs
RUN mkdir -p /app/data /app/logs && \
chown -R appuser:appuser /app/data /app/logs
# Create a startup script for better initialization
RUN echo '#!/bin/bash\n\
# Wait for database to be ready\n\
echo "Waiting for database connection..."\n\
while ! python -c "import psycopg2; psycopg2.connect(host=\"$DB_HOST\", port=\"$DB_PORT\", user=\"$DB_USER\", password=\"$DB_PASSWORD\", dbname=\"$DB_NAME\")" 2>/dev/null; do\n\
echo "Database not ready, waiting..."\n\
sleep 2\n\
done\n\
echo "Database connection established!"\n\
\n\
# Initialize database if needed\n\
python -c "from db_setup import db_config_manager; db_config_manager.load_config(); db_config_manager._update_environment_variables()"\n\
\n\
# Start the application with gunicorn\n\
echo "Starting application with gunicorn..."\n\
exec gunicorn --config gunicorn.conf.py main:app' > /app/start.sh && \
chmod +x /app/start.sh && \
chown appuser:appuser /app/start.sh
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 5000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:5000/ || exit 1
# Default command
CMD ["/app/start.sh"]
+209
View File
@@ -0,0 +1,209 @@
# Debugging URL Suffix Not Saving Issue
## Problem
The app is not saving the URL suffix to the `admin_settings` table.
## Debug Logging Added
I've added comprehensive debug logging to help diagnose the issue. The logs will show:
1. **When the form is submitted:**
- Which button was clicked (Save vs Activate)
- What form data was received
2. **When saving settings:**
- The generated URL suffix
- Whether the UPDATE query executed
- The result of the UPDATE query
- Verification of what's actually in the database
3. **When activating voting:**
- What URL suffix is retrieved from the database
- Whether a new suffix needs to be generated
- The final suffix being used
## How to Debug
### Step 1: Deploy the Updated Code
Deploy the updated code with debug logging to production:
```bash
# Build new image
docker build -t your-registry/motm-app:latest .
# Push to registry
docker push your-registry/motm-app:latest
# Deploy to Kubernetes
helm upgrade motm-app ./helm-chart/motm-app --namespace motm-app
```
### Step 2: Test the MOTM Admin Page
1. Go to https://motm.ervine.cloud/admin/motm
2. Fill in the form:
- Match date
- Opposition team
- Current MOTM (optional)
- Current DotD (optional)
- Voting deadline (optional)
3. Click **"Save Settings"** button
4. Check the logs
### Step 3: Check the Logs
```bash
# Get the pod name
kubectl get pods -n motm-app -l app.kubernetes.io/name=motm-app
# Watch the logs in real-time
kubectl logs -n motm-app -f <POD_NAME>
```
Or check recent logs:
```bash
kubectl logs -n motm-app -l app.kubernetes.io/name=motm-app --tail=100 | grep DEBUG
```
### Step 4: Analyze the Debug Output
Look for these debug messages:
#### When clicking "Save Settings":
```
DEBUG: POST request received
DEBUG: form.saveButton.data = True
DEBUG: form.activateButton.data = False
DEBUG: Save button clicked
DEBUG: Form data - team: [team name], date: [date]
DEBUG: Generated URL suffix: [suffix]
DEBUG: About to execute UPDATE query
DEBUG: UPDATE query result: True
DEBUG: Verification - URL suffix in DB: [suffix]
```
#### When clicking "Activate MotM Vote":
```
DEBUG: POST request received
DEBUG: form.saveButton.data = False
DEBUG: form.activateButton.data = True
DEBUG: Activate button clicked
DEBUG: Form data - team: [team name], date: [date]
DEBUG: Getting URL suffix from database
DEBUG: Query result: [result]
DEBUG: Using existing suffix: [suffix]
DEBUG: Final suffix: [suffix]
```
## Common Issues and Solutions
### Issue 1: Button Click Not Detected
**Symptoms:**
```
DEBUG: POST request received
DEBUG: form.saveButton.data = False
DEBUG: form.activateButton.data = False
DEBUG: Something went wrong - check with Smithers
```
**Cause:** The form button data isn't being submitted correctly.
**Solution:** Check the HTML form to ensure the buttons have the correct `name` attribute.
### Issue 2: UPDATE Query Fails
**Symptoms:**
```
DEBUG: UPDATE query result: False
```
**Cause:** The UPDATE query failed silently.
**Solution:** Check for SQL errors in the logs. The `sql_write_static` function prints errors.
### Issue 3: UPDATE Succeeds but Value Not Saved
**Symptoms:**
```
DEBUG: UPDATE query result: True
DEBUG: Verification - URL suffix in DB: None
```
**Cause:** The UPDATE query executed but didn't actually update the row.
**Solution:**
- Check if the WHERE clause is matching a row
- Verify the table structure
- Check if there's a transaction rollback happening
### Issue 4: Query Returns Empty Result
**Symptoms:**
```
DEBUG: Query result: []
```
**Cause:** No row matches the WHERE clause `userid = 'admin'`.
**Solution:**
- Check if the `userid` column has the value 'admin'
- Run the diagnostic script: `check_production_db.py`
## Manual Verification
After clicking "Save Settings", verify the URL suffix was saved:
```bash
kubectl exec -it <POD_NAME> -n motm-app -- python -c "
from db_config import sql_read_static
from sqlalchemy import text
result = sql_read_static(text('SELECT motm_url_suffix FROM admin_settings WHERE userid = \\'admin\\''))
print('URL suffix in database:', result[0]['motm_url_suffix'] if result else 'No data')
"
```
## Expected Behavior
### When clicking "Save Settings":
1. Form data is received ✅
2. URL suffix is generated ✅
3. UPDATE query executes ✅
4. URL suffix is saved to database ✅
5. Flash message shows the URL ✅
### When clicking "Activate MotM Vote":
1. Form data is received ✅
2. URL suffix is retrieved from database ✅
3. If missing, a new one is generated and saved ✅
4. Flash message shows the URL ✅
## Next Steps
1. **Deploy the updated code** with debug logging
2. **Test the MOTM admin page** and click "Save Settings"
3. **Check the logs** for debug messages
4. **Share the debug output** if the issue persists
5. **Verify the database** using the manual verification command
## Removing Debug Logging
Once the issue is resolved, you can remove the debug logging by searching for lines containing:
```python
print(f"DEBUG:
```
And removing them, or I can create a cleaned-up version for you.
## Support
If you continue to have issues after checking the debug logs:
1. Save the complete debug output
2. Check the application logs for any errors
3. Verify the database connection is working
4. Check if there are any database permission issues
5. Share the debug output and any error messages
+385
View File
@@ -0,0 +1,385 @@
# Helm Secrets and Gunicorn Updates
## Summary of Changes
This document describes the improvements made to support external Kubernetes secrets and production-ready gunicorn deployment.
## 1. External Secret Support
### Overview
The Helm chart now supports referencing an external Kubernetes secret instead of creating a managed one. This allows you to:
- Use existing secrets from secret management tools (e.g., External Secrets Operator, Sealed Secrets)
- Share secrets across multiple deployments
- Follow security best practices by not storing secrets in Helm values
### Configuration
#### values.yaml
```yaml
secrets:
# Use an existing external secret instead of creating one
useExternalSecret: false # Set to true to use external secret
externalSecretName: "" # Name of your existing secret
# Secret key names (consistent across both managed and external secrets)
dbPasswordKey: "db-password"
s3AccessKeyKey: "s3-access-key"
s3SecretKeyKey: "s3-secret-key"
# Values for managed secret (only used when useExternalSecret is false)
dbPassword: ""
s3AccessKey: ""
s3SecretKey: ""
```
#### Using an External Secret
**Example 1: Basic external secret**
```yaml
# values.yaml or values-production.yaml
secrets:
useExternalSecret: true
externalSecretName: "motm-app-credentials"
# The rest of the secret values are ignored when useExternalSecret is true
```
**Example 2: Your external secret should have these keys:**
```yaml
apiVersion: v1
kind: Secret
metadata:
name: motm-app-credentials
type: Opaque
data:
db-password: <base64-encoded-password>
s3-access-key: <base64-encoded-access-key>
s3-secret-key: <base64-encoded-secret-key>
```
**Example 3: Using with External Secrets Operator**
```yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: motm-app-credentials
spec:
secretStoreRef:
name: vault-backend
kind: SecretStore
target:
name: motm-app-credentials
data:
- secretKey: db-password
remoteRef:
key: motm/database
property: password
- secretKey: s3-access-key
remoteRef:
key: motm/s3
property: access_key
- secretKey: s3-secret-key
remoteRef:
key: motm/s3
property: secret_key
```
### Files Modified
- `helm-chart/motm-app/values.yaml` - Added external secret configuration
- `helm-chart/motm-app/templates/secret.yaml` - Made conditional based on `useExternalSecret`
- `helm-chart/motm-app/templates/deployment.yaml` - Updated to reference external or managed secret
## 2. S3 Environment Variable Support
### Overview
The S3 configuration now prioritizes environment variables over the JSON configuration file, allowing seamless deployment in Kubernetes without managing config files.
### Behavior
1. **In Kubernetes** (when `S3_ENABLED` or `S3_ACCESS_KEY_ID` env vars are set): Reads from environment variables
2. **Locally** (no env vars): Falls back to `s3_config.json` file
### Environment Variables
The following environment variables are now supported:
- `S3_ENABLED` - Enable/disable S3 (true/false)
- `S3_ACCESS_KEY_ID` - S3/MinIO access key (from secret)
- `S3_SECRET_ACCESS_KEY` - S3/MinIO secret key (from secret)
- `S3_STORAGE_PROVIDER` - Storage provider (`aws` or `minio`, default: aws)
- `S3_REGION` - AWS region (default: us-east-1)
- `S3_BUCKET` - S3/MinIO bucket name
- `S3_BUCKET_PREFIX` - Key prefix/folder (default: assets/)
- `S3_ENDPOINT` - Custom endpoint for MinIO or S3-compatible storage
- `S3_USE_SIGNED_URLS` - Use signed URLs (default: true)
- `S3_SIGNED_URL_EXPIRY` - Signed URL expiry in seconds (default: 3600)
- `S3_FALLBACK_TO_STATIC` - Fallback to static files on error (default: true)
- `S3_USE_SSL` - Use SSL/TLS for connections (default: true)
### Files Modified
- `s3_config.py` - Added `_load_from_env()` method and prioritized env vars
- `helm-chart/motm-app/templates/deployment.yaml` - Added `S3_ENABLED` environment variable
## 3. Gunicorn Production Server
### Overview
The container now uses gunicorn instead of Flask's development server for production-ready deployment.
### Benefits
- **Production-ready**: Gunicorn is a WSGI HTTP server designed for production
- **Better performance**: Multi-worker support for handling concurrent requests
- **Stability**: Auto-restart workers after handling requests to prevent memory leaks
- **Proper process management**: Better signal handling and graceful shutdowns
### Configuration
The gunicorn configuration is defined in `gunicorn.conf.py`:
- **Workers**: `(CPU cores * 2) + 1` for optimal performance
- **Timeout**: 30 seconds
- **Max requests**: 1000 per worker (with jitter) to prevent memory leaks
- **Logging**: Access and error logs to stdout/stderr
- **Preload**: App is preloaded for better performance
### Files Modified
- `Containerfile` - Updated startup script to use `gunicorn --config gunicorn.conf.py main:app`
### Note on main.py
The `main.py` file still contains:
```python
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
```
This is intentional and allows:
- **Local development**: Run with `python main.py` for development
- **Production**: Container uses gunicorn, which imports `app` from `main.py` directly
## S3/MinIO Configuration Examples
### AWS S3 Configuration
```yaml
# values-production.yaml
s3:
enabled: true
storageProvider: "aws"
endpoint: "" # Leave empty for AWS
region: "us-east-1"
bucket: "motm-assets-prod"
bucketPrefix: "assets/"
useSignedUrls: true
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: true
```
### MinIO Configuration (Self-Hosted)
```yaml
# values.yaml or values-production.yaml
s3:
enabled: true
storageProvider: "minio"
endpoint: "https://minio.yourdomain.com"
region: "us-east-1" # Required for boto3, but MinIO ignores it
bucket: "motm-assets"
bucketPrefix: "assets/"
useSignedUrls: false # Use public URLs if bucket is public
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: true
```
### MinIO Configuration (In-Cluster)
```yaml
# values-development.yaml
s3:
enabled: true
storageProvider: "minio"
endpoint: "http://minio.default.svc.cluster.local:9000"
region: "us-east-1"
bucket: "motm-assets-dev"
bucketPrefix: "dev/"
useSignedUrls: false
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: false # HTTP for internal service
```
### Digital Ocean Spaces / S3-Compatible Storage
```yaml
s3:
enabled: true
storageProvider: "minio" # Use minio provider for S3-compatible services
endpoint: "https://nyc3.digitaloceanspaces.com"
region: "nyc3"
bucket: "motm-assets"
bucketPrefix: "production/"
useSignedUrls: true
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: true
```
## Deployment Examples
### Example 1: Using Managed Secret
```bash
helm upgrade --install motm-app ./helm-chart/motm-app \
-f values-production.yaml \
--set secrets.useExternalSecret=false \
--set secrets.dbPassword="your-db-password" \
--set secrets.s3AccessKey="your-s3-key" \
--set secrets.s3SecretKey="your-s3-secret"
```
### Example 2: Using External Secret
```bash
# First create your external secret
kubectl create secret generic motm-app-credentials \
--from-literal=db-password="your-db-password" \
--from-literal=s3-access-key="your-s3-key" \
--from-literal=s3-secret-key="your-s3-secret"
# Then deploy with external secret reference
helm upgrade --install motm-app ./helm-chart/motm-app \
-f values-production.yaml \
--set secrets.useExternalSecret=true \
--set secrets.externalSecretName="motm-app-credentials"
```
### Example 3: Custom Secret Key Names
If your external secret uses different key names:
```bash
helm upgrade --install motm-app ./helm-chart/motm-app \
-f values-production.yaml \
--set secrets.useExternalSecret=true \
--set secrets.externalSecretName="my-secret" \
--set secrets.dbPasswordKey="database-password" \
--set secrets.s3AccessKeyKey="aws-access-key" \
--set secrets.s3SecretKeyKey="aws-secret-key"
```
## Backward Compatibility
All changes maintain backward compatibility:
1. **Database Configuration**:
- Still reads from `database_config.ini` for local deployments
- Environment variables take precedence in containers
2. **S3 Configuration**:
- Still reads from `s3_config.json` when no env vars are set
- Admin interface still allows configuration via web UI
3. **Helm Chart**:
- Default behavior (`useExternalSecret: false`) creates managed secret
- Existing deployments continue to work without changes
## Security Best Practices
1. **Never commit secrets** to version control
2. **Use external secrets** for production deployments
3. **Rotate credentials** regularly
4. **Use RBAC** to restrict access to secrets in Kubernetes
5. **Enable audit logging** for secret access
6. **Use secret management tools** (Vault, AWS Secrets Manager, etc.) with External Secrets Operator
## Testing
### Test Database Connection
```bash
kubectl exec -it deployment/motm-app -- env | grep DB_
# Should show DB_HOST, DB_PORT, DB_NAME, DB_USER
# DB_PASSWORD won't show (secret)
```
### Test S3 Configuration
```bash
kubectl exec -it deployment/motm-app -- env | grep S3_
# Should show S3_ENABLED, S3_REGION, S3_BUCKET, etc.
```
### Test Gunicorn
```bash
kubectl logs -f deployment/motm-app
# Should show: "Starting application with gunicorn..."
# And gunicorn worker logs
```
### Verify Secret is Used
```bash
kubectl get pods -l app=motm-app -o jsonpath='{.items[0].spec.containers[0].env}' | jq
# Check that secretKeyRef points to your external secret
```
## Troubleshooting
### Secret Not Found
```
Error: secret "motm-app-credentials" not found
```
**Solution**: Ensure the external secret exists before deploying:
```bash
kubectl get secret motm-app-credentials
```
### Wrong Secret Keys
```
Error: couldn't find key db-password in Secret
```
**Solution**: Verify your secret has the correct keys:
```bash
kubectl get secret motm-app-credentials -o jsonpath='{.data}' | jq 'keys'
```
### S3 Not Using Environment Variables
**Symptom**: S3 still reading from s3_config.json
**Solution**: Ensure `S3_ENABLED=true` is set in the deployment environment variables
### Gunicorn Not Starting
**Symptom**: Container keeps restarting
**Solution**: Check logs for import errors:
```bash
kubectl logs deployment/motm-app
```
## Migration Guide
### From Managed to External Secret
1. **Extract current secrets**:
```bash
kubectl get secret motm-app-secrets -o yaml > current-secret.yaml
```
2. **Create external secret** with same data but new name:
```bash
kubectl create secret generic motm-app-credentials \
--from-literal=db-password="$(kubectl get secret motm-app-secrets -o jsonpath='{.data.db-password}' | base64 -d)" \
--from-literal=s3-access-key="$(kubectl get secret motm-app-secrets -o jsonpath='{.data.s3-access-key}' | base64 -d)" \
--from-literal=s3-secret-key="$(kubectl get secret motm-app-secrets -o jsonpath='{.data.s3-secret-key}' | base64 -d)"
```
3. **Update Helm values**:
```yaml
secrets:
useExternalSecret: true
externalSecretName: "motm-app-credentials"
```
4. **Upgrade deployment**:
```bash
helm upgrade motm-app ./helm-chart/motm-app -f values-production.yaml
```
5. **Verify** and clean up old secret:
```bash
kubectl delete secret motm-app-secrets
```
## Summary
These updates provide:
- ✅ Flexible secret management (external or managed)
- ✅ Production-ready deployment with gunicorn
- ✅ Environment-based S3 configuration
- ✅ Backward compatibility with existing deployments
- ✅ Security best practices
- ✅ Easy migration path
+471
View File
@@ -0,0 +1,471 @@
# Implementation Summary
## Complete Overview of Recent Changes
This document summarizes all recent improvements to the MOTM application for production-ready Kubernetes deployment.
---
## 🎯 Changes Implemented
### 1. External Kubernetes Secret Support
### 2. S3/MinIO Full Configuration Support
### 3. Gunicorn Production Server
### 4. **Database-Backed S3 Configuration** ⭐ NEW
---
## 1. External Kubernetes Secret Support 🔐
### What Changed
- Helm chart now supports referencing external Kubernetes secrets
- Secrets can be managed by External Secrets Operator, Sealed Secrets, or manually
- Single secret contains DB password and S3 credentials
### Files Modified
- `helm-chart/motm-app/values.yaml`
- `helm-chart/motm-app/templates/secret.yaml`
- `helm-chart/motm-app/templates/deployment.yaml`
### Configuration
```yaml
secrets:
useExternalSecret: true
externalSecretName: "motm-credentials"
dbPasswordKey: "db-password"
s3AccessKeyKey: "s3-access-key"
s3SecretKeyKey: "s3-secret-key"
```
### Benefits
- ✅ Integration with secret management tools
- ✅ Centralized secret management
- ✅ No secrets in Helm values
- ✅ Kubernetes best practices
---
## 2. S3/MinIO Full Configuration Support 📦
### What Changed
- Complete MinIO support alongside AWS S3
- Helm values for all S3 configuration options
- Environment variables for all settings
### Files Modified
- `helm-chart/motm-app/values.yaml`
- `helm-chart/motm-app/templates/deployment.yaml`
- `helm-chart/motm-app/templates/configmap.yaml`
- `helm-chart/motm-app/values-production.yaml`
- `helm-chart/motm-app/values-development.yaml`
### Configuration Options
```yaml
s3:
enabled: true
storageProvider: "minio" # or "aws"
endpoint: "https://minio.example.com"
region: "us-east-1"
bucket: "motm-assets"
bucketPrefix: "assets/"
useSignedUrls: true
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: true
```
### Use Cases
- AWS S3 production deployments
- Self-hosted MinIO for on-premise
- Digital Ocean Spaces, Wasabi, etc.
- In-cluster MinIO for development
---
## 3. Gunicorn Production Server 🚀
### What Changed
- Container now uses Gunicorn instead of Flask development server
- Production-ready WSGI server with multi-worker support
- Proper signal handling and graceful shutdowns
### Files Modified
- `Containerfile`
### Configuration
- Auto-scales workers based on CPU cores: `(cores × 2) + 1`
- 30-second timeout
- 1000 requests per worker before restart (prevents memory leaks)
- Access and error logs to stdout/stderr
### Benefits
- ✅ Production-grade performance
- ✅ Better concurrency handling
- ✅ Auto-restart workers to prevent memory leaks
- ✅ Proper process management
---
## 4. Database-Backed S3 Configuration ⭐ NEW
### What Changed
**Three-tier configuration priority system:**
1. **Environment Variables** (Highest) - Kubernetes secrets
2. **Database Settings** (Medium) - Admin-configurable via web UI
3. **JSON File** (Lowest) - Local development
### Files Modified
- `database.py` - Added `S3Settings` model
- `s3_config.py` - Three-tier loading, database save/load
- `db_setup.py` - S3Settings initialization
- `templates/s3_config.html` - Security notice for credentials
### Architecture
#### S3Settings Database Table
```sql
CREATE TABLE s3_settings (
id INTEGER PRIMARY KEY,
userid VARCHAR(50) DEFAULT 'admin',
enabled BOOLEAN DEFAULT FALSE,
storage_provider VARCHAR(20) DEFAULT 'aws',
endpoint VARCHAR(255),
region VARCHAR(50) DEFAULT 'us-east-1',
bucket_name VARCHAR(255),
bucket_prefix VARCHAR(255) DEFAULT 'assets/',
use_signed_urls BOOLEAN DEFAULT TRUE,
signed_url_expiry INTEGER DEFAULT 3600,
fallback_to_static BOOLEAN DEFAULT TRUE,
use_ssl BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP,
updated_at TIMESTAMP
);
```
#### Configuration Loading Priority
```
1. Environment Variables (S3_ENABLED, S3_ACCESS_KEY_ID, etc.)
↓ (if not set)
2. Database (s3_settings table)
↓ (if not exists)
3. JSON File (s3_config.json)
↓ (if not exists)
4. Defaults (S3 disabled)
```
### Security Model
**🔒 Credentials are NEVER stored in database**
- **Production**: Credentials from environment variables (Kubernetes secrets)
- **Local Dev**: Credentials from JSON file
- **Database**: Only stores configuration (bucket, region, provider, etc.)
### Key Benefits
- ✅ **Zero-downtime configuration**: Change S3 settings via web UI without redeployment
- ✅ **Secure**: Credentials always from secure sources (secrets/env vars)
- ✅ **Flexible**: Different config per environment
- ✅ **Admin-friendly**: Web UI for configuration
- ✅ **Backward compatible**: Existing JSON file configs still work
### Admin Interface
Navigate to: **Admin Dashboard → S3 Configuration**
Features:
- Enable/disable S3 storage
- Select provider (AWS S3 or MinIO)
- Configure bucket, region, endpoint
- Test connection before saving
- Visual security notice about credentials
---
## Complete Deployment Examples
### Example 1: Production with External Secret + Database Config
**Step 1: Create External Secret**
```bash
kubectl create secret generic motm-credentials \
--from-literal=db-password="prod-db-password" \
--from-literal=s3-access-key="AKIAIOSFODNN7EXAMPLE" \
--from-literal=s3-secret-key="wJalrXUtnFEMI/K7MDENG/bPxRfiCY"
```
**Step 2: Deploy with Helm**
```bash
helm upgrade --install motm-app ./helm-chart/motm-app \
-f values-production.yaml \
--set secrets.useExternalSecret=true \
--set secrets.externalSecretName="motm-credentials"
```
**Step 3: Configure S3 via Web UI**
1. Navigate to S3 Configuration page
2. Enable S3, select provider (AWS/MinIO)
3. Enter bucket details
4. Test connection
5. Save to database
**Result:**
- ✅ Credentials from Kubernetes secret (secure)
- ✅ S3 config in database (admin-configurable)
- ✅ No redeployment needed for config changes
- ✅ Gunicorn serving requests
- ✅ Production-ready
---
### Example 2: Development with MinIO
**Step 1: Deploy MinIO to Cluster**
```bash
helm install minio bitnami/minio \
--set auth.rootUser=minioadmin \
--set auth.rootPassword=minioadmin \
--set defaultBuckets=motm-dev
```
**Step 2: Deploy App**
```bash
helm upgrade --install motm-app ./helm-chart/motm-app \
-f values-development.yaml
```
**Step 3: Configure MinIO via Web UI**
- Enable S3: ✓
- Provider: MinIO
- Endpoint: `http://minio.default.svc.cluster.local:9000`
- Bucket: `motm-dev`
- Access Key: `minioadmin` (from UI, saved to s3_config.json locally)
**Result:**
- ✅ Local MinIO for development
- ✅ S3 config in database
- ✅ Matches production architecture
- ✅ Fast iteration
---
### Example 3: Hybrid (Env Vars Override Database)
**Use Case:** Production with emergency override capability
**Normal Operation:**
- Database: Configuration managed by admins via web UI
- Secrets: Credentials from Kubernetes secrets
**Emergency Override:**
Set environment variable to force specific settings:
```yaml
env:
- name: S3_BUCKET
value: "emergency-backup-bucket"
```
Environment variables override database settings, allowing immediate changes without UI access.
---
## Migration Paths
### From File-Based to Database Config
**Current State:** Using `s3_config.json`
**Migration Steps:**
1. Deploy new version with database support
2. Open S3 Configuration page (current settings auto-populate from JSON)
3. Click "Save Configuration" → settings now in database
4. Remove `s3_config.json` (backup first)
5. Restart - settings load from database
**Rollback:** Keep `s3_config.json` as backup
---
### From Environment Variables to Database
**Current State:** All S3 config in environment variables
**Migration Steps:**
1. Keep credential env vars:
```yaml
env:
- name: S3_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: motm-credentials
key: s3-access-key
- name: S3_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: motm-credentials
key: s3-secret-key
```
2. Remove configuration env vars (bucket, region, etc.)
3. Configure via web UI → saves to database
4. Credentials from secrets, config from database
**Benefits:** Change config without redeployment
---
## Security Summary
### What's Secure
- ✅ DB passwords in Kubernetes secrets (never in ConfigMaps)
- ✅ S3 credentials in Kubernetes secrets (never in database)
- ✅ SSL/TLS for S3 connections
- ✅ Signed URLs for private S3 buckets
- ✅ Non-root container user
- ✅ Read-only root filesystem (option in Helm)
- ✅ No secrets in logs or version control
### Best Practices Followed
- Environment variables for secrets
- Database for configuration
- External secret management support
- Least privilege principle
- Defense in depth
---
## Testing Checklist
### Database Configuration
- [ ] S3 settings saved to database persist across restarts
- [ ] Web UI correctly displays current configuration
- [ ] Test connection button works for AWS S3
- [ ] Test connection button works for MinIO
- [ ] Credentials not saved to database (check DB directly)
- [ ] Configuration changes apply without restart
### Kubernetes Deployment
- [ ] External secret correctly referenced
- [ ] DB password loaded from secret
- [ ] S3 credentials loaded from secret
- [ ] Pod starts successfully with gunicorn
- [ ] Health checks pass
- [ ] Liveness and readiness probes work
### S3 Functionality
- [ ] Images load from S3/MinIO
- [ ] Fallback to static files works when S3 disabled
- [ ] Signed URLs generated correctly
- [ ] MinIO endpoint configuration works
- [ ] AWS S3 configuration works
- [ ] Multi-environment setup (dev with MinIO, prod with S3)
---
## Documentation
### Primary Documents
1. **HELM_SECRETS_GUNICORN_UPDATES.md** - Helm secrets, S3/MinIO in Helm, Gunicorn
2. **S3_DATABASE_CONFIG.md** ⭐ - Database-backed S3 configuration (detailed)
3. **IMPLEMENTATION_SUMMARY.md** (this file) - Complete overview
### Quick Reference
- **Helm Chart Values**: `helm-chart/motm-app/values.yaml`
- **Production Example**: `helm-chart/motm-app/values-production.yaml`
- **Development Example**: `helm-chart/motm-app/values-development.yaml`
- **S3 Config Code**: `s3_config.py`
- **Database Models**: `database.py`
- **Admin UI**: `templates/s3_config.html`
---
## Troubleshooting Quick Reference
| Issue | Solution |
|-------|----------|
| Secret not found | Verify external secret exists: `kubectl get secret motm-credentials` |
| S3 config not persisting | Check database connection, verify s3_settings table exists |
| Credentials not working | Check env vars are set: `kubectl exec pod -- env \| grep S3_` |
| Gunicorn not starting | Check logs: `kubectl logs deployment/motm-app` |
| Database migration failed | Run: `python -c "from database import init_database; init_database()"` |
| Settings not loading | Check priority: env vars > database > file |
---
## Summary
### What We Achieved
1. **Production-Ready Deployment**
- Kubernetes-native secret management
- Gunicorn WSGI server
- External secret operator support
2. **Flexible S3/MinIO Support**
- Full configuration options in Helm
- AWS S3 and MinIO support
- S3-compatible storage support
3. **Database-Backed Configuration**
- Admin-configurable without redeployment
- Secure credential management
- Three-tier priority system
- Backward compatible
4. **Security First**
- Credentials always from secure sources
- No secrets in database or ConfigMaps
- SSL/TLS support
- Kubernetes best practices
### Lines of Code Changed
- **Database**: +33 lines (S3Settings model)
- **S3 Config**: +75 lines (database integration)
- **Helm Chart**: +60 lines (external secrets, S3 config)
- **Container**: +3 lines (gunicorn)
- **UI**: +8 lines (security notice)
- **Setup**: +18 lines (S3 initialization)
- **Documentation**: +1500 lines
### Ready For
- ✅ Production Kubernetes deployment
- ✅ Multi-environment setups
- ✅ Self-hosted MinIO
- ✅ AWS S3 production use
- ✅ Zero-downtime configuration changes
- ✅ Enterprise secret management
- ✅ High-availability deployments
- ✅ CI/CD pipelines
---
## Next Steps (Optional Enhancements)
### Future Improvements
1. **Multi-Region S3**: Support failover between regions
2. **Backup Configuration**: Export/import S3 settings
3. **Audit Log**: Track configuration changes
4. **Per-Team Settings**: Different S3 configs per team
5. **CDN Integration**: CloudFront/CloudFlare in front of S3
6. **Metrics**: S3 usage statistics and monitoring
### Platform Enhancements
1. **Database Migrations**: Alembic for schema versioning
2. **Health Checks**: S3 connectivity in health endpoint
3. **Prometheus Metrics**: S3 request counts, errors
4. **Grafana Dashboard**: S3 performance visualization
---
## Conclusion
The MOTM application is now production-ready with:
- Secure, flexible secret management
- Database-backed S3 configuration for zero-downtime changes
- Full S3 and MinIO support
- Production-grade Gunicorn server
- Kubernetes-native architecture
All changes maintain backward compatibility while providing enterprise-grade features for production deployments.
🎉 **Ready to deploy!**
+107
View File
@@ -0,0 +1,107 @@
# Database Migration Summary
## Problem
Your production application is throwing SQL errors because:
1. The `votingdeadline` column is missing from the `admin_settings` table
2. The code was using wrong table/column names (fixed in code)
## What Was Fixed
### Code Changes (Already Applied)
✅ Fixed table name: `motmadminsettings` → `admin_settings`
✅ Fixed column names to use snake_case (e.g., `nextclub` → `next_club`)
✅ Added camelCase to snake_case conversion in `readSettings.py`
✅ Improved error handling for duplicate column creation
### Files Modified
- `main.py` - Updated all SQL queries
- `readSettings.py` - Added camelCase to snake_case conversion
## What You Need to Do
### Run the Migration on Production
**Option 1: Use the automated script (Easiest)**
```bash
cd /home/jonny/Projects/gcp-hockey-results/motm_app
./run_production_migration.sh motm-app
```
**Option 2: Manual steps**
```bash
# 1. Find your pod
kubectl get pods -n motm-app -l app.kubernetes.io/name=motm-app
# 2. Run the migration
kubectl exec -it <POD_NAME> -n motm-app -- python add_voting_deadline.py
# 3. Verify it worked
kubectl exec -it <POD_NAME> -n motm-app -- python -c "
from db_config import db_config
from sqlalchemy import text, inspect
engine = db_config.engine
inspector = inspect(engine)
columns = inspector.get_columns('admin_settings')
print('✓ votingdeadline exists' if any(c['name'] == 'votingdeadline' for c in columns) else '✗ missing')
"
# 4. Restart the pod
kubectl rollout restart deployment/motm-app -n motm-app
```
## Expected Results
After running the migration:
- ✅ The `votingdeadline` column will be added to `admin_settings` table
- ✅ The MOTM admin page will load without SQL errors
- ✅ You'll see the "Voting Deadline" field in the form
- ✅ You can set voting deadlines for matches
## Verification
Test the application:
1. Visit https://motm.ervine.cloud/admin/motm
2. Page should load without errors
3. You should see the "Voting Deadline" field
4. Set a deadline and activate voting
5. Visit the voting page - you should see a countdown timer
## Troubleshooting
### If the migration script isn't in the pod:
You need to rebuild and redeploy the Docker image:
```bash
# Build new image with migration script
docker build -t your-registry/motm-app:latest .
# Push to registry
docker push your-registry/motm-app:latest
# Deploy to Kubernetes
helm upgrade motm-app ./helm-chart/motm-app --namespace motm-app
```
### If you get "column already exists" error:
This is fine! The migration script is idempotent and will skip if the column already exists.
### If you get other errors:
Check the logs:
```bash
kubectl logs -n motm-app -l app.kubernetes.io/name=motm-app --tail=100
```
## Documentation
For detailed instructions, see:
- `PRODUCTION_MIGRATION_GUIDE.md` - Comprehensive migration guide
- `VOTING_DEADLINE_FEATURE.md` - Feature documentation
- `VOTING_DEADLINE_IMPLEMENTATION.md` - Implementation details
## Support
If you encounter issues:
1. Check pod logs for detailed error messages
2. Verify database connectivity
3. Ensure database user has ALTER TABLE permissions
4. Review the production migration guide
+187
View File
@@ -0,0 +1,187 @@
# MinIO Logo Display Fix
## Problem
Club logos were not displaying when deployed to Kubernetes because the application was generating AWS S3 URLs instead of MinIO URLs:
```
https://hockey-apps.s3.amazonaws.com/assets/logos/HKFC_crest.png
```
## Root Cause
The Helm chart values had `storageProvider: "aws"` configured, which caused the `s3_config.py` module's `_get_public_url()` method to generate AWS S3 URLs instead of MinIO URLs.
## Solution
Updated the Helm chart values files to use MinIO configuration:
### Changes Made
1. **`helm-chart/motm-app/values.yaml`** (default values):
- Changed `storageProvider: "aws"` → `"minio"`
- Set `endpoint: "http://minio.default.svc.cluster.local:9000"`
- Set `bucket: "hockey-apps"`
- Changed `useSignedUrls: true` → `false`
- Changed `useSSL: true` → `false`
2. **`helm-chart/motm-app/values-production.yaml`**:
- Changed `storageProvider: "aws"` → `"minio"`
- Set `endpoint: "http://minio.default.svc.cluster.local:9000"`
- Set `bucket: "hockey-apps"`
- Changed `useSignedUrls: true` → `false`
- Changed `useSSL: true` → `false`
3. **`helm-chart/motm-app/values-development.yaml`**:
- Already correctly configured with MinIO
## Deployment Instructions
### Option 1: Upgrade Existing Deployment
If you have an existing deployment, upgrade it with the new values:
```bash
cd /home/jonny/Projects/gcp-hockey-results/motm_app/helm-chart/motm-app
# For development
helm upgrade motm-app . -f values-development.yaml --namespace default
# For production
helm upgrade motm-app . -f values-production.yaml --namespace default
```
### Option 2: Redeploy from Scratch
```bash
cd /home/jonny/Projects/gcp-hockey-results/motm_app/helm-chart/motm-app
# Delete existing deployment
helm uninstall motm-app --namespace default
# Reinstall with correct configuration
helm install motm-app . -f values-production.yaml --namespace default
```
### Option 3: Override Values During Deployment
If you don't want to modify the files, you can override during deployment:
```bash
helm upgrade --install motm-app . \
--set s3.storageProvider=minio \
--set s3.endpoint="http://minio.default.svc.cluster.local:9000" \
--set s3.bucket=hockey-apps \
--set s3.useSignedUrls=false \
--set s3.useSSL=false \
--namespace default
```
## Important Considerations
### 1. MinIO Service Name
The endpoint `http://minio.default.svc.cluster.local:9000` assumes:
- MinIO service is named `minio`
- MinIO is deployed in the `default` namespace
- MinIO is running on port `9000`
If your MinIO service has a different name or is in a different namespace, update the endpoint accordingly:
```
http://<service-name>.<namespace>.svc.cluster.local:<port>
```
### 2. External MinIO Access
If you need to access MinIO from outside the cluster (e.g., for direct browser access or CDN), you can configure an external endpoint:
```yaml
s3:
storageProvider: "minio"
endpoint: "https://minio.yourdomain.com" # External endpoint
useSSL: true # Enable SSL for external access
useSignedUrls: true # Optional: use signed URLs for security
```
### 3. Bucket Configuration
Ensure the MinIO bucket `hockey-apps` exists and has the correct permissions:
```bash
# Using MinIO CLI (mc)
mc alias set myminio http://minio.default.svc.cluster.local:9000 <access-key> <secret-key>
mc mb myminio/hockey-apps
mc anonymous set download myminio/hockey-apps # Make bucket publicly readable
```
### 4. Upload Logos to MinIO
Ensure club logos are uploaded to the correct path in MinIO:
```
hockey-apps/assets/logos/HKFC_crest.png
hockey-apps/assets/logos/<other-club-logos>
```
## Verification
After deployment, verify the fix:
1. **Check Pod Environment Variables**:
```bash
kubectl exec -it <pod-name> -- env | grep S3
```
You should see:
```
S3_ENABLED=true
S3_STORAGE_PROVIDER=minio
S3_ENDPOINT=http://minio.default.svc.cluster.local:9000
S3_BUCKET=hockey-apps
S3_USE_SIGNED_URLS=false
S3_USE_SSL=false
```
2. **Check Logo URLs**:
- Visit the application in a browser
- Inspect a club logo image
- Verify the URL now points to MinIO, e.g.:
```
http://minio.default.svc.cluster.local:9000/hockey-apps/assets/logos/HKFC_crest.png
```
3. **Test Logo Loading**:
- Open the application
- Navigate to pages displaying club logos
- Confirm logos are now displaying correctly
## Rollback
If you need to rollback to AWS S3:
```bash
helm upgrade motm-app . \
--set s3.storageProvider=aws \
--set s3.endpoint="" \
--set s3.bucket=motm-assets \
--set s3.useSignedUrls=true \
--set s3.useSSL=true \
--namespace default
```
## Related Files
- `s3_config.py` - S3/MinIO configuration and URL generation
- `helm-chart/motm-app/templates/deployment.yaml` - Environment variable injection
- `helm-chart/motm-app/values.yaml` - Default configuration
- `helm-chart/motm-app/values-production.yaml` - Production configuration
- `helm-chart/motm-app/values-development.yaml` - Development configuration
## Technical Details
The `s3_config.py` module's `_get_public_url()` method (lines 285-303) generates URLs based on the storage provider:
- **AWS S3**: `https://{bucket}.s3.{region}.amazonaws.com/{key}`
- **MinIO**: `{protocol}://{endpoint}/{bucket}/{key}`
When `storageProvider: "minio"`, the code correctly generates MinIO URLs with the configured endpoint.
+192
View File
@@ -0,0 +1,192 @@
# PostgreSQL Compatibility Fix for Comments Management
## Issue
The comments management page was showing "No comments found" even though comments existed in the database. This was because the original implementation used SQLite-specific features (like `rowid`) that don't exist in PostgreSQL.
## Root Cause
Your database is PostgreSQL (as configured in `database_config.ini`), but the comments management code was written with SQLite assumptions:
1. **SQLite has `rowid`** - An implicit row identifier column
2. **PostgreSQL uses `ctid`** - A system column that serves a similar purpose but has different syntax
3. **Different DELETE/UPDATE syntax** - PostgreSQL doesn't support `LIMIT` directly in DELETE/UPDATE statements
## Fixes Applied
### 1. SELECT Query Fix (Reading Comments)
**Before:**
```sql
SELECT rowid, matchDate, comment FROM _motmcomments
```
**After:**
```sql
-- First tries to find an explicit ID column
SELECT column_name FROM information_schema.columns
WHERE table_name = '_motmcomments' AND column_name IN ('id', 'rowid', 'oid')
-- If found, uses that column
SELECT id as comment_id, matchDate, comment FROM _motmcomments
-- Otherwise, uses PostgreSQL's ctid
SELECT ctid::text as comment_id, matchDate, comment FROM _motmcomments
-- Last resort: generates row numbers
SELECT ROW_NUMBER() OVER (ORDER BY matchDate DESC) as comment_id,
matchDate, comment FROM _motmcomments
```
### 2. DELETE Query Fix
**Before:**
```sql
DELETE FROM _motmcomments WHERE rowid = :comment_id
```
**After:**
```sql
-- Primary method: Use ctid
DELETE FROM _motmcomments WHERE ctid = :comment_id::tid
-- Fallback: Match on date and comment content
DELETE FROM _motmcomments
WHERE ctid IN (
SELECT ctid FROM _motmcomments
WHERE matchDate = :match_date AND comment = :comment
LIMIT 1
)
```
### 3. UPDATE Query Fix
**Before:**
```sql
UPDATE _motmcomments SET comment = :comment WHERE rowid = :comment_id
```
**After:**
```sql
-- Primary method: Use ctid
UPDATE _motmcomments SET comment = :comment WHERE ctid = :comment_id::tid
-- Fallback: Match on date and comment content
UPDATE _motmcomments
SET comment = :new_comment
WHERE ctid IN (
SELECT ctid FROM _motmcomments
WHERE matchDate = :match_date AND comment = :old_comment
LIMIT 1
)
```
### 4. Template Updates
Updated `comments_management.html` to:
- Use `comment.comment_id` instead of `comment.rowid`
- Pass additional hidden fields: `match_date` and `original_comment`
- Handle string-based IDs (ctid is text like `(0,1)`)
- Use `CSS.escape()` for safe selector handling
### 5. JavaScript Updates
Updated JavaScript functions to handle non-numeric IDs:
```javascript
function toggleEdit(commentId) {
const escapedId = CSS.escape(String(commentId)); // Handle any string format
// ...
}
```
## Database Compatibility Matrix
| Feature | SQLite | PostgreSQL | MySQL |
|---------|--------|------------|-------|
| Implicit Row ID | `rowid` | `ctid` | None (need explicit PK) |
| ID Type | Integer | Text (tuple) | Integer |
| DELETE with LIMIT | ✓ Supported | ✗ Need subquery | ✓ Supported |
| information_schema | ✗ Limited | ✓ Full support | ✓ Full support |
## PostgreSQL `ctid` Explained
`ctid` is a system column in PostgreSQL that stores the physical location of a row:
- Format: `(page_number, tuple_index)` - e.g., `(0,1)` or `(42,17)`
- Type: `tid` (tuple identifier)
- Must be cast to text for display: `ctid::text`
- Must be cast from text for comparison: `'(0,1)'::tid`
**Important Notes:**
- `ctid` can change after `VACUUM` operations
- Not suitable for long-term row references
- Perfect for temporary identification within a transaction
- Our implementation includes fallback methods for robustness
## Testing
After the fix, the comments management page should:
1. **Display all comments** from the database
2. **Show proper IDs** (either from ctid or generated row numbers)
3. **Allow editing** - Update specific comments
4. **Allow deletion** - Remove individual comments
5. **Bulk operations** - Delete by match date or all comments
6. **Column management** - Drop unwanted columns
## Verifying the Fix
### Check Comments Exist
```sql
SELECT COUNT(*) FROM _motmcomments;
SELECT * FROM _motmcomments LIMIT 5;
```
### Check ctid Values
```sql
SELECT ctid::text, matchDate, comment FROM _motmcomments LIMIT 5;
```
### Test in Application
1. Navigate to `/admin/comments/manage`
2. Verify comments are displayed
3. Try editing a comment
4. Try deleting a comment
5. Check that operations succeed
## Known Limitations
1. **ctid instability**: After database maintenance (VACUUM FULL), ctid values change. Our fallback methods handle this.
2. **Duplicate comments**: If two identical comments exist for the same match date, the fallback methods will affect only the first match.
3. **Performance**: The fallback queries using subqueries are slightly slower than direct ctid lookups, but acceptable for the expected data volume.
## Future Improvements
Consider adding an explicit `id` column to `_motmcomments`:
```sql
ALTER TABLE _motmcomments ADD COLUMN id SERIAL PRIMARY KEY;
```
This would provide:
- Stable, permanent row identifiers
- Better performance
- Database-agnostic code
- Easier troubleshooting
## Related Files Modified
1. **`main.py`** (lines 1385-1520)
- Updated `comments_management()` function
- Multi-database query strategy
- Fallback error handling
2. **`templates/comments_management.html`**
- Changed `rowid` to `comment_id`
- Added hidden form fields
- Updated JavaScript for string IDs
## Summary
The comments management feature now works correctly with PostgreSQL by:
- Using PostgreSQL-specific `ctid` for row identification
- Implementing robust fallback methods
- Handling different data types gracefully
- Maintaining compatibility with future database types
All functionality (view, edit, delete, bulk operations) now works as intended.
+60
View File
@@ -0,0 +1,60 @@
# PostgreSQL Database Setup
This application is now configured to use PostgreSQL as the default database instead of SQLite.
## Database Configuration
The application connects to a PostgreSQL database with the following settings:
- **Host**: icarus.ipa.champion
- **Port**: 5432
- **Database**: motm
- **Username**: motm_user
- **Password**: q7y7f7Lv*sODJZ2wGiv0Wq5a
## Running the Application
### Linux/macOS
```bash
./run_motm.sh
```
### Windows
```cmd
run_motm.bat
```
### Manual Setup
If you need to run the application manually, set these environment variables:
```bash
export DATABASE_TYPE=postgresql
export POSTGRES_HOST=icarus.ipa.champion
export POSTGRES_PORT=5432
export POSTGRES_DATABASE=motm
export POSTGRES_USER=motm_user
export POSTGRES_PASSWORD='q7y7f7Lv*sODJZ2wGiv0Wq5a'
```
## Database Status
The PostgreSQL database contains the following data:
- **Players**: 3 players in the `_hkfc_players` table
- **Match Squad**: 3 players currently selected for the match squad
- **Admin Settings**: Configured with next match details
## Troubleshooting
If you encounter issues:
1. **Connection Failed**: Check if the PostgreSQL server is accessible
2. **Empty Data**: The database contains sample data - if you see empty tables, check the connection
3. **Permission Errors**: Ensure the `motm_user` has proper database permissions
## Testing Database Connection
Run the test script to verify everything is working:
```bash
python3 test_match_squad.py
```
This will test the database connection and display current data.
+160
View File
@@ -0,0 +1,160 @@
# Production Deployment Guide
## WSGI Server Setup
Your Flask application now uses **Gunicorn** as the production WSGI server instead of the Flask development server.
### Files Added:
- `gunicorn.conf.py` - Gunicorn configuration file
- `run_production.py` - WSGI entry point
- `start_production.sh` - Production startup script
- `motm-app.service` - Systemd service file (optional)
## Quick Start (Recommended)
### 1. Install Dependencies
```bash
pip install -r requirements.txt
```
### 2. Start Production Server
```bash
# Option A: Use the startup script (easiest)
./start_production.sh
# Option B: Start manually
gunicorn -c gunicorn.conf.py run_production:app
# Option C: Quick start with default settings
gunicorn --bind 0.0.0.0:5000 --workers 4 run_production:app
```
## Configuration Details
### Gunicorn Configuration (`gunicorn.conf.py`)
- **Workers**: `CPU_COUNT * 2 + 1` (automatically calculated)
- **Worker Class**: `sync` (good for Flask applications)
- **Timeout**: 30 seconds
- **Max Requests**: 1000 per worker (prevents memory leaks)
- **Logging**: Standard output (can be redirected)
- **Preload**: Enabled for better performance
### Environment Variables
- `FLASK_ENV=production` (automatically set)
## Alternative WSGI Servers
If you prefer different WSGI servers:
### 1. uWSGI
```bash
pip install uwsgi
uwsgi --http 0.0.0.0:5000 --module run_production:app --processes 4 --threads 2
```
### 2. Waitress (Windows-friendly)
```bash
pip install waitress
waitress-serve --host=0.0.0.0 --port=5000 run_production:app
```
### 3. Gevent (for async workloads)
```bash
pip install gunicorn[gevent]
gunicorn -c gunicorn.conf.py --worker-class gevent run_production:app
```
## Production Recommendations
### 1. Use a Reverse Proxy
Place Nginx or Apache in front of Gunicorn:
**Nginx Example:**
```nginx
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
### 2. SSL/HTTPS
For production, always use HTTPS:
- Use Let's Encrypt for free SSL certificates
- Configure SSL in your reverse proxy
- Update Gunicorn config with SSL settings if needed
### 3. Process Management
Use systemd or supervisor to manage the Gunicorn process:
**Systemd (Linux):**
```bash
sudo cp motm-app.service /etc/systemd/system/
sudo systemctl enable motm-app
sudo systemctl start motm-app
sudo systemctl status motm-app
```
### 4. Monitoring
- Monitor worker processes and memory usage
- Set up log rotation
- Use tools like Prometheus + Grafana for metrics
## Performance Tuning
### Worker Count
- **CPU-bound**: `workers = CPU_COUNT * 2`
- **I/O-bound**: `workers = CPU_COUNT * 2 + 1` (current setting)
- **High concurrency**: Consider async workers (gevent/eventlet)
### Memory Management
- Current: `max_requests = 1000` (restarts workers periodically)
- Adjust based on your memory constraints
### Timeout Settings
- Current: `timeout = 30` seconds
- Increase if you have long-running requests
## Troubleshooting
### Common Issues:
1. **Permission denied**: Check file permissions and user/group settings
2. **Port already in use**: Change port in `gunicorn.conf.py` or kill existing process
3. **Memory issues**: Reduce worker count or increase `max_requests`
4. **Slow responses**: Increase timeout or worker count
### Logs:
- Gunicorn logs to stdout/stderr by default
- Check systemd logs: `journalctl -u motm-app`
- Redirect logs to files if needed
## Security Notes
1. **Never run as root** in production
2. **Use HTTPS** for all production traffic
3. **Set proper file permissions** on your application files
4. **Keep dependencies updated** regularly
5. **Use environment variables** for sensitive configuration
## Migration from Development
Your application is now ready for production! The key changes:
- ✅ Gunicorn WSGI server instead of Flask dev server
- ✅ Production-optimized configuration
- ✅ Proper worker management
- ✅ Security improvements
- ✅ Performance optimizations
**Next Steps:**
1. Test the production setup locally
2. Deploy to your production server
3. Set up reverse proxy (Nginx/Apache)
4. Configure SSL certificates
5. Set up monitoring and logging
+234
View File
@@ -0,0 +1,234 @@
# Production Database Diagnostic Guide
## Issue
Getting "Admin settings not found" error when activating MOTM vote, even after saving settings.
## Root Cause Analysis
The code is looking for the `motm_url_suffix` column in the `admin_settings` table. The error suggests one of these issues in production:
1. **Wrong table name**: Production might be using `motmadminsettings` instead of `admin_settings`
2. **Missing column**: The `motm_url_suffix` column might not exist
3. **NULL value**: The `motm_url_suffix` might be NULL or empty
4. **No rows**: The table might be empty
## Diagnostic Steps
### Step 1: Run the Diagnostic Script
Run this in your production Kubernetes pod:
```bash
# Find your pod
kubectl get pods -n motm-app -l app.kubernetes.io/name=motm-app
# Run the diagnostic script
kubectl exec -it <POD_NAME> -n motm-app -- python check_production_db.py
```
### Step 2: Analyze the Output
The script will show:
- Which tables exist (`admin_settings` vs `motmadminsettings`)
- What data is in the table
- Whether the `motm_url_suffix` column has a value
- The exact query that's failing
### Step 3: Based on the Results
#### Scenario A: Table is `motmadminsettings` (Old Name)
If the output shows `motmadminsettings` exists but `admin_settings` doesn't:
**Solution**: Your production database still has the old table name. You need to either:
1. **Rename the table** (recommended):
```bash
kubectl exec -it <POD_NAME> -n motm-app -- python -c "
from db_config import db_config
from sqlalchemy import text
engine = db_config.engine
conn = engine.connect()
conn.execute(text('ALTER TABLE motmadminsettings RENAME TO admin_settings'))
conn.commit()
conn.close()
print('Table renamed successfully')
"
```
2. **Or update the code** to use `motmadminsettings` (not recommended, but works as a quick fix)
#### Scenario B: `motm_url_suffix` is NULL or Empty
If the output shows the column exists but is NULL or empty:
**Solution**: The column needs to be populated. Run this:
```bash
kubectl exec -it <POD_NAME> -n motm-app -- python -c "
from db_config import db_config
from sqlalchemy import text
import random
import string
# Generate a random URL suffix
def randomUrlSuffix(length=8):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))
engine = db_config.engine
conn = engine.connect()
urlSuffix = randomUrlSuffix(8)
conn.execute(text('UPDATE admin_settings SET motm_url_suffix = :suffix WHERE userid = \\'admin\\''), {'suffix': urlSuffix})
conn.commit()
conn.close()
print(f'URL suffix set to: {urlSuffix}')
"
```
#### Scenario C: Table is Empty
If the output shows 0 rows:
**Solution**: You need to initialize the admin settings. Run this:
```bash
kubectl exec -it <POD_NAME> -n motm-app -- python -c "
from db_config import db_config
from sqlalchemy import text
import random
import string
def randomUrlSuffix(length=8):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))
engine = db_config.engine
conn = engine.connect()
urlSuffix = randomUrlSuffix(8)
# Insert default admin settings
conn.execute(text('''
INSERT INTO admin_settings (userid, motm_url_suffix, next_fixture, prev_fixture)
VALUES ('admin', :suffix, 1, 0)
ON CONFLICT (userid) DO UPDATE SET motm_url_suffix = :suffix
'''), {'suffix': urlSuffix})
conn.commit()
conn.close()
print(f'Admin settings initialized with URL suffix: {urlSuffix}')
"
```
#### Scenario D: Column Doesn't Exist
If the output shows the column is missing:
**Solution**: Add the missing column:
```bash
kubectl exec -it <POD_NAME> -n motm-app -- python -c "
from db_config import db_config
from sqlalchemy import text
engine = db_config.engine
conn = engine.connect()
# Add the column if it doesn't exist
try:
conn.execute(text('ALTER TABLE admin_settings ADD COLUMN motm_url_suffix VARCHAR(50)'))
conn.commit()
print('Column added successfully')
except Exception as e:
if 'already exists' in str(e):
print('Column already exists')
else:
print(f'Error: {e}')
conn.close()
"
```
## Quick Fix Script
If you want to try a comprehensive fix that handles all scenarios:
```bash
kubectl exec -it <POD_NAME> -n motm-app -- python << 'EOF'
from db_config import db_config
from sqlalchemy import text
import random
import string
def randomUrlSuffix(length=8):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))
engine = db_config.engine
conn = engine.connect()
# Step 1: Check if table exists
try:
result = conn.execute(text("SELECT 1 FROM admin_settings LIMIT 1"))
print("✓ admin_settings table exists")
except:
print("✗ admin_settings table does not exist")
print("Please check if you're using the old table name 'motmadminsettings'")
conn.close()
exit(1)
# Step 2: Check if motm_url_suffix column exists
try:
result = conn.execute(text("SELECT motm_url_suffix FROM admin_settings LIMIT 1"))
print("✓ motm_url_suffix column exists")
except:
print("✗ motm_url_suffix column does not exist, adding it...")
conn.execute(text("ALTER TABLE admin_settings ADD COLUMN motm_url_suffix VARCHAR(50)"))
conn.commit()
print("✓ Column added")
# Step 3: Check if URL suffix has a value
result = conn.execute(text("SELECT motm_url_suffix FROM admin_settings WHERE userid = 'admin'"))
row = result.fetchone()
if row and row[0]:
print(f"✓ URL suffix exists: {row[0]}")
else:
print("✗ URL suffix is NULL or empty, setting it...")
urlSuffix = randomUrlSuffix(8)
conn.execute(text("UPDATE admin_settings SET motm_url_suffix = :suffix WHERE userid = 'admin'"), {'suffix': urlSuffix})
conn.commit()
print(f"✓ URL suffix set to: {urlSuffix}")
conn.close()
print("\n✓ All checks passed!")
EOF
```
## After Running the Fix
1. **Restart the application** to clear any cached connections:
```bash
kubectl rollout restart deployment/motm-app -n motm-app
```
2. **Test the MOTM admin page**:
- Go to https://motm.ervine.cloud/admin/motm
- Fill in the match details
- Click "Activate MotM Vote"
- It should work without errors
## Prevention
To prevent this issue in the future:
1. **Run database migrations** before deploying new code
2. **Use the migration script** (`add_voting_deadline.py`) to ensure all columns exist
3. **Test in staging** before deploying to production
4. **Monitor logs** for SQL errors
## Support
If you continue to have issues after running these diagnostics:
1. Save the output from `check_production_db.py`
2. Check the application logs: `kubectl logs -n motm-app -l app.kubernetes.io/name=motm-app --tail=100`
3. Verify the database connection is working
4. Check if there are any database permission issues
+219
View File
@@ -0,0 +1,219 @@
# Production Database Migration Guide
## Issue
The production database is missing the `votingdeadline` column, causing SQL errors when accessing the MOTM admin page.
## Solution
Run the migration script on the production Kubernetes cluster to add the missing column.
## Step-by-Step Instructions
### Option 1: Run Migration via kubectl exec (Recommended)
1. **Find your production pod:**
```bash
kubectl get pods -n <your-namespace> -l app.kubernetes.io/name=motm-app
```
Replace `<your-namespace>` with your actual namespace (e.g., `motm-app`, `default`, etc.)
2. **Execute the migration script:**
```bash
kubectl exec -it <pod-name> -n <your-namespace> -- python add_voting_deadline.py
```
Example:
```bash
kubectl exec -it motm-app-7d8f9b4c5-xk2mn -n motm-app -- python add_voting_deadline.py
```
3. **Verify the migration:**
```bash
kubectl exec -it <pod-name> -n <your-namespace> -- python -c "
from db_config import db_config
from sqlalchemy import text, inspect
engine = db_config.engine
inspector = inspect(engine)
columns = inspector.get_columns('admin_settings')
voting_deadline_exists = any(col['name'] == 'votingdeadline' for col in columns)
print('✓ votingdeadline column exists' if voting_deadline_exists else '✗ votingdeadline column missing')
"
```
### Option 2: Run Migration via Helm Job (Alternative)
If you prefer to run the migration as a Kubernetes job:
1. **Create a migration job manifest:**
```yaml
# migration-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: motm-migration-voting-deadline
namespace: motm-app
spec:
template:
spec:
containers:
- name: migration
image: your-registry/motm-app:latest
command: ["python", "add_voting_deadline.py"]
envFrom:
- secretRef:
name: motm-app-secrets
- configMapRef:
name: motm-app-config
restartPolicy: Never
backoffLimit: 3
```
2. **Apply the job:**
```bash
kubectl apply -f migration-job.yaml
```
3. **Check job status:**
```bash
kubectl get jobs -n motm-app
kubectl logs -n motm-app job/motm-migration-voting-deadline
```
4. **Clean up after successful migration:**
```bash
kubectl delete job motm-migration-voting-deadline -n motm-app
```
### Option 3: Run Migration via Helm Hook (Advanced)
For automated migrations during deployments:
1. **Create a migration job template:**
```yaml
# templates/migration-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "motm-app.fullname" . }}-migration
namespace: {{ .Release.Namespace }}
annotations:
"helm.sh/hook": pre-upgrade,pre-install
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
template:
spec:
containers:
- name: migration
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command: ["python", "add_voting_deadline.py"]
envFrom:
- secretRef:
name: {{ include "motm-app.fullname" . }}-secrets
restartPolicy: Never
backoffLimit: 3
```
2. **The migration will run automatically during helm upgrade**
## Verification
After running the migration, verify it worked:
1. **Check the application logs:**
```bash
kubectl logs -n <your-namespace> -l app.kubernetes.io/name=motm-app --tail=50
```
2. **Test the admin page:**
- Navigate to `https://motm.ervine.cloud/admin/motm`
- The page should load without SQL errors
- You should see the "Voting Deadline" field in the form
3. **Check for the column in the database:**
```bash
kubectl exec -it <pod-name> -n <your-namespace> -- python -c "
from db_config import db_config
from sqlalchemy import text, inspect
engine = db_config.engine
inspector = inspect(engine)
columns = inspector.get_columns('admin_settings')
print('Columns in admin_settings:')
for col in columns:
print(f' - {col[\"name\"]}: {col[\"type\"]}')
"
```
You should see `votingdeadline` in the list.
## Troubleshooting
### Issue: "pod not found"
**Solution:** Make sure you're using the correct namespace and pod name.
### Issue: "permission denied"
**Solution:** The migration script needs database write permissions. Ensure your database user has ALTER TABLE permissions.
### Issue: "column already exists"
**Solution:** This is fine! The migration script is idempotent and will skip if the column already exists.
### Issue: Migration fails
**Solution:** Check the pod logs for detailed error messages:
```bash
kubectl logs -n <your-namespace> <pod-name>
```
## Rollback (If Needed)
If the migration causes issues, you can rollback:
1. **Remove the column:**
```bash
kubectl exec -it <pod-name> -n <your-namespace> -- python -c "
from db_config import db_config
from sqlalchemy import text
engine = db_config.engine
with engine.connect() as conn:
conn.execute(text('ALTER TABLE admin_settings DROP COLUMN IF EXISTS votingdeadline'))
conn.commit()
print('Column removed')
"
```
2. **Restart the application:**
```bash
kubectl rollout restart deployment/motm-app -n <your-namespace>
```
## Quick Reference
```bash
# Find pod name
kubectl get pods -n motm-app -l app.kubernetes.io/name=motm-app
# Run migration
kubectl exec -it <POD_NAME> -n motm-app -- python add_voting_deadline.py
# Verify migration
kubectl exec -it <POD_NAME> -n motm-app -- python -c "from db_config import db_config; from sqlalchemy import text, inspect; engine = db_config.engine; inspector = inspect(engine); columns = inspector.get_columns('admin_settings'); print('✓ votingdeadline exists' if any(c['name'] == 'votingdeadline' for c in columns) else '✗ missing')"
# Check logs
kubectl logs -n motm-app -l app.kubernetes.io/name=motm-app --tail=100
```
## Next Steps
After the migration is complete:
1. ✅ Restart the application pods to clear any cached connections
2. ✅ Test the MOTM admin page
3. ✅ Set a voting deadline for the next match
4. ✅ Test the voting page to see the countdown timer
## Support
If you encounter any issues:
1. Check the pod logs for detailed error messages
2. Verify database connectivity
3. Ensure the database user has proper permissions
4. Review the application logs for any additional errors
+98
View File
@@ -0,0 +1,98 @@
#!/bin/bash
# Quick Fix Commands for MinIO Logo Issue
# Run these commands to fix the club logo display issue in Kubernetes
set -e
echo "=== MinIO Logo Fix Deployment Script ==="
echo ""
# Step 1: Find MinIO service endpoint
echo "Step 1: Finding MinIO service endpoint..."
echo "Current services in default namespace:"
kubectl get svc -n default | grep -i minio || echo "No MinIO service found in default namespace"
echo ""
echo "To search in all namespaces:"
echo "kubectl get svc --all-namespaces | grep -i minio"
echo ""
# Step 2: Check current deployment configuration
echo "Step 2: Checking current deployment..."
DEPLOYMENT=$(kubectl get deployment -n default -l app.kubernetes.io/name=motm-app -o name 2>/dev/null || echo "")
if [ -n "$DEPLOYMENT" ]; then
echo "Found deployment: $DEPLOYMENT"
echo "Current S3 environment variables:"
POD=$(kubectl get pods -n default -l app.kubernetes.io/name=motm-app -o name | head -n 1)
if [ -n "$POD" ]; then
kubectl exec -n default "$POD" -- env | grep S3_ || echo "No S3 env vars found"
fi
else
echo "No motm-app deployment found"
fi
echo ""
# Step 3: Navigate to helm chart directory
cd "$(dirname "$0")/helm-chart/motm-app" || exit 1
echo "Step 3: Changed to Helm chart directory: $(pwd)"
echo ""
# Step 4: Show upgrade command (don't execute automatically)
echo "Step 4: Ready to upgrade deployment"
echo ""
echo "Choose one of the following commands to upgrade:"
echo ""
echo "For PRODUCTION (recommended):"
echo " helm upgrade motm-app . -f values-production.yaml --namespace default"
echo ""
echo "For DEVELOPMENT:"
echo " helm upgrade motm-app . -f values-development.yaml --namespace default"
echo ""
echo "Or with custom MinIO endpoint (replace <endpoint> with your actual endpoint):"
echo " helm upgrade motm-app . \\"
echo " --set s3.storageProvider=minio \\"
echo " --set s3.endpoint=http://<service-name>.<namespace>.svc.cluster.local:9000 \\"
echo " --set s3.bucket=hockey-apps \\"
echo " --set s3.useSignedUrls=false \\"
echo " --set s3.useSSL=false \\"
echo " --namespace default"
echo ""
# Step 5: Verification commands
echo "After upgrade, verify with these commands:"
echo ""
echo "1. Check pod status:"
echo " kubectl get pods -n default -l app.kubernetes.io/name=motm-app"
echo ""
echo "2. Check environment variables in pod:"
echo " kubectl exec -n default \$(kubectl get pods -n default -l app.kubernetes.io/name=motm-app -o name | head -n 1) -- env | grep S3"
echo ""
echo "3. Check logs for errors:"
echo " kubectl logs -n default \$(kubectl get pods -n default -l app.kubernetes.io/name=motm-app -o name | head -n 1) --tail=50"
echo ""
echo "4. Test connection to MinIO from pod:"
echo " kubectl exec -n default \$(kubectl get pods -n default -l app.kubernetes.io/name=motm-app -o name | head -n 1) -- curl -I http://minio.default.svc.cluster.local:9000/minio/health/ready"
echo ""
# Step 6: MinIO bucket setup (if needed)
echo "If MinIO bucket doesn't exist or needs configuration:"
echo ""
echo "1. Install MinIO client (if not already installed):"
echo " wget https://dl.min.io/client/mc/release/linux-amd64/mc"
echo " chmod +x mc"
echo " sudo mv mc /usr/local/bin/"
echo ""
echo "2. Configure MinIO alias:"
echo " mc alias set myminio http://minio.default.svc.cluster.local:9000 <ACCESS_KEY> <SECRET_KEY>"
echo ""
echo "3. Create bucket (if it doesn't exist):"
echo " mc mb myminio/hockey-apps"
echo ""
echo "4. Set bucket policy to public read:"
echo " mc anonymous set download myminio/hockey-apps"
echo ""
echo "5. Upload logos to bucket:"
echo " mc cp --recursive ./static/images/clubs/ myminio/hockey-apps/assets/logos/"
echo ""
echo "=== End of Quick Fix Script ==="
+226
View File
@@ -0,0 +1,226 @@
# HKFC Men's C Team - MOTM (Man of the Match) System
This is a standalone Flask application for managing Man of the Match and Dick of the Day voting for the HKFC Men's C Team hockey club.
## Features
### Public Section
- **Voting Interface**: Players can vote for MOTM and DotD via secure random URLs
- **Match Comments**: View and add comments from matches
- **Current Holders**: Display current MOTM and DotD holders
### Admin Section
- **Match Management**: Set up upcoming matches, opposition teams, and fixtures
- **Squad Management**: Add/remove players from match squads
- **Statistics**: Record goals and assists for players
- **Voting Results**: View real-time voting charts and results
- **Player of the Year**: Track season-long MOTM/DotD statistics
## Installation
### Option 1: Using Virtual Environment (Recommended)
**Windows Setup:**
1. **Create virtual environment**:
```cmd
python -m venv venv
```
*If `python` doesn't work, try `py` or use the full path to python.exe*
2. **Activate virtual environment**:
```cmd
venv\Scripts\activate.bat
```
3. **Install dependencies**:
```cmd
pip install --upgrade pip
pip install -r requirements.txt
```
4. **Run the application**:
```cmd
python main.py
```
**Unix/Linux/Mac Setup:**
1. **Create virtual environment**:
```bash
python3 -m venv venv
```
2. **Activate virtual environment**:
```bash
source venv/bin/activate
```
3. **Install dependencies**:
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
4. **Run the application**:
```bash
python main.py
```
**Convenience Scripts:**
- After setup, you can use `activate_motm.bat` (Windows) or `source activate_motm.sh` (Unix)
- Or use `run_motm.bat` (Windows) or `./run_motm.sh` (Unix) to start directly
### Option 2: Manual Virtual Environment Setup
1. **Create virtual environment**:
```bash
python -m venv venv
```
2. **Activate virtual environment**:
- **Windows**: `venv\Scripts\activate`
- **Unix/Linux/Mac**: `source venv/bin/activate`
3. **Install dependencies**:
```bash
pip install -r requirements.txt
```
4. **Configure database settings** in `db_config.py`
5. **Run the application**:
```bash
python main.py
```
### Option 3: Global Installation (Not Recommended)
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Configure database settings in `db_config.py`
3. Run the application:
```bash
python main.py
```
The application will be available at `http://localhost:5000`
## Database Requirements
The application requires access to the following database tables:
- `_hkfcC_matchSquad` - Current match squad
- `_HKFC_players` - Player database
- `hkfcCAdminSettings` - Admin configuration
- `hockeyFixtures` - Match fixtures
- `_hkfc_c_motm` - MOTM/DotD voting results
- `_motmComments` - Match comments
- `_clubTeams` - Club and team information
- `mensHockeyClubs` - Club logos and information
## API Endpoints
### Public Endpoints
- `/` - Main index page
- `/motm/<randomUrlSuffix>` - Voting page (requires valid URL suffix)
- `/motm/comments` - Match comments
- `/motm/vote-thanks` - Vote submission processing
### Admin Endpoints (Basic Auth Required)
- `/admin/motm` - MOTM administration
- `/admin/squad` - Squad management
- `/admin/squad/submit` - Process squad selection
- `/admin/squad/list` - View current squad
- `/admin/squad/remove` - Remove player from squad
- `/admin/squad/reset` - Reset squad for new match
- `/admin/stats` - Goals and assists administration
- `/admin/voting` - Voting results charts
- `/admin/poty` - Player of the Year charts
### API Endpoints
- `/api/vote-results` - Get voting results as JSON
- `/api/poty-results` - Get Player of the Year results as JSON
- `/admin/api/team/<club>` - Get teams for a club
- `/admin/api/logo/<club>` - Get club logo URL
- `/admin/api/fixture/<fixture>` - Get fixture information
## Security
- Admin sections are protected with HTTP Basic Authentication
- Voting URLs use random suffixes to prevent unauthorized access
- All admin actions require authentication
## Usage
1. **Admin Setup**:
- Access `/admin/motm` to configure upcoming matches
- Use `/admin/squad` to select players for the match
- Activate voting to generate the public voting URL
2. **Player Voting**:
- Share the generated voting URL with players
- Players can vote for MOTM and DotD
- Optional comments can be added
3. **Results**:
- View real-time results at `/admin/voting`
- Track season statistics at `/admin/poty`
## Configuration
Update the following in `db_config.py`:
- Database connection details
- Cloud SQL configuration (if using Google Cloud)
- Local database settings
The application uses the same database as the main hockey results system, so ensure proper database access is configured.
## Virtual Environment Management
### Development Workflow
1. **Activate virtual environment** before making changes:
- Windows: `activate_motm.bat` or `venv\Scripts\activate`
- Unix/Linux/Mac: `source activate_motm.sh` or `source venv/bin/activate`
2. **Install new packages**:
```bash
pip install new-package-name
```
3. **Update requirements.txt** after adding packages:
```bash
pip freeze > requirements.txt
```
4. **Deactivate** when done:
```bash
deactivate
```
### Virtual Environment Benefits
- **Isolation**: Dependencies won't conflict with other Python projects
- **Version Control**: Pin specific package versions for reproducibility
- **Clean Environment**: Easy to recreate if corrupted
- **Deployment**: Same environment can be replicated in production
### Troubleshooting
**Virtual environment not activating?**
- Ensure Python 3.7+ is installed
- Check file permissions on activation scripts
- Try recreating: `python setup_venv.py`
**Dependencies not found?**
- Activate virtual environment first
- Check if packages are installed: `pip list`
- Reinstall requirements: `pip install -r requirements.txt`
**Permission errors on Unix/Linux/Mac?**
- Make scripts executable: `chmod +x *.sh`
- Run with proper permissions
+128
View File
@@ -0,0 +1,128 @@
# Revert to motmadminsettings - Summary
## What Was Reverted
All changes have been reverted to use the original table and column names that match your production database.
### Table Name
- **Before (my changes):** `admin_settings`
- **After (reverted):** `motmadminsettings` ✅
### Column Names (camelCase)
All column names reverted from snake_case to camelCase:
| Old (snake_case) | New (camelCase) |
|------------------|-----------------|
| `next_club` | `nextclub` ✅ |
| `next_team` | `nextteam` ✅ |
| `next_date` | `nextdate` ✅ |
| `oppo_logo` | `oppologo` ✅ |
| `hkfc_logo` | `hkfclogo` ✅ |
| `curr_motm` | `currmotm` ✅ |
| `curr_dotd` | `currdotd` ✅ |
| `next_fixture` | `nextfixture` ✅ |
| `motm_url_suffix` | `motmurlsuffix` ✅ |
| `prev_fixture` | `prevfixture` ✅ |
### WHERE Clauses
Removed all `WHERE userid = 'admin'` clauses from queries since the `motmadminsettings` table doesn't have a `userid` column.
## Files Modified
1. **`main.py`**
- All table references: `admin_settings` → `motmadminsettings`
- All column names: snake_case → camelCase
- Removed `WHERE userid = 'admin'` from all queries
2. **`readSettings.py`**
- Table reference: `admin_settings` → `motmadminsettings`
- Removed `WHERE userid = 'admin'` from query
- Removed camelCase to snake_case conversion logic
## Key Changes
### SQL Queries
**SELECT queries:**
```sql
-- Before (my changes)
SELECT next_club, next_team FROM admin_settings WHERE userid = 'admin'
-- After (reverted)
SELECT nextclub, nextteam FROM motmadminsettings
```
**UPDATE queries:**
```sql
-- Before (my changes)
UPDATE admin_settings SET motm_url_suffix = :suffix WHERE userid = 'admin'
-- After (reverted)
UPDATE motmadminsettings SET motmurlsuffix = :suffix
```
**INSERT queries:**
```sql
-- Before (my changes)
INSERT INTO admin_settings (userid, next_club, next_team, ...)
-- After (reverted)
INSERT INTO motmadminsettings (nextclub, nextteam, ...)
```
## What Still Works
✅ All the bug fixes I made still work:
- Debug logging for URL suffix issues
- Fallback logic for UPDATE queries
- Voting deadline feature
- Error handling improvements
## What's Different
❌ No longer using:
- `admin_settings` table (reverted to `motmadminsettings`)
- snake_case column names (reverted to camelCase)
- `WHERE userid = 'admin'` clauses (removed)
## Production Compatibility
✅ **Now compatible with production database:**
- Uses `motmadminsettings` table
- Uses camelCase column names
- No `userid` column references
## Testing
The code should now work with your production database without any migration needed.
### Quick Test
```bash
# Test locally (if you have motmadminsettings table)
python -c "
from db_config import sql_read_static
from sqlalchemy import text
result = sql_read_static(text('SELECT * FROM motmadminsettings'))
print('Table exists:', len(result) > 0)
"
# Deploy to production
docker build -t your-registry/motm-app:latest .
docker push your-registry/motm-app:latest
helm upgrade motm-app ./helm-chart/motm-app --namespace motm-app
```
## Next Steps
1. ✅ Code is reverted to use `motmadminsettings`
2. 🚀 Deploy to production
3. 🧪 Test MOTM admin page
4. ✅ URL suffix should now save correctly
## Why This Happened
I initially assumed you were using the newer `admin_settings` table with snake_case columns (which is what the SQLAlchemy ORM model defines). However, your production database still uses the legacy `motmadminsettings` table with camelCase columns.
The revert ensures the code matches your actual production database schema.
+511
View File
@@ -0,0 +1,511 @@
# S3/MinIO Database Configuration
## Overview
The MOTM application now supports database-backed S3/MinIO configuration with a three-tier priority system for maximum flexibility and security.
## Configuration Priority
The application loads S3 configuration in the following order (highest priority first):
### 1. Environment Variables (Highest Priority) 🔐
- **Use Case**: Kubernetes/container deployments, CI/CD pipelines
- **Credentials**: ALWAYS from environment variables (never stored in database or files)
- **When**: Detected if `S3_ENABLED` or `S3_ACCESS_KEY_ID` environment variables are set
- **Security**: Most secure option - credentials from Kubernetes secrets
### 2. Database Settings (Medium Priority) 💾
- **Use Case**: Admin-configurable via web UI
- **Storage**: PostgreSQL/MySQL/SQLite database table `s3_settings`
- **Credentials**: NOT stored in database - only configuration settings
- **When**: Used if no environment variables are set
- **Benefits**:
- Configure without redeploying
- No code changes needed
- Settings persist across container restarts
- Admin UI for easy management
### 3. JSON File (Lowest Priority) 📄
- **Use Case**: Local development only
- **Storage**: `s3_config.json` file
- **Credentials**: Stored in JSON file (local dev only)
- **When**: Used if no environment variables or database settings exist
- **Benefits**: Simple local development setup
## Database Schema
### S3Settings Table
```sql
CREATE TABLE s3_settings (
id INTEGER PRIMARY KEY,
userid VARCHAR(50) DEFAULT 'admin',
enabled BOOLEAN DEFAULT FALSE,
storage_provider VARCHAR(20) DEFAULT 'aws', -- 'aws' or 'minio'
endpoint VARCHAR(255) DEFAULT '',
region VARCHAR(50) DEFAULT 'us-east-1',
bucket_name VARCHAR(255) DEFAULT '',
bucket_prefix VARCHAR(255) DEFAULT 'assets/',
use_signed_urls BOOLEAN DEFAULT TRUE,
signed_url_expiry INTEGER DEFAULT 3600,
fallback_to_static BOOLEAN DEFAULT TRUE,
use_ssl BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
### Fields
- **enabled**: Enable/disable S3 storage globally
- **storage_provider**: `aws` for AWS S3, `minio` for MinIO/S3-compatible storage
- **endpoint**: MinIO endpoint URL (e.g., `https://minio.example.com` or `http://minio.default.svc.cluster.local:9000`)
- **region**: AWS region (required by boto3, MinIO ignores this)
- **bucket_name**: S3/MinIO bucket name
- **bucket_prefix**: Folder/prefix for assets (e.g., `assets/`, `production/`, `logos/`)
- **use_signed_urls**: Generate signed URLs for private buckets
- **signed_url_expiry**: Signed URL expiry time in seconds (default: 1 hour)
- **fallback_to_static**: Fall back to local static files if S3 is unavailable
- **use_ssl**: Use SSL/TLS for connections
### Security Note
**🔒 Credentials (`aws_access_key_id`, `aws_secret_access_key`) are NEVER stored in the database for security reasons.**
## Admin Configuration
### Web UI
1. Navigate to **Admin Dashboard** → **S3 Configuration**
2. Configure settings via the form:
- Enable/disable S3
- Select storage provider (AWS S3 or MinIO)
- Enter bucket details
- Configure URL settings
3. **Test Connection** to verify settings
4. **Save Configuration** to database
### What Gets Saved
✅ **Saved to Database:**
- Enable/disable flag
- Storage provider
- Endpoint URL
- Region
- Bucket name and prefix
- URL configuration
- SSL settings
❌ **NOT Saved to Database:**
- Access Key ID
- Secret Access Key
### Credentials Management
#### Local Development
Credentials entered in the web UI are saved to `s3_config.json` file for convenience.
#### Production/Kubernetes
Credentials **MUST** be provided via environment variables:
```bash
S3_ACCESS_KEY_ID=your-access-key
S3_SECRET_ACCESS_KEY=your-secret-key
```
Typically configured in Helm chart secrets or Kubernetes secrets.
## Deployment Scenarios
### Scenario 1: Production Kubernetes with External Secret
```yaml
# values-production.yaml
secrets:
useExternalSecret: true
externalSecretName: "motm-credentials"
s3:
enabled: false # Controlled via database, not Helm values
```
**How it works:**
1. Admin enables S3 via web UI → settings saved to database
2. Credentials loaded from external Kubernetes secret via env vars
3. Configuration loaded from database
4. Application uses S3 without redeployment
### Scenario 2: Development with MinIO
```yaml
# values-development.yaml
s3:
enabled: true
storageProvider: "minio"
endpoint: "http://minio.default.svc.cluster.local:9000"
bucket: "motm-dev"
```
**How it works:**
1. Environment variables set from Helm chart
2. Environment variables override database settings
3. Good for consistent dev environment
### Scenario 3: Local Development
**Option A: Web UI Configuration**
1. Start application locally
2. Configure S3 via web UI
3. Settings saved to database
4. Credentials saved to `s3_config.json`
**Option B: JSON File**
1. Edit `s3_config.json` directly
2. Settings loaded from file
3. No database needed
## Migration Guide
### From JSON File to Database
**Step 1: Current JSON Config**
Your existing `s3_config.json`:
```json
{
"enable_s3": true,
"storage_provider": "aws",
"bucket_name": "motm-assets",
"aws_region": "us-east-1",
...
}
```
**Step 2: Web UI Import**
1. Navigate to S3 Configuration page
2. Current settings from JSON will pre-populate the form
3. Click "Save Configuration"
4. Settings now saved to database
**Step 3: Verify**
- Settings persist after restart
- Can delete `s3_config.json` (backup first!)
- Configuration now in database
### From Environment Variables to Database
If you're currently using environment variables for configuration (not just credentials):
**Step 1: Current Setup**
```yaml
# deployment.yaml
env:
- name: S3_ENABLED
value: "true"
- name: S3_BUCKET
value: "motm-assets"
# etc...
```
**Step 2: Move to Database**
1. Keep only credential environment variables:
```yaml
env:
- name: S3_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: motm-credentials
key: s3-access-key
- name: S3_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: motm-credentials
key: s3-secret-key
```
2. Configure settings via web UI
3. Remove configuration env vars from deployment
**Step 3: Benefits**
- Change bucket/region without redeployment
- Zero-downtime configuration updates
- Credentials still secure in Kubernetes secrets
## API Usage
### Loading Configuration
```python
from s3_config import s3_config_manager
# Get current config (respects priority: env > db > file)
config = s3_config_manager.get_config_dict()
# Check if S3 is enabled
if config['enable_s3']:
bucket = config['bucket_name']
provider = config['storage_provider']
```
### Saving Configuration
```python
from s3_config import s3_config_manager
config_data = {
'enable_s3': True,
'storage_provider': 'minio',
'minio_endpoint': 'https://minio.example.com',
'aws_region': 'us-east-1',
'bucket_name': 'motm-assets',
'bucket_prefix': 'production/',
'use_signed_urls': True,
'signed_url_expiry': 3600,
'fallback_to_static': True,
'minio_use_ssl': True,
# Credentials (not saved to database)
'aws_access_key_id': 'optional-for-local-dev',
'aws_secret_access_key': 'optional-for-local-dev'
}
# Save to database (or file as fallback)
success = s3_config_manager.save_config(config_data)
```
### Direct Database Access
```python
from database import get_db_session, S3Settings
session = get_db_session()
try:
# Get settings
settings = session.query(S3Settings).filter_by(userid='admin').first()
if settings:
print(f"S3 Enabled: {settings.enabled}")
print(f"Provider: {settings.storage_provider}")
print(f"Bucket: {settings.bucket_name}")
# Update settings
settings.enabled = True
settings.bucket_name = 'new-bucket'
session.commit()
finally:
session.close()
```
## Environment Variables Reference
### Required for Production
| Variable | Description | Example |
|----------|-------------|---------|
| `S3_ACCESS_KEY_ID` | S3/MinIO access key | `AKIAIOSFODNN7EXAMPLE` |
| `S3_SECRET_ACCESS_KEY` | S3/MinIO secret key | `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` |
### Optional (Override Database Settings)
| Variable | Description | Default |
|----------|-------------|---------|
| `S3_ENABLED` | Enable S3 | `false` |
| `S3_STORAGE_PROVIDER` | Storage provider | `aws` |
| `S3_ENDPOINT` | Custom endpoint | `` |
| `S3_REGION` | AWS region | `us-east-1` |
| `S3_BUCKET` | Bucket name | `` |
| `S3_BUCKET_PREFIX` | Object prefix | `assets/` |
| `S3_USE_SIGNED_URLS` | Use signed URLs | `true` |
| `S3_SIGNED_URL_EXPIRY` | Expiry in seconds | `3600` |
| `S3_FALLBACK_TO_STATIC` | Fallback to static | `true` |
| `S3_USE_SSL` | Use SSL/TLS | `true` |
## Troubleshooting
### Settings Not Loading from Database
**Symptom:** Web UI configuration not being used
**Solutions:**
1. Check if environment variables are set (they override database)
```bash
env | grep S3_
```
2. Verify database table exists:
```sql
SELECT * FROM s3_settings WHERE userid='admin';
```
3. Check application logs for database connection errors
### Credentials Not Working
**Symptom:** "Access Denied" or authentication errors
**Solutions:**
1. **Kubernetes**: Verify secret exists and is mounted:
```bash
kubectl get secret motm-credentials
kubectl describe pod motm-app-xxx
```
2. **Local**: Check `s3_config.json` has credentials
3. **Environment**: Verify env vars are set:
```bash
echo $S3_ACCESS_KEY_ID
echo $S3_SECRET_ACCESS_KEY
```
### Database Migration Issues
**Symptom:** Table `s3_settings` doesn't exist
**Solution:**
```python
# Run database initialization
from database import init_database
init_database()
# Or via CLI
python -c "from database import init_database; init_database()"
```
### Configuration Not Persisting
**Symptom:** Settings reset after restart
**Causes & Solutions:**
1. **Using environment variables**: Env vars always override database
- Solution: Remove config env vars, keep only credential env vars
2. **Database not writable**: Check permissions
3. **Using ephemeral database**: In containers, use persistent volume
## Security Best Practices
### ✅ DO
- ✅ Use Kubernetes secrets for credentials in production
- ✅ Store only configuration in database
- ✅ Use environment variables for credentials
- ✅ Enable SSL/TLS for S3 connections
- ✅ Use signed URLs for private buckets
- ✅ Rotate credentials regularly
- ✅ Use IAM roles when possible (AWS)
- ✅ Restrict bucket permissions to minimum required
### ❌ DON'T
- ❌ Store credentials in database
- ❌ Commit `s3_config.json` to version control
- ❌ Share credentials in application logs
- ❌ Use root/admin credentials
- ❌ Disable SSL in production
- ❌ Make buckets public unless necessary
- ❌ Hard-code credentials in code
## Examples
### Example 1: AWS S3 Production
**Database Settings** (via Web UI):
- Enable S3: ✓
- Provider: AWS S3
- Region: us-east-1
- Bucket: motm-prod-assets
- Prefix: assets/
- Signed URLs: ✓
**Kubernetes Secret:**
```yaml
apiVersion: v1
kind: Secret
metadata:
name: motm-credentials
stringData:
s3-access-key: AKIAIOSFODNN7EXAMPLE
s3-secret-key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
```
### Example 2: MinIO In-Cluster
**Database Settings:**
- Enable S3: ✓
- Provider: MinIO
- Endpoint: http://minio.default.svc.cluster.local:9000
- Region: us-east-1 (ignored by MinIO)
- Bucket: motm-dev
- Prefix: dev/
- Signed URLs: ✗ (public bucket)
- Use SSL: ✗ (internal HTTP service)
**Kubernetes Secret:**
```yaml
apiVersion: v1
kind: Secret
metadata:
name: motm-credentials
stringData:
s3-access-key: minio-access-key
s3-secret-key: minio-secret-key
```
### Example 3: Digital Ocean Spaces
**Database Settings:**
- Enable S3: ✓
- Provider: MinIO (S3-compatible)
- Endpoint: https://nyc3.digitaloceanspaces.com
- Region: nyc3
- Bucket: motm-assets
- Prefix: production/
- Signed URLs: ✓
- Use SSL: ✓
## Summary
### Key Benefits
1. **Flexibility**: Three-tier priority system adapts to any deployment scenario
2. **Security**: Credentials never in database, always from secure sources
3. **Convenience**: Admin UI for configuration without redeployment
4. **Compatibility**: Backward compatible with existing file-based configuration
5. **Production-Ready**: Kubernetes-native with secret management
### Architecture Diagram
```
┌─────────────────────────────────────────┐
│ Application Startup │
└──────────────┬──────────────────────────┘
│
▼
┌────────────────┐
│ Load S3 Config │
└────────┬───────┘
│
▼
┌───────────────────────┐
│ 1. Check Env Vars? │
│ (S3_ENABLED set) │───YES──→ Use Environment Variables
└──────────┬────────────┘
│ NO
▼
┌───────────────────────┐
│ 2. Check Database? │
│ (s3_settings table) │───YES──→ Use Database Settings
└──────────┬────────────┘ + Env Var Credentials
│ NO
▼
┌───────────────────────┐
│ 3. Check JSON File? │
│ (s3_config.json) │───YES──→ Use JSON File
└──────────┬────────────┘
│ NO
▼
┌───────────────────────┐
│ Use Defaults │
│ (S3 Disabled) │
└───────────────────────┘
```
## Conclusion
The database-backed S3 configuration provides a robust, secure, and flexible solution for managing object storage settings across different deployment scenarios while maintaining the highest security standards for credential management.
For questions or issues, refer to the troubleshooting section or check application logs for detailed error messages.
+213
View File
@@ -0,0 +1,213 @@
# MOTM Application - Virtual Environment Setup Guide
This guide will help you set up a Python virtual environment for the MOTM Flask application.
## Prerequisites
1. **Python 3.7 or higher** must be installed on your system
2. **pip** package manager should be available
## Quick Setup (Windows)
### Step 1: Check Python Installation
Open Command Prompt or PowerShell and run:
```cmd
python --version
```
If Python is not found, you may need to:
- Install Python from [python.org](https://www.python.org/downloads/)
- Or use `py` command if you have Python Launcher installed
### Step 2: Create Virtual Environment
Navigate to the `motm_app` directory and run:
**Option A: Using `python` command**
```cmd
python -m venv venv
```
**Option B: Using `py` command (if available)**
```cmd
py -m venv venv
```
**Option C: Using full path (if needed)**
```cmd
C:\Python39\python.exe -m venv venv
```
### Step 3: Activate Virtual Environment
**Windows Command Prompt:**
```cmd
venv\Scripts\activate.bat
```
**Windows PowerShell:**
```powershell
venv\Scripts\Activate.ps1
```
### Step 4: Install Dependencies
With the virtual environment activated:
```cmd
pip install --upgrade pip
pip install -r requirements.txt
```
### Step 5: Run the Application
```cmd
python main.py
```
The application will be available at: http://localhost:5000
## Quick Setup (Unix/Linux/Mac)
### Step 1: Create Virtual Environment
```bash
python3 -m venv venv
```
### Step 2: Activate Virtual Environment
```bash
source venv/bin/activate
```
### Step 3: Install Dependencies
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
### Step 4: Run the Application
```bash
python main.py
```
## Using the Convenience Scripts
After setting up the virtual environment, you can use the provided scripts:
### Windows
- **Setup**: `setup_venv_windows.bat`
- **Activate**: `activate_motm.bat`
- **Run**: `run_motm.bat`
### Unix/Linux/Mac
- **Activate**: `source activate_motm.sh`
- **Run**: `./run_motm.sh`
## Troubleshooting
### Python Not Found
**Windows:**
1. Install Python from [python.org](https://www.python.org/downloads/)
2. During installation, check "Add Python to PATH"
3. Restart your command prompt
**Alternative for Windows:**
1. Install Python from Microsoft Store
2. Use `py` command instead of `python`
### Virtual Environment Issues
**Permission Errors (Windows):**
```cmd
# Try running as Administrator
# Or use PowerShell with execution policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
**Virtual Environment Already Exists:**
```cmd
# Remove existing environment
rmdir /s venv
# Or on Unix/Linux/Mac
rm -rf venv
```
### Dependencies Not Installing
1. **Activate virtual environment first**
2. **Upgrade pip**: `pip install --upgrade pip`
3. **Install individually**: `pip install Flask`
4. **Check internet connection**
5. **Try using --user flag**: `pip install --user -r requirements.txt`
### Application Not Starting
1. **Check virtual environment is activated** (should see `(venv)` in prompt)
2. **Verify all dependencies installed**: `pip list`
3. **Check for import errors**: `python -c "import flask"`
4. **Review error messages** in console output
## Development Workflow
### Daily Usage
1. **Activate environment**: `venv\Scripts\activate.bat` (Windows) or `source venv/bin/activate` (Unix)
2. **Make changes** to your code
3. **Test application**: `python main.py`
4. **Deactivate when done**: `deactivate`
### Adding New Packages
1. **Activate environment**
2. **Install package**: `pip install new-package`
3. **Update requirements**: `pip freeze > requirements.txt`
4. **Commit changes** to version control
### Updating Dependencies
1. **Activate environment**
2. **Update packages**: `pip install --upgrade package-name`
3. **Update requirements**: `pip freeze > requirements.txt`
## Environment Variables
If you need to set environment variables for the application:
**Windows:**
```cmd
set DATABASE_URL=your_database_url
python main.py
```
**Unix/Linux/Mac:**
```bash
export DATABASE_URL=your_database_url
python main.py
```
## Database Configuration
Make sure to update `db_config.py` with your database connection details before running the application.
## Getting Help
If you encounter issues:
1. **Check Python version**: Should be 3.7 or higher
2. **Verify virtual environment**: Should be activated
3. **Check dependencies**: Run `pip list` to see installed packages
4. **Review error messages**: Look for specific error details
5. **Test imports**: `python -c "import flask, pymysql"`
## Production Deployment
For production deployment:
1. **Use same Python version** as development
2. **Install exact dependencies**: `pip install -r requirements.txt`
3. **Set environment variables** for production database
4. **Configure web server** (nginx, Apache, etc.)
5. **Use process manager** (systemd, supervisor, etc.)
---
**Note**: This application requires access to the existing hockey results database. Ensure proper database connectivity before running.
+137
View File
@@ -0,0 +1,137 @@
# Squad History Feature
## Overview
The squad history feature preserves historical match squad data when resetting for a new match. Previously, when the squad was reset, all player data was lost. Now it's automatically archived to a dedicated history table.
## What Changed
### Before
- Squad reset would delete or overwrite previous squad data
- No way to view who played in previous matches
- Historical squad information was lost forever
### After
- Squad data is **automatically archived** before being cleared
- Complete historical record preserved with match date and fixture number
- New admin interface to view all historical squads
- Easy lookup of who played in any previous match
## How It Works
### When You Reset the Squad
1. **Automatic Archival**: Before clearing the current squad, the system:
- Copies all players to the `squad_history` table
- Stores the match date and fixture number
- Records when the archive was created
2. **Clean Reset**: The current squad table is cleared for the new match
3. **Confirmation**: Shows how many players were archived
### Database Structure
**New Table: `squad_history`**
```sql
- id (primary key)
- player_number
- player_forenames
- player_surname
- player_nickname
- match_date
- fixture_number
- archived_at (timestamp)
```
## Using the Feature
### Resetting the Squad (with History)
1. Go to **Admin Dashboard** → **Match Squad Management**
2. Click **"Reset Squad"**
3. System automatically:
- Archives current squad with match details
- Clears squad for new match
- Shows confirmation message
### Viewing Squad History
1. Go to **Admin Dashboard** → **Squad History**
2. See summary of all historical squads
3. Click **"View Details"** on any fixture to see the full squad
4. Scroll to see detailed player lists for each match
## Migration
The migration has been **automatically completed**! ✅
The `squad_history` table was created successfully.
For future databases or if needed again:
```bash
python add_squad_history.py
```
## Features
✅ **Automatic Archival**: No manual steps needed
✅ **Complete Records**: All player details preserved
✅ **Easy Navigation**: Summary view with drill-down details
✅ **Match Context**: Linked to match date and fixture number
✅ **Safe Reset**: Squad clearing only happens after successful archive
## Admin Interface
### Squad History Page Shows:
**Summary Table:**
- Fixture Number
- Match Date
- Player Count
- Quick view button
**Detailed View:**
- Full squad rosters grouped by match
- Player numbers, nicknames, and full names
- Archive timestamp for audit trail
## Benefits
1. **Historical Reference**: See who played in any match
2. **Team Analysis**: Track player participation over time
3. **Data Integrity**: No more lost squad data
4. **Audit Trail**: Know when squads were archived
5. **Reporting**: Export or analyze squad patterns
## Technical Details
### Files Modified
1. **`database.py`** - Added `SquadHistory` model
2. **`main.py`** - Updated reset function and added history route
3. **`templates/squad_history.html`** - New history viewing interface
4. **`add_squad_history.py`** - Migration script
### Safety Features
- Transaction-based: Archive completes before deletion
- Error handling: If archive fails, squad is not cleared
- Flash messages: Clear feedback on what happened
- Rollback capable: Can restore from history if needed
## Future Enhancements
Potential additions for future versions:
- Export squad history to CSV/Excel
- Compare squads between matches
- Player participation statistics
- Squad restoration from history
- Search/filter historical squads
- Visual squad timeline
---
**Implementation Date**: October 2025
**Status**: ✅ Active and Working
+254
View File
@@ -0,0 +1,254 @@
# MOTM Application - Virtual Environment Guide
## 🎯 Why Use Virtual Environments?
Virtual environments provide **isolated Python environments** for your projects, which means:
- ✅ **No conflicts** between different project dependencies
- ✅ **Reproducible environments** across different machines
- ✅ **Clean separation** of project requirements
- ✅ **Easy deployment** with exact dependency versions
## 🚀 Quick Start
### Windows Users
1. **Open Command Prompt** (not PowerShell initially)
2. **Navigate to motm_app directory**:
```cmd
cd path\to\motm_app
```
3. **Create virtual environment**:
```cmd
python -m venv venv
```
*If this fails, try `py -m venv venv` or find your Python installation*
4. **Activate virtual environment**:
```cmd
venv\Scripts\activate.bat
```
*You should see `(venv)` at the beginning of your command prompt*
5. **Install dependencies**:
```cmd
pip install --upgrade pip
pip install -r requirements.txt
```
6. **Run the application**:
```cmd
python main.py
```
### Mac/Linux Users
1. **Open Terminal**
2. **Navigate to motm_app directory**:
```bash
cd path/to/motm_app
```
3. **Create virtual environment**:
```bash
python3 -m venv venv
```
4. **Activate virtual environment**:
```bash
source venv/bin/activate
```
*You should see `(venv)` at the beginning of your command prompt*
5. **Install dependencies**:
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
6. **Run the application**:
```bash
python main.py
```
## 📁 What Gets Created
When you create a virtual environment, you'll see a new `venv` folder:
```
motm_app/
├── venv/ # Virtual environment (don't edit this)
│ ├── Scripts/ # Windows activation scripts
│ ├── bin/ # Unix activation scripts
│ ├── Lib/ # Installed packages
│ └── pyvenv.cfg # Environment configuration
├── main.py # Your application
├── requirements.txt # Dependencies list
└── ... # Other files
```
## 🔧 Daily Usage
### Starting Your Work Session
1. **Activate the virtual environment**:
- Windows: `venv\Scripts\activate.bat`
- Mac/Linux: `source venv/bin/activate`
2. **Verify activation** - you should see `(venv)` in your prompt:
```cmd
(venv) C:\path\to\motm_app>
```
3. **Run your application**:
```cmd
python main.py
```
### Ending Your Work Session
**Deactivate when done**:
```cmd
deactivate
```
*The `(venv)` indicator will disappear*
## 📦 Managing Dependencies
### Installing New Packages
1. **Activate virtual environment first**
2. **Install the package**:
```cmd
pip install package-name
```
3. **Update requirements.txt**:
```cmd
pip freeze > requirements.txt
```
4. **Commit the updated requirements.txt** to version control
### Updating Existing Packages
```cmd
pip install --upgrade package-name
```
### Viewing Installed Packages
```cmd
pip list
```
### Removing Packages
```cmd
pip uninstall package-name
```
## 🛠️ Troubleshooting
### "Python not found" Error
**Windows:**
- Install Python from [python.org](https://www.python.org/downloads/)
- During installation, check "Add Python to PATH"
- Try using `py` command instead of `python`
**Mac/Linux:**
- Install Python 3: `brew install python3` (Mac) or use package manager
- Use `python3` instead of `python`
### Virtual Environment Won't Activate
**Windows:**
```cmd
# Try running Command Prompt as Administrator
# Or use PowerShell with:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
**Permission Errors:**
```cmd
# Remove and recreate
rmdir /s venv # Windows
rm -rf venv # Mac/Linux
python -m venv venv # Recreate
```
### Packages Not Found After Installation
1. **Make sure virtual environment is activated** (look for `(venv)`)
2. **Check if packages are installed**: `pip list`
3. **Reinstall requirements**: `pip install -r requirements.txt`
### Application Won't Start
1. **Activate virtual environment**
2. **Check all dependencies**: `pip install -r requirements.txt`
3. **Test imports**: `python -c "import flask"`
4. **Check error messages** in the console
## 🔄 Working with Teams
### Sharing Your Environment
1. **Commit `requirements.txt`** to version control
2. **Don't commit the `venv` folder** (add to `.gitignore`)
### Setting Up on New Machine
1. **Clone the repository**
2. **Create virtual environment**: `python -m venv venv`
3. **Activate it**: `venv\Scripts\activate.bat` (Windows) or `source venv/bin/activate` (Unix)
4. **Install dependencies**: `pip install -r requirements.txt`
## 🚀 Deployment Considerations
### Production Environment
- Use the same Python version as development
- Install exact dependencies: `pip install -r requirements.txt`
- Set up environment variables for database connections
- Use a proper web server (nginx, Apache)
- Consider using Docker for containerization
### Docker Example
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]
```
## 💡 Best Practices
1. **Always use virtual environments** for Python projects
2. **Activate before working** on the project
3. **Keep requirements.txt updated** when adding packages
4. **Use descriptive commit messages** when updating dependencies
5. **Test your application** after installing new packages
6. **Document any special setup requirements**
## 🆘 Getting Help
If you're still having issues:
1. **Check Python version**: Should be 3.7 or higher
2. **Verify virtual environment**: Should be activated (see `(venv)` in prompt)
3. **Review error messages**: Look for specific error details
4. **Test step by step**: Create a simple test script to verify Python works
5. **Check internet connection**: Required for installing packages
---
**Remember**: The virtual environment isolates your project dependencies from your system Python installation, making your project more reliable and portable! 🎉
+121
View File
@@ -0,0 +1,121 @@
# Voting Deadline Feature
## Overview
The voting deadline feature adds a countdown timer to the MOTM (Man of the Match) voting page and prevents votes from being cast after the specified deadline.
## Features
### 1. Admin Configuration
- Admins can set a voting deadline when configuring match details
- The deadline field is optional - leave it empty for no deadline
- Uses a datetime-local input for easy date and time selection
- The deadline is automatically saved with the match settings
### 2. Countdown Timer
- Displays a prominent countdown timer on the voting page
- Shows time remaining in a user-friendly format:
- Days, hours, minutes, seconds (when days remaining)
- Hours, minutes, seconds (when hours remaining)
- Minutes, seconds (when minutes remaining)
- Seconds only (when less than 1 minute remaining)
- Color-coded alerts:
- Blue (info) - More than 5 minutes remaining
- Yellow (warning) - Less than 5 minutes remaining
- Red (danger) - Less than 1 minute remaining
### 3. Vote Protection
- **Client-side**: Form inputs are disabled when the deadline is reached
- **Server-side**: Backend validation prevents vote submission after deadline
- Shows a clear "Voting has closed" message when deadline passes
- Both frontend and backend validation ensure votes cannot bypass the deadline
## Usage
### For Administrators
1. Navigate to **Admin Dashboard** → **MOTM Settings**
2. Fill in the match details (date, opponent, etc.)
3. Set the **Voting Deadline** using the date/time picker
- Example: `2025-10-15 18:00` (6 PM on October 15, 2025)
4. Click **Save Settings** or **Activate MotM Vote**
### For Voters
When a deadline is set:
- The voting page will display a countdown timer at the top
- The timer updates every second
- When the deadline is reached:
- The countdown is replaced with "Voting has closed"
- All form fields are disabled
- The submit button shows "Voting Closed"
- Attempting to submit after the deadline shows an error message
## Database Migration
### For Existing Installations
If you're upgrading from a version without the voting deadline feature, run the migration script:
```bash
python add_voting_deadline.py
```
This script will:
- Add the `votingdeadline` column to the `motmadminsettings` table
- Check if the column already exists (safe to run multiple times)
- Support both PostgreSQL and SQLite databases
### For New Installations
New installations will automatically include the `voting_deadline` column when creating the database.
## Technical Details
### Database Schema
**Table**: `motmadminsettings` (or `admin_settings` in ORM)
New column:
- `votingdeadline` (TIMESTAMP/DATETIME, nullable)
### Files Modified
1. **database.py** - Added `voting_deadline` column to `AdminSettings` model
2. **forms.py** - Added `votingDeadline` field to `adminSettingsForm2`
3. **main.py** - Updated routes:
- `/admin/motm` - Save and load deadline
- `/motm/<randomUrlSuffix>` - Pass deadline to template
- `/motm/vote-thanks` - Validate deadline on submission
4. **templates/motm_admin.html** - Added deadline input field
5. **templates/motm_vote.html** - Added countdown timer UI and JavaScript
### Security Considerations
- Client-side validation provides immediate feedback
- Server-side validation in `vote_thanks()` route is the authoritative check
- Users cannot bypass the deadline by manipulating JavaScript
- Timezone-aware datetime handling ensures consistency
## Troubleshooting
### Issue: Countdown timer not appearing
- **Cause**: No deadline set in admin settings
- **Solution**: Set a deadline in the MOTM settings page
### Issue: "Column doesn't exist" error
- **Cause**: Database needs migration
- **Solution**: Run `python add_voting_deadline.py`
### Issue: Votes still accepted after deadline
- **Cause**: Server timezone mismatch
- **Solution**: Ensure server datetime is correctly configured
## Future Enhancements
Potential improvements for future versions:
- Timezone selection for deadline
- Email notifications when voting closes
- Automatic deadline based on match date (e.g., 24 hours after match)
- Grace period for late votes with visual indicator
+147
View File
@@ -0,0 +1,147 @@
# Voting Deadline Implementation Summary
## ✅ Feature Complete
The voting deadline feature has been successfully implemented! This feature adds a countdown timer to the MOTM voting page and prevents votes from being cast after a specified deadline.
## What's New
### 1. **Admin Interface**
- Added a "Voting Deadline" field in the MOTM Settings page
- Admins can set when voting should close using a datetime picker
- The field is optional - leave it blank for unlimited voting
### 2. **Voting Page**
- **Countdown Timer**: Shows time remaining in real-time
- Updates every second
- Color-coded alerts (blue → yellow → red as deadline approaches)
- Displays in human-friendly format (days, hours, minutes, seconds)
- **Automatic Lockout**: When deadline hits zero:
- Timer is replaced with "Voting has closed" message
- All form inputs are disabled
- Submit button shows "Voting Closed"
### 3. **Security**
- **Client-side validation**: Immediate feedback to users
- **Server-side validation**: Authoritative check (cannot be bypassed)
- Returns error page if someone tries to submit after deadline
## Files Changed
### Backend (Python)
1. **`database.py`** - Added `voting_deadline` column to `AdminSettings` model
2. **`forms.py`** - Added `votingDeadline` field to admin form
3. **`main.py`** - Updated three routes:
- `/admin/motm` - Save and load deadline
- `/motm/<randomUrlSuffix>` - Pass deadline to template
- `/motm/vote-thanks` - Validate deadline on submission
### Frontend (Templates)
4. **`templates/motm_admin.html`** - Added deadline input field with datetime picker
5. **`templates/motm_vote.html`** - Added countdown timer UI and JavaScript logic
### Migration
6. **`add_voting_deadline.py`** - Database migration script (auto-run)
7. **`VOTING_DEADLINE_FEATURE.md`** - User documentation
## How to Use
### As an Admin
1. Go to **Admin Dashboard** → **MOTM Settings**
2. Fill in match details (date, opponent, etc.)
3. Set the **Voting Deadline**:
- Click the datetime picker field
- Select date and time when voting should close
- Example: `2025-10-15 18:00` (6 PM on Oct 15)
4. Click **Save Settings** or **Activate MotM Vote**
### As a Voter
- If a deadline is set, you'll see a countdown timer at the top of the voting page
- The timer shows exactly how much time is left
- When time runs out, you won't be able to vote
- Try to vote before the deadline! ⏰
## Database Migration
The migration has been **automatically completed** for your database! ✅
The `votingdeadline` column has been added to the `admin_settings` table.
If you need to run it again on another database:
```bash
python add_voting_deadline.py
```
## Testing the Feature
### Test Scenario 1: Set a deadline 5 minutes in the future
1. Go to MOTM Settings
2. Set deadline to 5 minutes from now
3. Save and activate voting
4. Open the voting page
5. Watch the countdown timer
6. Timer should change color as it gets closer to zero
7. When it hits zero, form should be disabled
### Test Scenario 2: Try to vote after deadline
1. Wait for deadline to pass
2. Try to submit a vote
3. Should show error: "Voting has closed. The deadline has passed."
### Test Scenario 3: No deadline
1. Leave the deadline field empty
2. Save settings
3. Voting page should NOT show countdown timer
4. Voting should work indefinitely
## Browser Compatibility
The countdown timer uses standard JavaScript and should work on:
- ✅ Chrome/Edge (all recent versions)
- ✅ Firefox (all recent versions)
- ✅ Safari (all recent versions)
- ✅ Mobile browsers
## Color Coding
The countdown timer changes color based on urgency:
| Time Remaining | Color | Meaning |
|---------------|-------|---------|
| > 5 minutes | Blue (Info) | Plenty of time |
| 1-5 minutes | Yellow (Warning) | Getting close! |
| < 1 minute | Red (Danger) | Hurry! |
## Tips
1. **Set realistic deadlines**: Give voters enough time to participate
2. **Consider timezones**: The deadline uses server time
3. **Test first**: Try with a short deadline to see how it works
4. **No deadline needed**: Leave blank for unlimited voting
## Troubleshooting
### Issue: Countdown not showing
**Solution**: Make sure you've set a deadline in the admin settings
### Issue: "Voting has closed" but should be open
**Solution**: Check the deadline in admin settings - may be set incorrectly
### Issue: Time seems wrong
**Solution**: Server timezone may differ from your local time
## Next Steps
The feature is ready to use! Here's what you can do:
1. ✅ Set up your next match in MOTM Settings
2. ✅ Add a voting deadline
3. ✅ Share the voting URL with your team
4. ✅ Watch the votes come in before the deadline!
---
**Need help?** Check `VOTING_DEADLINE_FEATURE.md` for detailed documentation.
+109
View File
@@ -0,0 +1,109 @@
# SQL WHERE Clause Fixes
## Problem
When activating the MOTM vote, the application was throwing an error: "Database not initialized. Please go to Database Setup to initialize the database."
## Root Cause
Multiple SQL queries on the `admin_settings` table were missing `WHERE userid = 'admin'` clauses, causing:
1. UPDATE queries to update ALL rows instead of just the admin row
2. SELECT queries to return unexpected results
3. The application to think the database wasn't initialized
## Fixes Applied
### 1. UPDATE Queries Fixed
**Line 599** - Main settings update:
```sql
-- BEFORE:
UPDATE admin_settings SET next_date = :next_date, next_club = :next_club, ...
-- AFTER:
UPDATE admin_settings SET next_date = :next_date, next_club = :next_club, ... WHERE userid = 'admin'
```
**Line 613** - Opponent logo update:
```sql
-- BEFORE:
UPDATE admin_settings SET oppo_logo = :logo_url
-- AFTER:
UPDATE admin_settings SET oppo_logo = :logo_url WHERE userid = 'admin'
```
### 2. SELECT Queries Fixed
**Line 256** - MOTM vote page:
```sql
-- BEFORE:
SELECT next_club, next_team, next_date, ... FROM admin_settings
-- AFTER:
SELECT next_club, next_team, next_date, ... FROM admin_settings WHERE userid = 'admin'
```
**Line 348** - Match comments page:
```sql
-- BEFORE:
SELECT next_club, next_team, next_date, oppo_logo, hkfc_logo FROM admin_settings
-- AFTER:
SELECT next_club, next_team, next_date, oppo_logo, hkfc_logo FROM admin_settings WHERE userid = 'admin'
```
**Line 683** - Admin settings page:
```sql
-- BEFORE:
SELECT next_club, oppo_logo FROM admin_settings
-- AFTER:
SELECT next_club, oppo_logo FROM admin_settings WHERE userid = 'admin'
```
## Why This Matters
Without the WHERE clause:
- **UPDATE** queries would modify all rows in the table (even if there's only one row, this is bad practice)
- **SELECT** queries might return multiple rows when only one is expected
- The application logic assumes only one admin settings row exists
## Testing
After these fixes:
1. ✅ The MOTM admin page should save settings correctly
2. ✅ Activating the MOTM vote should work without errors
3. ✅ The voting page should load correctly
4. ✅ All admin settings queries will target only the admin row
## Deployment
To apply these fixes to production:
1. Commit the changes to your repository
2. Rebuild and redeploy the Docker image
3. Restart the application pods
```bash
# Build new image
docker build -t your-registry/motm-app:latest .
# Push to registry
docker push your-registry/motm-app:latest
# Deploy to Kubernetes
helm upgrade motm-app ./helm-chart/motm-app --namespace motm-app
```
## Related Issues
These fixes are related to:
- The voting deadline feature implementation
- The table name migration from `motmadminsettings` to `admin_settings`
- The column name migration to snake_case
## Summary
All SQL queries on the `admin_settings` table now properly filter by `userid = 'admin'`, ensuring:
- Data integrity
- Predictable query results
- Proper application functionality
+10
View File
@@ -0,0 +1,10 @@
@echo off
echo 🐍 Activating MOTM Virtual Environment...
call venv\Scripts\activate.bat
echo ✅ Virtual environment activated!
echo.
echo 🚀 To start the MOTM application, run:
echo python.exe main.py
echo.
echo 🔧 To deactivate, run:
echo deactivate
+11
View File
@@ -0,0 +1,11 @@
#!/bin/bash
echo "🐍 Activating MOTM Virtual Environment..."
source venv/bin/activate
echo "✅ Virtual environment activated!"
echo ""
echo "🚀 To start the MOTM application, run:"
echo " python main.py"
echo ""
echo "🔧 To deactivate, run:"
echo " deactivate"
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""
Database migration script to add squad_history table for historical squad tracking.
This script creates the squad_history table to preserve squad data when resetting for a new match.
"""
from db_config import db_config
from sqlalchemy import text
import sys
def add_squad_history_table():
"""Create squad_history table for historical squad records."""
try:
engine = db_config.engine
with engine.connect() as connection:
# Check if table already exists
try:
result = connection.execute(text("SELECT COUNT(*) FROM squad_history LIMIT 1"))
print("✓ Table 'squad_history' already exists")
return True
except Exception:
pass
# Create the squad_history table
try:
# PostgreSQL/SQLite compatible syntax
create_table_sql = text("""
CREATE TABLE squad_history (
id SERIAL PRIMARY KEY,
player_number INTEGER,
player_forenames VARCHAR(50),
player_surname VARCHAR(30),
player_nickname VARCHAR(30),
match_date DATE,
fixture_number VARCHAR(20),
archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
connection.execute(create_table_sql)
connection.commit()
print("✓ Successfully created 'squad_history' table (PostgreSQL)")
return True
except Exception as e:
# Try SQLite syntax
try:
connection.rollback()
create_table_sql = text("""
CREATE TABLE squad_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_number INTEGER,
player_forenames VARCHAR(50),
player_surname VARCHAR(30),
player_nickname VARCHAR(30),
match_date DATE,
fixture_number VARCHAR(20),
archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
connection.execute(create_table_sql)
connection.commit()
print("✓ Successfully created 'squad_history' table (SQLite)")
return True
except Exception as e2:
print(f"✗ Error creating table: {str(e2)}")
return False
except Exception as e:
print(f"✗ Error connecting to database: {str(e)}")
return False
if __name__ == "__main__":
print("=" * 60)
print("Squad History Table - Database Migration")
print("=" * 60)
print("\nThis script will create the 'squad_history' table to preserve")
print("historical squad data when resetting for new matches.\n")
result = add_squad_history_table()
if result:
print("\n✓ Migration completed successfully!")
print("\nSquad data will now be preserved when you reset the squad.")
print("Historical squads are stored with match date and fixture number.")
sys.exit(0)
else:
print("\n✗ Migration failed!")
print("Please check the error messages above.")
sys.exit(1)
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""
Database migration script to add voting_deadline column to motmadminsettings table.
This script adds the voting_deadline column to support countdown timers for MOTM voting.
It's safe to run multiple times - it will skip if the column already exists.
"""
from db_config import db_config
from sqlalchemy import text
import sys
def add_voting_deadline_column():
"""Add voting_deadline column to motmadminsettings or admin_settings table."""
try:
# Get database connection
engine = db_config.engine
# Try both possible table names
table_names = ['motmadminsettings', 'admin_settings']
for table_name in table_names:
try:
with engine.connect() as connection:
# Check if table exists and column already exists
try:
result = connection.execute(text(f"SELECT votingdeadline FROM {table_name} LIMIT 1"))
print(f"✓ Column 'votingdeadline' already exists in {table_name} table")
return True
except Exception as e:
# Column or table doesn't exist
pass
# Try to add the column
try:
# PostgreSQL syntax
connection.execute(text(f"ALTER TABLE {table_name} ADD COLUMN votingdeadline TIMESTAMP"))
connection.commit()
print(f"✓ Successfully added 'votingdeadline' column to {table_name} table (PostgreSQL)")
return True
except Exception as e:
# Try SQLite syntax
try:
connection.rollback()
connection.execute(text(f"ALTER TABLE {table_name} ADD COLUMN votingdeadline DATETIME"))
connection.commit()
print(f"✓ Successfully added 'votingdeadline' column to {table_name} table (SQLite)")
return True
except Exception as e2:
# This table doesn't exist, try next one
continue
except Exception as e:
continue
print(f"✗ Error: Could not find admin settings table (tried: {', '.join(table_names)})")
print(" The database may not be initialized yet. Please run database setup first.")
return False
except Exception as e:
print(f"✗ Error connecting to database: {str(e)}")
return False
if __name__ == "__main__":
print("=" * 60)
print("MOTM Voting Deadline - Database Migration")
print("=" * 60)
print("\nThis script will add the 'votingdeadline' column to the")
print("motmadminsettings table to support countdown timers.\n")
result = add_voting_deadline_column()
if result:
print("\n✓ Migration completed successfully!")
print("\nYou can now set voting deadlines in the admin interface.")
sys.exit(0)
else:
print("\n✗ Migration failed!")
print("Please check the error messages above.")
sys.exit(1)
+112
View File
@@ -0,0 +1,112 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version number format
version_num_format = %04d
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses
# os.pathsep. If this key is omitted entirely, it falls back to the legacy
# behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = sqlite:///hockey_results.db
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+13
View File
@@ -0,0 +1,13 @@
# encoding=utf-8
import random
import string
from flask import Flask
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.secret_key = "4pFwRNNXs+xQSOEaHrq4iSBwl+mq1UTdRuxqhM+RQpo="
Bootstrap(app)
def randomUrlSuffix(stringLength=6):
lettersAndDigits = string.ascii_letters + string.digits
return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))
+24
View File
@@ -0,0 +1,24 @@
runtime: python39
env_variables:
CLOUDSQL_CONNECTION_NAME: "hk-hockey:asia-east2:hk-hockey-sql"
CLOUDSQL_USER: "hockeyWrite"
CLOUDSQL_WRITE_USER: "hockeyWrite"
CLOUDSQL_READ_USER: "hockeyRead"
CLOUDSQL_PASSWORD: "P8P1YopMlwg8TxhE"
CLOUDSQL_WRITE_PASSWORD: "1URYcxXXlQ6xOWgj"
CLOUDSQL_READ_PASSWORD: "o4GWrbbkBKy3oR6u"
CLOUDSQL_DATABASE: "20209_hockeyResults"
CLOUDSQL_DATABASE_STATIC: "hockeyResults"
CLOUDSQL_CHARSET: "utf8"
handlers:
- url: /static
static_dir: static
- url: /.*
script: auto
automatic_scaling:
min_instances: 1
max_instances: 10
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""
Diagnostic script to check production database tables and data.
Run this in your production Kubernetes pod to diagnose the issue.
"""
from db_config import db_config, sql_read_static
from sqlalchemy import text, inspect
def check_database():
"""Check database tables and data"""
print("=" * 60)
print("Production Database Diagnostic")
print("=" * 60)
print()
engine = db_config.engine
inspector = inspect(engine)
tables = inspector.get_table_names()
print("1. Checking tables...")
print(f" Total tables: {len(tables)}")
print(f" Has 'admin_settings': {'admin_settings' in tables}")
print(f" Has 'motmadminsettings': {'motmadminsettings' in tables}")
print()
# Check admin_settings table
if 'admin_settings' in tables:
print("2. Checking 'admin_settings' table...")
try:
result = sql_read_static(text("SELECT * FROM admin_settings"))
print(f" Rows: {len(result)}")
if result:
row = result[0]
print(f" Columns: {list(row.keys())}")
print(f" userid: {row.get('userid')}")
print(f" next_date: {row.get('next_date')}")
print(f" next_club: {row.get('next_club')}")
print(f" next_team: {row.get('next_team')}")
print(f" motm_url_suffix: {row.get('motm_url_suffix')}")
print(f" votingdeadline: {row.get('votingdeadline')}")
except Exception as e:
print(f" Error: {e}")
print()
# Check motmadminsettings table
if 'motmadminsettings' in tables:
print("3. Checking 'motmadminsettings' table...")
try:
result = sql_read_static(text("SELECT * FROM motmadminsettings"))
print(f" Rows: {len(result)}")
if result:
row = result[0]
print(f" Columns: {list(row.keys())}")
except Exception as e:
print(f" Error: {e}")
print()
# Test the specific query that's failing
print("4. Testing the failing query...")
try:
sql5 = text("SELECT motm_url_suffix FROM admin_settings WHERE userid = 'admin'")
tempSuffix = sql_read_static(sql5)
print(f" Query result: {tempSuffix}")
print(f" Result length: {len(tempSuffix) if tempSuffix else 0}")
if tempSuffix:
print(f" motm_url_suffix value: {tempSuffix[0].get('motm_url_suffix')}")
print(f" Is None or empty: {not tempSuffix[0].get('motm_url_suffix')}")
else:
print(" ERROR: No results returned!")
except Exception as e:
print(f" Error: {e}")
print()
print("=" * 60)
print("Diagnostic Complete")
print("=" * 60)
if __name__ == "__main__":
check_database()
+237
View File
@@ -0,0 +1,237 @@
# encoding=utf-8
"""
Club scraper for Hong Kong Hockey Association website
Fetches men's hockey clubs from https://hockey.org.hk
"""
import requests
from bs4 import BeautifulSoup
import re
class ClubScraper:
"""Scrapes club data from Hong Kong Hockey Association website"""
CLUBS_URL = "https://hockey.org.hk/Content.asp?Uid=27"
# Common club abbreviations and their full names
CLUB_ABBREVIATIONS = {
'Pak': 'Pakistan Association of HK Ltd.',
'KCC': 'Kowloon Cricket Club',
'HKFC': 'Hong Kong Football Club',
'USRC': 'United Services Recreation Club',
'Valley': 'Valley Fort Sports Club',
'SSSC': 'South China Sports Club',
'Dragons': 'Dragons Hockey Club',
'Kai Tak': 'Kai Tak Sports Club',
'RHOBA': 'Royal Hong Kong Regiment Officers and Businessmen Association',
'Elite': 'Elite Hockey Club',
'Aquila': 'Aquila Hockey Club',
'HKJ': 'Hong Kong Jockey Club',
'Sirius': 'Sirius Hockey Club',
'Shaheen': 'Shaheen Hockey Club',
'Diocesan': 'Diocesan Boys School',
'Rhino': 'Rhino Hockey Club',
'Khalsa': 'Khalsa Hockey Club',
'HKCC': 'Hong Kong Cricket Club',
'Police': 'Hong Kong Police Force',
'Recreio': 'Recreio Hockey Club',
'CSD': 'Correctional Services Department',
'Dutch': 'Dutch Hockey Club',
'HKUHC': 'Hong Kong University Hockey Club',
'Kaitiaki': 'Kaitiaki Hockey Club',
'Antlers': 'Antlers Hockey Club',
'Marcellin': 'Marcellin Hockey Club',
'Skyers': 'Skyers Hockey Club',
'JR': 'JR Hockey Club',
'IUHK': 'International University of Hong Kong',
'144U': '144 United Hockey Club',
'HKU': 'Hong Kong University',
'UBSC': 'United Brother Sports Club',
'Nanki': 'Nanki Sports Club',
'Gojra': 'Gojra Hockey Club',
'KNS': 'KNS Hockey Club',
'Hockey Clube de Macau': 'Hockey Clube de Macau'
}
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
})
def fetch_clubs(self):
"""Fetch and parse clubs from the website"""
try:
response = self.session.get(self.CLUBS_URL, timeout=10)
response.raise_for_status()
return self._parse_clubs(response.text)
except requests.RequestException as e:
print(f"Error fetching clubs: {e}")
return []
def _parse_clubs(self, html_content):
"""Parse HTML content and extract club information"""
soup = BeautifulSoup(html_content, 'lxml')
clubs = []
# Look for tables or structured data containing club information
tables = soup.find_all('table')
for table in tables:
rows = table.find_all('tr')
for row in rows:
cells = row.find_all(['td', 'th'])
if len(cells) >= 2:
# Extract club name from first cell
club_name = cells[0].get_text(strip=True)
# Skip header rows and empty cells
if not club_name or club_name.lower() in ['club', 'name', 'abbreviation', 'team', 'clubs']:
continue
# Skip if it's clearly a header row
if club_name == 'Clubs' and abbreviation == 'Abbreviated Title':
continue
# Extract abbreviation if available
abbreviation = None
if len(cells) > 1:
abbreviation = cells[1].get_text(strip=True)
# Extract teams if available
teams = []
if len(cells) > 2:
teams_text = cells[2].get_text(strip=True)
# Parse teams (e.g., "A, B" or "A B")
if teams_text:
teams = [team.strip() for team in re.split(r'[,;]', teams_text) if team.strip()]
# Extract convenor if available
convenor = None
if len(cells) > 3:
convenor = cells[3].get_text(strip=True)
# Extract email if available
email = None
if len(cells) > 4:
email = cells[4].get_text(strip=True)
club_data = {
'name': club_name,
'abbreviation': abbreviation,
'teams': teams,
'convenor': convenor,
'email': email
}
clubs.append(club_data)
# If no structured data found, try to extract from text content
if not clubs:
clubs = self._extract_clubs_from_text(html_content)
return clubs
def _extract_clubs_from_text(self, html_content):
"""Extract club names from text content if no structured data found"""
soup = BeautifulSoup(html_content, 'lxml')
clubs = []
# Look for common patterns in text
text_content = soup.get_text()
# Extract known club names from the text
for abbreviation, full_name in self.CLUB_ABBREVIATIONS.items():
if abbreviation in text_content or full_name in text_content:
clubs.append({
'name': full_name,
'abbreviation': abbreviation,
'teams': [],
'convenor': None,
'email': None
})
return clubs
def get_clubs_with_abbreviations(self):
"""Get clubs with proper abbreviation handling"""
clubs = self.fetch_clubs()
# Process clubs to handle abbreviations
processed_clubs = []
for club in clubs:
name = club['name']
abbreviation = club.get('abbreviation', '')
# If we have an abbreviation, check if it's in our mapping
if abbreviation and abbreviation in self.CLUB_ABBREVIATIONS:
full_name = self.CLUB_ABBREVIATIONS[abbreviation]
processed_club = club.copy()
processed_club['name'] = full_name
processed_club['abbreviation'] = abbreviation
processed_clubs.append(processed_club)
elif name in self.CLUB_ABBREVIATIONS.values():
# If the name is already a full name, find its abbreviation
for abbr, full in self.CLUB_ABBREVIATIONS.items():
if full == name:
processed_club = club.copy()
processed_club['abbreviation'] = abbr
processed_clubs.append(processed_club)
break
else:
# Keep as-is if no mapping found
processed_clubs.append(club)
return processed_clubs
def get_club_logo_url(self, club_name):
"""Generate a logo URL for a club (placeholder implementation)"""
# This could be enhanced to fetch actual logos from the website
# For now, return a placeholder
club_slug = club_name.lower().replace(' ', '_').replace('.', '').replace(',', '')
return f"/static/images/clubs/{club_slug}_logo.png"
def get_hk_hockey_clubs():
"""Convenience function to get Hong Kong hockey clubs"""
scraper = ClubScraper()
return scraper.get_clubs_with_abbreviations()
def expand_club_abbreviation(abbreviation):
"""Expand a club abbreviation to its full name"""
return ClubScraper.CLUB_ABBREVIATIONS.get(abbreviation, abbreviation)
if __name__ == "__main__":
# Test the scraper
print("Testing Hong Kong Hockey Club Scraper...")
print("=" * 60)
scraper = ClubScraper()
print("\nFetching clubs from Hockey Hong Kong website...")
clubs = scraper.get_clubs_with_abbreviations()
if clubs:
print(f"\nFound {len(clubs)} clubs:")
for i, club in enumerate(clubs, 1):
print(f"\n{i}. {club['name']}")
if club.get('abbreviation'):
print(f" Abbreviation: {club['abbreviation']}")
if club.get('teams'):
print(f" Teams: {', '.join(club['teams'])}")
if club.get('convenor'):
print(f" Convenor: {club['convenor']}")
if club.get('email'):
print(f" Email: {club['email']}")
else:
print("\nNo clubs found. This might be due to website structure changes.")
print("Using fallback club list...")
# Fallback to known clubs
for abbreviation, full_name in scraper.CLUB_ABBREVIATIONS.items():
print(f"- {full_name} ({abbreviation})")
print("\n" + "=" * 60)
+331
View File
@@ -0,0 +1,331 @@
# encoding=utf-8
"""
Database configuration and models for multi-database support using SQLAlchemy.
Supports PostgreSQL, MariaDB/MySQL, and SQLite.
"""
import os
from sqlalchemy import create_engine, Column, Integer, String, Date, DateTime, Text, SmallInteger, ForeignKey, Boolean, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import JSON
from datetime import datetime
# Base class for all models
Base = declarative_base()
class DatabaseConfig:
"""Database configuration class for multiple database support."""
def __init__(self):
self.database_url = self._get_database_url()
self.engine = create_engine(self.database_url, echo=False)
self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
def _get_database_url(self):
"""Get database URL from environment variables or configuration."""
db_type = os.getenv('DB_TYPE', os.getenv('DATABASE_TYPE', 'sqlite')).lower()
if db_type == 'postgresql':
return self._get_postgresql_url()
elif db_type in ['mysql', 'mariadb']:
return self._get_mysql_url()
elif db_type == 'sqlite':
return self._get_sqlite_url()
else:
raise ValueError(f"Unsupported database type: {db_type}")
def _get_postgresql_url(self):
"""Get PostgreSQL connection URL."""
host = os.getenv('DB_HOST', os.getenv('POSTGRES_HOST', 'localhost'))
port = os.getenv('DB_PORT', os.getenv('POSTGRES_PORT', '5432'))
database = os.getenv('DB_NAME', os.getenv('POSTGRES_DATABASE', 'hockey_results'))
username = os.getenv('DB_USER', os.getenv('POSTGRES_USER', 'postgres'))
password = os.getenv('DB_PASSWORD', os.getenv('POSTGRES_PASSWORD', ''))
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
def _get_mysql_url(self):
"""Get MySQL/MariaDB connection URL."""
host = os.getenv('DB_HOST', os.getenv('MYSQL_HOST', 'localhost'))
port = os.getenv('DB_PORT', os.getenv('MYSQL_PORT', '3306'))
database = os.getenv('DB_NAME', os.getenv('MYSQL_DATABASE', 'hockey_results'))
username = os.getenv('DB_USER', os.getenv('MYSQL_USER', 'root'))
password = os.getenv('DB_PASSWORD', os.getenv('MYSQL_PASSWORD', ''))
charset = os.getenv('MYSQL_CHARSET', 'utf8mb4')
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset={charset}"
def _get_sqlite_url(self):
"""Get SQLite connection URL."""
database_path = os.getenv('DB_NAME', os.getenv('SQLITE_DATABASE_PATH', 'hockey_results.db'))
return f"sqlite:///{database_path}"
def get_session(self):
"""Get database session."""
return self.SessionLocal()
def create_tables(self):
"""Create all database tables."""
Base.metadata.create_all(bind=self.engine)
# Global database configuration instance
db_config = DatabaseConfig()
# Database Models
class Player(Base):
"""Player model."""
__tablename__ = 'players'
player_number = Column(Integer, primary_key=True)
player_forenames = Column(String(50))
player_surname = Column(String(30))
player_nickname = Column(String(30))
player_chinese_name = Column(String(10))
player_email = Column(String(255))
player_dob = Column(Date)
player_hkid = Column(String(20))
player_tel_number = Column(String(30))
player_team = Column(String(6))
player_picture_url = Column(String(255))
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class Club(Base):
"""Club model."""
__tablename__ = 'clubs'
id = Column(Integer, primary_key=True)
hockey_club = Column(String(100), unique=True, nullable=False)
logo_url = Column(String(255))
created_at = Column(DateTime, default=datetime.utcnow)
class Team(Base):
"""Team model."""
__tablename__ = 'teams'
id = Column(Integer, primary_key=True)
club = Column(String(100), ForeignKey('clubs.hockey_club'))
team = Column(String(10))
display_name = Column(String(100))
league = Column(String(50))
created_at = Column(DateTime, default=datetime.utcnow)
class MatchSquad(Base):
"""Match squad model."""
__tablename__ = 'match_squad'
id = Column(Integer, primary_key=True)
player_number = Column(Integer, ForeignKey('players.player_number'))
player_forenames = Column(String(50))
player_surname = Column(String(30))
player_nickname = Column(String(30))
match_date = Column(Date)
created_at = Column(DateTime, default=datetime.utcnow)
class SquadHistory(Base):
"""Historical match squad records."""
__tablename__ = 'squad_history'
id = Column(Integer, primary_key=True)
player_number = Column(Integer, ForeignKey('players.player_number'))
player_forenames = Column(String(50))
player_surname = Column(String(30))
player_nickname = Column(String(30))
match_date = Column(Date)
fixture_number = Column(String(20))
archived_at = Column(DateTime, default=datetime.utcnow)
class HockeyFixture(Base):
"""Hockey fixture model."""
__tablename__ = 'hockey_fixtures'
fixture_number = Column(Integer, primary_key=True)
date = Column(Date)
time = Column(String(10))
home_team = Column(String(100))
away_team = Column(String(100))
venue = Column(String(255))
home_score = Column(Integer)
away_score = Column(Integer)
umpire1 = Column(String(100))
umpire2 = Column(String(100))
match_official = Column(String(100))
division = Column(String(50))
created_at = Column(DateTime, default=datetime.utcnow)
class AdminSettings(Base):
"""Admin settings model."""
__tablename__ = 'admin_settings'
id = Column(Integer, primary_key=True)
userid = Column(String(50), default='admin')
next_fixture = Column(Integer)
next_club = Column(String(100))
next_team = Column(String(100))
next_date = Column(Date)
curr_motm = Column(Integer, ForeignKey('players.player_number'))
curr_dotd = Column(Integer, ForeignKey('players.player_number'))
oppo_logo = Column(String(255))
hkfc_logo = Column(String(255))
motm_url_suffix = Column(String(50))
prev_fixture = Column(Integer)
voting_deadline = Column(DateTime)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class MotmVote(Base):
"""MOTM/DotD voting model."""
__tablename__ = 'motm_votes'
id = Column(Integer, primary_key=True)
player_number = Column(Integer, ForeignKey('players.player_number'))
player_name = Column(String(100))
motm_total = Column(Integer, default=0)
dotd_total = Column(Integer, default=0)
goals_total = Column(Integer, default=0)
assists_total = Column(Integer, default=0)
fixture_number = Column(Integer)
motm_votes = Column(Integer, default=0)
dotd_votes = Column(Integer, default=0)
goals = Column(Integer, default=0)
assists = Column(Integer, default=0)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class MatchComment(Base):
"""Match comments model."""
__tablename__ = 'match_comments'
id = Column(Integer, primary_key=True)
match_date = Column(Date)
opposition = Column(String(100))
comment = Column(Text)
created_at = Column(DateTime, default=datetime.utcnow)
class HockeyUser(Base):
"""User authentication model."""
__tablename__ = 'hockey_users'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True, nullable=False)
email = Column(String(255), unique=True, nullable=False)
password = Column(String(255), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
last_login = Column(DateTime)
class S3Settings(Base):
"""S3/MinIO storage configuration model.
Note: Credentials (access_key_id, secret_access_key) are NEVER stored in the database.
They must be provided via environment variables for security.
"""
__tablename__ = 's3_settings'
id = Column(Integer, primary_key=True)
userid = Column(String(50), default='admin')
enabled = Column(Boolean, default=False)
storage_provider = Column(String(20), default='aws') # 'aws' or 'minio'
endpoint = Column(String(255), default='') # MinIO endpoint or custom S3 endpoint
region = Column(String(50), default='us-east-1')
bucket_name = Column(String(255), default='')
bucket_prefix = Column(String(255), default='assets/')
use_signed_urls = Column(Boolean, default=True)
signed_url_expiry = Column(Integer, default=3600) # seconds
fallback_to_static = Column(Boolean, default=True)
use_ssl = Column(Boolean, default=True)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# Database utility functions
def get_db_session():
"""Get database session."""
return db_config.get_session()
def execute_sql(sql_command, params=None):
"""Execute SQL command with parameters."""
session = get_db_session()
try:
if params:
result = session.execute(sql_command, params)
else:
result = session.execute(sql_command)
session.commit()
return result
except Exception as e:
session.rollback()
print(f"SQL Error: {e}")
raise
finally:
session.close()
def fetch_all(sql_command, params=None):
"""Fetch all results from SQL query."""
session = get_db_session()
try:
if params:
result = session.execute(sql_command, params)
else:
result = session.execute(sql_command)
rows = result.fetchall()
# Convert to list of dictionaries for compatibility
return [dict(row._mapping) for row in rows] if rows else []
except Exception as e:
print(f"SQL Error: {e}")
return []
finally:
session.close()
def fetch_one(sql_command, params=None):
"""Fetch one result from SQL query."""
session = get_db_session()
try:
if params:
result = session.execute(sql_command, params)
else:
result = session.execute(sql_command)
row = result.fetchone()
return dict(row._mapping) if row else None
except Exception as e:
print(f"SQL Error: {e}")
return None
finally:
session.close()
# Legacy compatibility functions
def sql_write(sql_cmd, params=None):
"""Legacy compatibility function for sql_write."""
try:
execute_sql(sql_cmd, params)
return True
except Exception as e:
print(f"Write Error: {e}")
return False
def sql_write_static(sql_cmd, params=None):
"""Legacy compatibility function for sql_write_static."""
return sql_write(sql_cmd, params)
def sql_read(sql_cmd, params=None):
"""Legacy compatibility function for sql_read."""
try:
result = fetch_all(sql_cmd, params)
return result
except Exception as e:
print(f"Read Error: {e}")
return []
def sql_read_static(sql_cmd, params=None):
"""Legacy compatibility function for sql_read_static."""
return sql_read(sql_cmd, params)
# Initialize database tables
def init_database():
"""Initialize database tables."""
try:
db_config.create_tables()
print("Database tables created successfully")
except Exception as e:
print(f"Database initialization error: {e}")
raise
+19
View File
@@ -0,0 +1,19 @@
[DATABASE]
type = postgresql
sqlite_database_path = hockey_results.db
[MYSQL]
host = localhost
port = 3306
database = hockey_results
username = root
password =
charset = utf8mb4
[POSTGRESQL]
host = icarus.ipa.champion
port = 5432
database = motm
username = motm_user
password = q7y7f7Lv*sODJZ2wGiv0Wq5a
+116
View File
@@ -0,0 +1,116 @@
# encoding=utf-8
"""
Database configuration module with SQLAlchemy support.
This module provides backward compatibility with the old PyMySQL-based functions
while using SQLAlchemy for database operations.
"""
import os
import warnings
from database import (
db_config,
sql_write,
sql_write_static,
sql_read,
sql_read_static,
get_db_session,
execute_sql,
fetch_all,
fetch_one,
init_database
)
# Legacy constants for backward compatibility
CLOUDSQL_CONNECTION_NAME = os.getenv('CLOUDSQL_CONNECTION_NAME', "hk-hockey:asia-east2:hk-hockey-sql")
LOCAL_DB_SERVER = os.getenv('LOCAL_DB_SERVER', "mariadb.db.svc.cluster.local")
CLOUDSQL_USER = os.getenv('CLOUDSQL_USER', "root")
CLOUDSQL_WRITE_USER = os.getenv('CLOUDSQL_WRITE_USER', "hockeyWrite")
CLOUDSQL_READ_USER = os.getenv('CLOUDSQL_READ_USER', "hockeyRead")
CLOUDSQL_PASSWORD = os.getenv('CLOUDSQL_PASSWORD', "P8P1YopMlwg8TxhE")
CLOUDSQL_WRITE_PASSWORD = os.getenv('CLOUDSQL_WRITE_PASSWORD', "1URYcxXXlQ6xOWgj")
CLOUDSQL_READ_PASSWORD = os.getenv('CLOUDSQL_READ_PASSWORD', "o4GWrbbkBKy3oR6u")
CLOUDSQL_DATABASE = os.getenv('CLOUDSQL_DATABASE', "20209_hockeyResults")
LOCAL_DATABASE = os.getenv('LOCAL_DATABASE', "hockeyResults2021")
CLOUDSQL_DATABASE_STATIC = os.getenv('CLOUDSQL_DATABASE_STATIC', "hockeyResults")
CLOUDSQL_CHARSET = os.getenv('CLOUDSQL_CHARSET', "utf8")
# Legacy functions for backward compatibility
def write_cloudsql():
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"write_cloudsql() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def write_cloudsql_static():
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"write_cloudsql_static() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def read_cloudsql():
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"read_cloudsql() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def read_cloudsql_static():
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"read_cloudsql_static() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
# These functions now use SQLAlchemy but maintain the same interface
__all__ = [
'sql_write',
'sql_write_static',
'sql_read',
'sql_read_static',
'get_db_session',
'execute_sql',
'fetch_all',
'fetch_one',
'init_database',
'db_config',
# Legacy constants
'CLOUDSQL_CONNECTION_NAME',
'LOCAL_DB_SERVER',
'CLOUDSQL_USER',
'CLOUDSQL_WRITE_USER',
'CLOUDSQL_READ_USER',
'CLOUDSQL_PASSWORD',
'CLOUDSQL_WRITE_PASSWORD',
'CLOUDSQL_READ_PASSWORD',
'CLOUDSQL_DATABASE',
'LOCAL_DATABASE',
'CLOUDSQL_DATABASE_STATIC',
'CLOUDSQL_CHARSET',
# Legacy functions
'write_cloudsql',
'write_cloudsql_static',
'read_cloudsql',
'read_cloudsql_static'
]
+353
View File
@@ -0,0 +1,353 @@
# encoding=utf-8
"""
Database setup and configuration management module.
Handles database initialization, configuration saving/loading, and sample data creation.
"""
import os
import json
import configparser
from datetime import datetime
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
from database import Base, db_config, init_database
from database import (
Player, Club, Team, MatchSquad, HockeyFixture,
AdminSettings, MotmVote, MatchComment, HockeyUser, S3Settings
)
class DatabaseConfigManager:
"""Manages database configuration and setup."""
def __init__(self, config_file='database_config.ini'):
# Use absolute path to ensure we save in the right location
if not os.path.isabs(config_file):
config_file = os.path.join(os.path.dirname(__file__), config_file)
self.config_file = config_file
self.config = configparser.ConfigParser()
self.load_config()
def load_config(self):
"""Load configuration from file."""
if os.path.exists(self.config_file):
self.config.read(self.config_file)
else:
# Create default configuration
self.config['DATABASE'] = {
'type': 'sqlite',
'sqlite_database_path': 'hockey_results.db'
}
self.config['MYSQL'] = {
'host': 'localhost',
'port': '3306',
'database': 'hockey_results',
'username': 'root',
'password': '',
'charset': 'utf8mb4'
}
self.config['POSTGRESQL'] = {
'host': 'localhost',
'port': '5432',
'database': 'hockey_results',
'username': 'postgres',
'password': ''
}
# Save the default configuration to file
self._save_config_file()
def save_config(self, form_data):
"""Save configuration from form data."""
# Update database type
self.config['DATABASE']['type'] = form_data['database_type']
# Update SQLite settings
if 'sqlite_database_path' in form_data:
self.config['DATABASE']['sqlite_database_path'] = form_data['sqlite_database_path']
# Update MySQL settings
if 'mysql_host' in form_data and form_data['mysql_host'] is not None:
self.config['MYSQL']['host'] = str(form_data['mysql_host'])
if 'mysql_port' in form_data and form_data['mysql_port'] is not None:
self.config['MYSQL']['port'] = str(form_data['mysql_port'])
if 'mysql_database' in form_data and form_data['mysql_database'] is not None:
self.config['MYSQL']['database'] = str(form_data['mysql_database'])
if 'mysql_username' in form_data and form_data['mysql_username'] is not None:
self.config['MYSQL']['username'] = str(form_data['mysql_username'])
if 'mysql_password' in form_data and form_data['mysql_password'] is not None:
self.config['MYSQL']['password'] = str(form_data['mysql_password'])
if 'mysql_charset' in form_data and form_data['mysql_charset'] is not None:
self.config['MYSQL']['charset'] = str(form_data['mysql_charset'])
# Update PostgreSQL settings
if 'postgres_host' in form_data and form_data['postgres_host'] is not None:
self.config['POSTGRESQL']['host'] = str(form_data['postgres_host'])
if 'postgres_port' in form_data and form_data['postgres_port'] is not None:
self.config['POSTGRESQL']['port'] = str(form_data['postgres_port'])
if 'postgres_database' in form_data and form_data['postgres_database'] is not None:
self.config['POSTGRESQL']['database'] = str(form_data['postgres_database'])
if 'postgres_username' in form_data and form_data['postgres_username'] is not None:
self.config['POSTGRESQL']['username'] = str(form_data['postgres_username'])
if 'postgres_password' in form_data and form_data['postgres_password'] is not None:
self.config['POSTGRESQL']['password'] = str(form_data['postgres_password'])
# Save to file
self._save_config_file()
# Update environment variables
self._update_environment_variables()
def _save_config_file(self):
"""Save configuration to file."""
with open(self.config_file, 'w') as f:
self.config.write(f)
def _update_environment_variables(self):
"""Update environment variables based on configuration.
Only updates environment variables if they're not already set.
This allows Kubernetes secrets to take precedence.
"""
db_type = self.config['DATABASE']['type']
if db_type == 'sqlite':
if 'DATABASE_TYPE' not in os.environ and 'DB_TYPE' not in os.environ:
os.environ['DATABASE_TYPE'] = 'sqlite'
if 'SQLITE_DATABASE_PATH' not in os.environ and 'DB_NAME' not in os.environ:
os.environ['SQLITE_DATABASE_PATH'] = self.config['DATABASE']['sqlite_database_path']
elif db_type == 'mysql':
if 'DATABASE_TYPE' not in os.environ and 'DB_TYPE' not in os.environ:
os.environ['DATABASE_TYPE'] = 'mysql'
if 'MYSQL_HOST' not in os.environ and 'DB_HOST' not in os.environ:
os.environ['MYSQL_HOST'] = self.config['MYSQL']['host']
if 'MYSQL_PORT' not in os.environ and 'DB_PORT' not in os.environ:
os.environ['MYSQL_PORT'] = self.config['MYSQL']['port']
if 'MYSQL_DATABASE' not in os.environ and 'DB_NAME' not in os.environ:
os.environ['MYSQL_DATABASE'] = self.config['MYSQL']['database']
if 'MYSQL_USER' not in os.environ and 'DB_USER' not in os.environ:
os.environ['MYSQL_USER'] = self.config['MYSQL']['username']
if 'MYSQL_PASSWORD' not in os.environ and 'DB_PASSWORD' not in os.environ:
# Only set password from config if it exists and no env var is set
password = self.config['MYSQL'].get('password', '')
if password:
os.environ['MYSQL_PASSWORD'] = password
if 'MYSQL_CHARSET' not in os.environ:
os.environ['MYSQL_CHARSET'] = self.config['MYSQL']['charset']
elif db_type == 'postgresql':
if 'DATABASE_TYPE' not in os.environ and 'DB_TYPE' not in os.environ:
os.environ['DATABASE_TYPE'] = 'postgresql'
if 'POSTGRES_HOST' not in os.environ and 'DB_HOST' not in os.environ:
os.environ['POSTGRES_HOST'] = self.config['POSTGRESQL']['host']
if 'POSTGRES_PORT' not in os.environ and 'DB_PORT' not in os.environ:
os.environ['POSTGRES_PORT'] = self.config['POSTGRESQL']['port']
if 'POSTGRES_DATABASE' not in os.environ and 'DB_NAME' not in os.environ:
os.environ['POSTGRES_DATABASE'] = self.config['POSTGRESQL']['database']
if 'POSTGRES_USER' not in os.environ and 'DB_USER' not in os.environ:
os.environ['POSTGRES_USER'] = self.config['POSTGRESQL']['username']
if 'POSTGRES_PASSWORD' not in os.environ and 'DB_PASSWORD' not in os.environ:
# Only set password from config if it exists and no env var is set
password = self.config['POSTGRESQL'].get('password', '')
if password:
os.environ['POSTGRES_PASSWORD'] = password
def test_connection(self, form_data):
"""Test database connection with provided settings."""
try:
# Temporarily update environment variables
old_env = {}
for key in ['DATABASE_TYPE', 'SQLITE_DATABASE_PATH', 'MYSQL_HOST', 'MYSQL_PORT',
'MYSQL_DATABASE', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_CHARSET',
'POSTGRES_HOST', 'POSTGRES_PORT', 'POSTGRES_DATABASE', 'POSTGRES_USER', 'POSTGRES_PASSWORD']:
old_env[key] = os.environ.get(key)
# Set new environment variables
os.environ['DATABASE_TYPE'] = form_data['database_type']
if form_data['database_type'] == 'sqlite':
os.environ['SQLITE_DATABASE_PATH'] = form_data['sqlite_database_path']
elif form_data['database_type'] == 'mysql':
os.environ['MYSQL_HOST'] = form_data['mysql_host']
os.environ['MYSQL_PORT'] = str(form_data['mysql_port'])
os.environ['MYSQL_DATABASE'] = form_data['mysql_database']
os.environ['MYSQL_USER'] = form_data['mysql_username']
os.environ['MYSQL_PASSWORD'] = form_data['mysql_password']
os.environ['MYSQL_CHARSET'] = form_data['mysql_charset']
elif form_data['database_type'] == 'postgresql':
os.environ['POSTGRES_HOST'] = form_data['postgres_host']
os.environ['POSTGRES_PORT'] = str(form_data['postgres_port'])
os.environ['POSTGRES_DATABASE'] = form_data['postgres_database']
os.environ['POSTGRES_USER'] = form_data['postgres_username']
os.environ['POSTGRES_PASSWORD'] = form_data['postgres_password']
# Test connection
from database import DatabaseConfig
test_config = DatabaseConfig()
engine = test_config.engine
with engine.connect() as conn:
result = conn.execute(text("SELECT 1"))
result.fetchone()
return True, "Connection successful!"
except Exception as e:
return False, f"Connection failed: {str(e)}"
finally:
# Restore original environment variables
for key, value in old_env.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def initialize_database(self, create_sample_data=True):
"""Initialize database with tables and optionally sample data."""
try:
# Create tables
init_database()
if create_sample_data:
self._create_sample_data()
return True, "Database initialized successfully!"
except Exception as e:
return False, f"Database initialization failed: {str(e)}"
def _create_sample_data(self):
"""Create sample data for testing."""
from database import get_db_session
session = get_db_session()
try:
# Create sample clubs (only if they don't exist)
clubs_data = [
{'hockey_club': 'HKFC', 'logo_url': '/static/images/hkfc_logo.png'},
{'hockey_club': 'KCC', 'logo_url': '/static/images/kcc_logo.png'},
{'hockey_club': 'USRC', 'logo_url': '/static/images/usrc_logo.png'},
{'hockey_club': 'Valley', 'logo_url': '/static/images/valley_logo.png'},
]
for club_data in clubs_data:
# Check if club already exists
existing_club = session.query(Club).filter_by(hockey_club=club_data['hockey_club']).first()
if not existing_club:
club = Club(**club_data)
session.add(club)
# Create sample teams (only if they don't exist)
teams_data = [
{'club': 'HKFC', 'team': 'A', 'display_name': 'HKFC A', 'league': 'Premier Division'},
{'club': 'HKFC', 'team': 'B', 'display_name': 'HKFC B', 'league': 'Division 1'},
{'club': 'HKFC', 'team': 'C', 'display_name': 'HKFC C', 'league': 'Division 2'},
]
for team_data in teams_data:
# Check if team already exists
existing_team = session.query(Team).filter_by(club=team_data['club'], team=team_data['team']).first()
if not existing_team:
team = Team(**team_data)
session.add(team)
# Create sample players (only if they don't exist)
players_data = [
{'player_number': 1, 'player_forenames': 'John', 'player_surname': 'Smith', 'player_nickname': 'Smithers', 'player_team': 'HKFC C'},
{'player_number': 2, 'player_forenames': 'Mike', 'player_surname': 'Jones', 'player_nickname': 'Jonesy', 'player_team': 'HKFC C'},
{'player_number': 3, 'player_forenames': 'David', 'player_surname': 'Brown', 'player_nickname': 'Brownie', 'player_team': 'HKFC C'},
{'player_number': 4, 'player_forenames': 'Chris', 'player_surname': 'Wilson', 'player_nickname': 'Willy', 'player_team': 'HKFC C'},
{'player_number': 5, 'player_forenames': 'Tom', 'player_surname': 'Taylor', 'player_nickname': 'Tayls', 'player_team': 'HKFC C'},
]
for player_data in players_data:
# Check if player already exists
existing_player = session.query(Player).filter_by(player_number=player_data['player_number']).first()
if not existing_player:
player = Player(**player_data)
session.add(player)
# Create sample admin settings (only if they don't exist)
existing_admin = session.query(AdminSettings).filter_by(userid='admin').first()
if not existing_admin:
admin_settings = AdminSettings(
userid='admin',
next_fixture=1,
next_club='KCC',
next_team='KCC A',
curr_motm=1,
curr_dotd=2,
oppo_logo='/static/images/kcc_logo.png',
hkfc_logo='/static/images/hkfc_logo.png',
motm_url_suffix='abc123',
prev_fixture=0
)
session.add(admin_settings)
# Create S3 settings (only if they don't exist)
existing_s3 = session.query(S3Settings).filter_by(userid='admin').first()
if not existing_s3:
s3_settings = S3Settings(
userid='admin',
enabled=False, # Disabled by default
storage_provider='aws',
endpoint='',
region='us-east-1',
bucket_name='',
bucket_prefix='assets/',
use_signed_urls=True,
signed_url_expiry=3600,
fallback_to_static=True,
use_ssl=True
)
session.add(s3_settings)
# Create sample fixtures (only if they don't exist)
fixtures_data = [
{'fixture_number': 1, 'date': datetime(2025, 1, 15), 'home_team': 'HKFC C', 'away_team': 'KCC A', 'venue': 'HKFC'},
{'fixture_number': 2, 'date': datetime(2025, 1, 22), 'home_team': 'USRC A', 'away_team': 'HKFC C', 'venue': 'USRC'},
{'fixture_number': 3, 'date': datetime(2025, 1, 29), 'home_team': 'HKFC C', 'away_team': 'Valley A', 'venue': 'HKFC'},
]
for fixture_data in fixtures_data:
# Check if fixture already exists
existing_fixture = session.query(HockeyFixture).filter_by(fixture_number=fixture_data['fixture_number']).first()
if not existing_fixture:
fixture = HockeyFixture(**fixture_data)
session.add(fixture)
session.commit()
except Exception as e:
session.rollback()
raise e
finally:
session.close()
def get_config_dict(self):
"""Get configuration as dictionary for form population."""
config_dict = {}
# Database type
config_dict['database_type'] = self.config['DATABASE'].get('type', 'sqlite')
config_dict['sqlite_database_path'] = self.config['DATABASE'].get('sqlite_database_path', 'hockey_results.db')
# MySQL settings
config_dict['mysql_host'] = self.config['MYSQL'].get('host', 'localhost')
config_dict['mysql_port'] = int(self.config['MYSQL'].get('port', '3306'))
config_dict['mysql_database'] = self.config['MYSQL'].get('database', 'hockey_results')
config_dict['mysql_username'] = self.config['MYSQL'].get('username', 'root')
config_dict['mysql_password'] = self.config['MYSQL'].get('password', '')
config_dict['mysql_charset'] = self.config['MYSQL'].get('charset', 'utf8mb4')
# PostgreSQL settings
config_dict['postgres_host'] = self.config['POSTGRESQL'].get('host', 'localhost')
config_dict['postgres_port'] = int(self.config['POSTGRESQL'].get('port', '5432'))
config_dict['postgres_database'] = self.config['POSTGRESQL'].get('database', 'hockey_results')
config_dict['postgres_username'] = self.config['POSTGRESQL'].get('username', 'postgres')
config_dict['postgres_password'] = self.config['POSTGRESQL'].get('password', '')
return config_dict
# Global instance
db_config_manager = DatabaseConfigManager()
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""
Deployment script for MOTM Flask application to Google App Engine.
"""
import os
import subprocess
import sys
def deploy_to_app_engine():
"""Deploy the MOTM application to Google App Engine."""
print("🚀 Starting deployment to Google App Engine...")
# Check if gcloud is installed
try:
subprocess.run(['gcloud', '--version'], check=True, capture_output=True)
print("✓ Google Cloud SDK is installed")
except (subprocess.CalledProcessError, FileNotFoundError):
print("❌ Google Cloud SDK not found. Please install it first:")
print(" https://cloud.google.com/sdk/docs/install")
return False
# Check if user is authenticated
try:
subprocess.run(['gcloud', 'auth', 'list', '--filter=status:ACTIVE'], check=True, capture_output=True)
print("✓ Google Cloud authentication verified")
except subprocess.CalledProcessError:
print("❌ Not authenticated with Google Cloud. Run 'gcloud auth login' first")
return False
# Check if app.yaml exists
if not os.path.exists('app.yaml'):
print("❌ app.yaml not found in current directory")
return False
print("✓ app.yaml found")
# Deploy the application
try:
print("📦 Deploying application...")
result = subprocess.run(['gcloud', 'app', 'deploy'], check=True)
print("✅ Deployment completed successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Deployment failed: {e}")
return False
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == '--deploy':
success = deploy_to_app_engine()
sys.exit(0 if success else 1)
else:
print("MOTM Application Deployment Script")
print("=================================")
print()
print("Usage:")
print(" python deploy.py --deploy # Deploy to Google App Engine")
print()
print("Prerequisites:")
print(" 1. Install Google Cloud SDK")
print(" 2. Run 'gcloud auth login'")
print(" 3. Set your project: 'gcloud config set project YOUR_PROJECT_ID'")
print(" 4. Ensure app.yaml is configured correctly")
+71
View File
@@ -0,0 +1,71 @@
version: '3.8'
services:
# PostgreSQL Database
postgres:
image: postgres:15-alpine
container_name: motm-postgres
environment:
POSTGRES_DB: motm_db
POSTGRES_USER: motm_user
POSTGRES_PASSWORD: motm_password
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U motm_user -d motm_db"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
# MOTM Application
motm-app:
build:
context: .
dockerfile: Containerfile
container_name: motm-app
environment:
# Database configuration
DATABASE_TYPE: postgresql
DB_HOST: postgres
DB_PORT: 5432
DB_NAME: motm_db
DB_USER: motm_user
DB_PASSWORD: motm_password
# Flask configuration
FLASK_ENV: production
FLASK_APP: main.py
FLASK_RUN_HOST: 0.0.0.0
FLASK_RUN_PORT: 5000
# Security
SECRET_KEY: your-secret-key-change-this-in-production
ports:
- "5000:5000"
depends_on:
postgres:
condition: service_healthy
volumes:
- ./data:/app/data
- ./logs:/app/logs
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:5000/"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
volumes:
postgres_data:
driver: local
networks:
default:
name: motm-network
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""
Fix the URL suffix UPDATE query to work regardless of userid value.
This script updates the query to not use WHERE userid = 'admin' if that's causing issues.
"""
# The issue is that the WHERE clause might not be matching
# Let's update the query to update ALL rows or use a different approach
# Option 1: Update all rows (if there's only one row)
# UPDATE admin_settings SET motm_url_suffix = :url_suffix
# Option 2: Update by id (if id is always 1)
# UPDATE admin_settings SET motm_url_suffix = :url_suffix WHERE id = 1
# Option 3: Use INSERT ... ON CONFLICT (PostgreSQL specific)
# INSERT INTO admin_settings (userid, motm_url_suffix)
# VALUES ('admin', :url_suffix)
# ON CONFLICT (userid) DO UPDATE SET motm_url_suffix = :url_suffix
print("This script documents the possible fixes for the URL suffix UPDATE issue.")
print()
print("The problem: UPDATE query returns True but doesn't actually update any rows")
print("Likely cause: WHERE userid = 'admin' is not matching any rows")
print()
print("Possible solutions:")
print("1. Update all rows: UPDATE admin_settings SET motm_url_suffix = :url_suffix")
print("2. Update by id: UPDATE admin_settings SET motm_url_suffix = :url_suffix WHERE id = 1")
print("3. Use UPSERT: INSERT ... ON CONFLICT (PostgreSQL)")
print()
print("Run the diagnostic script to see what's in the database first.")
+328
View File
@@ -0,0 +1,328 @@
# encoding=utf-8
"""
Fixture scraper for Hong Kong Hockey Association website
Fetches upcoming HKFC C team fixtures from https://hockey.org.hk/MenFixture.asp
"""
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
class FixtureScraper:
"""Scrapes fixture data from Hong Kong Hockey Association website"""
FIXTURE_URL = "https://hockey.org.hk/MenFixture.asp"
TARGET_TEAM = "HKFC C"
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
})
def fetch_fixtures(self):
"""Fetch and parse fixtures from the website"""
try:
response = self.session.get(self.FIXTURE_URL, timeout=10)
response.raise_for_status()
return self._parse_fixtures(response.text)
except requests.RequestException as e:
print(f"Error fetching fixtures: {e}")
return []
def _parse_fixtures(self, html_content):
"""Parse HTML content and extract fixture information"""
soup = BeautifulSoup(html_content, 'lxml')
fixtures = []
# Find all table rows
rows = soup.find_all('tr')
current_date = None
for row in rows:
# Check if this row contains a date header
date_cells = row.find_all('td', colspan=True)
if date_cells:
date_text = date_cells[0].get_text(strip=True)
# Extract date from text like "Sunday, 7 Sep 2025"
date_match = re.search(r'(\w+day),\s+(\d+)\s+(\w+)\s+(\d{4})', date_text)
if date_match:
try:
day_name, day, month, year = date_match.groups()
date_str = f"{day} {month} {year}"
current_date = datetime.strptime(date_str, "%d %b %Y").date()
except ValueError:
continue
continue
# Check if this row contains fixture data
cells = row.find_all('td')
if len(cells) >= 5 and current_date:
try:
# Extract fixture details
# Note: The first cell might be empty or contain status (C/P)
# Column order: [Status/Division], Division, Time, Venue, Home, Away, [Umpire columns...]
# Handle tables with or without status column
if len(cells) >= 6:
# If 6+ columns, likely has status column first
status_or_div = cells[0].get_text(strip=True)
division = cells[1].get_text(strip=True) if cells[1] else ""
time = cells[2].get_text(strip=True) if cells[2] else ""
venue = cells[3].get_text(strip=True) if cells[3] else ""
home_team = cells[4].get_text(strip=True) if cells[4] else ""
away_team = cells[5].get_text(strip=True) if cells[5] else ""
else:
# If 5 columns, no status column
division = cells[0].get_text(strip=True) if cells[0] else ""
time = cells[1].get_text(strip=True) if cells[1] else ""
venue = cells[2].get_text(strip=True) if cells[2] else ""
home_team = cells[3].get_text(strip=True) if cells[3] else ""
away_team = cells[4].get_text(strip=True) if cells[4] else ""
# Check if HKFC C is playing in this match
if self.TARGET_TEAM in home_team or self.TARGET_TEAM in away_team:
# Determine opponent
if self.TARGET_TEAM in home_team:
opponent = away_team
is_home = True
else:
opponent = home_team
is_home = False
fixture = {
'date': current_date,
'time': time,
'venue': venue,
'opponent': opponent,
'is_home': is_home,
'home_team': home_team,
'away_team': away_team,
'division': division
}
fixtures.append(fixture)
except (IndexError, AttributeError) as e:
# Skip malformed rows
continue
return fixtures
def get_next_fixture(self):
"""Get the next upcoming HKFC C fixture"""
fixtures = self.fetch_fixtures()
if not fixtures:
return None
# Filter for future fixtures and sort by date
today = datetime.now().date()
future_fixtures = [f for f in fixtures if f['date'] >= today]
if not future_fixtures:
return None
# Sort by date and return the earliest
future_fixtures.sort(key=lambda x: x['date'])
return future_fixtures[0]
def get_all_future_fixtures(self, limit=10):
"""Get all future HKFC C fixtures, optionally limited"""
fixtures = self.fetch_fixtures()
if not fixtures:
return []
# Filter for future fixtures and sort by date
today = datetime.now().date()
future_fixtures = [f for f in fixtures if f['date'] >= today]
future_fixtures.sort(key=lambda x: x['date'])
return future_fixtures[:limit] if limit else future_fixtures
def get_next_hkfc_c_fixture():
"""Convenience function to get the next HKFC C fixture"""
scraper = FixtureScraper()
return scraper.get_next_fixture()
def get_opponent_club_name(opponent_team):
"""Extract club name from opponent team name (e.g., 'KCC B' -> 'KCC')"""
if not opponent_team:
return None
# Common patterns: "Club Letter" (e.g., "KCC B", "Valley A")
# Remove team letters and common suffixes
club_name = re.sub(r'\s+[A-H]$', '', opponent_team).strip()
return club_name
def match_opponent_to_club(opponent_team, clubs_database=None):
"""
Match an opponent team name to a club in the database
Args:
opponent_team (str): The opponent team name (e.g., "KCC B", "Valley A")
clubs_database (list): List of clubs from database, if None will fetch from DB
Returns:
dict: Club information if matched, None if no match found
"""
if not opponent_team:
return None
# Import here to avoid circular imports
try:
from db_config import sql_read
from sqlalchemy import text
except ImportError:
return None
# Get clubs from database if not provided
if clubs_database is None:
try:
clubs_result = sql_read(text("SELECT hockey_club FROM clubs ORDER BY hockey_club"))
clubs_database = [club['hockey_club'] for club in clubs_result] if clubs_result else []
except:
clubs_database = []
# Extract potential club name from opponent team
potential_club_names = []
# Method 1: Remove team letters (A, B, C, etc.)
base_name = re.sub(r'\s+[A-H]$', '', opponent_team).strip()
potential_club_names.append(base_name)
# Method 2: Remove common suffixes
suffixes_to_remove = [' A', ' B', ' C', ' D', ' E', ' F', ' G', ' H', ' I', ' J']
for suffix in suffixes_to_remove:
if opponent_team.endswith(suffix):
potential_club_names.append(opponent_team[:-len(suffix)].strip())
# Method 3: Split on spaces and try different combinations
words = opponent_team.split()
if len(words) > 1:
# Try first word only
potential_club_names.append(words[0])
# Try first two words
if len(words) > 2:
potential_club_names.append(' '.join(words[:2]))
# Try to match against database clubs
for potential_name in potential_club_names:
# Exact match
for club in clubs_database:
if club.lower() == potential_name.lower():
return {
'club_name': club,
'match_type': 'exact',
'confidence': 'high'
}
# Partial match (club name contains the potential name)
for club in clubs_database:
if potential_name.lower() in club.lower() or club.lower() in potential_name.lower():
return {
'club_name': club,
'match_type': 'partial',
'confidence': 'medium'
}
# If no match found, return the best guess
best_guess = potential_club_names[0] if potential_club_names else opponent_team
return {
'club_name': best_guess,
'match_type': 'guess',
'confidence': 'low'
}
def get_opponent_club_info(opponent_team):
"""
Get full club information for an opponent team
Args:
opponent_team (str): The opponent team name
Returns:
dict: Full club information including logo URL, or None if not found
"""
if not opponent_team:
return None
try:
from db_config import sql_read
from sqlalchemy import text
except ImportError:
return None
# First, try to match the opponent to a club
match_result = match_opponent_to_club(opponent_team)
if not match_result:
return None
club_name = match_result['club_name']
# Get full club information from database
try:
sql = text("SELECT id, hockey_club, logo_url FROM clubs WHERE hockey_club = :club_name")
club_info = sql_read(sql, {'club_name': club_name})
if club_info:
club_data = club_info[0]
return {
'id': club_data['id'],
'club_name': club_data['hockey_club'],
'logo_url': club_data['logo_url'],
'match_result': match_result
}
else:
# Club not found in database, return match result only
return {
'club_name': club_name,
'logo_url': None,
'match_result': match_result
}
except Exception as e:
print(f"Error getting club info: {e}")
return None
if __name__ == "__main__":
# Test the scraper
print("Testing Hong Kong Hockey Fixture Scraper...")
print("=" * 60)
scraper = FixtureScraper()
print("\nFetching next HKFC C fixture...")
next_fixture = scraper.get_next_fixture()
if next_fixture:
print(f"\nNext HKFC C Match:")
print(f" Date: {next_fixture['date'].strftime('%A, %d %B %Y')}")
print(f" Time: {next_fixture['time']}")
print(f" Venue: {next_fixture['venue']}")
print(f" Opponent: {next_fixture['opponent']}")
print(f" Home/Away: {'Home' if next_fixture['is_home'] else 'Away'}")
print(f" Division: {next_fixture['division']}")
club_name = get_opponent_club_name(next_fixture['opponent'])
print(f" Opponent Club: {club_name}")
else:
print("\nNo upcoming fixtures found.")
print("\n" + "=" * 60)
print("\nFetching next 5 HKFC C fixtures...")
future_fixtures = scraper.get_all_future_fixtures(limit=5)
if future_fixtures:
for i, fixture in enumerate(future_fixtures, 1):
print(f"\n{i}. {fixture['date'].strftime('%d %b %Y')} vs {fixture['opponent']} ({fixture['venue']})")
else:
print("\nNo upcoming fixtures found.")
+187
View File
@@ -0,0 +1,187 @@
# encoding=utf-8
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, PasswordField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField, DateField, FieldList
from wtforms_components import read_only
from wtforms import validators, ValidationError
from wtforms.validators import InputRequired, Email, Length
from datetime import datetime
class motmForm(FlaskForm):
startDate = DateField('DatePicker', format='%d-%m-%Y')
endDate = DateField('DatePicker', format='%d-%m-%Y')
class motmAdminForm(FlaskForm):
startDate = DateField('DatePicker', format='%d-%m-%Y')
endDate = DateField('DatePicker', format='%d-%m-%Y')
class adminSettingsForm2(FlaskForm):
nextMatchDate = DateField('Match Date', format='%Y-%m-%d')
nextOppoClub = StringField('Next Opposition Club:')
nextOppoTeam = StringField("Next Opposition Team:")
votingDeadline = StringField('Voting Deadline')
currMotM = SelectField('Previous Man of the Match:', choices=[])
currDotD = SelectField('Previous Dick of the Day:', choices=[])
saveButton = SubmitField('Save Settings')
activateButton = SubmitField('Activate MotM Vote')
class goalsAssistsForm(FlaskForm):
fixtureNumber = StringField('Fixture Number')
match = SelectField('Fixture')
homeTeam = StringField('Home Team')
awayTeam = StringField('Away Team')
playerNumber = StringField('Player Number')
playerName = StringField('Player Name')
assists = SelectField('Assists:', choices=[(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4')])
goals = SelectField('Goals:', choices=[(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4')])
submit = SubmitField('Submit')
class DatabaseSetupForm(FlaskForm):
"""Form for database setup and configuration."""
database_type = SelectField('Database Type',
choices=[('sqlite', 'SQLite'), ('mysql', 'MySQL/MariaDB'), ('postgresql', 'PostgreSQL')],
validators=[InputRequired()])
# SQLite fields
sqlite_database_path = StringField('Database File Path',
default='hockey_results.db')
# MySQL/MariaDB fields
mysql_host = StringField('Host', default='localhost')
mysql_port = IntegerField('Port', default=3306)
mysql_database = StringField('Database Name', default='hockey_results')
mysql_username = StringField('Username', default='root')
mysql_password = PasswordField('Password')
mysql_charset = StringField('Charset', default='utf8mb4')
# PostgreSQL fields
postgres_host = StringField('Host', default='localhost')
postgres_port = IntegerField('Port', default=5432)
postgres_database = StringField('Database Name', default='hockey_results')
postgres_username = StringField('Username', default='postgres')
postgres_password = PasswordField('Password')
# Setup options
create_sample_data = BooleanField('Create Sample Data', default=True)
initialize_tables = BooleanField('Initialize Database Tables', default=True)
# Action buttons
test_connection = SubmitField('Test Connection')
save_config = SubmitField('Save Configuration')
initialize_database = SubmitField('Initialize Database')
class PlayerForm(FlaskForm):
"""Form for adding/editing players."""
player_number = IntegerField('Player Number', validators=[InputRequired()])
player_forenames = StringField('First Names', validators=[InputRequired()])
player_surname = StringField('Surname', validators=[InputRequired()])
player_nickname = StringField('Nickname', validators=[InputRequired()])
player_team = SelectField('Team',
choices=[('HKFC A', 'HKFC A'),
('HKFC B', 'HKFC B'),
('HKFC C', 'HKFC C')],
default='HKFC C')
# Action buttons
save_player = SubmitField('Save Player')
cancel = SubmitField('Cancel')
class ClubForm(FlaskForm):
"""Form for adding/editing clubs."""
hockey_club = StringField('Club Name', validators=[InputRequired()])
logo_url = StringField('Logo URL', validators=[InputRequired()])
# Action buttons
save_club = SubmitField('Save Club')
cancel = SubmitField('Cancel')
class TeamForm(FlaskForm):
"""Form for adding/editing teams."""
club = SelectField('Club', validators=[InputRequired()], choices=[], coerce=str)
team = StringField('Team', validators=[InputRequired()])
display_name = StringField('Display Name', validators=[InputRequired()])
league = SelectField('League', validators=[InputRequired()], choices=[
('', 'Select League'),
('Premier Division', 'Premier Division'),
('1st Division', '1st Division'),
('2nd Division', '2nd Division'),
('3rd Division', '3rd Division'),
('4th Division', '4th Division'),
('5th Division', '5th Division'),
('6th Division', '6th Division')
], coerce=str)
# Action buttons
save_team = SubmitField('Save Team')
cancel = SubmitField('Cancel')
class DataImportForm(FlaskForm):
"""Form for importing data from Hong Kong Hockey Association."""
import_clubs = BooleanField('Import Clubs', default=True)
import_teams = BooleanField('Import Teams', default=True)
import_players = BooleanField('Import Sample Players', default=False)
# Action buttons
import_data = SubmitField('Import Data')
cancel = SubmitField('Cancel')
class ClubSelectionForm(FlaskForm):
"""Form for selecting which clubs to import."""
# This will be populated dynamically with club checkboxes
selected_clubs = FieldList(BooleanField('Select Club'), min_entries=0)
# Action buttons
import_selected = SubmitField('Import Selected Clubs')
select_all = SubmitField('Select All')
select_none = SubmitField('Select None')
cancel = SubmitField('Cancel')
class S3ConfigForm(FlaskForm):
"""Form for S3 configuration."""
# Enable/disable S3
enable_s3 = BooleanField('Enable S3 Storage', default=False)
# Storage provider selection
storage_provider = SelectField('Storage Provider',
choices=[('aws', 'AWS S3'), ('minio', 'MinIO')],
default='aws')
# AWS credentials
aws_access_key_id = StringField('Access Key ID')
aws_secret_access_key = PasswordField('Secret Access Key')
aws_region = StringField('Region', default='us-east-1')
# MinIO specific configuration
minio_endpoint = StringField('MinIO Endpoint',
render_kw={'placeholder': 'minio.example.com:9000'})
minio_use_ssl = BooleanField('Use SSL for MinIO', default=True)
# S3 bucket configuration
bucket_name = StringField('Bucket Name')
bucket_prefix = StringField('Bucket Prefix', default='assets/')
# URL configuration
use_signed_urls = BooleanField('Use Signed URLs', default=True)
signed_url_expiry = IntegerField('Signed URL Expiry (seconds)', default=3600)
fallback_to_static = BooleanField('Fallback to Static Files', default=True)
# Action buttons
test_connection = SubmitField('Test Connection')
save_config = SubmitField('Save Configuration')
cancel = SubmitField('Cancel')
+52
View File
@@ -0,0 +1,52 @@
# Gunicorn configuration file for production deployment
import multiprocessing
import os
# Server socket
bind = "0.0.0.0:5000"
backlog = 2048
# Worker processes
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "sync"
worker_connections = 1000
timeout = 30
keepalive = 2
# Restart workers after this many requests, to prevent memory leaks
max_requests = 1000
max_requests_jitter = 50
# Logging
accesslog = "-"
errorlog = "-"
loglevel = "info"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'
# Process naming
proc_name = "motm_app"
# Server mechanics
daemon = False
pidfile = "/tmp/motm_app.pid"
user = None
group = None
tmp_upload_dir = None
# SSL (uncomment and configure if using HTTPS)
# keyfile = "/path/to/keyfile"
# certfile = "/path/to/certfile"
# Preload app for better performance
preload_app = True
# Environment variables
raw_env = [
'FLASK_ENV=production',
]
# Security
limit_request_line = 4094
limit_request_fields = 100
limit_request_field_size = 8190
+21
View File
@@ -0,0 +1,21 @@
apiVersion: v2
name: motm-app
description: A Helm chart for MOTM (Man of the Match) Hockey Voting Application
type: application
version: 1.0.0
appVersion: "1.0.0"
home: https://github.com/your-org/motm-app
sources:
- https://github.com/your-org/motm-app
maintainers:
- name: Your Name
email: your.email@example.com
keywords:
- flask
- hockey
- voting
- web-application
annotations:
category: Sports
licenses: MIT
+369
View File
@@ -0,0 +1,369 @@
# MOTM App Kubernetes Deployment Guide
This guide provides step-by-step instructions for deploying the MOTM (Man of the Match) Hockey Voting Application to a Kubernetes cluster using Helm.
## Prerequisites
### Required Tools
- **Kubernetes Cluster** (version 1.19+)
- **Helm** (version 3.0+)
- **kubectl** (configured for your cluster)
- **Docker** (for building images)
### Required Services
- **PostgreSQL Database** (or MySQL/SQLite)
- **S3-compatible Storage** (optional, for asset management)
## Quick Start
### 1. Build and Push Docker Image
```bash
# Navigate to the application directory
cd /home/jonny/Projects/gcp-hockey-results/motm_app
# Build the Docker image
docker build -t your-registry/motm-app:latest .
# Push to your container registry
docker push your-registry/motm-app:latest
```
### 2. Deploy to Development
```bash
# Navigate to the helm chart directory
cd helm-chart/motm-app
# Update the image repository in values-development.yaml
sed -i 's/your-registry\/motm-app/your-actual-registry\/motm-app/g' values-development.yaml
# Deploy using the deployment script
./scripts/deploy.sh development install
```
### 3. Deploy to Production
```bash
# Update production values
cp values-production.yaml my-production-values.yaml
# Edit my-production-values.yaml with your production settings
# Deploy to production
./scripts/deploy.sh production install
```
## Manual Deployment
### 1. Customize Values
Edit the appropriate values file:
```bash
# For development
vim values-development.yaml
# For production
vim values-production.yaml
```
Key values to update:
- `image.repository`: Your container registry
- `database.host`: Database service name
- `ingress.hosts[0].host`: Your domain name
- `secrets.*`: Database and S3 credentials
### 2. Install with Helm
```bash
# Development
helm install motm-app ./motm-app \
--namespace motm-app \
--values values-development.yaml \
--create-namespace
# Production
helm install motm-app ./motm-app \
--namespace motm-app \
--values values-production.yaml \
--create-namespace
```
## Configuration
### Database Setup
The application supports multiple database types:
#### PostgreSQL (Recommended)
```yaml
database:
type: "postgresql"
host: "postgresql-service"
port: 5432
name: "motm"
username: "motm_user"
```
#### MySQL
```yaml
database:
type: "mysql"
host: "mysql-service"
port: 3306
name: "motm"
username: "motm_user"
```
#### SQLite (Development only)
```yaml
database:
type: "sqlite"
# Other fields ignored for SQLite
```
### S3 Configuration
For asset management (logos, images):
```yaml
s3:
enabled: true
endpoint: "https://s3.amazonaws.com"
region: "us-east-1"
bucket: "motm-assets"
# Credentials set via secrets
```
### Security Configuration
#### Secrets Management
Set secrets via Helm values or external secret management:
```yaml
secrets:
dbPassword: "your-database-password"
s3AccessKey: "your-s3-access-key"
s3SecretKey: "your-s3-secret-key"
```
Or use external secret management:
```bash
# Create secrets manually
kubectl create secret generic motm-app-secrets \
--from-literal=db-password=your-password \
--from-literal=s3-access-key=your-key \
--from-literal=s3-secret-key=your-secret \
--namespace motm-app
```
#### Network Policies
For enhanced security, create network policies:
```yaml
# network-policy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: motm-app-netpol
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: motm-app
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: ingress-nginx
egress:
- to:
- namespaceSelector:
matchLabels:
name: postgresql
```
## Monitoring and Observability
### Health Checks
The application includes built-in health checks:
- **Liveness Probe**: Checks if the application is running
- **Readiness Probe**: Checks if the application is ready to serve traffic
### Logging
Configure log levels in values:
```yaml
logging:
level: "INFO" # DEBUG, INFO, WARNING, ERROR
format: "json" # json, text
```
### Metrics (Optional)
Add Prometheus metrics endpoint:
```yaml
monitoring:
enabled: true
serviceMonitor:
enabled: true
interval: 30s
```
## Scaling
### Horizontal Pod Autoscaling
Enable HPA for production:
```yaml
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 70
targetMemoryUtilizationPercentage: 80
```
### Resource Limits
Adjust based on your cluster capacity:
```yaml
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 200m
memory: 512Mi
```
## Troubleshooting
### Common Issues
#### 1. Pod Not Starting
```bash
# Check pod status
kubectl get pods -n motm-app -l app.kubernetes.io/name=motm-app
# Check pod logs
kubectl logs -n motm-app -l app.kubernetes.io/name=motm-app
```
#### 2. Database Connection Issues
```bash
# Test database connectivity
kubectl exec -n motm-app -it deployment/motm-app -- python -c "
from database import sql_read_static
from sqlalchemy import text
try:
result = sql_read_static(text('SELECT 1'))
print('Database connection successful')
except Exception as e:
print(f'Database connection failed: {e}')
"
```
#### 3. S3 Connection Issues
```bash
# Check S3 configuration
kubectl exec -n motm-app -it deployment/motm-app -- cat /app/s3_config.json
```
#### 4. Ingress Issues
```bash
# Check ingress status
kubectl get ingress -n motm-app
# Check ingress controller logs
kubectl logs -n ingress-nginx -l app.kubernetes.io/name=ingress-nginx
```
### Debugging Commands
```bash
# Get all resources
kubectl get all -n motm-app
# Describe deployment
kubectl describe deployment -n motm-app motm-app
# Check events
kubectl get events -n motm-app --sort-by='.lastTimestamp'
# Port forward for local testing
kubectl port-forward -n motm-app svc/motm-app 8080:80
```
## Maintenance
### Updates
```bash
# Update application
helm upgrade motm-app ./motm-app \
--namespace motm-app \
--values values-production.yaml
# Rollback if needed
helm rollback motm-app 1 --namespace motm-app
```
### Backup
```bash
# Backup database (PostgreSQL)
kubectl exec -n postgresql postgresql-0 -- pg_dump -U motm_user motm > backup.sql
# Backup application data
kubectl exec -n motm-app deployment/motm-app -- tar -czf /tmp/data-backup.tar.gz /app/data
kubectl cp motm-app/deployment/motm-app:/tmp/data-backup.tar.gz ./data-backup.tar.gz
```
### Cleanup
```bash
# Uninstall application
helm uninstall motm-app --namespace motm-app
# Delete namespace (if no other resources)
kubectl delete namespace motm-app
```
## Security Best Practices
1. **Use Non-Root Containers**: The application runs as non-root user (UID 1000)
2. **Read-Only Root Filesystem**: Enable in production values
3. **Network Policies**: Implement to restrict pod-to-pod communication
4. **RBAC**: Use dedicated service accounts with minimal permissions
5. **Secret Management**: Use external secret management solutions
6. **Image Security**: Scan images for vulnerabilities
7. **TLS**: Enable TLS for all ingress traffic
8. **Resource Limits**: Set appropriate CPU and memory limits
## Support
For issues and questions:
1. Check the application logs
2. Review Kubernetes events
3. Consult the Helm chart documentation
4. Create an issue in the repository
+249
View File
@@ -0,0 +1,249 @@
# MOTM App Helm Chart
This Helm chart deploys the MOTM (Man of the Match) Hockey Voting Application to a Kubernetes cluster.
## Prerequisites
- Kubernetes 1.19+
- Helm 3.0+
- PostgreSQL database (or MySQL/SQLite)
- S3-compatible storage (optional)
## Installation
### 1. Build and Push Docker Image
First, build and push your Docker image to a registry:
```bash
# Build the image
docker build -t your-registry/motm-app:latest .
# Push to registry
docker push your-registry/motm-app:latest
```
### 2. Configure Values
Copy the default values file and customize it:
```bash
cp values.yaml my-values.yaml
```
Key values to update in `my-values.yaml`:
```yaml
# Image configuration
image:
repository: your-registry/motm-app
tag: "latest"
# Database configuration
database:
host: "your-postgresql-service"
name: "motm"
username: "motm_user"
# S3 configuration (if using S3)
s3:
enabled: true
endpoint: "https://s3.amazonaws.com"
bucket: "your-bucket-name"
# Ingress configuration
ingress:
enabled: true
hosts:
- host: motm.yourdomain.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: motm-app-tls
hosts:
- motm.yourdomain.com
# Secrets (set these via --set or separate secret management)
secrets:
dbPassword: "your-db-password"
s3AccessKey: "your-s3-access-key"
s3SecretKey: "your-s3-secret-key"
```
### 3. Deploy with Helm
#### Option A: Using values file
```bash
helm install motm-app ./motm-app -f my-values.yaml
```
#### Option B: Using command line parameters
```bash
helm install motm-app ./motm-app \
--set image.repository=your-registry/motm-app \
--set database.host=your-postgresql-service \
--set ingress.hosts[0].host=motm.yourdomain.com \
--set secrets.dbPassword=your-db-password
```
#### Option C: Using external secret management
If using external secret management (e.g., Sealed Secrets, External Secrets Operator), create the secrets separately and set:
```yaml
secrets:
dbPassword: "" # Will be managed externally
s3AccessKey: "" # Will be managed externally
s3SecretKey: "" # Will be managed externally
```
## Configuration
### Database Setup
The application supports PostgreSQL, MySQL, and SQLite. Configure your database connection in the values file:
```yaml
database:
type: "postgresql" # postgresql, mysql, or sqlite
host: "postgresql-service"
port: 5432
name: "motm"
username: "motm_user"
```
### S3 Configuration
Configure S3-compatible storage for asset management:
```yaml
s3:
enabled: true
endpoint: "https://s3.amazonaws.com"
region: "us-east-1"
bucket: "motm-assets"
```
### Resource Limits
Adjust resource limits based on your cluster capacity:
```yaml
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 100m
memory: 256Mi
```
### Autoscaling
Enable horizontal pod autoscaling:
```yaml
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 80
```
## Upgrading
To upgrade the application:
```bash
helm upgrade motm-app ./motm-app -f my-values.yaml
```
## Uninstalling
To uninstall the application:
```bash
helm uninstall motm-app
```
## Troubleshooting
### Check Pod Status
```bash
kubectl get pods -l app.kubernetes.io/name=motm-app
```
### View Logs
```bash
kubectl logs -l app.kubernetes.io/name=motm-app
```
### Check Service
```bash
kubectl get svc -l app.kubernetes.io/name=motm-app
```
### Debug Database Connection
```bash
kubectl exec -it deployment/motm-app -- python -c "
from database import sql_read_static
from sqlalchemy import text
try:
result = sql_read_static(text('SELECT 1'))
print('Database connection successful')
except Exception as e:
print(f'Database connection failed: {e}')
"
```
## Values Reference
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `image.repository` | string | `"your-registry/motm-app"` | Image repository |
| `image.tag` | string | `"latest"` | Image tag |
| `service.type` | string | `"ClusterIP"` | Service type |
| `ingress.enabled` | bool | `true` | Enable ingress |
| `database.type` | string | `"postgresql"` | Database type |
| `database.host` | string | `"postgresql-service"` | Database host |
| `s3.enabled` | bool | `true` | Enable S3 storage |
| `resources.limits.cpu` | string | `"500m"` | CPU limit |
| `resources.limits.memory` | string | `"512Mi"` | Memory limit |
## Security Considerations
1. **Secrets Management**: Use proper secret management solutions (e.g., Sealed Secrets, External Secrets Operator)
2. **Network Policies**: Implement network policies to restrict pod-to-pod communication
3. **RBAC**: Configure proper RBAC for service accounts
4. **Image Security**: Use non-root containers and scan images for vulnerabilities
5. **TLS**: Enable TLS for ingress and internal communication
## Monitoring
The chart includes basic health checks. For production deployments, consider adding:
- Prometheus metrics endpoint
- ServiceMonitor for Prometheus Operator
- Grafana dashboards
- Alerting rules
## Support
For issues and questions, please refer to the application documentation or create an issue in the repository.
+266
View File
@@ -0,0 +1,266 @@
#!/bin/bash
# MOTM App Helm Deployment Script
# Usage: ./deploy.sh [environment] [action]
# Environment: development, staging, production
# Action: install, upgrade, uninstall, template
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default values
ENVIRONMENT=${1:-development}
ACTION=${2:-install}
RELEASE_NAME="motm-app"
CHART_PATH="./motm-app"
NAMESPACE="motm-app"
# Function to print colored output
print_status() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Function to check prerequisites
check_prerequisites() {
print_status "Checking prerequisites..."
# Check if helm is installed
if ! command -v helm &> /dev/null; then
print_error "Helm is not installed. Please install Helm 3.0+"
exit 1
fi
# Check if kubectl is installed
if ! command -v kubectl &> /dev/null; then
print_error "kubectl is not installed. Please install kubectl"
exit 1
fi
# Check if we can connect to Kubernetes cluster
if ! kubectl cluster-info &> /dev/null; then
print_error "Cannot connect to Kubernetes cluster"
exit 1
fi
print_success "Prerequisites check passed"
}
# Function to create namespace
create_namespace() {
print_status "Creating namespace: $NAMESPACE"
kubectl create namespace $NAMESPACE --dry-run=client -o yaml | kubectl apply -f -
print_success "Namespace created/verified"
}
# Function to validate values file
validate_values() {
local values_file="values-${ENVIRONMENT}.yaml"
if [[ ! -f "$values_file" ]]; then
print_error "Values file $values_file not found"
exit 1
fi
print_status "Validating values file: $values_file"
# Check for required values
if ! grep -q "repository:" "$values_file"; then
print_error "Image repository not specified in $values_file"
exit 1
fi
if ! grep -q "host:" "$values_file"; then
print_error "Database host not specified in $values_file"
exit 1
fi
print_success "Values file validation passed"
}
# Function to template the chart
template_chart() {
local values_file="values-${ENVIRONMENT}.yaml"
print_status "Generating Kubernetes manifests..."
helm template $RELEASE_NAME $CHART_PATH \
--namespace $NAMESPACE \
--values $values_file \
--output-dir ./generated-manifests
print_success "Manifests generated in ./generated-manifests/"
}
# Function to install the chart
install_chart() {
local values_file="values-${ENVIRONMENT}.yaml"
print_status "Installing MOTM App in $ENVIRONMENT environment..."
helm install $RELEASE_NAME $CHART_PATH \
--namespace $NAMESPACE \
--values $values_file \
--create-namespace \
--wait \
--timeout 10m
print_success "MOTM App installed successfully"
# Show status
kubectl get pods -n $NAMESPACE -l app.kubernetes.io/name=motm-app
}
# Function to upgrade the chart
upgrade_chart() {
local values_file="values-${ENVIRONMENT}.yaml"
print_status "Upgrading MOTM App in $ENVIRONMENT environment..."
helm upgrade $RELEASE_NAME $CHART_PATH \
--namespace $NAMESPACE \
--values $values_file \
--wait \
--timeout 10m
print_success "MOTM App upgraded successfully"
# Show status
kubectl get pods -n $NAMESPACE -l app.kubernetes.io/name=motm-app
}
# Function to uninstall the chart
uninstall_chart() {
print_warning "Uninstalling MOTM App from $ENVIRONMENT environment..."
read -p "Are you sure you want to uninstall? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
helm uninstall $RELEASE_NAME --namespace $NAMESPACE
print_success "MOTM App uninstalled successfully"
else
print_status "Uninstall cancelled"
fi
}
# Function to show status
show_status() {
print_status "Showing MOTM App status..."
echo "=== Helm Release Status ==="
helm status $RELEASE_NAME --namespace $NAMESPACE
echo -e "\n=== Pods Status ==="
kubectl get pods -n $NAMESPACE -l app.kubernetes.io/name=motm-app
echo -e "\n=== Services ==="
kubectl get svc -n $NAMESPACE -l app.kubernetes.io/name=motm-app
echo -e "\n=== Ingress ==="
kubectl get ingress -n $NAMESPACE -l app.kubernetes.io/name=motm-app
}
# Function to show logs
show_logs() {
print_status "Showing MOTM App logs..."
kubectl logs -n $NAMESPACE -l app.kubernetes.io/name=motm-app --tail=100 -f
}
# Function to show help
show_help() {
echo "MOTM App Helm Deployment Script"
echo ""
echo "Usage: $0 [environment] [action]"
echo ""
echo "Environments:"
echo " development Deploy to development environment"
echo " staging Deploy to staging environment"
echo " production Deploy to production environment"
echo ""
echo "Actions:"
echo " install Install the application (default)"
echo " upgrade Upgrade the application"
echo " uninstall Uninstall the application"
echo " template Generate Kubernetes manifests"
echo " status Show application status"
echo " logs Show application logs"
echo " help Show this help message"
echo ""
echo "Examples:"
echo " $0 development install"
echo " $0 production upgrade"
echo " $0 staging template"
echo " $0 development status"
}
# Main execution
main() {
case $ACTION in
install)
check_prerequisites
create_namespace
validate_values
install_chart
;;
upgrade)
check_prerequisites
create_namespace
validate_values
upgrade_chart
;;
uninstall)
check_prerequisites
uninstall_chart
;;
template)
check_prerequisites
validate_values
template_chart
;;
status)
check_prerequisites
show_status
;;
logs)
check_prerequisites
show_logs
;;
help|--help|-h)
show_help
;;
*)
print_error "Unknown action: $ACTION"
show_help
exit 1
;;
esac
}
# Run main function
main "$@"
@@ -0,0 +1,75 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "motm-app.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "motm-app.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "motm-app.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "motm-app.labels" -}}
helm.sh/chart: {{ include "motm-app.chart" . }}
{{ include "motm-app.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- with .Values.labels }}
{{- toYaml . | nindent 0 }}
{{- end }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "motm-app.selectorLabels" -}}
app.kubernetes.io/name: {{ include "motm-app.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Create the name of the service account to use
*/}}
{{- define "motm-app.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "motm-app.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
@@ -0,0 +1,50 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "motm-app.fullname" . }}-config
labels:
{{- include "motm-app.labels" . | nindent 4 }}
data:
database_config.ini: |
[DATABASE]
type = {{ .Values.database.type }}
sqlite_database_path = hockey_results.db
[MYSQL]
host = {{ .Values.database.host }}
port = {{ .Values.database.port }}
database = {{ .Values.database.name }}
username = {{ .Values.database.username }}
charset = utf8mb4
[POSTGRESQL]
host = {{ .Values.database.host }}
port = {{ .Values.database.port }}
database = {{ .Values.database.name }}
username = {{ .Values.database.username }}
---
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "motm-app.fullname" . }}-s3-config
labels:
{{- include "motm-app.labels" . | nindent 4 }}
data:
s3_config.json: |
{
"enable_s3": {{ .Values.s3.enabled }},
"aws_access_key_id": "",
"aws_secret_access_key": "",
"aws_region": "{{ .Values.s3.region }}",
"bucket_name": "{{ .Values.s3.bucket }}",
"bucket_prefix": "{{ .Values.s3.bucketPrefix }}",
"endpoint_url": "{{ .Values.s3.endpoint }}",
"storage_provider": "{{ .Values.s3.storageProvider }}",
"minio_endpoint": "{{ .Values.s3.endpoint }}",
"minio_use_ssl": {{ .Values.s3.useSSL }},
"use_signed_urls": {{ .Values.s3.useSignedUrls }},
"signed_url_expiry": {{ .Values.s3.signedUrlExpiry }},
"fallback_to_static": {{ .Values.s3.fallbackToStatic }},
"use_ssl": {{ .Values.s3.useSSL }},
"verify_ssl": true
}
@@ -0,0 +1,164 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "motm-app.fullname" . }}
labels:
{{- include "motm-app.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount | default 1 }}
{{- end }}
selector:
matchLabels:
{{- include "motm-app.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "motm-app.selectorLabels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "motm-app.serviceAccountName" . }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: http
containerPort: 5000
protocol: TCP
env:
# Application environment variables
{{- range $key, $value := .Values.env }}
- name: {{ $key }}
value: {{ $value | quote }}
{{- end }}
# Database configuration
- name: DB_HOST
value: {{ .Values.database.host | quote }}
- name: DB_PORT
value: {{ .Values.database.port | quote }}
- name: DB_NAME
value: {{ .Values.database.name | quote }}
- name: DB_USER
value: {{ .Values.database.username | quote }}
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
{{- if .Values.secrets.useExternalSecret }}
name: {{ .Values.secrets.externalSecretName | quote }}
{{- else }}
name: {{ include "motm-app.fullname" . }}-secrets
{{- end }}
key: {{ .Values.secrets.dbPasswordKey }}
# S3/MinIO configuration
{{- if .Values.s3.enabled }}
- name: S3_ENABLED
value: "true"
- name: S3_STORAGE_PROVIDER
value: {{ .Values.s3.storageProvider | quote }}
- name: S3_ENDPOINT
value: {{ .Values.s3.endpoint | quote }}
- name: S3_REGION
value: {{ .Values.s3.region | quote }}
- name: S3_BUCKET
value: {{ .Values.s3.bucket | quote }}
- name: S3_BUCKET_PREFIX
value: {{ .Values.s3.bucketPrefix | quote }}
- name: S3_USE_SIGNED_URLS
value: {{ .Values.s3.useSignedUrls | quote }}
- name: S3_SIGNED_URL_EXPIRY
value: {{ .Values.s3.signedUrlExpiry | quote }}
- name: S3_FALLBACK_TO_STATIC
value: {{ .Values.s3.fallbackToStatic | quote }}
- name: S3_USE_SSL
value: {{ .Values.s3.useSSL | quote }}
- name: S3_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
{{- if .Values.secrets.useExternalSecret }}
name: {{ .Values.secrets.externalSecretName | quote }}
{{- else }}
name: {{ include "motm-app.fullname" . }}-secrets
{{- end }}
key: {{ .Values.secrets.s3AccessKeyKey }}
- name: S3_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
{{- if .Values.secrets.useExternalSecret }}
name: {{ .Values.secrets.externalSecretName | quote }}
{{- else }}
name: {{ include "motm-app.fullname" . }}-secrets
{{- end }}
key: {{ .Values.secrets.s3SecretKeyKey }}
{{- else }}
- name: S3_ENABLED
value: "false"
{{- end }}
livenessProbe:
httpGet:
path: {{ .Values.healthCheck.path }}
port: http
initialDelaySeconds: {{ .Values.healthCheck.initialDelaySeconds }}
periodSeconds: {{ .Values.healthCheck.periodSeconds }}
timeoutSeconds: {{ .Values.healthCheck.timeoutSeconds }}
failureThreshold: {{ .Values.healthCheck.failureThreshold }}
readinessProbe:
httpGet:
path: {{ .Values.healthCheck.path }}
port: http
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
resources:
{{- toYaml .Values.resources | nindent 12 }}
volumeMounts:
- name: config-volume
mountPath: /app/database_config.ini
subPath: database_config.ini
- name: s3-config-volume
mountPath: /app/s3_config.json
subPath: s3_config.json
{{- if .Values.persistence.enabled }}
- name: data-volume
mountPath: /app/data
{{- end }}
volumes:
- name: config-volume
configMap:
name: {{ include "motm-app.fullname" . }}-config
- name: s3-config-volume
configMap:
name: {{ include "motm-app.fullname" . }}-s3-config
{{- if .Values.persistence.enabled }}
- name: data-volume
persistentVolumeClaim:
claimName: {{ include "motm-app.fullname" . }}-pvc
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
@@ -0,0 +1,42 @@
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: {{ include "motm-app.fullname" . }}
labels:
{{- include "motm-app.labels" . | nindent 4 }}
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: {{ include "motm-app.fullname" . }}
minReplicas: {{ .Values.autoscaling.minReplicas }}
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
metrics:
{{- if .Values.autoscaling.targetCPUUtilizationPercentage }}
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
{{- end }}
{{- if .Values.autoscaling.targetMemoryUtilizationPercentage }}
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }}
{{- end }}
{{- end }}
@@ -0,0 +1,60 @@
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "motm-app.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
{{- if and .Values.ingress.className (not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class")) }}
{{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}}
{{- end }}
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
name: {{ $fullName }}
labels:
{{- include "motm-app.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }}
ingressClassName: {{ .Values.ingress.className }}
{{- end }}
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
- hosts:
{{- range .hosts }}
- {{ . | quote }}
{{- end }}
secretName: {{ .secretName }}
{{- end }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ .path }}
{{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }}
pathType: {{ .pathType }}
{{- end }}
backend:
{{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }}
service:
name: {{ $fullName }}
port:
number: {{ $svcPort }}
{{- else }}
serviceName: {{ $fullName }}
servicePort: {{ $svcPort }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,28 @@
{{- if .Values.podDisruptionBudget.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ include "motm-app.fullname" . }}
labels:
{{- include "motm-app.labels" . | nindent 4 }}
spec:
{{- if .Values.podDisruptionBudget.minAvailable }}
minAvailable: {{ .Values.podDisruptionBudget.minAvailable }}
{{- end }}
{{- if .Values.podDisruptionBudget.maxUnavailable }}
maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }}
{{- end }}
selector:
matchLabels:
{{- include "motm-app.selectorLabels" . | nindent 6 }}
{{- end }}
@@ -0,0 +1,31 @@
{{- if .Values.persistence.enabled }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ include "motm-app.fullname" . }}-pvc
labels:
{{- include "motm-app.labels" . | nindent 4 }}
spec:
accessModes:
- {{ .Values.persistence.accessMode }}
resources:
requests:
storage: {{ .Values.persistence.size }}
{{- if .Values.persistence.storageClass }}
{{- if (eq "-" .Values.persistence.storageClass) }}
storageClassName: ""
{{- else }}
storageClassName: "{{ .Values.persistence.storageClass }}"
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,32 @@
{{- if not .Values.secrets.useExternalSecret }}
apiVersion: v1
kind: Secret
metadata:
name: {{ include "motm-app.fullname" . }}-secrets
labels:
{{- include "motm-app.labels" . | nindent 4 }}
type: Opaque
data:
# Database password
{{- if .Values.secrets.dbPassword }}
{{ .Values.secrets.dbPasswordKey }}: {{ .Values.secrets.dbPassword | b64enc | quote }}
{{- else }}
{{ .Values.secrets.dbPasswordKey }}: {{ "changeme" | b64enc | quote }}
{{- end }}
{{- if .Values.s3.enabled }}
# S3 credentials
{{- if .Values.secrets.s3AccessKey }}
{{ .Values.secrets.s3AccessKeyKey }}: {{ .Values.secrets.s3AccessKey | b64enc | quote }}
{{- else }}
{{ .Values.secrets.s3AccessKeyKey }}: {{ "changeme" | b64enc | quote }}
{{- end }}
{{- if .Values.secrets.s3SecretKey }}
{{ .Values.secrets.s3SecretKeyKey }}: {{ .Values.secrets.s3SecretKey | b64enc | quote }}
{{- else }}
{{ .Values.secrets.s3SecretKeyKey }}: {{ "changeme" | b64enc | quote }}
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,20 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "motm-app.fullname" . }}
labels:
{{- include "motm-app.labels" . | nindent 4 }}
{{- with .Values.service.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
targetPort: {{ .Values.service.targetPort }}
protocol: TCP
name: http
selector:
{{- include "motm-app.selectorLabels" . | nindent 4 }}
@@ -0,0 +1,22 @@
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "motm-app.serviceAccountName" . }}
labels:
{{- include "motm-app.labels" . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- end }}
@@ -0,0 +1,143 @@
# Development values for MOTM App
# Use this file for development/staging environments
# Application Configuration
app:
name: motm-app-dev
version: "dev"
# Image Configuration
image:
repository: your-registry/motm-app
tag: "dev" # Use dev tag for development
pullPolicy: Always # Always pull latest dev image
# Resource Limits for Development (lighter)
resources:
limits:
cpu: 200m
memory: 256Mi
requests:
cpu: 50m
memory: 128Mi
# No autoscaling for development
autoscaling:
enabled: false
# Pod Disruption Budget
podDisruptionBudget:
enabled: false
# Security Context (more permissive for development)
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
readOnlyRootFilesystem: false # Allow writing for development
runAsNonRoot: true
runAsUser: 1000
# Service Configuration
service:
type: ClusterIP
port: 80
targetPort: 5000
# Ingress Configuration for Development
ingress:
enabled: true
className: "nginx"
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "false" # No SSL for dev
cert-manager.io/cluster-issuer: "letsencrypt-staging"
hosts:
- host: motm-dev.yourdomain.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: motm-app-dev-tls
hosts:
- motm-dev.yourdomain.com
# Database Configuration for Development
database:
type: "postgresql"
host: "postgresql-dev-service"
port: 5432
name: "motm_dev"
username: "motm_user"
# S3/MinIO Configuration for Development
# Example: Using MinIO for local development
s3:
enabled: true
storageProvider: "minio" # Use MinIO for development
endpoint: "http://minio.default.svc.cluster.local:9000" # Internal MinIO service
region: "us-east-1" # MinIO ignores this but required for boto3
bucket: "motm-assets-dev"
bucketPrefix: "assets/"
useSignedUrls: false # Use public URLs in development
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: false # HTTP for local MinIO
# Alternative AWS S3 configuration for development:
# storageProvider: "aws"
# endpoint: ""
# region: "us-east-1"
# bucket: "motm-assets-dev"
# useSSL: true
# Environment Variables for Development
env:
FLASK_ENV: "development"
FLASK_APP: "main.py"
FLASK_RUN_HOST: "0.0.0.0"
FLASK_RUN_PORT: "5000"
PYTHONUNBUFFERED: "1"
PYTHONDONTWRITEBYTECODE: "1"
FLASK_DEBUG: "1" # Enable debug mode for development
# Health Checks
healthCheck:
enabled: true
path: "/"
initialDelaySeconds: 10
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 5
# Persistence for Development
persistence:
enabled: true
storageClass: "standard" # Use standard storage class
accessMode: ReadWriteOnce
size: 1Gi
# Monitoring (disabled for development)
monitoring:
enabled: false
# Logging
logging:
level: "DEBUG"
format: "text"
# Labels and Annotations
labels:
environment: "development"
team: "development"
annotations:
deployment.kubernetes.io/revision: "dev"
podLabels:
environment: "development"
podAnnotations:
debug: "true"
@@ -0,0 +1,181 @@
# Production values for MOTM App
# Use this file as a template for production deployment
# Application Configuration
app:
name: motm-app
version: "1.0.0"
# Image Configuration
image:
repository: your-registry/motm-app
tag: "v1.0.0" # Use specific version tags in production
pullPolicy: IfNotPresent
# Resource Limits for Production
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 200m
memory: 512Mi
# Autoscaling for Production
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 70
targetMemoryUtilizationPercentage: 80
# Pod Disruption Budget
podDisruptionBudget:
enabled: true
minAvailable: 1
# Security Context
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 1000
# Service Configuration
service:
type: ClusterIP
port: 80
targetPort: 5000
# Ingress Configuration for Production
ingress:
enabled: true
className: "nginx"
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/rate-limit: "100"
nginx.ingress.kubernetes.io/rate-limit-window: "1m"
hosts:
- host: motm.yourdomain.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: motm-app-tls
hosts:
- motm.yourdomain.com
# Database Configuration
database:
type: "postgresql"
host: "postgresql-primary-service"
port: 5432
name: "motm_prod"
username: "motm_user"
# S3/MinIO Configuration for Production
s3:
enabled: true
storageProvider: "minio" # Use "aws" for AWS S3 or "minio" for MinIO
endpoint: "http://minio.default.svc.cluster.local:9000" # MinIO internal service endpoint
region: "us-east-1" # Required for boto3 even with MinIO
bucket: "hockey-apps"
bucketPrefix: "assets/"
useSignedUrls: false # Use public URLs (MinIO bucket should be public read)
signedUrlExpiry: 3600
fallbackToStatic: true
useSSL: false # Use HTTP for internal cluster communication
# Alternative external MinIO configuration (for external access):
# storageProvider: "minio"
# endpoint: "https://minio.yourdomain.com" # External MinIO endpoint
# region: "us-east-1"
# bucket: "hockey-apps"
# useSignedUrls: false
# useSSL: true # Use HTTPS for external access
# Environment Variables
env:
FLASK_ENV: "production"
FLASK_APP: "main.py"
FLASK_RUN_HOST: "0.0.0.0"
FLASK_RUN_PORT: "5000"
PYTHONUNBUFFERED: "1"
PYTHONDONTWRITEBYTECODE: "1"
# Health Checks
healthCheck:
enabled: true
path: "/"
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
# Persistence for Production
persistence:
enabled: true
storageClass: "fast-ssd" # Use fast storage class
accessMode: ReadWriteOnce
size: 10Gi
# Monitoring
monitoring:
enabled: true
serviceMonitor:
enabled: true
interval: 30s
scrapeTimeout: 10s
# Logging
logging:
level: "INFO"
format: "json"
# Node Selector for Production
nodeSelector:
node-type: "production"
# Tolerations
tolerations:
- key: "production"
operator: "Equal"
value: "true"
effect: "NoSchedule"
# Affinity Rules
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app.kubernetes.io/name
operator: In
values:
- motm-app
topologyKey: kubernetes.io/hostname
# Labels and Annotations
labels:
environment: "production"
team: "platform"
annotations:
deployment.kubernetes.io/revision: "1"
podLabels:
environment: "production"
podAnnotations:
prometheus.io/scrape: "true"
prometheus.io/port: "5000"
prometheus.io/path: "/metrics"
+236
View File
@@ -0,0 +1,236 @@
# Default values for motm-app
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# Application Configuration
app:
name: motm-app
version: "1.0.0"
description: "MOTM Hockey Voting Application"
# Image Configuration
image:
repository: harbor.ervine.dev/pubblic/hockey/motm-app
tag: "0.1.1"
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
# tag: ""
# Image pull secrets
imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""
# Service Account
serviceAccount:
# Specifies whether a service account should be created
create: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: ""
# Pod Security Context
podSecurityContext:
fsGroup: 1000
runAsNonRoot: true
runAsUser: 1000
# Container Security Context
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
readOnlyRootFilesystem: false
runAsNonRoot: true
runAsUser: 1000
# Service Configuration
service:
type: ClusterIP
port: 80
targetPort: 5000
annotations: {}
# Ingress Configuration
ingress:
enabled: true
className: ""
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
hosts:
- host: motm.yourdomain.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: motm-app-tls
hosts:
- motm.yourdomain.com
# Resource Limits and Requests
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 100m
memory: 256Mi
# Autoscaling
autoscaling:
enabled: false
minReplicas: 1
maxReplicas: 10
targetCPUUtilizationPercentage: 80
targetMemoryUtilizationPercentage: 80
# Node Selector
nodeSelector: {}
# Tolerations
tolerations: []
# Affinity
affinity: {}
# Pod Disruption Budget
podDisruptionBudget:
enabled: false
minAvailable: 1
# Database Configuration
database:
type: "postgresql" # postgresql, mysql, sqlite
host: "postgresql-service"
port: 5432
name: "motm"
username: "motm_user"
# Password should be set via secret
# password: ""
# S3/MinIO Configuration
s3:
# Enable S3 storage (if false, uses local static files)
enabled: true
# Storage provider: "aws" or "minio"
storageProvider: "minio"
# S3/MinIO endpoint
# For AWS: "https://s3.amazonaws.com" or leave empty to use default
# For MinIO: "https://minio.example.com" or "http://minio.default.svc.cluster.local:9000"
endpoint: "http://minio.default.svc.cluster.local:9000"
# AWS region (used for AWS S3, required for boto3 even with MinIO)
region: "us-east-1"
# S3 bucket name
bucket: "hockey-apps"
# Bucket prefix/folder for assets (e.g., "assets/", "motm/", etc.)
bucketPrefix: "assets/"
# Use signed URLs for asset access (recommended for private buckets)
useSignedUrls: false
# Signed URL expiry time in seconds (default: 1 hour)
signedUrlExpiry: 3600
# Fallback to local static files if S3 access fails
fallbackToStatic: true
# SSL/TLS configuration
useSSL: false
# Credentials (should be set via secrets in production)
# These are ignored if secrets.useExternalSecret is true
accessKeyId: ""
secretAccessKey: ""
# Environment Variables
env:
FLASK_ENV: "production"
FLASK_APP: "main.py"
FLASK_RUN_HOST: "0.0.0.0"
FLASK_RUN_PORT: "5000"
PYTHONUNBUFFERED: "1"
PYTHONDONTWRITEBYTECODE: "1"
# ConfigMap for application configuration
configMap:
databaseConfig: |
[DATABASE]
type = {{ .Values.database.type }}
[MYSQL]
host = {{ .Values.database.host }}
port = {{ .Values.database.port }}
database = {{ .Values.database.name }}
username = {{ .Values.database.username }}
[POSTGRESQL]
host = {{ .Values.database.host }}
port = {{ .Values.database.port }}
database = {{ .Values.database.name }}
username = {{ .Values.database.username }}
# Secrets Configuration
secrets:
# Use an existing external secret instead of creating one
# If useExternalSecret is true, the chart will reference the external secret
# If false, the chart will create a secret with the provided values
useExternalSecret: false
externalSecretName: "" # Name of the existing secret to reference
# Secret key names (used for both external and managed secrets)
dbPasswordKey: "db-password"
s3AccessKeyKey: "s3-access-key"
s3SecretKeyKey: "s3-secret-key"
# Values for managed secret (only used when useExternalSecret is false)
# Database password
dbPassword: ""
# S3 credentials
s3AccessKey: ""
s3SecretKey: ""
# Health Checks
healthCheck:
enabled: true
path: "/"
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
# Persistence
persistence:
enabled: false
# storageClass: ""
accessMode: ReadWriteOnce
size: 1Gi
# Monitoring
monitoring:
enabled: false
serviceMonitor:
enabled: false
interval: 30s
scrapeTimeout: 10s
# Logging
logging:
level: "INFO"
format: "json"
# Labels and Annotations
labels: {}
annotations: {}
podLabels: {}
podAnnotations: {}
+13
View File
@@ -0,0 +1,13 @@
-- Database initialization script for MOTM application
-- This script runs when the PostgreSQL container starts for the first time
-- Create the database if it doesn't exist (this is handled by POSTGRES_DB env var)
-- But we can add any additional setup here
-- Create extensions if needed
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- The application will handle table creation through SQLAlchemy
-- This file is here for any additional database setup that might be needed
+2557
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=MOTM App - Man of the Match Voting System
After=network.target
[Service]
Type=exec
User=www-data
Group=www-data
WorkingDirectory=/home/jonny/Projects/gcp-hockey-results/motm_app
Environment=PATH=/home/jonny/Projects/gcp-hockey-results/motm_app/venv/bin
Environment=FLASK_ENV=production
ExecStart=/home/jonny/Projects/gcp-hockey-results/motm_app/venv/bin/gunicorn -c gunicorn.conf.py run_production:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
+19
View File
@@ -0,0 +1,19 @@
# encoding=utf-8
import pymysql
import os
from db_config import sql_read_static
from sqlalchemy import text
def mySettings(setting):
try:
# Convert setting to lowercase for PostgreSQL compatibility
setting_lower = setting.lower()
sql = text("SELECT " + setting_lower + " FROM motmadminsettings")
rows = sql_read_static(sql)
if rows:
return rows[0][setting_lower]
else:
return None
except Exception as e:
print(e)
return None
+34
View File
@@ -0,0 +1,34 @@
Flask>=2.0.0,<3.0.0
Werkzeug>=2.0.0
email-validator
flask_login
Flask-BasicAuth
Flask-Bootstrap
flask_wtf
wtforms>=3.0.0
wtforms_components
MarkupSafe>=2.0.0
# Web scraping
requests>=2.31.0
beautifulsoup4>=4.12.0
lxml>=4.9.0
# SQLAlchemy and database drivers
SQLAlchemy>=2.0.0
Flask-SQLAlchemy>=3.0.0
alembic>=1.12.0
# Database drivers
pymysql>=1.1.0
psycopg2-binary>=2.9.0
PyMySQL>=1.1.0
# AWS S3 support
boto3>=1.34.0
# Legacy support (can be removed after migration)
flask-mysql
# Production WSGI server
gunicorn>=21.0.0
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# Script to revert all table and column name changes back to motmadminsettings
echo "This script will help you revert the table name changes."
echo "The issue is that production uses 'motmadminsettings' with camelCase columns,"
echo "but I changed everything to 'admin_settings' with snake_case columns."
echo ""
echo "You have two options:"
echo "1. Revert the code to use motmadminsettings (old table)"
echo "2. Migrate production database to use admin_settings (new table)"
echo ""
echo "Which would you prefer?"
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# Script to run the voting deadline migration on production
echo "=========================================="
echo "Running Voting Deadline Migration"
echo "=========================================="
echo ""
# Check if we're in a Kubernetes environment
if [ -n "$KUBERNETES_SERVICE_HOST" ]; then
echo "Running in Kubernetes environment"
python add_voting_deadline.py
else
echo "Running locally"
echo ""
echo "To run on production Kubernetes cluster:"
echo "1. kubectl get pods -n <your-namespace>"
echo "2. kubectl exec -it <pod-name> -n <your-namespace> -- python add_voting_deadline.py"
echo ""
echo "Or if using Helm:"
echo "helm upgrade motm-app ./helm-chart/motm-app --namespace <your-namespace>"
echo ""
python add_voting_deadline.py
fi
echo ""
echo "Migration complete!"
+16
View File
@@ -0,0 +1,16 @@
@echo off
echo 🐍 Starting MOTM Application...
REM Set PostgreSQL environment variables
set DATABASE_TYPE=postgresql
set POSTGRES_HOST=icarus.ipa.champion
set POSTGRES_PORT=5432
set POSTGRES_DATABASE=motm
set POSTGRES_USER=motm_user
set POSTGRES_PASSWORD=q7y7f7Lv*sODJZ2wGiv0Wq5a
echo 📊 Using PostgreSQL database: %POSTGRES_DATABASE% on %POSTGRES_HOST%
call venv\Scripts\activate.bat
python.exe main.py
pause
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
echo "🐍 Starting MOTM Application..."
# Set PostgreSQL environment variables
export DATABASE_TYPE=postgresql
export POSTGRES_HOST=icarus.ipa.champion
export POSTGRES_PORT=5432
export POSTGRES_DATABASE=motm
export POSTGRES_USER=motm_user
export POSTGRES_PASSWORD='q7y7f7Lv*sODJZ2wGiv0Wq5a'
echo "📊 Using PostgreSQL database: $POSTGRES_DATABASE on $POSTGRES_HOST"
source venv/bin/activate
python main.py
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""
Production WSGI entry point for MOTM App
This file is used by Gunicorn to run the application in production
"""
from main import app
if __name__ == "__main__":
# This should not be called directly in production
# Use: gunicorn -c gunicorn.conf.py run_production:app
app.run(host='0.0.0.0', port=5000, debug=False)
+102
View File
@@ -0,0 +1,102 @@
#!/bin/bash
# Quick script to run the voting deadline migration on production Kubernetes
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}MOTM App - Production Migration${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
# Default namespace
NAMESPACE="${1:-motm-app}"
echo -e "${YELLOW}Using namespace: ${NAMESPACE}${NC}"
echo ""
# Step 1: Find the pod
echo -e "${YELLOW}Step 1: Finding production pod...${NC}"
POD_NAME=$(kubectl get pods -n "$NAMESPACE" -l app.kubernetes.io/name=motm-app -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || echo "")
if [ -z "$POD_NAME" ]; then
echo -e "${RED}✗ Error: Could not find motm-app pod in namespace '$NAMESPACE'${NC}"
echo ""
echo "Available namespaces:"
kubectl get namespaces
echo ""
echo "Usage: $0 [namespace]"
echo "Example: $0 motm-app"
exit 1
fi
echo -e "${GREEN}✓ Found pod: ${POD_NAME}${NC}"
echo ""
# Step 2: Check if migration script exists in pod
echo -e "${YELLOW}Step 2: Checking migration script...${NC}"
if kubectl exec -n "$NAMESPACE" "$POD_NAME" -- test -f /app/add_voting_deadline.py 2>/dev/null; then
echo -e "${GREEN}✓ Migration script found${NC}"
else
echo -e "${RED}✗ Error: Migration script not found in pod${NC}"
echo "The add_voting_deadline.py script needs to be in the Docker image."
echo "Please rebuild and redeploy the application."
exit 1
fi
echo ""
# Step 3: Run the migration
echo -e "${YELLOW}Step 3: Running migration...${NC}"
if kubectl exec -n "$NAMESPACE" "$POD_NAME" -- python /app/add_voting_deadline.py; then
echo -e "${GREEN}✓ Migration completed successfully!${NC}"
else
echo -e "${RED}✗ Migration failed!${NC}"
exit 1
fi
echo ""
# Step 4: Verify the migration
echo -e "${YELLOW}Step 4: Verifying migration...${NC}"
VERIFY_CMD="from db_config import db_config; from sqlalchemy import text, inspect; engine = db_config.engine; inspector = inspect(engine); columns = inspector.get_columns('admin_settings'); voting_deadline_exists = any(col['name'] == 'votingdeadline' for col in columns); print('✓ votingdeadline column exists' if voting_deadline_exists else '✗ votingdeadline column missing')"
if kubectl exec -n "$NAMESPACE" "$POD_NAME" -- python -c "$VERIFY_CMD" 2>&1 | grep -q "✓"; then
echo -e "${GREEN}✓ Verification successful!${NC}"
else
echo -e "${RED}✗ Verification failed!${NC}"
echo "The column may not have been created properly."
exit 1
fi
echo ""
# Step 5: Restart the pod to clear cached connections
echo -e "${YELLOW}Step 5: Restarting pod to clear cached connections...${NC}"
kubectl rollout restart deployment/motm-app -n "$NAMESPACE" 2>/dev/null || \
kubectl delete pod "$POD_NAME" -n "$NAMESPACE"
echo -e "${GREEN}✓ Pod restart initiated${NC}"
echo ""
# Wait for pod to be ready
echo -e "${YELLOW}Waiting for pod to be ready...${NC}"
kubectl wait --for=condition=ready pod -l app.kubernetes.io/name=motm-app -n "$NAMESPACE" --timeout=120s
echo ""
# Summary
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Migration Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "Next steps:"
echo "1. Visit https://motm.ervine.cloud/admin/motm"
echo "2. The page should load without SQL errors"
echo "3. You should see the 'Voting Deadline' field"
echo "4. Set a deadline for your next match"
echo ""
echo "To check logs:"
echo " kubectl logs -n $NAMESPACE -l app.kubernetes.io/name=motm-app --tail=50"
echo ""
+14
View File
@@ -0,0 +1,14 @@
{
"enable_s3": true,
"storage_provider": "minio",
"aws_access_key_id": "5MoE0Vz8F9vVgulClesUV3GReh2nIiXG",
"aws_secret_access_key": "0h[c8lSHUE'<",
"aws_region": "us-east-1",
"minio_endpoint": "s3.ervine.cloud:443",
"minio_use_ssl": true,
"bucket_name": "hockey-app",
"bucket_prefix": "assets/",
"use_signed_urls": true,
"signed_url_expiry": 3600,
"fallback_to_static": true
}
+14
View File
@@ -0,0 +1,14 @@
{
"enable_s3": true,
"storage_provider": "minio",
"aws_access_key_id": "AKIARLJ7D6ZPRRLQHWD7",
"aws_secret_access_key": "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",
"aws_region": "us-east-1",
"minio_endpoint": "s3.ervine.cloud:443",
"minio_use_ssl": true,
"bucket_name": "hockey-app",
"bucket_prefix": "assets/",
"use_signed_urls": true,
"signed_url_expiry": 3600,
"fallback_to_static": true
}
+527
View File
@@ -0,0 +1,527 @@
# encoding=utf-8
"""
S3 Configuration and Service Module
Handles S3 credentials and asset retrieval for the MOTM application.
"""
import os
import json
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
class S3ConfigManager:
"""Manages S3 configuration settings.
Configuration priority (highest to lowest):
1. Environment variables (from Kubernetes secrets)
2. Database settings (admin-configurable via web UI)
3. JSON file (local development fallback)
Note: Credentials are ALWAYS from environment variables for security.
"""
def __init__(self):
self.config_file = 's3_config.json'
self.config = self.load_config()
def load_config(self) -> Dict[str, Any]:
"""Load S3 configuration from environment variables, database, or file.
Priority:
1. Environment variables (for Kubernetes/container deployments)
2. Database settings (admin-configurable via web UI)
3. Configuration file (for local/legacy deployments)
"""
# Priority 1: Check if running in Kubernetes/container mode with env vars
if os.getenv('S3_ENABLED') or os.getenv('S3_ACCESS_KEY_ID'):
return self._load_from_env()
# Priority 2: Try loading from database
db_config = self._load_from_database()
if db_config:
return db_config
# Priority 3: Fall back to file-based configuration
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return self.get_default_config()
# Default: Disabled, use local static files
return self.get_default_config()
def _load_from_env(self) -> Dict[str, Any]:
"""Load S3 configuration from environment variables."""
return {
'aws_access_key_id': os.getenv('S3_ACCESS_KEY_ID', ''),
'aws_secret_access_key': os.getenv('S3_SECRET_ACCESS_KEY', ''),
'aws_region': os.getenv('S3_REGION', 'us-east-1'),
'bucket_name': os.getenv('S3_BUCKET', ''),
'bucket_prefix': os.getenv('S3_BUCKET_PREFIX', 'assets/'),
'enable_s3': os.getenv('S3_ENABLED', 'false').lower() in ('true', '1', 'yes'),
'use_signed_urls': os.getenv('S3_USE_SIGNED_URLS', 'true').lower() in ('true', '1', 'yes'),
'signed_url_expiry': int(os.getenv('S3_SIGNED_URL_EXPIRY', '3600')),
'fallback_to_static': os.getenv('S3_FALLBACK_TO_STATIC', 'true').lower() in ('true', '1', 'yes'),
'storage_provider': os.getenv('S3_STORAGE_PROVIDER', 'aws'),
'minio_endpoint': os.getenv('S3_ENDPOINT', ''),
'minio_use_ssl': os.getenv('S3_USE_SSL', 'true').lower() in ('true', '1', 'yes'),
'endpoint_url': os.getenv('S3_ENDPOINT', '') # For compatibility
}
def _load_from_database(self) -> Optional[Dict[str, Any]]:
"""Load S3 configuration from database.
Returns None if database is not available or no settings exist.
Credentials are always loaded from environment variables.
"""
try:
# Import here to avoid circular dependency
from database import get_db_session, S3Settings
session = get_db_session()
try:
# Get settings for admin user
settings = session.query(S3Settings).filter_by(userid='admin').first()
if not settings:
return None
# Build configuration from database settings
# Credentials ALWAYS come from environment variables
return {
'enable_s3': settings.enabled,
'aws_access_key_id': os.getenv('S3_ACCESS_KEY_ID', ''),
'aws_secret_access_key': os.getenv('S3_SECRET_ACCESS_KEY', ''),
'storage_provider': settings.storage_provider,
'aws_region': settings.region,
'bucket_name': settings.bucket_name,
'bucket_prefix': settings.bucket_prefix,
'use_signed_urls': settings.use_signed_urls,
'signed_url_expiry': settings.signed_url_expiry,
'fallback_to_static': settings.fallback_to_static,
'minio_endpoint': settings.endpoint,
'minio_use_ssl': settings.use_ssl,
'endpoint_url': settings.endpoint # For compatibility
}
finally:
session.close()
except Exception as e:
# Database not available or table doesn't exist yet
# This is normal during initial setup
return None
def get_default_config(self) -> Dict[str, Any]:
"""Get default S3 configuration."""
return {
'aws_access_key_id': '',
'aws_secret_access_key': '',
'aws_region': 'us-east-1',
'bucket_name': '',
'bucket_prefix': 'assets/',
'enable_s3': False,
'use_signed_urls': True,
'signed_url_expiry': 3600, # 1 hour in seconds
'fallback_to_static': True,
'storage_provider': 'aws', # 'aws' or 'minio'
'minio_endpoint': '', # MinIO endpoint URL
'minio_use_ssl': True # Whether to use SSL for MinIO
}
def save_config(self, config_data: Dict[str, Any]) -> bool:
"""Save S3 configuration to database.
Note: Credentials are NOT saved to database for security.
They should be provided via environment variables.
"""
try:
from database import get_db_session, S3Settings
session = get_db_session()
try:
# Get or create settings for admin user
settings = session.query(S3Settings).filter_by(userid='admin').first()
if not settings:
settings = S3Settings(userid='admin')
session.add(settings)
# Update settings from config_data
# NOTE: We do NOT save credentials to database
settings.enabled = config_data.get('enable_s3', False)
settings.storage_provider = config_data.get('storage_provider', 'aws')
settings.endpoint = config_data.get('minio_endpoint', config_data.get('endpoint_url', ''))
settings.region = config_data.get('aws_region', 'us-east-1')
settings.bucket_name = config_data.get('bucket_name', '')
settings.bucket_prefix = config_data.get('bucket_prefix', 'assets/')
settings.use_signed_urls = config_data.get('use_signed_urls', True)
settings.signed_url_expiry = config_data.get('signed_url_expiry', 3600)
settings.fallback_to_static = config_data.get('fallback_to_static', True)
settings.use_ssl = config_data.get('minio_use_ssl', True)
session.commit()
# Reload config from database
self.config = self.load_config()
return True
except Exception as e:
session.rollback()
print(f"Error saving S3 config to database: {e}")
# Fall back to file-based save for local development
return self._save_to_file(config_data)
finally:
session.close()
except Exception as e:
print(f"Database not available, falling back to file: {e}")
# Fall back to file-based save for local development
return self._save_to_file(config_data)
def _save_to_file(self, config_data: Dict[str, Any]) -> bool:
"""Save S3 configuration to JSON file (fallback for local development)."""
try:
with open(self.config_file, 'w') as f:
json.dump(config_data, f, indent=2)
self.config = config_data
return True
except IOError:
return False
def get_config_dict(self) -> Dict[str, Any]:
"""Get current configuration as dictionary."""
return self.config.copy()
def test_connection(self, config_data: Optional[Dict[str, Any]] = None) -> tuple[bool, str]:
"""Test S3 connection with provided or current configuration."""
if config_data:
test_config = config_data
else:
test_config = self.config
if not test_config.get('enable_s3', False):
return True, "S3 is disabled - using local static files"
try:
# Determine storage provider
storage_provider = test_config.get('storage_provider', 'aws')
if storage_provider == 'minio':
# Create MinIO client
minio_endpoint = test_config.get('minio_endpoint', '')
if not minio_endpoint:
return False, "MinIO endpoint is required when using MinIO"
# Parse endpoint to remove protocol if present
if minio_endpoint.startswith('http://'):
endpoint_host = minio_endpoint[7:]
use_ssl = False
elif minio_endpoint.startswith('https://'):
endpoint_host = minio_endpoint[8:]
use_ssl = True
else:
endpoint_host = minio_endpoint
use_ssl = test_config.get('minio_use_ssl', True)
# Construct the full endpoint URL
endpoint_url = f"{'https' if use_ssl else 'http'}://{endpoint_host}"
s3_client = boto3.client(
's3',
aws_access_key_id=test_config.get('aws_access_key_id', ''),
aws_secret_access_key=test_config.get('aws_secret_access_key', ''),
region_name=test_config.get('aws_region', 'us-east-1'),
endpoint_url=endpoint_url,
use_ssl=use_ssl,
verify=True # Enable SSL certificate verification
)
provider_name = "MinIO"
else:
# Create AWS S3 client
s3_client = boto3.client(
's3',
aws_access_key_id=test_config.get('aws_access_key_id', ''),
aws_secret_access_key=test_config.get('aws_secret_access_key', ''),
region_name=test_config.get('aws_region', 'us-east-1')
)
provider_name = "AWS S3"
# Test connection by listing bucket
bucket_name = test_config.get('bucket_name', '')
if not bucket_name:
return False, "Bucket name is required when S3 is enabled"
s3_client.head_bucket(Bucket=bucket_name)
return True, f"Successfully connected to {provider_name} bucket: {bucket_name}"
except ClientError as e:
error_code = e.response['Error']['Code']
provider_name = "MinIO" if test_config.get('storage_provider', 'aws') == 'minio' else "AWS S3"
if error_code == '404':
return False, f"{provider_name} bucket '{bucket_name}' not found"
elif error_code == '403':
return False, f"Access denied to {provider_name} bucket. Check credentials and permissions"
else:
return False, f"{provider_name} error: {e.response['Error']['Message']}"
except NoCredentialsError:
return False, "AWS credentials not found"
except Exception as e:
provider_name = "MinIO" if test_config.get('storage_provider', 'aws') == 'minio' else "AWS S3"
return False, f"{provider_name} connection error: {str(e)}"
class S3AssetService:
"""Service for retrieving assets from S3."""
def __init__(self, config_manager: S3ConfigManager):
self.config_manager = config_manager
self._s3_client = None
def _get_public_url(self, bucket_name: str, s3_key: str) -> str:
"""Generate public URL for S3 or MinIO."""
config = self.config_manager.config
storage_provider = config.get('storage_provider', 'aws')
if storage_provider == 'minio':
minio_endpoint = config.get('minio_endpoint', '')
use_ssl = config.get('minio_use_ssl', True)
protocol = 'https' if use_ssl else 'http'
# Parse endpoint to remove protocol if present
if minio_endpoint.startswith('http://'):
minio_endpoint = minio_endpoint[7:]
elif minio_endpoint.startswith('https://'):
minio_endpoint = minio_endpoint[8:]
return f"{protocol}://{minio_endpoint}/{bucket_name}/{s3_key}"
else:
return f"https://{bucket_name}.s3.{config.get('aws_region', 'us-east-1')}.amazonaws.com/{s3_key}"
@property
def s3_client(self):
"""Lazy-loaded S3 client."""
if self._s3_client is None and self.config_manager.config.get('enable_s3', False):
config = self.config_manager.config
storage_provider = config.get('storage_provider', 'aws')
if storage_provider == 'minio':
# Create MinIO client
minio_endpoint = config.get('minio_endpoint', '')
use_ssl = config.get('minio_use_ssl', True)
# Parse endpoint to remove protocol if present
if minio_endpoint.startswith('http://'):
endpoint_host = minio_endpoint[7:]
use_ssl = False
elif minio_endpoint.startswith('https://'):
endpoint_host = minio_endpoint[8:]
use_ssl = True
else:
endpoint_host = minio_endpoint
# Construct the full endpoint URL
endpoint_url = f"{'https' if use_ssl else 'http'}://{endpoint_host}"
self._s3_client = boto3.client(
's3',
aws_access_key_id=config.get('aws_access_key_id', ''),
aws_secret_access_key=config.get('aws_secret_access_key', ''),
region_name=config.get('aws_region', 'us-east-1'),
endpoint_url=endpoint_url,
use_ssl=use_ssl,
verify=True, # Enable SSL certificate verification
config=boto3.session.Config(
s3={
'addressing_style': 'path'
},
signature_version='s3v4'
)
)
else:
# Create AWS S3 client
self._s3_client = boto3.client(
's3',
aws_access_key_id=config.get('aws_access_key_id', ''),
aws_secret_access_key=config.get('aws_secret_access_key', ''),
region_name=config.get('aws_region', 'us-east-1')
)
return self._s3_client
def get_logo_url(self, logo_path: str, club_name: str = '') -> str:
"""Get logo URL from S3 or fallback to static."""
config = self.config_manager.config
if not config.get('enable_s3', False):
return self._get_static_logo_url(logo_path)
bucket_name = config.get('bucket_name', '')
bucket_prefix = config.get('bucket_prefix', 'motm-assets/')
if not bucket_name:
return self._get_static_logo_url(logo_path)
# Clean up the logo path
if logo_path.startswith('/static/'):
s3_key = bucket_prefix + logo_path.replace('/static/', '')
elif logo_path.startswith('logos/'):
s3_key = bucket_prefix + logo_path
else:
s3_key = bucket_prefix + 'logos/' + logo_path
try:
if config.get('use_signed_urls', True):
# Generate signed URL
expiry = config.get('signed_url_expiry', 3600)
signed_url = self.s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': s3_key},
ExpiresIn=expiry
)
return signed_url
else:
# Return public URL
return self._get_public_url(bucket_name, s3_key)
except ClientError:
# Fallback to static if S3 fails
if config.get('fallback_to_static', True):
return self._get_static_logo_url(logo_path)
return ''
def get_logo_url_public(self, logo_path: str, club_name: str = '') -> str:
"""Get logo URL from S3 using public URLs (no authentication)."""
config = self.config_manager.config
if not config.get('enable_s3', False):
return self._get_static_logo_url(logo_path)
bucket_name = config.get('bucket_name', '')
bucket_prefix = config.get('bucket_prefix', 'assets/')
if not bucket_name:
return self._get_static_logo_url(logo_path)
# Clean up the logo path
if logo_path.startswith('/static/'):
s3_key = bucket_prefix + logo_path.replace('/static/', '')
elif logo_path.startswith('logos/'):
s3_key = bucket_prefix + logo_path
else:
s3_key = bucket_prefix + 'logos/' + logo_path
try:
# Always return public URL (no authentication)
return self._get_public_url(bucket_name, s3_key)
except Exception:
# Fallback to static if S3 fails
if config.get('fallback_to_static', True):
return self._get_static_logo_url(logo_path)
return ''
def get_asset_url(self, asset_path: str) -> str:
"""Get any asset URL from S3 or fallback to static."""
config = self.config_manager.config
if not config.get('enable_s3', False):
return f"/static/{asset_path}"
bucket_name = config.get('bucket_name', '')
bucket_prefix = config.get('bucket_prefix', 'motm-assets/')
if not bucket_name:
return f"/static/{asset_path}"
# Clean up the asset path
if asset_path.startswith('/static/'):
s3_key = bucket_prefix + asset_path.replace('/static/', '')
else:
s3_key = bucket_prefix + asset_path
try:
if config.get('use_signed_urls', True):
# Generate signed URL
expiry = config.get('signed_url_expiry', 3600)
signed_url = self.s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': s3_key},
ExpiresIn=expiry
)
return signed_url
else:
# Return public URL
return self._get_public_url(bucket_name, s3_key)
except ClientError:
# Fallback to static if S3 fails
if config.get('fallback_to_static', True):
return f"/static/{asset_path}"
return ''
def get_asset_url_public(self, asset_path: str) -> str:
"""Get any asset URL from S3 using public URLs (no authentication)."""
config = self.config_manager.config
if not config.get('enable_s3', False):
return f"/static/{asset_path}"
bucket_name = config.get('bucket_name', '')
bucket_prefix = config.get('bucket_prefix', 'assets/')
if not bucket_name:
return f"/static/{asset_path}"
# Clean up the asset path
if asset_path.startswith('/static/'):
s3_key = bucket_prefix + asset_path.replace('/static/', '')
else:
s3_key = bucket_prefix + asset_path
try:
# Always return public URL (no authentication)
return self._get_public_url(bucket_name, s3_key)
except Exception:
# Fallback to static if S3 fails
if config.get('fallback_to_static', True):
return f"/static/{asset_path}"
return ''
def upload_asset(self, file_path: str, s3_key: str) -> tuple[bool, str]:
"""Upload an asset to S3."""
config = self.config_manager.config
if not config.get('enable_s3', False):
return False, "S3 is disabled"
bucket_name = config.get('bucket_name', '')
bucket_prefix = config.get('bucket_prefix', 'motm-assets/')
if not bucket_name:
return False, "Bucket name not configured"
full_s3_key = bucket_prefix + s3_key
try:
self.s3_client.upload_file(file_path, bucket_name, full_s3_key)
return True, f"Successfully uploaded {s3_key} to S3"
except ClientError as e:
return False, f"Upload failed: {e.response['Error']['Message']}"
except Exception as e:
return False, f"Upload error: {str(e)}"
def _get_static_logo_url(self, logo_path: str) -> str:
"""Get static logo URL as fallback."""
if logo_path.startswith('/static/'):
return logo_path
return f"/static/images/{logo_path}"
# Global instances
s3_config_manager = S3ConfigManager()
s3_asset_service = S3AssetService(s3_config_manager)
+148
View File
@@ -0,0 +1,148 @@
# MOTM Flask Application - Virtual Environment Setup (PowerShell)
# Run this script in PowerShell: .\setup_venv.ps1
Write-Host "MOTM Flask Application - Virtual Environment Setup" -ForegroundColor Green
Write-Host "=" * 60 -ForegroundColor Green
# Check Python installation
Write-Host "`n🐍 Checking Python installation..." -ForegroundColor Yellow
$pythonCommands = @('python', 'python3', 'py')
$pythonCmd = $null
foreach ($cmd in $pythonCommands) {
try {
$version = & $cmd --version 2>$null
if ($LASTEXITCODE -eq 0) {
$pythonCmd = $cmd
Write-Host "✅ Found Python: $version" -ForegroundColor Green
break
}
}
catch {
# Continue to next command
}
}
if (-not $pythonCmd) {
Write-Host "❌ Python not found. Please install Python 3.7+ from python.org" -ForegroundColor Red
Write-Host " Make sure to check 'Add Python to PATH' during installation" -ForegroundColor Yellow
Read-Host "Press Enter to exit"
exit 1
}
# Check if virtual environment already exists
$venvDir = "venv"
if (Test-Path $venvDir) {
Write-Host "`n⚠ Virtual environment '$venvDir' already exists" -ForegroundColor Yellow
$recreate = Read-Host "Do you want to recreate it? (y/N)"
if ($recreate -match '^[yY]') {
Write-Host "🗑️ Removing existing virtual environment..." -ForegroundColor Yellow
Remove-Item -Recurse -Force $venvDir
} else {
Write-Host "Using existing virtual environment..." -ForegroundColor Green
$skipCreation = $true
}
}
# Create virtual environment
if (-not $skipCreation) {
Write-Host "`n📦 Creating virtual environment in '$venvDir'..." -ForegroundColor Yellow
try {
& $pythonCmd -m venv $venvDir
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Virtual environment created successfully!" -ForegroundColor Green
} else {
throw "Virtual environment creation failed"
}
}
catch {
Write-Host "❌ Failed to create virtual environment: $_" -ForegroundColor Red
Read-Host "Press Enter to exit"
exit 1
}
}
# Install dependencies
Write-Host "`n📚 Installing dependencies..." -ForegroundColor Yellow
$pipCmd = Join-Path $venvDir "Scripts\pip.exe"
if (-not (Test-Path $pipCmd)) {
$pipCmd = Join-Path $venvDir "Scripts\pip"
}
try {
# Upgrade pip first
Write-Host "🔄 Upgrading pip..." -ForegroundColor Yellow
& $pipCmd install --upgrade pip
# Install requirements
Write-Host "📦 Installing application dependencies..." -ForegroundColor Yellow
& $pipCmd install -r requirements.txt
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Dependencies installed successfully!" -ForegroundColor Green
} else {
throw "Dependencies installation failed"
}
}
catch {
Write-Host "❌ Failed to install dependencies: $_" -ForegroundColor Red
Read-Host "Press Enter to exit"
exit 1
}
# Create convenience scripts
Write-Host "`n📝 Creating convenience scripts..." -ForegroundColor Yellow
# Update the batch files to use the correct Python command
$activateScript = @"
@echo off
echo 🐍 Activating MOTM Virtual Environment...
call venv\Scripts\activate.bat
echo ✅ Virtual environment activated!
echo.
echo 🚀 To start the MOTM application, run:
echo $pythonCmd main.py
echo.
echo 🔧 To deactivate, run:
echo deactivate
"@
$runScript = @"
@echo off
echo 🐍 Starting MOTM Application...
call venv\Scripts\activate.bat
$pythonCmd main.py
pause
"@
$activateScript | Out-File -FilePath "activate_motm.bat" -Encoding ASCII
$runScript | Out-File -FilePath "run_motm.bat" -Encoding ASCII
Write-Host "✅ Convenience scripts created!" -ForegroundColor Green
# Print completion message
Write-Host "`n" + "=" * 60 -ForegroundColor Green
Write-Host "🎉 MOTM Virtual Environment Setup Complete!" -ForegroundColor Green
Write-Host "=" * 60 -ForegroundColor Green
Write-Host "`n📋 To use the virtual environment:" -ForegroundColor Cyan
Write-Host " 1. Activate: .\activate_motm.bat" -ForegroundColor White
Write-Host " 2. Run app: .\run_motm.bat" -ForegroundColor White
Write-Host " 3. Deactivate: deactivate" -ForegroundColor White
Write-Host "`n🔧 Manual activation:" -ForegroundColor Cyan
Write-Host " venv\Scripts\activate.bat" -ForegroundColor White
Write-Host " $pythonCmd main.py" -ForegroundColor White
Write-Host "`n🌐 The application will be available at: http://localhost:5000" -ForegroundColor Cyan
Write-Host "`n📚 For development:" -ForegroundColor Cyan
Write-Host " - Activate the venv before installing new packages" -ForegroundColor White
Write-Host " - Use 'pip install <package>' to add dependencies" -ForegroundColor White
Write-Host " - Update requirements.txt with 'pip freeze > requirements.txt'" -ForegroundColor White
Write-Host "`n🚀 Ready to start! Run: .\run_motm.bat" -ForegroundColor Green
Read-Host "`nPress Enter to exit"
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""
Setup script to create and configure a Python virtual environment for the MOTM application.
"""
import os
import sys
import subprocess
import platform
def create_virtual_environment():
"""Create a Python virtual environment for the MOTM application."""
print("🐍 Setting up Python virtual environment for MOTM application...")
print("=" * 60)
# Check Python version
python_version = sys.version_info
print(f"✓ Python version: {python_version.major}.{python_version.minor}.{python_version.micro}")
if python_version < (3, 7):
print("❌ Python 3.7 or higher is required")
return False
# Determine the virtual environment directory name
venv_dir = "venv"
# Check if virtual environment already exists
if os.path.exists(venv_dir):
print(f"⚠ Virtual environment '{venv_dir}' already exists")
response = input("Do you want to recreate it? (y/N): ").strip().lower()
if response in ['y', 'yes']:
print(f"🗑️ Removing existing virtual environment...")
if platform.system() == "Windows":
subprocess.run(['rmdir', '/s', '/q', venv_dir], shell=True)
else:
subprocess.run(['rm', '-rf', venv_dir])
else:
print("Using existing virtual environment...")
return True
# Create virtual environment
print(f"📦 Creating virtual environment in '{venv_dir}'...")
try:
subprocess.run([sys.executable, '-m', 'venv', venv_dir], check=True)
print("✅ Virtual environment created successfully!")
except subprocess.CalledProcessError as e:
print(f"❌ Failed to create virtual environment: {e}")
return False
return True
def get_activation_script():
"""Get the appropriate activation script for the current platform."""
if platform.system() == "Windows":
return os.path.join("venv", "Scripts", "activate.bat")
else:
return os.path.join("venv", "bin", "activate")
def install_dependencies():
"""Install required dependencies in the virtual environment."""
print("\n📚 Installing dependencies...")
# Determine the pip command based on platform
if platform.system() == "Windows":
pip_cmd = os.path.join("venv", "Scripts", "pip")
else:
pip_cmd = os.path.join("venv", "bin", "pip")
# Check if requirements.txt exists
if not os.path.exists("requirements.txt"):
print("❌ requirements.txt not found")
return False
try:
# Upgrade pip first
print("🔄 Upgrading pip...")
subprocess.run([pip_cmd, "install", "--upgrade", "pip"], check=True)
# Install requirements
print("📦 Installing application dependencies...")
subprocess.run([pip_cmd, "install", "-r", "requirements.txt"], check=True)
print("✅ Dependencies installed successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install dependencies: {e}")
return False
def create_activation_scripts():
"""Create convenient activation scripts."""
print("\n📝 Creating activation scripts...")
# Windows batch script
windows_script = """@echo off
echo 🐍 Activating MOTM Virtual Environment...
call venv\\Scripts\\activate.bat
echo ✅ Virtual environment activated!
echo.
echo 🚀 To start the MOTM application, run:
echo python main.py
echo.
echo 🔧 To deactivate, run:
echo deactivate
"""
# Unix shell script
unix_script = """#!/bin/bash
echo "🐍 Activating MOTM Virtual Environment..."
source venv/bin/activate
echo "✅ Virtual environment activated!"
echo ""
echo "🚀 To start the MOTM application, run:"
echo " python main.py"
echo ""
echo "🔧 To deactivate, run:"
echo " deactivate"
"""
# Write platform-specific scripts
if platform.system() == "Windows":
with open("activate_motm.bat", "w") as f:
f.write(windows_script)
print("✓ Created activate_motm.bat for Windows")
else:
with open("activate_motm.sh", "w") as f:
f.write(unix_script)
# Make it executable
os.chmod("activate_motm.sh", 0o755)
print("✓ Created activate_motm.sh for Unix/Linux")
return True
def create_run_script():
"""Create a script to run the application directly."""
print("📝 Creating run script...")
# Windows batch script
windows_run = """@echo off
echo 🐍 Starting MOTM Application...
call venv\\Scripts\\activate.bat
python main.py
pause
"""
# Unix shell script
unix_run = """#!/bin/bash
echo "🐍 Starting MOTM Application..."
source venv/bin/activate
python main.py
"""
if platform.system() == "Windows":
with open("run_motm.bat", "w") as f:
f.write(windows_run)
print("✓ Created run_motm.bat")
else:
with open("run_motm.sh", "w") as f:
f.write(unix_run)
os.chmod("run_motm.sh", 0o755)
print("✓ Created run_motm.sh")
def print_instructions():
"""Print setup completion instructions."""
print("\n" + "=" * 60)
print("🎉 MOTM Virtual Environment Setup Complete!")
print("=" * 60)
if platform.system() == "Windows":
print("\n📋 To use the virtual environment:")
print(" 1. Activate: activate_motm.bat")
print(" 2. Run app: run_motm.bat")
print(" 3. Deactivate: deactivate")
print("\n🔧 Manual activation:")
print(" venv\\Scripts\\activate.bat")
print(" python main.py")
else:
print("\n📋 To use the virtual environment:")
print(" 1. Activate: source activate_motm.sh")
print(" 2. Run app: ./run_motm.sh")
print(" 3. Deactivate: deactivate")
print("\n🔧 Manual activation:")
print(" source venv/bin/activate")
print(" python main.py")
print("\n🌐 The application will be available at: http://localhost:5000")
print("\n📚 For development:")
print(" - Activate the venv before installing new packages")
print(" - Use 'pip install <package>' to add dependencies")
print(" - Update requirements.txt with 'pip freeze > requirements.txt'")
def main():
"""Main setup function."""
# Change to the script's directory
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
print("MOTM Flask Application - Virtual Environment Setup")
print("=" * 60)
# Step 1: Create virtual environment
if not create_virtual_environment():
sys.exit(1)
# Step 2: Install dependencies
if not install_dependencies():
sys.exit(1)
# Step 3: Create convenience scripts
create_activation_scripts()
create_run_script()
# Step 4: Print instructions
print_instructions()
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
@echo off
echo MOTM Flask Application - Virtual Environment Setup
echo ================================================
echo.
echo 🐍 Creating Python virtual environment...
REM Check if virtual environment already exists
if exist venv (
echo ⚠ Virtual environment 'venv' already exists
set /p recreate="Do you want to recreate it? (y/N): "
if /i "%recreate%"=="y" (
echo 🗑️ Removing existing virtual environment...
rmdir /s /q venv
) else (
echo Using existing virtual environment...
goto :install_deps
)
)
REM Create virtual environment
echo 📦 Creating virtual environment in 'venv'...
python.exe -m venv venv
if errorlevel 1 (
echo ❌ Failed to create virtual environment
pause
exit /b 1
)
echo ✅ Virtual environment created successfully!
:install_deps
echo.
echo 📚 Installing dependencies...
REM Upgrade pip first
echo 🔄 Upgrading pip...
venv\Scripts\pip install --upgrade pip
REM Install requirements
echo 📦 Installing application dependencies...
venv\Scripts\pip install -r requirements.txt
if errorlevel 1 (
echo ❌ Failed to install dependencies
pause
exit /b 1
)
echo ✅ Dependencies installed successfully!
echo.
echo ================================================
echo 🎉 MOTM Virtual Environment Setup Complete!
echo ================================================
echo.
echo 📋 To use the virtual environment:
echo 1. Activate: activate_motm.bat
echo 2. Run app: run_motm.bat
echo 3. Deactivate: deactivate
echo.
echo 🔧 Manual activation:
echo venv\Scripts\activate.bat
echo python main.py
echo.
echo 🌐 The application will be available at: http://localhost:5000
echo.
echo 📚 For development:
echo - Activate the venv before installing new packages
echo - Use 'pip install ^<package^>' to add dependencies
echo - Update requirements.txt with 'pip freeze ^> requirements.txt'
echo.
pause
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
# Production startup script for MOTM App
echo "Starting MOTM App in production mode..."
# Check if virtual environment exists
if [ ! -d "venv" ]; then
echo "Creating virtual environment..."
python3 -m venv venv
fi
# Activate virtual environment
echo "Activating virtual environment..."
source venv/bin/activate
# Install/upgrade dependencies
echo "Installing dependencies..."
pip install --upgrade pip
pip install -r requirements.txt
# Set production environment
export FLASK_ENV=production
# Start Gunicorn
echo "Starting Gunicorn WSGI server..."
gunicorn -c gunicorn.conf.py run_production:app
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
<svg width="120" height="80" xmlns="http://www.w3.org/2000/svg">
<rect width="120" height="80" fill="#f8f9fa" stroke="#dee2e6" stroke-width="2"/>
<text x="60" y="45" font-family="Arial, sans-serif" font-size="12" text-anchor="middle" fill="#6c757d">Club Logo</text>
</svg>

After

Width:  |  Height:  |  Size: 277 B

@@ -0,0 +1 @@
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==
File diff suppressed because one or more lines are too long
+46
View File
@@ -0,0 +1,46 @@
from markupsafe import Markup
class matchSquadTable:
def __init__(self, items):
self.items = items
self.border = True
self.classes = []
def __html__(self):
"""Generate HTML table from items"""
if not self.items:
return Markup('<div class="alert alert-info text-center"><i class="fas fa-info-circle me-2"></i>No players in squad</div>')
# Start table with Bootstrap 5 classes
classes_str = ' '.join(self.classes) if self.classes else 'table table-striped table-hover'
html = f'<div class="table-responsive"><table class="{classes_str} mb-0">\n'
# Table header with modern styling
html += ' <thead class="table-dark">\n <tr>\n'
html += ' <th><i class="fas fa-hashtag me-1"></i>Player Number</th>\n'
html += ' <th><i class="fas fa-user me-1"></i>Nickname</th>\n'
html += ' <th><i class="fas fa-id-card me-1"></i>Surname</th>\n'
html += ' <th><i class="fas fa-id-card me-1"></i>Forenames</th>\n'
html += ' <th class="text-center"><i class="fas fa-cog me-1"></i>Actions</th>\n'
html += ' </tr>\n </thead>\n'
# Table body with enhanced styling
html += ' <tbody>\n'
for item in self.items:
html += ' <tr>\n'
html += f' <td><span class="badge bg-primary fs-6">#{item.get("playernumber", "")}</span></td>\n'
html += f' <td><strong>{item.get("playernickname", "")}</strong></td>\n'
html += f' <td>{item.get("playersurname", "")}</td>\n'
html += f' <td>{item.get("playerforenames", "")}</td>\n'
html += f' <td class="text-center">'
html += f'<form method="post" action="/admin/squad/remove?playerNumber={item.get("playernumber", "")}" class="d-inline">'
html += f'<button type="submit" class="btn btn-danger btn-sm" data-confirm="Are you sure you want to remove player #{item.get("playernumber", "")} from the squad?">'
html += f'<i class="fas fa-trash me-1"></i>Remove</button></form></td>\n'
html += ' </tr>\n'
html += ' </tbody>\n'
# End table
html += '</table></div>\n'
return Markup(html)
+334
View File
@@ -0,0 +1,334 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Club - HKFC Men's C Team</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3>Add New Club</h3>
</div>
<div class="card-body">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="POST">
{{ form.hidden_tag() }}
<div class="mb-3">
{{ form.hockey_club.label(class="form-label") }}
{{ form.hockey_club(class="form-control") }}
{% if form.hockey_club.errors %}
<div class="text-danger">
{% for error in form.hockey_club.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
</div>
<div class="mb-3">
{{ form.logo_url.label(class="form-label") }}
<div class="input-group">
{{ form.logo_url(class="form-control", id="logoUrl", onchange="previewLogo()") }}
<button type="button" class="btn btn-outline-secondary" onclick="browseS3()" title="Browse S3 Storage">
<i class="fas fa-cloud"></i> Browse S3
</button>
</div>
{% if form.logo_url.errors %}
<div class="text-danger">
{% for error in form.logo_url.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
<small class="form-text text-muted">Enter the full URL to the club's logo image or use the S3 browser to select from your configured storage.</small>
<!-- Logo Preview -->
<div id="logoPreview" class="mt-2" style="display: none;">
<label class="form-label small">Preview:</label>
<div class="border rounded p-2 bg-light">
<img id="previewImage" src="" alt="Logo preview" style="max-height: 80px; max-width: 120px;" onerror="this.style.display='none'; document.getElementById('previewError').style.display='block';" onload="document.getElementById('previewError').style.display='none';">
<div id="previewError" class="text-muted small" style="display: none;">Unable to load image</div>
</div>
</div>
</div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
{{ form.cancel(class="btn btn-secondary me-md-2") }}
{{ form.save_club(class="btn btn-primary") }}
</div>
</form>
</div>
</div>
<!-- S3 Browser Modal -->
<div class="modal fade" id="s3BrowserModal" tabindex="-1" aria-labelledby="s3BrowserModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="s3BrowserModalLabel">Browse S3 Storage</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="s3BrowserContent">
<div class="text-center">
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p>Loading S3 contents...</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="selectS3FileBtn" onclick="selectS3File()" disabled>Select File</button>
</div>
</div>
</div>
</div>
<div class="mt-3">
<a href="/admin/clubs" class="btn btn-outline-secondary">Back to Club Management</a>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function previewLogo() {
const urlInput = document.getElementById('logoUrl');
const previewDiv = document.getElementById('logoPreview');
const previewImg = document.getElementById('previewImage');
if (urlInput.value.trim()) {
previewImg.src = urlInput.value;
previewDiv.style.display = 'block';
} else {
previewDiv.style.display = 'none';
}
}
// S3 Browser functionality
let selectedS3File = null;
let currentS3Path = '';
function browseS3() {
// Reset state
selectedS3File = null;
currentS3Path = '';
// Show loading state
document.getElementById('s3BrowserContent').innerHTML = `
<div class="text-center">
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p>Loading S3 contents...</p>
</div>
`;
// Show modal
const s3BrowserModal = new bootstrap.Modal(document.getElementById('s3BrowserModal'));
s3BrowserModal.show();
// Load S3 contents from root of assets folder
loadS3Contents('');
}
function loadS3Contents(path) {
fetch(`/admin/api/s3-browser?path=${encodeURIComponent(path)}`)
.then(response => response.json())
.then(data => {
if (data.success) {
displayS3Contents(data);
} else {
document.getElementById('s3BrowserContent').innerHTML = `
<div class="alert alert-danger" role="alert">
<strong>Error:</strong> ${data.message}
</div>
`;
}
})
.catch(error => {
console.error('Error:', error);
document.getElementById('s3BrowserContent').innerHTML = `
<div class="alert alert-danger" role="alert">
<strong>Error:</strong> Failed to load S3 contents. Please try again.
</div>
`;
});
}
function displayS3Contents(data) {
currentS3Path = data.path;
let html = `
<div class="row mb-3">
<div class="col-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#" onclick="loadS3Contents('')">assets</a>
</li>
`;
// Build breadcrumb
if (data.path !== '') {
const pathParts = data.path.split('/').filter(p => p);
let currentPath = '';
pathParts.forEach((part, index) => {
currentPath += part + '/';
const isLast = index === pathParts.length - 1;
html += `<li class="breadcrumb-item ${isLast ? 'active' : ''}">`;
if (!isLast) {
html += `<a href="#" onclick="loadS3Contents('${currentPath}')">${part}</a>`;
} else {
html += part;
}
html += '</li>';
});
}
html += `
</ol>
</nav>
</div>
</div>
<div class="row">
`;
// Display folders
if (data.folders.length > 0) {
data.folders.forEach(folder => {
html += `
<div class="col-md-3 mb-3">
<div class="card h-100 folder-card" onclick="loadS3Contents('${folder.path}')" style="cursor: pointer;">
<div class="card-body text-center">
<i class="fas fa-folder fa-3x text-warning mb-2"></i>
<h6 class="card-title">${folder.name}</h6>
</div>
</div>
</div>
`;
});
}
// Display files
if (data.files.length > 0) {
data.files.forEach(file => {
const isImage = /\.(jpg|jpeg|png|gif|svg|webp)$/i.test(file.name);
const fileSize = formatFileSize(file.size);
html += `
<div class="col-md-3 mb-3">
<div class="card h-100 file-card" onclick="selectS3FileItem('${file.path}', '${file.url}')" style="cursor: pointer;">
<div class="card-body text-center">
`;
if (isImage) {
html += `
<img src="${file.url}" alt="${file.name}" class="img-fluid mb-2" style="max-height: 100px; max-width: 100%; object-fit: contain;">
`;
} else {
html += `
<i class="fas fa-file fa-3x text-primary mb-2"></i>
`;
}
html += `
<h6 class="card-title">${file.name}</h6>
<small class="text-muted">${fileSize}</small>
</div>
</div>
</div>
`;
});
}
if (data.folders.length === 0 && data.files.length === 0) {
html += `
<div class="col-12">
<div class="alert alert-info text-center">
<i class="fas fa-info-circle"></i> No files or folders found in this directory.
</div>
</div>
`;
}
html += `
</div>
`;
document.getElementById('s3BrowserContent').innerHTML = html;
}
function selectS3FileItem(filePath, fileUrl) {
// Remove previous selection
document.querySelectorAll('.file-card').forEach(card => {
card.classList.remove('border-primary');
});
// Add selection to clicked card
event.currentTarget.classList.add('border-primary');
// Store selected file
selectedS3File = {
path: filePath,
url: fileUrl
};
// Enable select button
document.getElementById('selectS3FileBtn').disabled = false;
}
function selectS3File() {
if (selectedS3File) {
// Update the logo URL field
const logoUrlField = document.getElementById('logoUrl');
if (logoUrlField) {
logoUrlField.value = selectedS3File.path;
// Trigger preview update
previewLogo();
}
// Close modal
const s3BrowserModal = bootstrap.Modal.getInstance(document.getElementById('s3BrowserModal'));
s3BrowserModal.hide();
}
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Preview logo on page load if URL is already filled
document.addEventListener('DOMContentLoaded', function() {
previewLogo();
});
</script>
</body>
</html>
+109
View File
@@ -0,0 +1,109 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Player - HKFC Men's C Team</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3>Add New Player</h3>
</div>
<div class="card-body">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="POST">
{{ form.hidden_tag() }}
<div class="mb-3">
{{ form.player_number.label(class="form-label") }}
{{ form.player_number(class="form-control") }}
{% if form.player_number.errors %}
<div class="text-danger">
{% for error in form.player_number.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
</div>
<div class="mb-3">
{{ form.player_forenames.label(class="form-label") }}
{{ form.player_forenames(class="form-control") }}
{% if form.player_forenames.errors %}
<div class="text-danger">
{% for error in form.player_forenames.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
</div>
<div class="mb-3">
{{ form.player_surname.label(class="form-label") }}
{{ form.player_surname(class="form-control") }}
{% if form.player_surname.errors %}
<div class="text-danger">
{% for error in form.player_surname.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
</div>
<div class="mb-3">
{{ form.player_nickname.label(class="form-label") }}
{{ form.player_nickname(class="form-control") }}
{% if form.player_nickname.errors %}
<div class="text-danger">
{% for error in form.player_nickname.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
</div>
<div class="mb-3">
{{ form.player_team.label(class="form-label") }}
{{ form.player_team(class="form-select") }}
{% if form.player_team.errors %}
<div class="text-danger">
{% for error in form.player_team.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
</div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
{{ form.cancel(class="btn btn-secondary me-md-2") }}
{{ form.save_player(class="btn btn-primary") }}
</div>
</form>
</div>
</div>
<div class="mt-3">
<a href="/admin/players" class="btn btn-outline-secondary">Back to Player Management</a>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
+101
View File
@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Team - HKFC Men's C Team</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3>Add New Team</h3>
</div>
<div class="card-body">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="POST">
{{ form.hidden_tag() }}
<div class="mb-3">
{{ form.club.label(class="form-label") }}
{{ form.club(class="form-select") }}
{% if form.club.errors %}
<div class="text-danger">
{% for error in form.club.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
<small class="form-text text-muted">Select the club from the list of available clubs</small>
</div>
<div class="mb-3">
{{ form.team.label(class="form-label") }}
{{ form.team(class="form-control") }}
{% if form.team.errors %}
<div class="text-danger">
{% for error in form.team.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
<small class="form-text text-muted">Enter the team identifier (e.g., A, B, C, 1st, 2nd)</small>
</div>
<div class="mb-3">
{{ form.display_name.label(class="form-label") }}
{{ form.display_name(class="form-control") }}
{% if form.display_name.errors %}
<div class="text-danger">
{% for error in form.display_name.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
<small class="form-text text-muted">Enter the full display name (e.g., HKFC A, KCC 1st Team)</small>
</div>
<div class="mb-3">
{{ form.league.label(class="form-label") }}
{{ form.league(class="form-select") }}
{% if form.league.errors %}
<div class="text-danger">
{% for error in form.league.errors %}
<small>{{ error }}</small>
{% endfor %}
</div>
{% endif %}
<small class="form-text text-muted">Select the league/division from the list</small>
</div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
{{ form.cancel(class="btn btn-secondary me-md-2") }}
{{ form.save_team(class="btn btn-primary") }}
</div>
</form>
</div>
</div>
<div class="mt-3">
<a href="/admin/teams" class="btn btn-outline-secondary">Back to Team Management</a>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
+371
View File
@@ -0,0 +1,371 @@
{% extends "base.html" %}
{% block title %}Admin Dashboard - HKFC Men's C Team MOTM System{% endblock %}
{% block content %}
<!-- Dashboard Header -->
<div class="row mb-4">
<div class="col-12">
<div class="card">
<div class="card-body text-center">
<h1 class="card-title">
<i class="fas fa-tachometer-alt text-primary me-2"></i>
Admin Dashboard
</h1>
<p class="lead text-muted">Central hub for all administrative functions</p>
</div>
</div>
</div>
</div>
<!-- Quick Actions -->
<div class="row mb-4">
<div class="col-12">
<div class="card">
<div class="card-header bg-primary text-white">
<h5 class="card-title mb-0">
<i class="fas fa-bolt me-2"></i>Quick Actions
</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-3 mb-3">
<a href="/admin/import" class="btn btn-outline-primary w-100">
<i class="fas fa-download me-2"></i>
<div class="text-start">
<div class="fw-bold">Import Data</div>
<small class="text-muted">Import from HKHA</small>
</div>
</a>
</div>
<div class="col-md-3 mb-3">
<a href="/admin/squad" class="btn btn-outline-success w-100">
<i class="fas fa-list-check me-2"></i>
<div class="text-start">
<div class="fw-bold">Select Squad</div>
<small class="text-muted">Choose match squad</small>
</div>
</a>
</div>
<div class="col-md-3 mb-3">
<a href="/admin/motm" class="btn btn-outline-warning w-100">
<i class="fas fa-trophy me-2"></i>
<div class="text-start">
<div class="fw-bold">MOTM Settings</div>
<small class="text-muted">Manage voting</small>
</div>
</a>
</div>
<div class="col-md-3 mb-3">
<a href="/admin/motm/manage" class="btn btn-outline-danger w-100">
<i class="fas fa-database me-2"></i>
<div class="text-start">
<div class="fw-bold">MOTM Management</div>
<small class="text-muted">Reset & drop columns</small>
</div>
</a>
</div>
<div class="col-md-3 mb-3">
<a href="/admin/comments/manage" class="btn btn-outline-warning w-100">
<i class="fas fa-comments me-2"></i>
<div class="text-start">
<div class="fw-bold">Comments Management</div>
<small class="text-muted">Edit & delete comments</small>
</div>
</a>
</div>
<div class="col-md-3 mb-3">
<a href="/admin/profile" class="btn btn-outline-secondary w-100">
<i class="fas fa-user-cog me-2"></i>
<div class="text-start">
<div class="fw-bold">Admin Profile</div>
<small class="text-muted">Account settings</small>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Data Management Section -->
<div class="row mb-4">
<div class="col-12">
<div class="card">
<div class="card-header bg-success text-white">
<h5 class="card-title mb-0">
<i class="fas fa-database me-2"></i>Data Management
</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-4 mb-3">
<div class="card h-100 border-success">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-users text-success me-2"></i>Club Management
</h6>
</div>
<div class="card-body">
<p class="card-text">Manage hockey clubs, logos, and club information.</p>
<div class="d-grid gap-2">
<a href="/admin/clubs" class="btn btn-success">
<i class="fas fa-eye me-2"></i>View Clubs
</a>
<a href="/admin/clubs/add" class="btn btn-outline-success">
<i class="fas fa-plus me-2"></i>Add Club
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 mb-3">
<div class="card h-100 border-primary">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-user text-primary me-2"></i>Player Management
</h6>
</div>
<div class="card-body">
<p class="card-text">Add, edit, and manage player information and squads.</p>
<div class="d-grid gap-2">
<a href="/admin/players" class="btn btn-primary">
<i class="fas fa-eye me-2"></i>View Players
</a>
<a href="/admin/players/add" class="btn btn-outline-primary">
<i class="fas fa-plus me-2"></i>Add Player
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 mb-3">
<div class="card h-100 border-info">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-layer-group text-info me-2"></i>Team Management
</h6>
</div>
<div class="card-body">
<p class="card-text">Manage hockey teams and their associations with clubs.</p>
<div class="d-grid gap-2">
<a href="/admin/teams" class="btn btn-info">
<i class="fas fa-eye me-2"></i>View Teams
</a>
<a href="/admin/teams/add" class="btn btn-outline-info">
<i class="fas fa-plus me-2"></i>Add Team
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Analytics & Reports Section -->
<div class="row mb-4">
<div class="col-12">
<div class="card">
<div class="card-header bg-info text-white">
<h5 class="card-title mb-0">
<i class="fas fa-chart-bar me-2"></i>Analytics & Reports
</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-4 mb-3">
<div class="card h-100 border-info">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-poll text-info me-2"></i>Vote Charts
</h6>
</div>
<div class="card-body">
<p class="card-text">View current vote counts and MOTM/DotD results for the current match.</p>
<div class="d-grid gap-2">
<a href="/admin/voting" class="btn btn-info">
<i class="fas fa-chart-pie me-2"></i>View Vote Charts
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 mb-3">
<div class="card h-100 border-success">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-trophy text-success me-2"></i>Player of the Year
</h6>
</div>
<div class="card-body">
<p class="card-text">View Player of the Year standings and cumulative MOTM votes.</p>
<div class="d-grid gap-2">
<a href="/admin/poty" class="btn btn-success">
<i class="fas fa-medal me-2"></i>View POTY Chart
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 mb-3">
<div class="card h-100 border-warning">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-futbol text-warning me-2"></i>Goals & Assists
</h6>
</div>
<div class="card-body">
<p class="card-text">Manage goals and assists statistics for matches.</p>
<div class="d-grid gap-2">
<a href="/admin/stats" class="btn btn-warning">
<i class="fas fa-plus me-2"></i>Add Stats
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- System Management Section -->
<div class="row mb-4">
<div class="col-12">
<div class="card">
<div class="card-header bg-warning text-dark">
<h5 class="card-title mb-0">
<i class="fas fa-cogs me-2"></i>System Management
</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-4 mb-3">
<div class="card h-100 border-warning">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-cloud text-warning me-2"></i>S3 Storage
</h6>
</div>
<div class="card-body">
<p class="card-text">Configure and manage S3 storage for assets and logos.</p>
<div class="d-grid gap-2">
<a href="/admin/s3-config" class="btn btn-warning">
<i class="fas fa-cog me-2"></i>Configure S3
</a>
<a href="/admin/s3-status" class="btn btn-outline-warning">
<i class="fas fa-info-circle me-2"></i>View Status
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 mb-3">
<div class="card h-100 border-secondary">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-database text-secondary me-2"></i>Database
</h6>
</div>
<div class="card-body">
<p class="card-text">Manage database configuration and status.</p>
<div class="d-grid gap-2">
<a href="/admin/database-status" class="btn btn-secondary">
<i class="fas fa-info-circle me-2"></i>Database Status
</a>
<a href="/admin/database-setup" class="btn btn-outline-secondary">
<i class="fas fa-wrench me-2"></i>Database Setup
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 mb-3">
<div class="card h-100 border-dark">
<div class="card-header bg-light">
<h6 class="card-title mb-0">
<i class="fas fa-list-check text-dark me-2"></i>Squad Management
</h6>
</div>
<div class="card-body">
<p class="card-text">Manage match squads and player selections.</p>
<div class="d-grid gap-2">
<a href="/admin/squad/list" class="btn btn-dark">
<i class="fas fa-eye me-2"></i>View Squad
</a>
<a href="/admin/squad/history" class="btn btn-outline-dark">
<i class="fas fa-history me-2"></i>Squad History
</a>
<a href="/admin/squad/reset" class="btn btn-outline-dark">
<i class="fas fa-refresh me-2"></i>Reset Squad
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- System Status -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header bg-info text-white">
<h5 class="card-title mb-0">
<i class="fas fa-heartbeat me-2"></i>System Status
</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-3 text-center">
<div class="mb-2">
<i class="fas fa-server text-success fs-1"></i>
</div>
<h6>Database</h6>
<span class="badge bg-success">
<span class="status-indicator status-online"></span>Online
</span>
</div>
<div class="col-md-3 text-center">
<div class="mb-2">
<i class="fas fa-cloud text-info fs-1"></i>
</div>
<h6>S3 Storage</h6>
<span class="badge bg-info">
<span class="status-indicator status-online"></span>Configured
</span>
</div>
<div class="col-md-3 text-center">
<div class="mb-2">
<i class="fas fa-users text-primary fs-1"></i>
</div>
<h6>Active Users</h6>
<span class="badge bg-primary">1</span>
</div>
<div class="col-md-3 text-center">
<div class="mb-2">
<i class="fas fa-calendar text-warning fs-1"></i>
</div>
<h6>Next Match</h6>
<span class="badge bg-warning">Pending</span>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

Some files were not shown because too many files have changed in this diff Show More