Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Add multi-site WordPress management and UI overhaul

Juan Denise36c3247b314
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index 88b0a0bb..50011ce2 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -1,12 +1,107 @@
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
-from app.models import User, Application
+from app.models import User, Application, WordPressSite
from app.services.wordpress_service import WordPressService
from app import db
wordpress_bp = Blueprint('wordpress', __name__)
+def _resolve_app(site_or_app_id):
+ """Resolve an ID to an Application. Tries WordPressSite first, then Application."""
+ wp_site = WordPressSite.query.get(site_or_app_id)
+ if wp_site and wp_site.application:
+ return wp_site.application
+ return Application.query.get(site_or_app_id)
+
+
+# ==================== WORDPRESS SITES HUB ENDPOINTS ====================
+
+@wordpress_bp.route('/sites', methods=['GET'])
+@jwt_required()
+def list_sites():
+ """List all WordPress sites (production sites with environment counts)."""
+ result = WordPressService.get_sites()
+ return jsonify(result), 200
+
+
+@wordpress_bp.route('/sites', methods=['POST'])
+@jwt_required()
+def create_site():
+ """Create a new WordPress site via Docker."""
+ data = request.get_json() or {}
+ name = data.get('name')
+ admin_email = data.get('adminEmail', '')
+
+ if not name:
+ return jsonify({'error': 'Site name is required'}), 400
+
+ current_user_id = get_jwt_identity()
+ result = WordPressService.create_site(name, admin_email, current_user_id)
+
+ if result.get('success'):
+ return jsonify(result), 201
+ return jsonify(result), 400
+
+
+@wordpress_bp.route('/sites/<int:site_id>', methods=['GET'])
+@jwt_required()
+def get_site(site_id):
+ """Get site detail with environments."""
+ result = WordPressService.get_site(site_id)
+ if 'error' in result:
+ return jsonify(result), 404
+ return jsonify(result), 200
+
+
+@wordpress_bp.route('/sites/<int:site_id>', methods=['DELETE'])
+@jwt_required()
+def delete_site(site_id):
+ """Delete site and all its environments."""
+ result = WordPressService.delete_site(site_id)
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@wordpress_bp.route('/sites/<int:site_id>/environments', methods=['GET'])
+@jwt_required()
+def list_environments(site_id):
+ """List environments for a site."""
+ result = WordPressService.get_environments(site_id)
+ if 'error' in result:
+ return jsonify(result), 404
+ return jsonify(result), 200
+
+
+@wordpress_bp.route('/sites/<int:site_id>/environments', methods=['POST'])
+@jwt_required()
+def create_environment(site_id):
+ """Create a staging or development environment."""
+ data = request.get_json() or {}
+ env_type = data.get('type', '')
+
+ if not env_type:
+ return jsonify({'error': 'Environment type is required'}), 400
+
+ current_user_id = get_jwt_identity()
+ result = WordPressService.create_environment(site_id, env_type, current_user_id)
+
+ if result.get('success'):
+ return jsonify(result), 201
+ return jsonify(result), 400
+
+
+@wordpress_bp.route('/sites/<int:site_id>/environments/<int:env_id>', methods=['DELETE'])
+@jwt_required()
+def delete_environment(site_id, env_id):
+ """Delete a non-production environment."""
+ result = WordPressService.delete_environment(env_id)
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
# ==================== STANDALONE WORDPRESS (DOCKER) ENDPOINTS ====================
@wordpress_bp.route('/standalone/status', methods=['GET'])
@@ -145,7 +240,7 @@ def get_wordpress_info(app_id):
"""Get WordPress site info."""
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -168,7 +263,7 @@ def get_wordpress_info(app_id):
@admin_required
def update_wordpress(app_id):
"""Update WordPress core."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -187,7 +282,7 @@ def get_plugins(app_id):
"""Get installed plugins."""
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -204,7 +299,7 @@ def get_plugins(app_id):
@admin_required
def install_plugin(app_id):
"""Install a plugin."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json()
if not app:
@@ -226,7 +321,7 @@ def install_plugin(app_id):
@admin_required
def uninstall_plugin(app_id, plugin):
"""Uninstall a plugin."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -240,7 +335,7 @@ def uninstall_plugin(app_id, plugin):
@admin_required
def activate_plugin(app_id, plugin):
"""Activate a plugin."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -254,7 +349,7 @@ def activate_plugin(app_id, plugin):
@admin_required
def deactivate_plugin(app_id, plugin):
"""Deactivate a plugin."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -268,7 +363,7 @@ def deactivate_plugin(app_id, plugin):
@admin_required
def update_plugins(app_id):
"""Update plugins."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json()
if not app:
@@ -286,7 +381,7 @@ def get_themes(app_id):
"""Get installed themes."""
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -303,7 +398,7 @@ def get_themes(app_id):
@admin_required
def install_theme(app_id):
"""Install a theme."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json()
if not app:
@@ -325,7 +420,7 @@ def install_theme(app_id):
@admin_required
def activate_theme(app_id, theme):
"""Activate a theme."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -340,7 +435,7 @@ def activate_theme(app_id, theme):
@admin_required
def create_backup(app_id):
"""Create a backup."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json() or {}
if not app:
@@ -359,7 +454,7 @@ def list_backups(app_id):
"""List backups for a site."""
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -378,7 +473,7 @@ def list_backups(app_id):
@admin_required
def restore_backup(app_id):
"""Restore a backup."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json()
if not app:
@@ -406,7 +501,7 @@ def delete_backup(backup_name):
@admin_required
def harden_wordpress(app_id):
"""Apply security hardening."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -420,7 +515,7 @@ def harden_wordpress(app_id):
@admin_required
def search_replace(app_id):
"""Search and replace in database."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json()
if not app:
@@ -443,7 +538,7 @@ def search_replace(app_id):
@admin_required
def optimize_database(app_id):
"""Optimize WordPress database."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -457,7 +552,7 @@ def optimize_database(app_id):
@admin_required
def flush_cache(app_id):
"""Flush WordPress cache."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
if not app:
return jsonify({'error': 'Application not found'}), 404
@@ -472,7 +567,7 @@ def flush_cache(app_id):
@admin_required
def create_wp_user(app_id):
"""Create a WordPress user."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json()
if not app:
@@ -496,7 +591,7 @@ def create_wp_user(app_id):
@admin_required
def reset_wp_password(app_id, user):
"""Reset a WordPress user's password."""
- app = Application.query.get(app_id)
+ app = _resolve_app(app_id)
data = request.get_json() or {}
if not app:
diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py
index aad59d84..b478db0c 100644
--- a/backend/app/services/docker_service.py
+++ b/backend/app/services/docker_service.py
@@ -8,6 +8,27 @@ from datetime import datetime
class DockerService:
"""Service for managing Docker containers, images, and compose stacks."""
+ _compose_cmd = None
+
+ @classmethod
+ def _get_compose_cmd(cls):
+ """Detect whether to use 'docker compose' (v2) or 'docker-compose' (v1)."""
+ if cls._compose_cmd is not None:
+ return cls._compose_cmd
+ try:
+ result = subprocess.run(
+ ['docker', 'compose', 'version'],
+ capture_output=True, text=True
+ )
+ if result.returncode == 0:
+ cls._compose_cmd = ['docker', 'compose']
+ return cls._compose_cmd
+ except Exception:
+ pass
+ # Fallback to docker-compose (v1)
+ cls._compose_cmd = ['docker-compose']
+ return cls._compose_cmd
+
@staticmethod
def is_docker_installed():
"""Check if Docker is installed and running."""
@@ -680,11 +701,11 @@ class DockerService:
# ==================== DOCKER COMPOSE ====================
- @staticmethod
- def compose_up(project_path, detach=True, build=False):
+ @classmethod
+ def compose_up(cls, project_path, detach=True, build=False):
"""Start Docker Compose services."""
try:
- cmd = ['docker', 'compose', 'up']
+ cmd = cls._get_compose_cmd() + ['up']
if detach:
cmd.append('-d')
if build:
@@ -700,11 +721,11 @@ class DockerService:
except Exception as e:
return {'success': False, 'error': str(e)}
- @staticmethod
- def compose_down(project_path, volumes=False, remove_orphans=True):
+ @classmethod
+ def compose_down(cls, project_path, volumes=False, remove_orphans=True):
"""Stop Docker Compose services."""
try:
- cmd = ['docker', 'compose', 'down']
+ cmd = cls._get_compose_cmd() + ['down']
if volumes:
cmd.append('-v')
if remove_orphans:
@@ -720,8 +741,8 @@ class DockerService:
except Exception as e:
return {'success': False, 'error': str(e)}
- @staticmethod
- def compose_ps(project_path):
+ @classmethod
+ def compose_ps(cls, project_path):
"""List Docker Compose services.
Handles multiple output formats from docker compose ps --format json:
@@ -733,7 +754,7 @@ class DockerService:
"""
try:
result = subprocess.run(
- ['docker', 'compose', 'ps', '--format', 'json'],
+ cls._get_compose_cmd() + ['ps', '--format', 'json'],
cwd=project_path,
capture_output=True, text=True
)
@@ -761,11 +782,11 @@ class DockerService:
except Exception:
return []
- @staticmethod
- def compose_logs(project_path, service=None, tail=100):
+ @classmethod
+ def compose_logs(cls, project_path, service=None, tail=100):
"""Get Docker Compose logs."""
try:
- cmd = ['docker', 'compose', 'logs', '--tail', str(tail)]
+ cmd = cls._get_compose_cmd() + ['logs', '--tail', str(tail)]
if service:
cmd.append(service)
@@ -777,11 +798,11 @@ class DockerService:
except Exception as e:
return {'success': False, 'error': str(e)}
- @staticmethod
- def compose_restart(project_path, service=None):
+ @classmethod
+ def compose_restart(cls, project_path, service=None):
"""Restart Docker Compose services."""
try:
- cmd = ['docker', 'compose', 'restart']
+ cmd = cls._get_compose_cmd() + ['restart']
if service:
cmd.append(service)
@@ -795,11 +816,11 @@ class DockerService:
except Exception as e:
return {'success': False, 'error': str(e)}
- @staticmethod
- def compose_pull(project_path, service=None):
+ @classmethod
+ def compose_pull(cls, project_path, service=None):
"""Pull Docker Compose images."""
try:
- cmd = ['docker', 'compose', 'pull']
+ cmd = cls._get_compose_cmd() + ['pull']
if service:
cmd.append(service)
@@ -813,12 +834,12 @@ class DockerService:
except Exception as e:
return {'success': False, 'error': str(e)}
- @staticmethod
- def validate_compose_file(project_path):
+ @classmethod
+ def validate_compose_file(cls, project_path):
"""Validate a Docker Compose file."""
try:
result = subprocess.run(
- ['docker', 'compose', 'config', '--quiet'],
+ cls._get_compose_cmd() + ['config', '--quiet'],
cwd=project_path,
capture_output=True, text=True
)
@@ -828,12 +849,12 @@ class DockerService:
except Exception as e:
return {'valid': False, 'error': str(e)}
- @staticmethod
- def get_compose_config(project_path):
+ @classmethod
+ def get_compose_config(cls, project_path):
"""Get parsed Docker Compose configuration."""
try:
result = subprocess.run(
- ['docker', 'compose', 'config'],
+ cls._get_compose_cmd() + ['config'],
cwd=project_path,
capture_output=True, text=True
)
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index f2a27986..06ef72b4 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -55,7 +55,12 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
@classmethod
def wp_cli(cls, path: str, command: List[str], user: str = 'www-data') -> Dict:
- """Execute a WP-CLI command."""
+ """Execute a WP-CLI command. Auto-detects Docker-based sites."""
+ # Check if this is a Docker-based site (has docker-compose.yml)
+ compose_file = os.path.join(path, 'docker-compose.yml')
+ if os.path.exists(compose_file):
+ return cls._wp_cli_docker(path, command)
+
if not cls.is_wp_cli_installed():
install_result = cls.install_wp_cli()
if not install_result['success']:
@@ -81,6 +86,58 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
except Exception as e:
return {'success': False, 'error': str(e)}
+ @classmethod
+ def _wp_cli_docker(cls, path: str, command: List[str]) -> Dict:
+ """Execute a WP-CLI command inside a Docker WordPress container."""
+ # Resolve container name from the Application record
+ container_name = None
+ from app.models import Application
+ app = Application.query.filter_by(root_path=path).first()
+ if app:
+ container_name = app.name
+
+ if not container_name:
+ # Fallback: derive from directory name
+ container_name = os.path.basename(path)
+
+ try:
+ # Ensure WP-CLI is available inside the container
+ check = subprocess.run(
+ ['docker', 'exec', container_name, 'which', 'wp'],
+ capture_output=True, text=True, timeout=10
+ )
+ if check.returncode != 0:
+ # Install WP-CLI inside the container
+ install_cmd = (
+ 'curl -sO https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'
+ ' && chmod +x wp-cli.phar && mv wp-cli.phar /usr/local/bin/wp'
+ )
+ install = subprocess.run(
+ ['docker', 'exec', container_name, 'bash', '-c', install_cmd],
+ capture_output=True, text=True, timeout=120
+ )
+ if install.returncode != 0:
+ return {'success': False, 'error': f'Failed to install WP-CLI in container: {install.stderr}'}
+
+ # Run wp-cli inside the WordPress container
+ cmd = ['docker', 'exec', container_name, 'wp', '--allow-root'] + command
+ result = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=60
+ )
+
+ return {
+ 'success': result.returncode == 0,
+ 'output': result.stdout,
+ 'error': result.stderr if result.returncode != 0 else None
+ }
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Command timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
@classmethod
def install_wordpress(cls, path: str, config: Dict) -> Dict:
"""Install WordPress at the specified path."""
@@ -854,3 +911,300 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
if not stop_result.get('success'):
return stop_result
return cls.start_wordpress_standalone()
+
+ # ========================================
+ # WORDPRESS SITES HUB (MULTI-SITE MANAGEMENT)
+ # ========================================
+
+ @classmethod
+ def _enrich_site_data(cls, site, site_data: Dict) -> Dict:
+ """Add runtime info (status, name, port, url) to site data dict."""
+ if site.application:
+ site_data['name'] = site.application.name
+ site_data['port'] = site.application.port
+ running = cls._check_container_running(site.application.name)
+ if running and site.application.status != 'running':
+ site.application.status = 'running'
+ elif not running and site.application.status == 'running':
+ site.application.status = 'stopped'
+ site_data['status'] = site.application.status
+
+ # Build access URL from port
+ if site.application.port:
+ site_data['url'] = f"http://localhost:{site.application.port}"
+ return site_data
+
+ @classmethod
+ def get_sites(cls) -> Dict:
+ """Get all production WordPress sites with environment counts."""
+ from app.models import WordPressSite
+
+ sites = WordPressSite.query.filter_by(is_production=True).all()
+ result = []
+
+ for site in sites:
+ site_data = site.to_dict()
+ env_count = WordPressSite.query.filter_by(production_site_id=site.id).count()
+ site_data['environment_count'] = env_count
+ cls._enrich_site_data(site, site_data)
+ result.append(site_data)
+
+ return {'sites': result}
+
+ @classmethod
+ def get_site(cls, site_id: int) -> Dict:
+ """Get a single WordPress site with its environments."""
+ from app.models import WordPressSite
+
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'error': 'Site not found'}
+
+ site_data = site.to_dict(include_environments=True)
+ cls._enrich_site_data(site, site_data)
+
+ # Also enrich environment data
+ if 'environments' in site_data:
+ for env_data in site_data['environments']:
+ env = WordPressSite.query.get(env_data.get('id'))
+ if env:
+ cls._enrich_site_data(env, env_data)
+
+ return {'site': site_data}
+
+ @classmethod
+ def create_site(cls, name: str, admin_email: str, user_id: int) -> Dict:
+ """Create a new WordPress site via Docker."""
+ from app import db
+ from app.models import Application, WordPressSite
+ from app.services.template_service import TemplateService
+
+ # Sanitize name for Docker
+ safe_name = name.lower().replace(' ', '-')
+ safe_name = ''.join(c for c in safe_name if c.isalnum() or c == '-')
+
+ # Check for duplicate name
+ existing = Application.query.filter_by(name=safe_name).first()
+ if existing:
+ return {'success': False, 'error': f'A site with name "{safe_name}" already exists'}
+
+ try:
+ result = TemplateService.install_template(
+ template_id='wordpress',
+ app_name=safe_name,
+ user_variables={},
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return result
+
+ variables = result.get('variables', {})
+ http_port = variables.get('HTTP_PORT')
+
+ # Find the Application record created by TemplateService
+ app = Application.query.filter_by(name=safe_name).first()
+ if not app:
+ return {'success': False, 'error': 'Application record not created'}
+
+ # Create WordPressSite record
+ wp_site = WordPressSite(
+ application_id=app.id,
+ admin_email=admin_email,
+ is_production=True,
+ environment_type='production',
+ wp_version='6.4',
+ compose_project_name=safe_name
+ )
+ db.session.add(wp_site)
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': 'WordPress site created successfully',
+ 'site': wp_site.to_dict(),
+ 'http_port': http_port
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_site(cls, site_id: int) -> Dict:
+ """Delete a WordPress site and all its environments."""
+ from app import db
+ from app.models import WordPressSite, Application
+ from app.services.docker_service import DockerService
+
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.is_production:
+ return {'success': False, 'error': 'Can only delete production sites from this endpoint. Use delete_environment for non-production.'}
+
+ try:
+ # Delete all child environments first
+ environments = WordPressSite.query.filter_by(production_site_id=site.id).all()
+ for env in environments:
+ cls._teardown_wp_site(env)
+
+ # Delete the production site
+ cls._teardown_wp_site(site)
+
+ db.session.commit()
+ return {'success': True, 'message': 'Site and all environments deleted'}
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_environments(cls, site_id: int) -> Dict:
+ """Get all environments for a production WordPress site."""
+ from app.models import WordPressSite
+
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'error': 'Site not found'}
+
+ if not site.is_production:
+ return {'error': 'Not a production site'}
+
+ # Production env first
+ prod_data = site.to_dict()
+ cls._enrich_site_data(site, prod_data)
+ environments = [prod_data]
+
+ # Child environments
+ children = WordPressSite.query.filter_by(production_site_id=site.id).all()
+ for child in children:
+ env_data = child.to_dict()
+ cls._enrich_site_data(child, env_data)
+ environments.append(env_data)
+
+ return {'environments': environments}
+
+ @classmethod
+ def create_environment(cls, site_id: int, env_type: str, user_id: int = 1) -> Dict:
+ """Create a staging or development environment for a site."""
+ from app import db
+ from app.models import WordPressSite, Application
+ from app.services.template_service import TemplateService
+
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.is_production:
+ return {'success': False, 'error': 'Can only create environments from a production site'}
+
+ if env_type not in ('staging', 'development'):
+ return {'success': False, 'error': 'Environment type must be staging or development'}
+
+ # Check if this environment type already exists
+ existing = WordPressSite.query.filter_by(
+ production_site_id=site.id,
+ environment_type=env_type
+ ).first()
+ if existing:
+ return {'success': False, 'error': f'{env_type.capitalize()} environment already exists'}
+
+ # Build name from parent
+ parent_name = site.application.name if site.application else f'wp-site-{site.id}'
+ env_name = f'{parent_name}-{env_type[:3]}' # e.g., mysite-sta, mysite-dev
+
+ try:
+ result = TemplateService.install_template(
+ template_id='wordpress',
+ app_name=env_name,
+ user_variables={},
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return result
+
+ variables = result.get('variables', {})
+ http_port = variables.get('HTTP_PORT')
+
+ app = Application.query.filter_by(name=env_name).first()
+ if not app:
+ return {'success': False, 'error': 'Application record not created'}
+
+ wp_env = WordPressSite(
+ application_id=app.id,
+ admin_email=site.admin_email,
+ is_production=False,
+ production_site_id=site.id,
+ environment_type=env_type,
+ wp_version=site.wp_version or '6.4',
+ compose_project_name=env_name
+ )
+ db.session.add(wp_env)
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': f'{env_type.capitalize()} environment created',
+ 'environment': wp_env.to_dict(),
+ 'http_port': http_port
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_environment(cls, env_id: int) -> Dict:
+ """Delete a non-production environment."""
+ from app import db
+ from app.models import WordPressSite
+
+ env = WordPressSite.query.get(env_id)
+ if not env:
+ return {'success': False, 'error': 'Environment not found'}
+
+ if env.is_production:
+ return {'success': False, 'error': 'Cannot delete production environment. Delete the site instead.'}
+
+ try:
+ cls._teardown_wp_site(env)
+ db.session.commit()
+ return {'success': True, 'message': 'Environment deleted'}
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _teardown_wp_site(cls, wp_site) -> None:
+ """Tear down Docker stack and delete records for a WordPressSite."""
+ from app import db
+ from app.services.docker_service import DockerService
+
+ if wp_site.application and wp_site.application.root_path:
+ root_path = wp_site.application.root_path
+ if os.path.exists(root_path):
+ DockerService.compose_down(root_path, remove_volumes=True)
+ shutil.rmtree(root_path, ignore_errors=True)
+
+ if wp_site.application:
+ db.session.delete(wp_site.application)
+
+ db.session.delete(wp_site)
+
+ @classmethod
+ def _check_container_running(cls, app_name: str) -> bool:
+ """Check if a Docker container is running by app name."""
+ try:
+ import subprocess
+ result = subprocess.run(
+ ['docker', 'ps', '--filter', f'name={app_name}', '--format', '{{.Names}}'],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+ return app_name in result.stdout
+ except Exception:
+ return False
diff --git a/backend/wp-cli.phar b/backend/wp-cli.phar
new file mode 100644
index 00000000..4432e71d
Binary files /dev/null and b/backend/wp-cli.phar differ
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index e4f65f38..85ed8ef0 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -162,9 +162,9 @@ function AppRoutes() {
<Route path="apps" element={<Applications />} />
<Route path="apps/:id" element={<ApplicationDetail />} />
<Route path="wordpress" element={<WordPress />} />
- <Route path="wordpress/:id" element={<WordPressDetail />} />
<Route path="wordpress/projects" element={<WordPressProjects />} />
<Route path="wordpress/projects/:id" element={<WordPressProject />} />
+ <Route path="wordpress/:id" element={<WordPressDetail />} />
<Route path="templates" element={<Templates />} />
<Route path="workflow" element={<WorkflowBuilder />} />
<Route path="domains" element={<Domains />} />
diff --git a/frontend/src/pages/WordPress.jsx b/frontend/src/pages/WordPress.jsx
index 9a0c1882..4049ca96 100644
--- a/frontend/src/pages/WordPress.jsx
+++ b/frontend/src/pages/WordPress.jsx
@@ -1,177 +1,102 @@
import { useState, useEffect } from 'react';
-import { api } from '../services/api';
+import { useNavigate } from 'react-router-dom';
+import wordpressApi from '../services/wordpress';
import { useToast } from '../contexts/ToastContext';
import { useResourceTier } from '../contexts/ResourceTierContext';
import ResourceGate from '../components/ResourceGate';
import Spinner from '../components/Spinner';
-import ConfirmDialog from '../components/ConfirmDialog';
function WordPress() {
- const [status, setStatus] = useState(null);
+ const [sites, setSites] = useState([]);
const [loading, setLoading] = useState(true);
- const [actionLoading, setActionLoading] = useState(false);
- const [showInstallModal, setShowInstallModal] = useState(false);
- const [confirmDialog, setConfirmDialog] = useState(null);
- const [installForm, setInstallForm] = useState({
- adminEmail: ''
- });
+ const [showCreateModal, setShowCreateModal] = useState(false);
+ const [createLoading, setCreateLoading] = useState(false);
+ const [createForm, setCreateForm] = useState({ name: '', adminEmail: '' });
+ const navigate = useNavigate();
const toast = useToast();
const { isLiteTier } = useResourceTier();
useEffect(() => {
- loadData();
+ loadSites();
}, []);
- const loadData = async () => {
+ const loadSites = async () => {
setLoading(true);
try {
- await loadStatus();
+ const data = await wordpressApi.getSites();
+ setSites(data.sites || []);
} catch (error) {
- console.error('Failed to load WordPress data:', error);
+ console.error('Failed to load WordPress sites:', error);
+ setSites([]);
} finally {
setLoading(false);
}
};
- const loadStatus = async () => {
- try {
- const data = await api.getWordPressStatus();
- setStatus(data);
- } catch (error) {
- console.error('Failed to load status:', error);
- setStatus({ installed: false });
- }
- };
-
- const handleInstall = async () => {
- if (!installForm.adminEmail) {
- toast.error('Admin email is required');
+ const handleCreate = async () => {
+ if (!createForm.name) {
+ toast.error('Site name is required');
return;
}
- setActionLoading(true);
+ setCreateLoading(true);
try {
- const result = await api.installWordPress(installForm);
+ const result = await wordpressApi.createSite(createForm);
if (result.success) {
- toast.success('WordPress installed successfully');
- setShowInstallModal(false);
- await loadData();
+ toast.success('WordPress site created successfully');
+ setShowCreateModal(false);
+ setCreateForm({ name: '', adminEmail: '' });
+ await loadSites();
} else {
- toast.error(result.error || 'Installation failed');
+ toast.error(result.error || 'Failed to create site');
}
} catch (error) {
- toast.error(`Failed to install: ${error.message}`);
- } finally {
- setActionLoading(false);
- }
- };
-
- const handleUninstall = () => {
- setConfirmDialog({
- title: 'Uninstall WordPress',
- message: 'Are you sure you want to uninstall WordPress? This will stop the containers but preserve your data.',
- confirmText: 'Uninstall',
- variant: 'danger',
- onConfirm: async () => {
- setActionLoading(true);
- try {
- await api.uninstallWordPress(false);
- toast.success('WordPress uninstalled');
- await loadData();
- } catch (error) {
- toast.error(`Failed to uninstall: ${error.message}`);
- } finally {
- setActionLoading(false);
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null)
- });
- };
-
- const handleStart = async () => {
- setActionLoading(true);
- try {
- await api.startWordPress();
- toast.success('WordPress started');
- await loadStatus();
- } catch (error) {
- toast.error(`Failed to start: ${error.message}`);
- } finally {
- setActionLoading(false);
- }
- };
-
- const handleStop = () => {
- setConfirmDialog({
- title: 'Stop WordPress',
- message: 'Are you sure you want to stop WordPress?',
- confirmText: 'Stop',
- variant: 'warning',
- onConfirm: async () => {
- setActionLoading(true);
- try {
- await api.stopWordPress();
- toast.success('WordPress stopped');
- await loadStatus();
- } catch (error) {
- toast.error(`Failed to stop: ${error.message}`);
- } finally {
- setActionLoading(false);
- setConfirmDialog(null);
- }
- },
- onCancel: () => setConfirmDialog(null)
- });
- };
-
- const handleRestart = async () => {
- setActionLoading(true);
- try {
- await api.restartWordPress();
- toast.success('WordPress restarted');
- await loadStatus();
- } catch (error) {
- toast.error(`Failed to restart: ${error.message}`);
+ toast.error(`Failed to create site: ${error.message}`);
} finally {
- setActionLoading(false);
- }
- };
-
- const openWordPress = () => {
- if (status?.url_path) {
- window.open(`${window.location.origin}${status.url_path}`, '_blank');
- } else if (status?.http_port) {
- window.open(`http://${window.location.hostname}:${status.http_port}`, '_blank');
- }
- };
-
- const openWpAdmin = () => {
- if (status?.url_path) {
- window.open(`${window.location.origin}${status.url_path}/wp-admin`, '_blank');
- } else if (status?.http_port) {
- window.open(`http://${window.location.hostname}:${status.http_port}/wp-admin`, '_blank');
- }
- };
-
- const getWordPressUrl = () => {
- if (status?.url_path) {
- return `${window.location.origin}${status.url_path}`;
+ setCreateLoading(false);
}
- return `http://${window.location.hostname}:${status?.http_port}`;
};
if (loading) {
return (
- <div className="page-loading">
- <Spinner size="lg" />
+ <div className="docker-page-new wordpress-page">
+ <div className="page-header">
+ <div className="page-header-content">
+ <h1>WordPress</h1>
+ <p className="page-description">Manage your WordPress sites</p>
+ </div>
+ </div>
+ <div className="wp-sites-grid">
+ {[1, 2, 3].map(i => (
+ <div key={i} className="wp-site-card-skeleton">
+ <div className="wp-site-card-skeleton-header">
+ <div className="wp-site-card-skeleton-icon" />
+ <div className="wp-site-card-skeleton-info">
+ <div className="wp-site-card-skeleton-name" />
+ <div className="wp-site-card-skeleton-url" />
+ </div>
+ <div className="wp-site-card-skeleton-status" />
+ </div>
+ <div className="wp-site-card-skeleton-body">
+ <div className="wp-site-card-skeleton-meta">
+ <div className="wp-site-card-skeleton-label" />
+ <div className="wp-site-card-skeleton-value" />
+ </div>
+ <div className="wp-site-card-skeleton-meta">
+ <div className="wp-site-card-skeleton-label" />
+ <div className="wp-site-card-skeleton-value" />
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
</div>
);
}
- // Not installed + lite tier -> resource gate
- if (!status?.installed && isLiteTier) {
+ // Lite tier with no sites -> resource gate
+ if (sites.length === 0 && isLiteTier) {
return (
<div className="docker-page-new wordpress-page">
<ResourceGate feature="wordpress_create">
@@ -182,57 +107,21 @@ function WordPress() {
}
return (
- <div className="git-page wordpress-standalone-page">
+ <div className="docker-page-new wordpress-page">
<div className="page-header">
<div className="page-header-content">
<h1>WordPress</h1>
- <p className="page-description">Self-hosted WordPress powered by Docker</p>
+ <p className="page-description">Manage your WordPress sites</p>
</div>
<div className="page-header-actions">
- {!status?.installed ? (
- <button className="btn btn-primary" onClick={() => setShowInstallModal(true)}>
- Install WordPress
- </button>
- ) : (
- <>
- <button
- className="btn btn-secondary"
- onClick={openWordPress}
- disabled={!status?.running}
- >
- Open WordPress
- </button>
- <button
- className="btn btn-secondary"
- onClick={openWpAdmin}
- disabled={!status?.running}
- >
- Open wp-admin
- </button>
- {status?.running ? (
- <button
- className="btn btn-warning"
- onClick={handleStop}
- disabled={actionLoading}
- >
- Stop
- </button>
- ) : (
- <button
- className="btn btn-primary"
- onClick={handleStart}
- disabled={actionLoading}
- >
- Start
- </button>
- )}
- </>
- )}
+ <button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
+ Create Site
+ </button>
</div>
</div>
- {/* Not installed - show install screen */}
- {!status?.installed && (
+ {sites.length === 0 ? (
<div className="empty-state-large">
<div className="empty-icon">
<svg viewBox="0 0 24 24" width="64" height="64" fill="none" stroke="currentColor" strokeWidth="1.5">
@@ -241,128 +130,87 @@ function WordPress() {
<path d="M2 12h20"/>
</svg>
</div>
- <h2>WordPress Not Installed</h2>
- <p>Deploy WordPress with MySQL using Docker Compose. One-click setup with automatic configuration.</p>
- <div className="resource-warning">
- <div className="warning-header">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
- <strong>Resource Requirements</strong>
- </div>
- <ul>
- <li><strong>Memory:</strong> 512MB minimum, 1GB recommended</li>
- <li><strong>Storage:</strong> 2GB minimum, 10GB recommended</li>
- <li>Deploys WordPress + MySQL 8.0 containers</li>
- </ul>
- </div>
- <button className="btn btn-primary" onClick={() => setShowInstallModal(true)}>
- Install WordPress
+ <h2>No WordPress Sites</h2>
+ <p>Create your first WordPress site powered by Docker. Each site gets its own isolated environment with MySQL.</p>
+ <button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
+ Create Site
</button>
</div>
- )}
-
- {/* Installed - show status */}
- {status?.installed && (
- <>
- <div className="status-cards">
- <div className={`status-card ${status?.running ? 'success' : 'danger'}`}>
- <div className="status-icon">
- {status?.running ? (
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
- ) : (
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
- )}
- </div>
- <div className="status-info">
- <span className="status-label">Status</span>
- <span className="status-value">{status?.running ? 'Running' : 'Stopped'}</span>
- </div>
- </div>
- <div className="status-card">
- <div className="status-icon">
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
- </div>
- <div className="status-info">
- <span className="status-label">Version</span>
- <span className="status-value">{status?.version || '6.4'}</span>
- </div>
- </div>
- <div className="status-card">
- <div className="status-icon">
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
- </div>
- <div className="status-info">
- <span className="status-label">Port</span>
- <span className="status-value">{status?.http_port || '—'}</span>
- </div>
- </div>
- </div>
-
- <div className="overview-tab">
- <div className="info-card">
- <h3>Access</h3>
- <div className="info-grid">
- <div className="info-item">
- <span className="info-label">URL</span>
- <span className="info-value">
- {status?.running ? (
- <a href={getWordPressUrl()} target="_blank" rel="noopener noreferrer">
- {getWordPressUrl()}
- </a>
- ) : '—'}
- </span>
+ ) : (
+ <div className="wp-sites-grid">
+ {sites.map(site => (
+ <div
+ key={site.id}
+ className="wp-site-card"
+ onClick={() => navigate(`/wordpress/${site.id}`)}
+ >
+ <div className="wp-site-card-header">
+ <div className="wp-site-icon">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <circle cx="12" cy="12" r="10"/>
+ <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
+ <path d="M2 12h20"/>
+ </svg>
</div>
- <div className="info-item">
- <span className="info-label">Admin Panel</span>
- <span className="info-value">
- {status?.running ? (
- <a href={`${getWordPressUrl()}/wp-admin`} target="_blank" rel="noopener noreferrer">
- {getWordPressUrl()}/wp-admin
- </a>
- ) : '—'}
- </span>
+ <div className="wp-site-info">
+ <h3 className="wp-site-name">{site.name || site.application?.name || `Site ${site.id}`}</h3>
+ {site.port && (
+ <span className="wp-site-url">:{site.port}</span>
+ )}
</div>
- <div className="info-item">
- <span className="info-label">HTTP Port</span>
- <span className="info-value code">{status?.http_port || '—'}</span>
+ <div className={`wp-site-status ${site.status === 'running' ? 'running' : 'stopped'}`}>
+ <span className="status-dot" />
+ {site.status === 'running' ? 'Running' : 'Stopped'}
</div>
</div>
- </div>
-
- <div className="info-card">
- <h3>Actions</h3>
- <div className="info-grid">
- <div className="quick-actions">
- {status?.running ? (
- <>
- <button className="btn btn-secondary" onClick={handleRestart} disabled={actionLoading}>
- Restart
- </button>
- <button className="btn btn-warning" onClick={handleStop} disabled={actionLoading}>
- Stop
- </button>
- </>
- ) : (
- <button className="btn btn-primary" onClick={handleStart} disabled={actionLoading}>
- Start
- </button>
- )}
- <button className="btn btn-danger" onClick={handleUninstall} disabled={actionLoading}>
- Uninstall
- </button>
+ <div className="wp-site-card-body">
+ <div className="wp-site-meta">
+ <div className="wp-site-meta-item">
+ <span className="meta-label">Version</span>
+ <span className="meta-value">{site.wp_version || '6.4'}</span>
+ </div>
+ <div className="wp-site-meta-item">
+ <span className="meta-label">Environments</span>
+ <span className="meta-value">{(site.environment_count || 0) + 1}</span>
+ </div>
</div>
+ {site.url && site.status === 'running' && (
+ <div className="wp-site-card-links">
+ <a
+ href={site.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="wp-site-link"
+ onClick={e => e.stopPropagation()}
+ >
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
+ Open Site
+ </a>
+ <a
+ href={`${site.url}/wp-admin`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="wp-site-link"
+ onClick={e => e.stopPropagation()}
+ >
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
+ WP Admin
+ </a>
+ </div>
+ )}
</div>
</div>
- </div>
- </>
+ ))}
+ </div>
)}
- {/* Install Modal */}
- {showInstallModal && (
- <div className="modal-overlay" onClick={() => !actionLoading && setShowInstallModal(false)}>
+ {/* Create Site Modal */}
+ {showCreateModal && (
+ <div className="modal-overlay" onClick={() => !createLoading && setShowCreateModal(false)}>
<div className="modal modal-lg" onClick={e => e.stopPropagation()}>
<div className="modal-header">
- <h3>Install WordPress</h3>
- <button className="modal-close" onClick={() => !actionLoading && setShowInstallModal(false)}>
+ <h3>Create WordPress Site</h3>
+ <button className="modal-close" onClick={() => !createLoading && setShowCreateModal(false)}>
&times;
</button>
</div>
@@ -370,58 +218,59 @@ function WordPress() {
<div className="install-warning">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
<div>
- <strong>This will install:</strong>
+ <strong>This will create:</strong>
<ul>
- <li>WordPress 6.4 (Apache)</li>
- <li>MySQL 8.0 database</li>
- <li>Nginx reverse proxy at /wordpress</li>
+ <li>WordPress 6.4 (Apache) container</li>
+ <li>MySQL 8.0 database container</li>
+ <li>Isolated Docker network</li>
</ul>
</div>
</div>
<div className="form-group">
<label>
- Admin Email <span className="required">*</span>
+ Site Name <span className="required">*</span>
</label>
+ <input
+ type="text"
+ value={createForm.name}
+ onChange={e => setCreateForm({ ...createForm, name: e.target.value })}
+ placeholder="my-wordpress-site"
+ disabled={createLoading}
+ />
+ <span className="form-hint">Used as the Docker project name. Letters, numbers, and hyphens only.</span>
+ </div>
+
+ <div className="form-group">
+ <label>Admin Email</label>
<input
type="email"
- value={installForm.adminEmail}
- onChange={e => setInstallForm({ ...installForm, adminEmail: e.target.value })}
+ value={createForm.adminEmail}
+ onChange={e => setCreateForm({ ...createForm, adminEmail: e.target.value })}
placeholder="[email protected]"
- disabled={actionLoading}
+ disabled={createLoading}
/>
</div>
</div>
<div className="modal-footer">
<button
className="btn btn-secondary"
- onClick={() => setShowInstallModal(false)}
- disabled={actionLoading}
+ onClick={() => setShowCreateModal(false)}
+ disabled={createLoading}
>
Cancel
</button>
<button
className="btn btn-primary"
- onClick={handleInstall}
- disabled={actionLoading || !installForm.adminEmail}
+ onClick={handleCreate}
+ disabled={createLoading || !createForm.name}
>
- {actionLoading ? <><Spinner size="sm" /> Installing...</> : 'Install WordPress'}
+ {createLoading ? <><Spinner size="sm" /> Creating...</> : 'Create Site'}
</button>
</div>
</div>
</div>
)}
-
- {confirmDialog && (
- <ConfirmDialog
- title={confirmDialog.title}
- message={confirmDialog.message}
- confirmText={confirmDialog.confirmText}
- variant={confirmDialog.variant}
- onConfirm={confirmDialog.onConfirm}
- onCancel={confirmDialog.onCancel}
- />
- )}
</div>
);
}
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
index 23c86545..6f6da154 100644
--- a/frontend/src/pages/WordPressDetail.jsx
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -219,7 +219,7 @@ const WordPressDetail = () => {
<ErrorBoundary key={activeTab} onRetry={loadSite}>
{activeTab === 'overview' && <OverviewTab site={site} onUpdate={loadSite} />}
{activeTab === 'environments' && <EnvironmentsTab siteId={site.id} site={site} onUpdate={loadSite} />}
- {activeTab === 'database' && <DatabaseTab siteId={site.id} />}
+ {activeTab === 'database' && <DatabaseTab siteId={site.id} site={site} />}
{activeTab === 'plugins' && <PluginsTab siteId={site.id} />}
{activeTab === 'themes' && <ThemesTab siteId={site.id} />}
{activeTab === 'git' && <GitTab siteId={site.id} site={site} onUpdate={loadSite} />}
@@ -402,13 +402,13 @@ const OverviewTab = ({ site, onUpdate }) => {
</a>
</>
)}
- {site.is_production && (
+ {site.is_production && (site.environments || []).length < 2 && (
<button
className="quick-action-btn"
onClick={() => setShowEnvModal(true)}
>
<Plus size={16} />
- Create Dev Env
+ Create Environment
</button>
)}
<button
@@ -434,13 +434,20 @@ const OverviewTab = ({ site, onUpdate }) => {
</div>
</div>
- {showEnvModal && (
- <CreateEnvironmentModal
- onClose={() => setShowEnvModal(false)}
- onCreate={handleCreateEnvironment}
- productionDomain={site.url}
- />
- )}
+ {showEnvModal && (() => {
+ const envs = site.environments || [];
+ const modalHasStaging = envs.some(e => e.environment_type === 'staging');
+ const modalHasDev = envs.some(e => e.environment_type === 'development');
+ return (
+ <CreateEnvironmentModal
+ onClose={() => setShowEnvModal(false)}
+ onCreate={handleCreateEnvironment}
+ productionDomain={site.url}
+ hasStaging={modalHasStaging}
+ hasDev={modalHasDev}
+ />
+ );
+ })()}
</div>
);
};
@@ -571,11 +578,17 @@ const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
);
}
+ // Filter out production from the environments list (it's shown separately)
+ const childEnvs = environments.filter(e => e.id !== site.id && !e.is_production);
+ const hasStaging = childEnvs.some(e => e.environment_type === 'staging');
+ const hasDev = childEnvs.some(e => e.environment_type === 'development');
+ const canCreateMore = site.is_production && (!hasStaging || !hasDev);
+
return (
<div className="environments-tab">
<div className="section-header">
<h3>Environments</h3>
- {site.is_production && (
+ {canCreateMore && (
<button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
<Plus size={14} /> Create Environment
</button>
@@ -597,7 +610,7 @@ const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
/>
{/* Dev/staging environments */}
- {environments.map(env => (
+ {childEnvs.map(env => (
<EnvironmentCard
key={env.id}
environment={env}
@@ -608,7 +621,7 @@ const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
))}
</div>
- {environments.length === 0 && site.is_production && (
+ {childEnvs.length === 0 && site.is_production && (
<div className="hint-box">
<p>No development or staging environments yet.</p>
<p>Create an environment to safely test changes before deploying to production.</p>
@@ -620,6 +633,8 @@ const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
onClose={() => setShowCreateModal(false)}
onCreate={handleCreateEnvironment}
productionDomain={site.url}
+ hasStaging={hasStaging}
+ hasDev={hasDev}
/>
)}
</div>
@@ -627,9 +642,11 @@ const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
};
// Create Environment Modal
-const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain }) => {
+const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain, hasStaging = false, hasDev = false }) => {
+ // Default to whichever type is still available
+ const defaultType = !hasDev ? 'development' : !hasStaging ? 'staging' : 'development';
const [formData, setFormData] = useState({
- type: 'development',
+ type: defaultType,
name: '',
domain: '',
cloneDb: true,
@@ -688,8 +705,8 @@ const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain }) => {
<div className="form-group">
<label>Environment Type</label>
<select name="type" value={formData.type} onChange={handleChange}>
- <option value="development">Development</option>
- <option value="staging">Staging</option>
+ {!hasDev && <option value="development">Development</option>}
+ {!hasStaging && <option value="staging">Staging</option>}
</select>
</div>
@@ -768,7 +785,7 @@ const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain }) => {
};
// Database Tab
-const DatabaseTab = ({ siteId }) => {
+const DatabaseTab = ({ siteId, site }) => {
const toast = useToast();
const [snapshots, setSnapshots] = useState([]);
const [loading, setLoading] = useState(true);
@@ -837,7 +854,44 @@ const DatabaseTab = ({ siteId }) => {
return (
<div className="database-tab">
- <div className="section-header">
+ {/* Database Connection Info */}
+ <div className="app-panel">
+ <div className="app-panel-header">
+ <Database size={16} />
+ Database Connection
+ </div>
+ <div className="app-panel-body">
+ <div className="app-info-grid">
+ <div className="app-info-item">
+ <span className="app-info-label">Database Name</span>
+ <span className="app-info-value mono">{site?.db_name || 'wordpress'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Database User</span>
+ <span className="app-info-value mono">{site?.db_user || 'wordpress'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Database Host</span>
+ <span className="app-info-value mono">{site?.db_host || 'db'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Table Prefix</span>
+ <span className="app-info-value mono">{site?.db_prefix || 'wp_'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Container</span>
+ <span className="app-info-value mono">{site?.compose_project_name ? `${site.compose_project_name}-db` : '-'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Engine</span>
+ <span className="app-info-value">MySQL 8.0</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Snapshots */}
+ <div className="section-header" style={{ marginTop: 24 }}>
<h3>Database Snapshots</h3>
<button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
<Plus size={14} /> Create Snapshot
diff --git a/frontend/src/styles/pages/_wordpress.less b/frontend/src/styles/pages/_wordpress.less
index 6ea0cf28..9773761d 100644
--- a/frontend/src/styles/pages/_wordpress.less
+++ b/frontend/src/styles/pages/_wordpress.less
@@ -31,6 +31,106 @@
// WordPress Page Layout (extends Docker page styles)
.wordpress-page {
+ .page-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: @space-6;
+ padding: @space-4 @space-4 0;
+ flex-wrap: wrap;
+ gap: @space-4;
+
+ .page-header-content {
+ h1 {
+ font-size: @font-size-2xl;
+ font-weight: @font-weight-semibold;
+ margin: 0 0 @space-1 0;
+ }
+
+ .page-description {
+ color: @text-secondary;
+ margin: 0;
+ }
+ }
+
+ .page-header-actions {
+ display: flex;
+ gap: @space-2;
+ }
+ }
+
+ .empty-state-large {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 60px @space-6;
+ background: @bg-card;
+ border-radius: @radius-xl;
+ text-align: center;
+ margin: 0 @space-4;
+
+ .empty-icon {
+ color: @text-tertiary;
+ margin-bottom: @space-6;
+
+ svg {
+ stroke: #21759b;
+ }
+ }
+
+ h2 {
+ margin: 0 0 @space-3 0;
+ font-size: @font-size-2xl;
+ font-weight: @font-weight-semibold;
+ }
+
+ p {
+ margin: 0 0 @space-6 0;
+ color: @text-secondary;
+ max-width: 460px;
+ }
+ }
+
+ .install-warning {
+ display: flex;
+ gap: @space-3;
+ padding: @space-4;
+ background: fade(@color-warning, 8%);
+ border: 1px solid fade(@color-warning, 20%);
+ border-radius: @radius-md;
+ margin-bottom: @space-4;
+
+ > svg {
+ flex-shrink: 0;
+ color: @color-warning;
+ margin-top: 2px;
+ }
+
+ strong {
+ display: block;
+ margin-bottom: @space-2;
+ }
+
+ ul {
+ margin: 0;
+ padding-left: @space-4;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+
+ li {
+ margin-bottom: @space-1;
+ }
+ }
+ }
+
+ .form-hint {
+ display: block;
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-top: @space-1;
+ }
+
.docker-empty {
.wp-empty-icon {
color: @text-tertiary;
@@ -192,6 +292,28 @@
}
}
+.wp-site-card-links {
+ display: flex;
+ gap: @space-3;
+ margin-top: @space-3;
+ padding-top: @space-3;
+ border-top: 1px solid @border-subtle;
+}
+
+.wp-site-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: @font-size-xs;
+ font-weight: @font-weight-medium;
+ color: @color-primary;
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
+}
+
.wp-site-card-footer {
display: flex;
gap: @space-2;