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 WordPress site management API and models

Juan Denisf4ed11ceafa4
diff --git a/EXPLORATIONS_AND_FUTURE.md b/EXPLORATIONS_AND_FUTURE.md
deleted file mode 100644
index 87a67c7e..00000000
--- a/EXPLORATIONS_AND_FUTURE.md
+++ /dev/null
@@ -1,672 +0,0 @@
-# ServerKit: Explorations and Future Directions
-
-> A deep dive into where ServerKit stands, where it should go, and practical next steps.
->
-> *Written: January 2026*
-
----
-
-## Table of Contents
-
-1. [Current State Assessment](#current-state-assessment)
-2. [WordPress Dev/Prod Environment Architecture](#wordpress-devprod-environment-architecture)
-3. [Testing the Go Agent Locally](#testing-the-go-agent-locally)
-4. [Future of ServerKit](#future-of-serverkit)
-5. [Recommended Next Steps](#recommended-next-steps)
-
----
-
-## Current State Assessment
-
-### What ServerKit Has Achieved
-
-ServerKit has matured into a **legitimate self-hosted server control panel** with impressive breadth:
-
-| Area | Maturity | Notes |
-|------|----------|-------|
-| **Multi-Server Agents** | Production-Ready | Go agent with WSS, HMAC auth, cross-platform builds |
-| **Docker Management** | Complete | Full container lifecycle, compose support, logs streaming |
-| **WordPress Support** | Good | WP-CLI, one-click install, security hardening |
-| **Git Deployment** | Complete | Webhooks, rollback, zero-downtime deploys |
-| **Security** | Strong | 2FA, encryption at rest, audit logging, ClamAV |
-| **Monitoring** | Good | Real-time metrics, alerts, webhooks |
-| **Multi-Environment** | Partial | UI exists, but workflow needs refinement |
-
-### What's Missing for Real-World Usage
-
-1. **Backup & Restore** - Critical gap. No automated backups = risky for production.
-2. **Database Sync/Clone** - For dev/prod workflows, you need this.
-3. **Team Permissions** - Single-user limits commercial viability.
-4. **Agent Stress Testing** - No evidence of load testing at scale.
-
----
-
-## WordPress Dev/Prod Environment Architecture
-
-### The Vision
-
-You want to explore:
-- **Dev and Prod WordPress instances**
-- **Synced from GitHub**
-- **Sharing the same DB (or a mini version of prod DB)**
-
-This is a real-world workflow that ServerKit should excel at. Let me break down the options:
-
-### Option A: Shared Database (Live Sync)
-
-```
-┌─────────────────────────────────────────────────────────────┐
-│ GitHub Repository │
-│ (wp-content/themes, wp-content/plugins) │
-└─────────────────────────────────────────────────────────────┘
- │
- ┌───────────────┴───────────────┐
- ▼ ▼
- ┌─────────────────┐ ┌─────────────────┐
- │ DEV Server │ │ PROD Server │
- │ (Agent #1) │ │ (Agent #2) │
- │ │ │ │
- │ ┌───────────┐ │ │ ┌───────────┐ │
- │ │ WordPress │ │ │ │ WordPress │ │
- │ │ (Dev) │ │ │ │ (Prod) │ │
- │ └─────┬─────┘ │ │ └─────┬─────┘ │
- └────────┼────────┘ └────────┼────────┘
- │ │
- └───────────┬───────────────────┘
- ▼
- ┌─────────────────┐
- │ Shared MySQL │
- │ (Prod Server) │
- │ │
- │ wp_* tables │
- └─────────────────┘
-```
-
-**Pros:**
-- Real-time content sync
-- No data drift between environments
-- Simple conceptually
-
-**Cons:**
-- **Dangerous** - Dev changes affect prod data
-- URL serialization issues in WordPress (siteurl, home options)
-- Not recommended for real workflows
-
-**Verdict:** Avoid this pattern. WordPress stores serialized URLs in the database, making true DB sharing problematic.
-
-### Option B: Mini Prod Database (Recommended)
-
-```
-┌─────────────────────────────────────────────────────────────┐
-│ GitHub Repository │
-│ (wp-content/themes, wp-content/plugins) │
-└─────────────────────────────────────────────────────────────┘
- │
- ┌───────────────┴───────────────┐
- ▼ ▼
- ┌─────────────────┐ ┌─────────────────┐
- │ DEV Server │ │ PROD Server │
- │ (Agent #1) │ │ (Agent #2) │
- │ │ │ │
- │ ┌───────────┐ │ │ ┌───────────┐ │
- │ │ WordPress │ │ │ │ WordPress │ │
- │ │ (Dev) │ │ │ │ (Prod) │ │
- │ └─────┬─────┘ │ │ └─────┬─────┘ │
- │ │ │ │ │ │
- │ ┌─────┴─────┐ │ │ ┌─────┴─────┐ │
- │ │ MySQL │ │◄────────────│ │ MySQL │ │
- │ │ (Clone) │ │ Nightly │ │ (Prod) │ │
- │ └───────────┘ │ Sync │ └───────────┘ │
- └─────────────────┘ └─────────────────┘
-```
-
-**How It Works:**
-
-1. **Prod runs normally** with live database
-2. **Nightly job** creates a mysqldump of prod
-3. **Sanitize the dump:**
- - Run search-replace for URLs (`prod.example.com` → `dev.example.com`)
- - Optionally anonymize user data
- - Truncate large tables (logs, analytics)
-4. **Import to dev** database
-5. **Dev has fresh, realistic data** without affecting prod
-
-**Implementation in ServerKit:**
-
-This requires a new feature: **Database Sync Jobs**
-
-```python
-# Proposed: backend/app/services/db_sync_service.py
-
-class DatabaseSyncService:
- def create_sync_job(self, source_app_id, target_app_id, options):
- """
- Create a scheduled database sync from source to target.
-
- Options:
- - schedule: cron expression
- - search_replace: dict of find/replace patterns
- - anonymize: bool - anonymize user emails/names
- - exclude_tables: list of tables to skip
- - truncate_tables: list of tables to empty
- """
- pass
-
- def run_sync(self, job_id):
- """Execute a database sync job."""
- # 1. Dump source database
- # 2. Apply transformations
- # 3. Import to target
- # 4. Run wp search-replace if WordPress
- pass
-```
-
-### Option C: Read Replica (Advanced)
-
-```
- ┌─────────────────┐ ┌─────────────────┐
- │ DEV Server │ │ PROD Server │
- │ │ │ │
- │ ┌───────────┐ │ │ ┌───────────┐ │
- │ │ WordPress │ │ │ │ WordPress │ │
- │ └─────┬─────┘ │ │ └─────┬─────┘ │
- │ │ │ │ │ │
- │ ┌─────┴─────┐ │ │ ┌─────┴─────┐ │
- │ │ MySQL │ │ │ │ MySQL │ │
- │ │ (Replica) │◄─┼─────────────┼──│ (Primary) │ │
- │ └───────────┘ │ Binlog │ └───────────┘ │
- └─────────────────┘ Replication └─────────────────┘
-```
-
-**Pros:**
-- Near real-time sync (seconds)
-- Dev sees exactly what prod sees
-
-**Cons:**
-- Read-only dev database
-- Complex to set up cross-server
-- Still has URL serialization issues
-
-**Verdict:** Overkill for WordPress. Better for read-heavy APIs.
-
-### Recommended Architecture: GitHub-Driven Dev/Prod
-
-Here's what I'd actually build:
-
-```
-┌─────────────────────────────────────────────────────────────┐
-│ GitHub Repository │
-│ │
-│ ├── wp-content/ │
-│ │ ├── themes/my-theme/ │
-│ │ └── plugins/my-plugin/ │
-│ ├── .github/workflows/ │
-│ │ ├── deploy-dev.yml # On push to develop branch │
-│ │ └── deploy-prod.yml # On push to main branch │
-│ └── serverkit.yaml # Environment config │
-└─────────────────────────────────────────────────────────────┘
- │
- ┌────────────────────┴────────────────────┐
- │ │
- │ push to develop push to main │
- ▼ ▼
-┌─────────────────┐ ┌─────────────────┐
-│ ServerKit API │ │ ServerKit API │
-│ (Webhook) │ │ (Webhook) │
-└────────┬────────┘ └────────┬────────┘
- │ │
- ▼ ▼
-┌─────────────────┐ ┌─────────────────┐
-│ DEV Server │ │ PROD Server │
-│ │ │ │
-│ WordPress │ │ WordPress │
-│ dev.site.com │ │ www.site.com │
-│ │ │ │
-│ MySQL (local) │◄────── Weekly ──────│ MySQL (local) │
-│ Sanitized copy │ Sync │ Live data │
-└─────────────────┘ └─────────────────┘
-```
-
-**The Workflow:**
-
-1. **Developer pushes to `develop` branch**
-2. **GitHub Action** calls ServerKit webhook
-3. **ServerKit pulls code** on dev server
-4. **Runs `wp theme activate`, `wp plugin activate`** as needed
-5. **Developer tests on dev.site.com**
-6. **When ready, merge PR to `main`**
-7. **Same process for production**
-
-**Weekly Database Sync:**
-
-```yaml
-# serverkit.yaml in repo root
-environments:
- dev:
- server: dev-server-id
- app: wordpress-dev-id
- domain: dev.site.com
- db_sync:
- source: prod
- schedule: "0 3 * * 0" # Sunday 3 AM
- search_replace:
- - ["https://www.site.com", "https://dev.site.com"]
- anonymize_users: true
- truncate_tables:
- - wp_statistics_*
- - wp_actionscheduler_*
-
- prod:
- server: prod-server-id
- app: wordpress-prod-id
- domain: www.site.com
-```
-
-### What ServerKit Needs to Support This
-
-| Feature | Current Status | Priority |
-|---------|---------------|----------|
-| Git webhook deployments | ✅ Done | - |
-| Multi-environment app linking | ✅ Done | - |
-| Database dump/export | ❌ Missing | **High** |
-| Database import with transformations | ❌ Missing | **High** |
-| WP-CLI search-replace integration | ⚠️ Partial | Medium |
-| Scheduled sync jobs | ❌ Missing | Medium |
-| Cross-server database operations | ❌ Missing | Medium |
-
----
-
-## Testing the Go Agent Locally
-
-### Your Goal
-
-Test the ServerKit Go agent on your Windows PC to understand:
-- How it connects to the control plane
-- How commands flow through
-- What happens with Docker operations
-- Whether it's stable
-
-### Setting Up the Test Environment
-
-#### Prerequisites
-
-1. **Go 1.21+** installed
-2. **Docker Desktop** running (for Docker commands)
-3. **ServerKit backend** running (localhost or remote)
-
-#### Step 1: Build the Agent
-
-```powershell
-# Navigate to agent directory
-cd C:\Users\Juan\Documents\GitHub\ServerKit\agent
-
-# Build for Windows
-go build -o serverkit-agent.exe ./cmd/agent
-
-# Or use the Makefile (if you have make installed)
-make build-windows
-```
-
-#### Step 2: Create Test Configuration
-
-Create `agent-config.yaml` in the agent directory:
-
-```yaml
-# agent-config.yaml
-server_url: "ws://localhost:5000" # Your ServerKit backend
-# server_url: "wss://serverkit.yourdomain.com" # For production
-
-# Leave empty - will be populated on first registration
-api_key: ""
-api_secret: ""
-
-# Logging
-log_level: "debug"
-log_file: "agent.log"
-
-# Heartbeat interval (seconds)
-heartbeat_interval: 30
-
-# Enable Docker integration
-docker_enabled: true
-docker_socket: "npipe:////./pipe/docker_engine" # Windows Docker socket
-```
-
-#### Step 3: Register the Agent
-
-First, create a server in ServerKit UI to get a registration token, then:
-
-```powershell
-# Register with the control plane
-.\serverkit-agent.exe register --token YOUR_REGISTRATION_TOKEN
-
-# This will:
-# 1. Connect to ServerKit backend
-# 2. Exchange token for API credentials
-# 3. Save credentials to config file
-# 4. Print success message
-```
-
-#### Step 4: Run the Agent
-
-```powershell
-# Run in foreground (for testing)
-.\serverkit-agent.exe run --config agent-config.yaml
-
-# You should see:
-# [INFO] Connecting to ws://localhost:5000/agent
-# [INFO] Authenticated successfully
-# [INFO] Starting heartbeat loop (30s interval)
-# [DEBUG] Sending heartbeat with metrics...
-```
-
-### Testing Agent Functionality
-
-#### Test 1: Verify Connection
-
-In ServerKit UI:
-- Go to Servers page
-- Your test server should show as "Online"
-- Last seen should update every 30 seconds
-
-#### Test 2: Docker Commands
-
-If Docker Desktop is running:
-
-```powershell
-# In ServerKit UI, try:
-# - View containers
-# - Start/stop a container
-# - View container logs
-
-# Agent logs should show:
-# [DEBUG] Received command: docker:container:list
-# [DEBUG] Executing Docker command...
-# [DEBUG] Sending response with 5 containers
-```
-
-#### Test 3: System Metrics
-
-Check Monitoring page in ServerKit:
-- CPU usage should show Windows Task Manager equivalent
-- Memory should match your system
-- Disk usage for C: drive
-
-#### Test 4: Terminal Access
-
-Try opening a terminal session to your test server:
-- Should spawn PowerShell on Windows
-- Commands should execute
-- Output should stream back
-
-### Common Issues and Fixes
-
-| Issue | Cause | Fix |
-|-------|-------|-----|
-| "Connection refused" | Backend not running | Start Flask backend |
-| "Docker not available" | Docker Desktop not running | Start Docker Desktop |
-| "Authentication failed" | Invalid/expired token | Re-register agent |
-| "TLS handshake error" | Self-signed cert | Use `ws://` for local testing |
-| Metrics not updating | Heartbeat blocked | Check firewall rules |
-
-### Agent Architecture Deep Dive
-
-```
-┌─────────────────────────────────────────────────────────────┐
-│ ServerKit Go Agent │
-├─────────────────────────────────────────────────────────────┤
-│ │
-│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
-│ │ Config │ │ Logger │ │ Auth │ │
-│ │ Manager │ │ (Zerolog) │ │ (HMAC) │ │
-│ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
-│ │ │ │ │
-│ └──────────────┼──────────────┘ │
-│ │ │
-│ ┌────────────────────┴────────────────────┐ │
-│ │ WebSocket Client │ │
-│ │ (gorilla/websocket + reconnect) │ │
-│ └────────────────────┬────────────────────┘ │
-│ │ │
-│ ┌──────────────┼──────────────┐ │
-│ │ │ │ │
-│ ▼ ▼ ▼ │
-│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
-│ │ Docker │ │ Metrics │ │ Terminal │ │
-│ │ Handler │ │ Collector │ │ PTY │ │
-│ │ │ │ │ │ │ │
-│ │ - List │ │ - CPU │ │ - Spawn │ │
-│ │ - Start │ │ - Memory │ │ - Resize │ │
-│ │ - Stop │ │ - Disk │ │ - Input │ │
-│ │ - Logs │ │ - Network │ │ - Output │ │
-│ │ - Stats │ │ │ │ │ │
-│ └───────────┘ └───────────┘ └───────────┘ │
-│ │
-└─────────────────────────────────────────────────────────────┘
-```
-
-### Agent Test Checklist
-
-- [ ] Agent builds without errors
-- [ ] Agent connects to backend
-- [ ] Heartbeat appears in server list
-- [ ] Metrics show in monitoring page
-- [ ] Docker containers list correctly
-- [ ] Container start/stop works
-- [ ] Container logs stream
-- [ ] Terminal opens and accepts input
-- [ ] Agent survives backend restart (reconnect)
-- [ ] Agent handles network interruption gracefully
-
----
-
-## Future of ServerKit
-
-### My Honest Assessment
-
-ServerKit has grown from a simple control panel into something with real architectural depth. The Go agent is a significant investment that positions it for multi-server, enterprise-like features. But there are strategic decisions ahead.
-
-### Where ServerKit Sits in the Market
-
-```
- Complexity
- ▲
- │
- Kubernetes ────┼──────────────● CloudPanel
- Nomad │ ● Coolify
- │ ● ServerKit (today)
- │ ● Dokku
- │ ● CapRover
- ────────────────────────────────────────► Features
- │
- Portainer ●
- │
- Cockpit ● │
- │
-```
-
-**Current Position:** ServerKit is between CapRover/Dokku (simple) and CloudPanel/Coolify (feature-rich).
-
-**Opportunity:** The multi-server Go agent puts ServerKit closer to what teams actually need for real production workloads.
-
-### Three Possible Futures
-
-#### Future A: WordPress Hosting Platform
-
-**Focus:** Become the best self-hosted WordPress management platform.
-
-**What to build:**
-- Staging/production sync (database cloning)
-- WordPress-specific monitoring (slow queries, plugin conflicts)
-- One-click backup to S3/Backblaze
-- Malware scanning with auto-remediation
-- WordPress multisite support
-- WP-CLI exposed as API
-
-**Target users:** WordPress agencies, freelancers with multiple client sites
-
-**Competitors:** GridPane, SpinupWP, RunCloud
-
-**My take:** This is a viable niche. WordPress agencies pay well for good tooling. But it limits ServerKit's appeal.
-
-#### Future B: Mini-Kubernetes Alternative
-
-**Focus:** Multi-server orchestration without Kubernetes complexity.
-
-**What to build:**
-- Service mesh between agents (internal DNS)
-- Load balancing across servers
-- Container scheduling (deploy to least-loaded server)
-- Cross-server networking
-- Secrets management (Vault-like)
-- Log aggregation (ship logs to central location)
-
-**Target users:** Small-medium teams who outgrew single servers but don't want Kubernetes
-
-**Competitors:** Nomad, Docker Swarm (dead), Coolify
-
-**My take:** This is the more ambitious path. The Go agent is already 70% of what's needed. The question is whether you want to compete at this level.
-
-#### Future C: Developer-First Homelab Manager
-
-**Focus:** Self-hosting for developers who want to own their infrastructure.
-
-**What to build:**
-- One-click apps (like Umbrel, CasaOS)
-- Personal cloud features (Nextcloud, Vaultwarden integration)
-- Tunnel support (Cloudflare Tunnel, Tailscale)
-- Mobile-friendly dashboard
-- Simple DNS management
-- Local SSL with mkcert/step-ca
-
-**Target users:** Developers, homelabbers, privacy-conscious users
-
-**Competitors:** Umbrel, CasaOS, Tipi
-
-**My take:** Growing market, but harder to monetize. Good for adoption, hard for revenue.
-
-### My Recommendation: Hybrid Approach
-
-Don't pick one future. Build the **foundation** that supports all three:
-
-```
- ┌─────────────────────────────────┐
- │ User-Facing Products │
- ├─────────┬───────────┬───────────┤
- │WordPress│ App │ Homelab │
- │Platform │ Platform │ Suite │
- ├─────────┴───────────┴───────────┤
- │ ServerKit Core Platform │
- │ │
- │ ┌─────┐ ┌─────┐ ┌───────────┐ │
- │ │Agents│ │Apps │ │ Templates │ │
- │ └─────┘ └─────┘ └───────────┘ │
- │ ┌─────┐ ┌─────┐ ┌───────────┐ │
- │ │ DB │ │ SSL │ │ Webhooks │ │
- │ └─────┘ └─────┘ └───────────┘ │
- └─────────────────────────────────┘
-```
-
-**Core investments that pay off in all futures:**
-
-1. **Backup & Restore** - Everyone needs this
-2. **Database Sync** - Dev/prod workflows are universal
-3. **API Stability** - Third-party integrations
-4. **Agent Reliability** - More agents = more value
-5. **Plugin/Extension System** - Let community build
-
-### Roadmap Recommendation
-
-#### Q1 2026: Foundation (Now)
-
-| Priority | Feature | Why |
-|----------|---------|-----|
-| **P0** | Backup & Restore | Can't run production without backups |
-| **P0** | Database sync/clone | Enables dev/prod workflows |
-| **P1** | Agent stress testing | Prove multi-server works at scale |
-| **P1** | WordPress staging sync | Popular request, differentiator |
-
-#### Q2 2026: Scale
-
-| Priority | Feature | Why |
-|----------|---------|-----|
-| **P0** | Team/user management | Required for teams |
-| **P1** | Role-based permissions | Security requirement |
-| **P1** | Cross-server log aggregation | Ops visibility |
-| **P2** | Agent auto-update (production-grade) | Reduce maintenance burden |
-
-#### Q3 2026: Ecosystem
-
-| Priority | Feature | Why |
-|----------|---------|-----|
-| **P1** | Plugin/extension system | Community growth |
-| **P1** | API v2 (stable, versioned) | Third-party integrations |
-| **P2** | Template marketplace | Discoverability |
-| **P2** | Tunnel support (Cloudflare/Tailscale) | Homelab market |
-
-#### Q4 2026: Differentiation
-
-Choose a direction based on traction:
-- If WordPress is hot → WordPress-specific features
-- If multi-server is hot → Orchestration features
-- If homelab is hot → Personal cloud features
-
----
-
-## Recommended Next Steps
-
-### Immediate (This Week)
-
-1. **Build and test the Go agent locally**
- - Follow the steps in Section 3
- - Document any issues you find
- - Test Docker commands specifically
-
-2. **Prototype database sync**
- - Manual mysqldump → transform → import
- - Use WP-CLI for search-replace
- - Prove the workflow works before automating
-
-3. **Set up a real dev/prod WordPress pair**
- - Two Docker instances on same machine
- - Different ports, different databases
- - Test the GitHub webhook flow
-
-### Short-term (This Month)
-
-4. **Design the Database Sync feature**
- - UI mockups
- - API design
- - Agent-side implementation
-
-5. **Backup & Restore MVP**
- - Even if manual (cron + mysqldump + rsync)
- - Restore must actually work
-
-### Medium-term (This Quarter)
-
-6. **Agent reliability improvements**
- - Reconnection logic stress testing
- - Memory leak detection
- - Long-running connection stability
-
-7. **Documentation**
- - Agent installation guide
- - Multi-server setup tutorial
- - WordPress dev/prod workflow guide
-
----
-
-## Final Thoughts
-
-ServerKit has the bones of something really useful. The Go agent is the right architectural choice for multi-server. The template system is flexible. The security features are more thorough than most open-source panels.
-
-The risk is feature sprawl - trying to be everything to everyone. The WordPress dev/prod workflow you want to explore is exactly the kind of **focused, real-world problem** that differentiates ServerKit from generic panels.
-
-Build for your own use case first. If you need WordPress staging with database sync, build that. You'll end up with something opinionated and useful rather than generic and forgettable.
-
-The market doesn't need another cPanel clone. It needs tools built by people who actually deploy and manage servers.
-
----
-
-*This document represents my analysis based on exploring the ServerKit codebase. These are recommendations, not requirements. Adjust based on your priorities and user feedback.*
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 959abd36..3137dcbd 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -84,8 +84,10 @@ def create_app(config_name=None):
# Register blueprints - PHP & WordPress
from app.api.php import php_bp
from app.api.wordpress import wordpress_bp
+ from app.api.wordpress_sites import wordpress_sites_bp
app.register_blueprint(php_bp, url_prefix='/api/v1/php')
app.register_blueprint(wordpress_bp, url_prefix='/api/v1/wordpress')
+ app.register_blueprint(wordpress_sites_bp, url_prefix='/api/v1/wordpress')
# Register blueprints - Python
from app.api.python import python_bp
diff --git a/backend/app/api/wordpress_sites.py b/backend/app/api/wordpress_sites.py
new file mode 100644
index 00000000..b4f4f2be
--- /dev/null
+++ b/backend/app/api/wordpress_sites.py
@@ -0,0 +1,799 @@
+"""
+WordPress Sites API
+
+API endpoints for WordPress site management including:
+- Site listing and creation
+- Environment management (dev/staging)
+- Database operations (snapshots, sync, clone)
+- Git integration
+"""
+
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+import json
+
+from app import db
+from app.models.application import Application
+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob
+from app.services.wordpress_service import WordPressService
+from app.services.wordpress_env_service import WordPressEnvService
+from app.services.db_sync_service import DatabaseSyncService
+from app.services.git_wordpress_service import GitWordPressService
+
+wordpress_sites_bp = Blueprint('wordpress_sites', __name__)
+
+
+# =============================================================================
+# Site Management
+# =============================================================================
+
+@wordpress_sites_bp.route('/sites', methods=['GET'])
+@jwt_required()
+def list_sites():
+ """List all WordPress sites."""
+ user_id = get_jwt_identity()
+ include_envs = request.args.get('include_environments', 'false').lower() == 'true'
+
+ # Get all WordPress applications for this user
+ sites = WordPressSite.query.join(Application).filter(
+ Application.user_id == user_id,
+ Application.app_type == 'wordpress'
+ ).all()
+
+ # Separate production and environment sites
+ production_sites = [s for s in sites if s.is_production]
+
+ return jsonify({
+ 'sites': [s.to_dict(include_environments=include_envs) for s in production_sites],
+ 'total': len(production_sites)
+ })
+
+
+@wordpress_sites_bp.route('/sites', methods=['POST'])
+@jwt_required()
+def create_site():
+ """Create a new WordPress site."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ # Validate required fields
+ required = ['name', 'domain', 'db_name', 'db_user', 'db_password', 'admin_email']
+ missing = [f for f in required if not data.get(f)]
+ if missing:
+ return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400
+
+ try:
+ # Create Application record
+ app = Application(
+ name=data['name'],
+ app_type='wordpress',
+ status='deploying',
+ php_version=data.get('php_version', '8.2'),
+ port=data.get('port'),
+ root_path=data.get('root_path', f"/var/www/{data['name'].lower().replace(' ', '_')}"),
+ environment_type='production',
+ user_id=user_id
+ )
+ db.session.add(app)
+ db.session.flush()
+
+ # Create WordPressSite record
+ site = WordPressSite(
+ application_id=app.id,
+ admin_email=data['admin_email'],
+ admin_user=data.get('admin_user', 'admin'),
+ db_name=data['db_name'],
+ db_user=data['db_user'],
+ db_host=data.get('db_host', 'localhost'),
+ db_prefix=data.get('db_prefix', 'wp_'),
+ is_production=True
+ )
+ db.session.add(site)
+
+ # Install WordPress
+ install_result = WordPressService.install_wordpress(
+ path=app.root_path,
+ config={
+ 'site_url': f"https://{data['domain']}",
+ 'site_title': data['name'],
+ 'admin_user': data.get('admin_user', 'admin'),
+ 'admin_password': data.get('admin_password'),
+ 'admin_email': data['admin_email'],
+ 'db_name': data['db_name'],
+ 'db_user': data['db_user'],
+ 'db_password': data['db_password'],
+ 'db_host': data.get('db_host', 'localhost'),
+ 'db_prefix': data.get('db_prefix', 'wp_')
+ }
+ )
+
+ if not install_result['success']:
+ db.session.rollback()
+ return jsonify({'error': install_result.get('error', 'Installation failed')}), 500
+
+ # Get WordPress version
+ wp_info = WordPressService.get_wordpress_info(app.root_path)
+ if wp_info:
+ site.wp_version = wp_info.get('version')
+
+ app.status = 'running'
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'site': site.to_dict(),
+ 'admin_password': install_result.get('admin_password')
+ }), 201
+
+ except Exception as e:
+ db.session.rollback()
+ return jsonify({'error': str(e)}), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>', methods=['GET'])
+@jwt_required()
+def get_site(site_id):
+ """Get a WordPress site by ID."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ include_envs = request.args.get('include_environments', 'true').lower() == 'true'
+ include_snaps = request.args.get('include_snapshots', 'false').lower() == 'true'
+
+ result = site.to_dict(include_environments=include_envs, include_snapshots=include_snaps)
+
+ # Add WordPress info from WP-CLI
+ if site.application and site.application.root_path:
+ wp_info = WordPressService.get_wordpress_info(site.application.root_path)
+ if wp_info:
+ result['wp_info'] = wp_info
+
+ return jsonify(result)
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>', methods=['DELETE'])
+@jwt_required()
+def delete_site(site_id):
+ """Delete a WordPress site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ # Check if this is a production site with environments
+ if site.is_production and site.environments:
+ return jsonify({
+ 'error': 'Cannot delete production site with active environments. Delete environments first.'
+ }), 400
+
+ try:
+ # Use environment service to clean up (handles files, database, etc.)
+ result = WordPressEnvService.delete_environment(
+ site_id,
+ delete_files=True,
+ delete_database=True
+ )
+
+ if not result['success']:
+ return jsonify(result), 500
+
+ return jsonify({'success': True, 'message': 'Site deleted'})
+
+ except Exception as e:
+ return jsonify({'error': str(e)}), 500
+
+
+# =============================================================================
+# Environment Management
+# =============================================================================
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/environments', methods=['GET'])
+@jwt_required()
+def list_environments(site_id):
+ """List all environments for a production site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ result = WordPressEnvService.get_environment_status(site_id)
+ return jsonify(result)
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/environments', methods=['POST'])
+@jwt_required()
+def create_environment(site_id):
+ """Create a new environment (dev/staging) for a production site."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ env_type = data.get('type', 'development')
+ if env_type not in ['development', 'staging']:
+ return jsonify({'error': 'Invalid environment type'}), 400
+
+ result = WordPressEnvService.create_environment(
+ production_site_id=site_id,
+ env_type=env_type,
+ config=data,
+ user_id=user_id
+ )
+
+ if result['success']:
+ return jsonify(result), 201
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/environments/<int:env_id>', methods=['DELETE'])
+@jwt_required()
+def delete_environment(site_id, env_id):
+ """Delete an environment."""
+ user_id = get_jwt_identity()
+
+ # Verify ownership
+ env_site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == env_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not env_site:
+ return jsonify({'error': 'Environment not found'}), 404
+
+ if env_site.production_site_id != site_id:
+ return jsonify({'error': 'Environment does not belong to this site'}), 400
+
+ result = WordPressEnvService.delete_environment(env_id)
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/sync', methods=['POST'])
+@jwt_required()
+def sync_environment(site_id):
+ """Sync an environment from its production source."""
+ user_id = get_jwt_identity()
+ data = request.get_json() or {}
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ if site.is_production:
+ return jsonify({'error': 'Cannot sync a production site'}), 400
+
+ result = WordPressEnvService.sync_environment(site_id, options=data)
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+# =============================================================================
+# Database Operations
+# =============================================================================
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots', methods=['GET'])
+@jwt_required()
+def list_snapshots(site_id):
+ """List database snapshots for a site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ snapshots = DatabaseSnapshot.query.filter_by(site_id=site_id).order_by(
+ DatabaseSnapshot.created_at.desc()
+ ).all()
+
+ return jsonify({
+ 'snapshots': [s.to_dict() for s in snapshots],
+ 'total': len(snapshots)
+ })
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots', methods=['POST'])
+@jwt_required()
+def create_snapshot(site_id):
+ """Create a database snapshot."""
+ user_id = get_jwt_identity()
+ data = request.get_json() or {}
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ result = DatabaseSyncService.create_snapshot(
+ db_name=site.db_name,
+ name=data.get('name', f"{site.application.name}_{site.id}"),
+ tag=data.get('tag'),
+ commit_sha=site.last_deploy_commit,
+ host=site.db_host,
+ user=site.db_user,
+ password=WordPressEnvService._get_db_password(site),
+ exclude_tables=data.get('exclude_tables', [])
+ )
+
+ if result['success']:
+ # Save to database
+ snapshot = DatabaseSnapshot(
+ site_id=site_id,
+ name=result['snapshot']['name'],
+ tag=data.get('tag'),
+ file_path=result['snapshot']['file_path'],
+ size_bytes=result['snapshot']['size_bytes'],
+ compressed=result['snapshot']['compressed'],
+ commit_sha=site.last_deploy_commit,
+ tables_included=json.dumps(result['snapshot'].get('tables', [])),
+ row_count=result['snapshot'].get('row_count', 0),
+ status='completed'
+ )
+ db.session.add(snapshot)
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'snapshot': snapshot.to_dict()
+ }), 201
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots/<int:snapshot_id>/restore', methods=['POST'])
+@jwt_required()
+def restore_snapshot(site_id, snapshot_id):
+ """Restore a database snapshot."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site_id).first()
+ if not snapshot:
+ return jsonify({'error': 'Snapshot not found'}), 404
+
+ # Create a backup before restoring
+ backup_result = DatabaseSyncService.create_snapshot(
+ db_name=site.db_name,
+ name=f"pre_restore_{snapshot_id}",
+ tag='pre-restore',
+ host=site.db_host,
+ user=site.db_user,
+ password=WordPressEnvService._get_db_password(site)
+ )
+
+ # Restore the snapshot
+ result = DatabaseSyncService.restore_snapshot(
+ file_path=snapshot.file_path,
+ target_db=site.db_name,
+ host=site.db_host,
+ user=site.db_user,
+ password=WordPressEnvService._get_db_password(site),
+ create_db=False
+ )
+
+ if result['success']:
+ return jsonify({
+ 'success': True,
+ 'message': 'Snapshot restored',
+ 'backup_path': backup_result.get('snapshot', {}).get('file_path') if backup_result.get('success') else None
+ })
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/snapshots/<int:snapshot_id>', methods=['DELETE'])
+@jwt_required()
+def delete_snapshot(site_id, snapshot_id):
+ """Delete a database snapshot."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site_id).first()
+ if not snapshot:
+ return jsonify({'error': 'Snapshot not found'}), 404
+
+ # Delete file
+ DatabaseSyncService.delete_snapshot(snapshot.file_path)
+
+ # Delete record
+ db.session.delete(snapshot)
+ db.session.commit()
+
+ return jsonify({'success': True, 'message': 'Snapshot deleted'})
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/clone-db', methods=['POST'])
+@jwt_required()
+def clone_database(site_id):
+ """Clone the database to another environment."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ target_site_id = data.get('target_site_id')
+ if not target_site_id:
+ return jsonify({'error': 'target_site_id is required'}), 400
+
+ target_site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == target_site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not target_site:
+ return jsonify({'error': 'Target site not found'}), 404
+
+ result = DatabaseSyncService.clone_database(
+ source_db=site.db_name,
+ target_db=target_site.db_name,
+ source_host=site.db_host,
+ target_host=target_site.db_host,
+ source_user=site.db_user,
+ target_user=target_site.db_user,
+ source_password=WordPressEnvService._get_db_password(site),
+ target_password=WordPressEnvService._get_db_password(target_site),
+ options=data.get('options', {})
+ )
+
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+# =============================================================================
+# Git Integration
+# =============================================================================
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/git', methods=['GET'])
+@jwt_required()
+def get_git_status(site_id):
+ """Get Git integration status for a site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ result = GitWordPressService.get_git_status(site_id)
+ return jsonify(result)
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/git', methods=['POST'])
+@jwt_required()
+def connect_repo(site_id):
+ """Connect a Git repository to a site."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ repo_url = data.get('repo_url')
+ if not repo_url:
+ return jsonify({'error': 'repo_url is required'}), 400
+
+ result = GitWordPressService.connect_repo(
+ site_id=site_id,
+ repo_url=repo_url,
+ branch=data.get('branch', 'main'),
+ paths=data.get('paths'),
+ auto_deploy=data.get('auto_deploy', False)
+ )
+
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/git', methods=['DELETE'])
+@jwt_required()
+def disconnect_repo(site_id):
+ """Disconnect Git repository from a site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ result = GitWordPressService.disconnect_repo(site_id)
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/git/commits', methods=['GET'])
+@jwt_required()
+def get_commits(site_id):
+ """Get recent commits from the connected repository."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ limit = request.args.get('limit', 20, type=int)
+ result = GitWordPressService.get_recent_commits(site_id, limit=limit)
+ return jsonify(result)
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/git/deploy', methods=['POST'])
+@jwt_required()
+def deploy_commit(site_id):
+ """Deploy a specific commit or branch."""
+ user_id = get_jwt_identity()
+ data = request.get_json() or {}
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ result = GitWordPressService.deploy_from_commit(
+ site_id=site_id,
+ commit_sha=data.get('commit_sha'),
+ branch=data.get('branch'),
+ create_snapshot=data.get('create_snapshot', True)
+ )
+
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/git/dev-from-commit', methods=['POST'])
+@jwt_required()
+def create_dev_from_commit(site_id):
+ """Create a development environment for a specific commit."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site:
+ return jsonify({'error': 'Site not found'}), 404
+
+ commit_sha = data.get('commit_sha')
+ if not commit_sha:
+ return jsonify({'error': 'commit_sha is required'}), 400
+
+ result = GitWordPressService.create_dev_for_commit(
+ production_site_id=site_id,
+ commit_sha=commit_sha,
+ config=data.get('config', {}),
+ user_id=user_id
+ )
+
+ if result['success']:
+ return jsonify(result), 201
+ else:
+ return jsonify(result), 500
+
+
+# =============================================================================
+# WordPress Operations (Plugins, Themes, etc.)
+# =============================================================================
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/plugins', methods=['GET'])
+@jwt_required()
+def get_plugins(site_id):
+ """Get installed plugins for a site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site or not site.application:
+ return jsonify({'error': 'Site not found'}), 404
+
+ plugins = WordPressService.get_plugins(site.application.root_path)
+ return jsonify({'plugins': plugins})
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/plugins', methods=['POST'])
+@jwt_required()
+def install_plugin(site_id):
+ """Install a plugin."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site or not site.application:
+ return jsonify({'error': 'Site not found'}), 404
+
+ plugin = data.get('plugin')
+ if not plugin:
+ return jsonify({'error': 'plugin is required'}), 400
+
+ result = WordPressService.install_plugin(
+ site.application.root_path,
+ plugin,
+ activate=data.get('activate', True)
+ )
+
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/themes', methods=['GET'])
+@jwt_required()
+def get_themes(site_id):
+ """Get installed themes for a site."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site or not site.application:
+ return jsonify({'error': 'Site not found'}), 404
+
+ themes = WordPressService.get_themes(site.application.root_path)
+ return jsonify({'themes': themes})
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/themes', methods=['POST'])
+@jwt_required()
+def install_theme(site_id):
+ """Install a theme."""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site or not site.application:
+ return jsonify({'error': 'Site not found'}), 404
+
+ theme = data.get('theme')
+ if not theme:
+ return jsonify({'error': 'theme is required'}), 400
+
+ result = WordPressService.install_theme(
+ site.application.root_path,
+ theme,
+ activate=data.get('activate', False)
+ )
+
+ if result['success']:
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
+@wordpress_sites_bp.route('/sites/<int:site_id>/update', methods=['POST'])
+@jwt_required()
+def update_wordpress(site_id):
+ """Update WordPress core."""
+ user_id = get_jwt_identity()
+
+ site = WordPressSite.query.join(Application).filter(
+ WordPressSite.id == site_id,
+ Application.user_id == user_id
+ ).first()
+
+ if not site or not site.application:
+ return jsonify({'error': 'Site not found'}), 404
+
+ # Create snapshot before update
+ snapshot_result = DatabaseSyncService.create_snapshot(
+ db_name=site.db_name,
+ name=f"pre_update_{site.wp_version}",
+ tag='pre-update',
+ host=site.db_host,
+ user=site.db_user,
+ password=WordPressEnvService._get_db_password(site)
+ )
+
+ result = WordPressService.update_wordpress(site.application.root_path)
+
+ if result['success']:
+ # Update version in database
+ wp_info = WordPressService.get_wordpress_info(site.application.root_path)
+ if wp_info:
+ site.wp_version = wp_info.get('version')
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'message': result.get('message'),
+ 'new_version': site.wp_version,
+ 'backup_snapshot': snapshot_result.get('snapshot', {}).get('file_path') if snapshot_result.get('success') else None
+ })
+ else:
+ return jsonify(result), 500
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 5d1950d2..b01c83c0 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -11,10 +11,12 @@ from app.models.workflow import Workflow
from app.models.webhook import GitWebhook, WebhookLog, GitDeployment
from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession
from app.models.security_alert import SecurityAlert
+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob
__all__ = [
'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',
'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog',
'MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment',
- 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert'
+ 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert',
+ 'WordPressSite', 'DatabaseSnapshot', 'SyncJob'
]
diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py
new file mode 100644
index 00000000..af9b886e
--- /dev/null
+++ b/backend/app/models/wordpress_site.py
@@ -0,0 +1,247 @@
+"""
+WordPress Site Models
+
+Extended models for WordPress-specific functionality including:
+- WordPress site metadata
+- Database snapshots for point-in-time recovery
+- Sync jobs for scheduled database synchronization
+"""
+
+from datetime import datetime
+from app import db
+import json
+
+
+class WordPressSite(db.Model):
+ """Extended WordPress-specific data linked to Application."""
+
+ __tablename__ = 'wordpress_sites'
+
+ id = db.Column(db.Integer, primary_key=True)
+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), unique=True, nullable=False)
+
+ # WordPress specifics
+ wp_version = db.Column(db.String(20))
+ multisite = db.Column(db.Boolean, default=False)
+ admin_user = db.Column(db.String(100))
+ admin_email = db.Column(db.String(200))
+
+ # Database info
+ db_name = db.Column(db.String(100))
+ db_user = db.Column(db.String(100))
+ db_host = db.Column(db.String(200), default='localhost')
+ db_prefix = db.Column(db.String(20), default='wp_')
+
+ # Git integration
+ git_repo_url = db.Column(db.String(500))
+ git_branch = db.Column(db.String(100), default='main')
+ git_paths = db.Column(db.Text) # JSON: paths to sync ['wp-content/themes', 'wp-content/plugins']
+ auto_deploy = db.Column(db.Boolean, default=False)
+ last_deploy_commit = db.Column(db.String(40))
+ last_deploy_at = db.Column(db.DateTime)
+
+ # Environment info
+ is_production = db.Column(db.Boolean, default=True)
+ production_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=True)
+
+ # Sync settings (JSON)
+ sync_config = db.Column(db.Text) # schedule, search_replace, anonymize, etc.
+
+ # Timestamps
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ application = db.relationship('Application', backref=db.backref('wp_site', uselist=False))
+ environments = db.relationship(
+ 'WordPressSite',
+ backref=db.backref('production_site', remote_side=[id]),
+ foreign_keys=[production_site_id]
+ )
+ snapshots = db.relationship('DatabaseSnapshot', backref='site', lazy='dynamic', cascade='all, delete-orphan')
+ sync_jobs_as_source = db.relationship(
+ 'SyncJob',
+ foreign_keys='SyncJob.source_site_id',
+ backref='source_site',
+ lazy='dynamic'
+ )
+ sync_jobs_as_target = db.relationship(
+ 'SyncJob',
+ foreign_keys='SyncJob.target_site_id',
+ backref='target_site',
+ lazy='dynamic'
+ )
+
+ def to_dict(self, include_environments=False, include_snapshots=False):
+ result = {
+ 'id': self.id,
+ 'application_id': self.application_id,
+ 'wp_version': self.wp_version,
+ 'multisite': self.multisite,
+ 'admin_user': self.admin_user,
+ 'admin_email': self.admin_email,
+ 'db_name': self.db_name,
+ 'db_user': self.db_user,
+ 'db_host': self.db_host,
+ 'db_prefix': self.db_prefix,
+ 'git_repo_url': self.git_repo_url,
+ 'git_branch': self.git_branch,
+ 'git_paths': json.loads(self.git_paths) if self.git_paths else None,
+ 'auto_deploy': self.auto_deploy,
+ 'last_deploy_commit': self.last_deploy_commit,
+ 'last_deploy_at': self.last_deploy_at.isoformat() if self.last_deploy_at else None,
+ 'is_production': self.is_production,
+ 'production_site_id': self.production_site_id,
+ 'sync_config': json.loads(self.sync_config) if self.sync_config else None,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
+ }
+
+ # Include application data
+ if self.application:
+ result['application'] = {
+ 'id': self.application.id,
+ 'name': self.application.name,
+ 'status': self.application.status,
+ 'root_path': self.application.root_path,
+ 'port': self.application.port,
+ 'domains': [d.to_dict() for d in self.application.domains]
+ }
+
+ if include_environments and self.is_production:
+ result['environments'] = [env.to_dict() for env in self.environments]
+
+ if include_snapshots:
+ result['snapshots'] = [snap.to_dict() for snap in self.snapshots.order_by(DatabaseSnapshot.created_at.desc()).limit(10)]
+
+ return result
+
+ def __repr__(self):
+ return f'<WordPressSite {self.id} app={self.application_id}>'
+
+
+class DatabaseSnapshot(db.Model):
+ """Point-in-time database snapshots for WordPress sites."""
+
+ __tablename__ = 'database_snapshots'
+
+ id = db.Column(db.Integer, primary_key=True)
+ site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False)
+
+ # Snapshot info
+ name = db.Column(db.String(200), nullable=False)
+ description = db.Column(db.Text)
+ tag = db.Column(db.String(100)) # e.g., 'pre-deploy', 'v1.2.0', 'auto-nightly'
+
+ # File info
+ file_path = db.Column(db.String(500), nullable=False)
+ size_bytes = db.Column(db.BigInteger, default=0)
+ compressed = db.Column(db.Boolean, default=True)
+
+ # Git context (optional)
+ commit_sha = db.Column(db.String(40)) # Git commit at snapshot time
+ commit_message = db.Column(db.Text)
+
+ # Metadata
+ tables_included = db.Column(db.Text) # JSON list of tables
+ row_count = db.Column(db.Integer)
+
+ # Status
+ status = db.Column(db.String(20), default='completed') # creating, completed, failed, deleted
+ error_message = db.Column(db.Text)
+
+ # Timestamps
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ expires_at = db.Column(db.DateTime) # Auto-cleanup date
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'site_id': self.site_id,
+ 'name': self.name,
+ 'description': self.description,
+ 'tag': self.tag,
+ 'file_path': self.file_path,
+ 'size_bytes': self.size_bytes,
+ 'size_human': self._format_size(self.size_bytes),
+ 'compressed': self.compressed,
+ 'commit_sha': self.commit_sha,
+ 'commit_message': self.commit_message,
+ 'tables_included': json.loads(self.tables_included) if self.tables_included else None,
+ 'row_count': self.row_count,
+ 'status': self.status,
+ 'error_message': self.error_message,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'expires_at': self.expires_at.isoformat() if self.expires_at else None,
+ }
+
+ @staticmethod
+ def _format_size(size_bytes):
+ if not size_bytes:
+ return '0 B'
+ for unit in ['B', 'KB', 'MB', 'GB']:
+ if size_bytes < 1024:
+ return f'{size_bytes:.1f} {unit}'
+ size_bytes /= 1024
+ return f'{size_bytes:.1f} TB'
+
+ def __repr__(self):
+ return f'<DatabaseSnapshot {self.id} "{self.name}">'
+
+
+class SyncJob(db.Model):
+ """Scheduled database synchronization jobs between WordPress environments."""
+
+ __tablename__ = 'sync_jobs'
+
+ id = db.Column(db.Integer, primary_key=True)
+
+ # Source and target sites
+ source_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False)
+ target_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False)
+
+ # Job name
+ name = db.Column(db.String(200))
+
+ # Schedule (cron expression)
+ schedule = db.Column(db.String(100)) # e.g., "0 3 * * 0" = Sunday 3 AM
+ enabled = db.Column(db.Boolean, default=True)
+
+ # Configuration (JSON)
+ config = db.Column(db.Text) # search_replace, anonymize, exclude_tables, truncate_tables
+
+ # Execution tracking
+ last_run = db.Column(db.DateTime)
+ last_run_status = db.Column(db.String(20)) # success, failed, running
+ last_run_duration = db.Column(db.Integer) # seconds
+ last_run_error = db.Column(db.Text)
+ next_run = db.Column(db.DateTime)
+ run_count = db.Column(db.Integer, default=0)
+
+ # Timestamps
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'source_site_id': self.source_site_id,
+ 'target_site_id': self.target_site_id,
+ 'schedule': self.schedule,
+ 'enabled': self.enabled,
+ 'config': json.loads(self.config) if self.config else None,
+ 'last_run': self.last_run.isoformat() if self.last_run else None,
+ 'last_run_status': self.last_run_status,
+ 'last_run_duration': self.last_run_duration,
+ 'last_run_error': self.last_run_error,
+ 'next_run': self.next_run.isoformat() if self.next_run else None,
+ 'run_count': self.run_count,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
+ 'source_site': self.source_site.to_dict() if self.source_site else None,
+ 'target_site': self.target_site.to_dict() if self.target_site else None,
+ }
+
+ def __repr__(self):
+ return f'<SyncJob {self.id} {self.source_site_id}->{self.target_site_id}>'
diff --git a/backend/app/services/db_sync_service.py b/backend/app/services/db_sync_service.py
new file mode 100644
index 00000000..8c188547
--- /dev/null
+++ b/backend/app/services/db_sync_service.py
@@ -0,0 +1,609 @@
+"""
+Database Sync Service
+
+Service for database cloning, transformation, and synchronization operations.
+Supports WordPress-specific features like URL search-replace and data anonymization.
+"""
+
+import os
+import subprocess
+import gzip
+import shutil
+import json
+import re
+from datetime import datetime, timedelta
+from typing import Dict, List, Optional
+from pathlib import Path
+
+
+class DatabaseSyncService:
+ """Service for database cloning, transformation, and sync operations."""
+
+ SNAPSHOT_DIR = '/var/backups/serverkit/snapshots'
+ TEMP_DIR = '/tmp/serverkit_db_sync'
+
+ @classmethod
+ def _ensure_dirs(cls):
+ """Ensure required directories exist."""
+ for dir_path in [cls.SNAPSHOT_DIR, cls.TEMP_DIR]:
+ os.makedirs(dir_path, exist_ok=True)
+
+ @classmethod
+ def _run_mysql(cls, command: str, database: str = None, host: str = 'localhost',
+ user: str = 'root', password: str = None) -> Dict:
+ """Execute a MySQL command."""
+ try:
+ cmd = ['mysql', '-h', host, '-u', user]
+ if password:
+ cmd.append(f'-p{password}')
+ if database:
+ cmd.extend(['-D', database])
+ cmd.extend(['-e', command])
+
+ result = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=300
+ )
+
+ 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 create_snapshot(cls, db_name: str, name: str = None, tag: str = None,
+ commit_sha: str = None, host: str = 'localhost',
+ user: str = 'root', password: str = None,
+ compress: bool = True, exclude_tables: List[str] = None) -> Dict:
+ """
+ Create a point-in-time database snapshot.
+
+ Args:
+ db_name: Database name to snapshot
+ name: Human-readable snapshot name
+ tag: Optional tag (e.g., 'pre-deploy', 'v1.2.0')
+ commit_sha: Git commit SHA at snapshot time
+ host: MySQL host
+ user: MySQL user
+ password: MySQL password
+ compress: Whether to gzip the dump
+ exclude_tables: List of tables to exclude
+
+ Returns:
+ Dict with success status and snapshot info
+ """
+ cls._ensure_dirs()
+
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
+ snapshot_name = name or f'{db_name}_{timestamp}'
+ safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', snapshot_name)
+
+ file_name = f'{safe_name}.sql'
+ if compress:
+ file_name += '.gz'
+
+ file_path = os.path.join(cls.SNAPSHOT_DIR, file_name)
+
+ try:
+ # Build mysqldump command
+ cmd = ['mysqldump', '-h', host, '-u', user]
+ if password:
+ cmd.append(f'-p{password}')
+
+ # Add options for consistent snapshot
+ cmd.extend([
+ '--single-transaction',
+ '--routines',
+ '--triggers',
+ '--add-drop-table',
+ ])
+
+ # Exclude tables if specified
+ if exclude_tables:
+ for table in exclude_tables:
+ cmd.extend(['--ignore-table', f'{db_name}.{table}'])
+
+ cmd.append(db_name)
+
+ # Execute dump
+ if compress:
+ # Pipe through gzip
+ dump_process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE
+ )
+ with gzip.open(file_path, 'wb') as f:
+ while True:
+ chunk = dump_process.stdout.read(8192)
+ if not chunk:
+ break
+ f.write(chunk)
+
+ dump_process.wait()
+ if dump_process.returncode != 0:
+ error = dump_process.stderr.read().decode()
+ return {'success': False, 'error': f'mysqldump failed: {error}'}
+ else:
+ with open(file_path, 'w') as f:
+ result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, text=True)
+ if result.returncode != 0:
+ return {'success': False, 'error': f'mysqldump failed: {result.stderr}'}
+
+ # Get file size
+ size_bytes = os.path.getsize(file_path)
+
+ # Get table list and row count
+ tables_result = cls._run_mysql(
+ f"SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.tables WHERE TABLE_SCHEMA = '{db_name}'",
+ host=host, user=user, password=password
+ )
+
+ tables = []
+ total_rows = 0
+ if tables_result['success']:
+ for line in tables_result['output'].strip().split('\n')[1:]:
+ parts = line.split('\t')
+ if len(parts) >= 2:
+ tables.append(parts[0])
+ try:
+ total_rows += int(parts[1]) if parts[1] != 'NULL' else 0
+ except ValueError:
+ pass
+
+ return {
+ 'success': True,
+ 'snapshot': {
+ 'name': snapshot_name,
+ 'tag': tag,
+ 'file_path': file_path,
+ 'size_bytes': size_bytes,
+ 'compressed': compress,
+ 'commit_sha': commit_sha,
+ 'tables': tables,
+ 'row_count': total_rows,
+ 'created_at': datetime.now().isoformat()
+ }
+ }
+
+ except Exception as e:
+ # Cleanup on failure
+ if os.path.exists(file_path):
+ os.remove(file_path)
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def restore_snapshot(cls, file_path: str, target_db: str,
+ host: str = 'localhost', user: str = 'root',
+ password: str = None, create_db: bool = True) -> Dict:
+ """
+ Restore a database snapshot.
+
+ Args:
+ file_path: Path to snapshot file (.sql or .sql.gz)
+ target_db: Target database name
+ host: MySQL host
+ user: MySQL user
+ password: MySQL password
+ create_db: Create database if it doesn't exist
+
+ Returns:
+ Dict with success status
+ """
+ if not os.path.exists(file_path):
+ return {'success': False, 'error': f'Snapshot file not found: {file_path}'}
+
+ try:
+ # Create database if needed
+ if create_db:
+ create_result = cls._run_mysql(
+ f"CREATE DATABASE IF NOT EXISTS `{target_db}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
+ host=host, user=user, password=password
+ )
+ if not create_result['success']:
+ return create_result
+
+ # Build mysql import command
+ cmd = ['mysql', '-h', host, '-u', user]
+ if password:
+ cmd.append(f'-p{password}')
+ cmd.append(target_db)
+
+ # Handle compressed files
+ if file_path.endswith('.gz'):
+ with gzip.open(file_path, 'rb') as f:
+ result = subprocess.run(
+ cmd,
+ stdin=f,
+ capture_output=True,
+ timeout=1800 # 30 min timeout for large DBs
+ )
+ else:
+ with open(file_path, 'r') as f:
+ result = subprocess.run(
+ cmd,
+ stdin=f,
+ capture_output=True,
+ timeout=1800
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr.decode() if result.stderr else 'Import failed'}
+
+ return {'success': True, 'message': f'Snapshot restored to {target_db}'}
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Restore timed out (>30 minutes)'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def clone_database(cls, source_db: str, target_db: str,
+ source_host: str = 'localhost', target_host: str = 'localhost',
+ source_user: str = 'root', target_user: str = 'root',
+ source_password: str = None, target_password: str = None,
+ options: Dict = None) -> Dict:
+ """
+ Clone a database with optional transformations.
+
+ Args:
+ source_db: Source database name
+ target_db: Target database name
+ source_host/target_host: MySQL hosts
+ source_user/target_user: MySQL users
+ source_password/target_password: MySQL passwords
+ options: Dict with transformation options:
+ - search_replace: Dict of {search: replace} for URL/string replacement
+ - table_prefix: New table prefix (e.g., 'wp_dev_')
+ - anonymize: Bool - anonymize user data
+ - exclude_tables: List of tables to skip
+ - truncate_tables: List of tables to empty (keep structure)
+
+ Returns:
+ Dict with success status and clone info
+ """
+ options = options or {}
+ cls._ensure_dirs()
+
+ try:
+ # Step 1: Create snapshot of source
+ snapshot_result = cls.create_snapshot(
+ db_name=source_db,
+ name=f'clone_{source_db}_to_{target_db}',
+ host=source_host,
+ user=source_user,
+ password=source_password,
+ compress=False, # Don't compress for transformation
+ exclude_tables=options.get('exclude_tables', [])
+ )
+
+ if not snapshot_result['success']:
+ return snapshot_result
+
+ dump_file = snapshot_result['snapshot']['file_path']
+ transformed_file = dump_file.replace('.sql', '_transformed.sql')
+
+ try:
+ # Step 2: Transform the dump if needed
+ needs_transform = any([
+ options.get('search_replace'),
+ options.get('table_prefix'),
+ options.get('anonymize'),
+ options.get('truncate_tables')
+ ])
+
+ if needs_transform:
+ transform_result = cls._transform_dump(
+ dump_file,
+ transformed_file,
+ options
+ )
+ if not transform_result['success']:
+ return transform_result
+ import_file = transformed_file
+ else:
+ import_file = dump_file
+
+ # Step 3: Drop and recreate target database
+ cls._run_mysql(
+ f"DROP DATABASE IF EXISTS `{target_db}`",
+ host=target_host, user=target_user, password=target_password
+ )
+
+ # Step 4: Restore to target
+ restore_result = cls.restore_snapshot(
+ file_path=import_file,
+ target_db=target_db,
+ host=target_host,
+ user=target_user,
+ password=target_password,
+ create_db=True
+ )
+
+ if not restore_result['success']:
+ return restore_result
+
+ return {
+ 'success': True,
+ 'message': f'Database cloned from {source_db} to {target_db}',
+ 'transformations_applied': list(options.keys()) if needs_transform else []
+ }
+
+ finally:
+ # Cleanup temp files
+ for f in [dump_file, transformed_file]:
+ if os.path.exists(f):
+ os.remove(f)
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _transform_dump(cls, input_file: str, output_file: str, options: Dict) -> Dict:
+ """
+ Transform a SQL dump file with search-replace and other modifications.
+
+ This handles WordPress serialized data properly using PHP-style serialization.
+ """
+ search_replace = options.get('search_replace', {})
+ new_prefix = options.get('table_prefix')
+ anonymize = options.get('anonymize', False)
+ truncate_tables = options.get('truncate_tables', [])
+
+ try:
+ with open(input_file, 'r', encoding='utf-8', errors='replace') as infile:
+ with open(output_file, 'w', encoding='utf-8') as outfile:
+ current_table = None
+
+ for line in infile:
+ # Track current table for truncation
+ if line.startswith('INSERT INTO'):
+ match = re.search(r'INSERT INTO `?(\w+)`?', line)
+ if match:
+ current_table = match.group(1)
+
+ # Skip inserts for truncated tables
+ if current_table and truncate_tables:
+ table_name = current_table
+ if new_prefix:
+ # Check both old and new prefix versions
+ for prefix in ['wp_', new_prefix]:
+ for t in truncate_tables:
+ if table_name == f'{prefix}{t}' or table_name == t:
+ # Skip this INSERT
+ if line.startswith('INSERT INTO'):
+ continue
+
+ # Table prefix replacement
+ if new_prefix and 'wp_' in line:
+ # Replace table references
+ line = re.sub(r'`wp_(\w+)`', f'`{new_prefix}\\1`', line)
+ # Replace in CREATE TABLE
+ line = line.replace('CREATE TABLE `wp_', f'CREATE TABLE `{new_prefix}')
+ # Replace in INSERT INTO
+ line = line.replace('INSERT INTO `wp_', f'INSERT INTO `{new_prefix}')
+
+ # Search and replace (handles serialized data)
+ for search, replace in search_replace.items():
+ line = cls._safe_search_replace(line, search, replace)
+
+ # Anonymize user data
+ if anonymize and 'user_email' in line.lower():
+ line = cls._anonymize_line(line)
+
+ outfile.write(line)
+
+ return {'success': True}
+
+ except Exception as e:
+ return {'success': False, 'error': f'Transform failed: {str(e)}'}
+
+ @classmethod
+ def _safe_search_replace(cls, text: str, search: str, replace: str) -> str:
+ """
+ Perform search-replace that handles WordPress serialized data.
+
+ WordPress stores serialized PHP arrays in the database with string length prefixes.
+ e.g., s:23:"http://example.com/path";
+
+ When replacing URLs, we need to update these length prefixes.
+ """
+ # Simple replacement first
+ if search not in text:
+ return text
+
+ # Handle serialized string format: s:LENGTH:"VALUE";
+ def replace_serialized(match):
+ original = match.group(2)
+ new_value = original.replace(search, replace)
+ new_length = len(new_value.encode('utf-8'))
+ return f's:{new_length}:"{new_value}"'
+
+ # Pattern for serialized strings that contain the search term
+ pattern = r's:(\d+):"([^"]*' + re.escape(search) + r'[^"]*)"'
+ text = re.sub(pattern, replace_serialized, text)
+
+ # Also do plain replacement for non-serialized occurrences
+ text = text.replace(search, replace)
+
+ return text
+
+ @classmethod
+ def _anonymize_line(cls, line: str) -> str:
+ """Anonymize user data in a SQL line."""
+ # Replace email addresses
+ line = re.sub(
+ r"'([^']+@[^']+)'",
+ lambda m: f"'user{hash(m.group(1)) % 10000}@example.com'",
+ line
+ )
+ return line
+
+ @classmethod
+ def run_search_replace(cls, db_name: str, search: str, replace: str,
+ table_prefix: str = 'wp_', host: str = 'localhost',
+ user: str = 'root', password: str = None,
+ dry_run: bool = False) -> Dict:
+ """
+ Run WordPress-aware search-replace on a database.
+
+ This is a pure SQL approach without requiring WP-CLI.
+ For better serialized data handling, use WP-CLI if available.
+
+ Args:
+ db_name: Database name
+ search: String to search for
+ replace: String to replace with
+ table_prefix: WordPress table prefix
+ host: MySQL host
+ user: MySQL user
+ password: MySQL password
+ dry_run: Only count replacements, don't apply
+
+ Returns:
+ Dict with success status and replacement count
+ """
+ try:
+ # Get list of tables
+ tables_result = cls._run_mysql(
+ f"SHOW TABLES LIKE '{table_prefix}%'",
+ database=db_name, host=host, user=user, password=password
+ )
+
+ if not tables_result['success']:
+ return tables_result
+
+ tables = [line.strip() for line in tables_result['output'].strip().split('\n')[1:] if line.strip()]
+ total_replacements = 0
+
+ for table in tables:
+ # Get columns
+ cols_result = cls._run_mysql(
+ f"SHOW COLUMNS FROM `{table}`",
+ database=db_name, host=host, user=user, password=password
+ )
+
+ if not cols_result['success']:
+ continue
+
+ # Find text/varchar columns
+ text_columns = []
+ for line in cols_result['output'].strip().split('\n')[1:]:
+ parts = line.split('\t')
+ if len(parts) >= 2:
+ col_name = parts[0]
+ col_type = parts[1].lower()
+ if any(t in col_type for t in ['varchar', 'text', 'longtext', 'mediumtext']):
+ text_columns.append(col_name)
+
+ # Count or replace in each column
+ for col in text_columns:
+ if dry_run:
+ count_query = f"SELECT COUNT(*) FROM `{table}` WHERE `{col}` LIKE '%{search}%'"
+ count_result = cls._run_mysql(
+ count_query,
+ database=db_name, host=host, user=user, password=password
+ )
+ if count_result['success']:
+ try:
+ count = int(count_result['output'].strip().split('\n')[1])
+ total_replacements += count
+ except (IndexError, ValueError):
+ pass
+ else:
+ # Note: This is basic replacement, doesn't handle serialized data perfectly
+ update_query = f"UPDATE `{table}` SET `{col}` = REPLACE(`{col}`, '{search}', '{replace}') WHERE `{col}` LIKE '%{search}%'"
+ cls._run_mysql(
+ update_query,
+ database=db_name, host=host, user=user, password=password
+ )
+
+ return {
+ 'success': True,
+ 'dry_run': dry_run,
+ 'replacements': total_replacements if dry_run else 'Applied to all matching rows',
+ 'tables_processed': len(tables)
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_snapshot(cls, file_path: str) -> Dict:
+ """Delete a snapshot file."""
+ try:
+ if os.path.exists(file_path):
+ os.remove(file_path)
+ return {'success': True, 'message': 'Snapshot deleted'}
+ return {'success': False, 'error': 'Snapshot file not found'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def list_snapshots(cls, site_name: str = None) -> List[Dict]:
+ """List available snapshots."""
+ cls._ensure_dirs()
+ snapshots = []
+
+ try:
+ for filename in os.listdir(cls.SNAPSHOT_DIR):
+ if not filename.endswith(('.sql', '.sql.gz')):
+ continue
+
+ if site_name and not filename.startswith(site_name):
+ continue
+
+ file_path = os.path.join(cls.SNAPSHOT_DIR, filename)
+ stat = os.stat(file_path)
+
+ snapshots.append({
+ 'name': filename.replace('.sql.gz', '').replace('.sql', ''),
+ 'file_path': file_path,
+ 'size_bytes': stat.st_size,
+ 'compressed': filename.endswith('.gz'),
+ 'created_at': datetime.fromtimestamp(stat.st_mtime).isoformat()
+ })
+
+ return sorted(snapshots, key=lambda x: x['created_at'], reverse=True)
+
+ except Exception:
+ return []
+
+ @classmethod
+ def cleanup_old_snapshots(cls, days: int = 30, keep_tagged: bool = True) -> Dict:
+ """
+ Clean up snapshots older than specified days.
+
+ Args:
+ days: Delete snapshots older than this many days
+ keep_tagged: Keep snapshots with tags (like 'v1.0.0')
+
+ Returns:
+ Dict with deleted count
+ """
+ cls._ensure_dirs()
+ cutoff = datetime.now() - timedelta(days=days)
+ deleted = 0
+
+ try:
+ for filename in os.listdir(cls.SNAPSHOT_DIR):
+ file_path = os.path.join(cls.SNAPSHOT_DIR, filename)
+ stat = os.stat(file_path)
+ file_time = datetime.fromtimestamp(stat.st_mtime)
+
+ if file_time < cutoff:
+ # TODO: Check if tagged in database before deleting
+ os.remove(file_path)
+ deleted += 1
+
+ return {'success': True, 'deleted': deleted}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e), 'deleted': deleted}
diff --git a/backend/app/services/git_wordpress_service.py b/backend/app/services/git_wordpress_service.py
new file mode 100644
index 00000000..abfd91cd
--- /dev/null
+++ b/backend/app/services/git_wordpress_service.py
@@ -0,0 +1,536 @@
+"""
+Git WordPress Service
+
+Connect Git repositories to WordPress wp-content for theme/plugin management.
+Supports deployment from specific commits and creating dev environments for any revision.
+"""
+
+import os
+import subprocess
+import shutil
+import json
+from datetime import datetime
+from typing import Dict, List, Optional
+
+from app import db
+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot
+from app.services.db_sync_service import DatabaseSyncService
+from app.services.wordpress_env_service import WordPressEnvService
+
+
+class GitWordPressService:
+ """Connect Git repositories to WordPress wp-content."""
+
+ DEFAULT_PATHS = ['wp-content/themes', 'wp-content/plugins']
+
+ @classmethod
+ def connect_repo(cls, site_id: int, repo_url: str, branch: str = 'main',
+ paths: List[str] = None, auto_deploy: bool = False) -> Dict:
+ """
+ Connect a Git repository to a WordPress site.
+
+ Args:
+ site_id: ID of the WordPressSite
+ repo_url: Git repository URL (HTTPS or SSH)
+ branch: Branch to track (default: main)
+ paths: What to sync (default: ['wp-content/themes', 'wp-content/plugins'])
+ auto_deploy: Enable automatic deployment on push
+
+ Returns:
+ Dict with success status
+ """
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.application or not site.application.root_path:
+ return {'success': False, 'error': 'Site application path not found'}
+
+ wp_path = site.application.root_path
+ paths = paths or cls.DEFAULT_PATHS
+
+ try:
+ # Validate repository URL
+ if not cls._validate_repo_url(repo_url):
+ return {'success': False, 'error': 'Invalid repository URL'}
+
+ # Test repository access
+ test_result = cls._test_repo_access(repo_url)
+ if not test_result['success']:
+ return test_result
+
+ # Initialize git in wp-content if not exists
+ wp_content_path = os.path.join(wp_path, 'wp-content')
+ git_result = cls._init_git_tracking(wp_content_path, repo_url, branch)
+ if not git_result['success']:
+ return git_result
+
+ # Update site record
+ site.git_repo_url = repo_url
+ site.git_branch = branch
+ site.git_paths = json.dumps(paths)
+ site.auto_deploy = auto_deploy
+
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': f'Repository connected successfully',
+ 'repo_url': repo_url,
+ 'branch': branch,
+ 'paths': paths
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def disconnect_repo(cls, site_id: int) -> Dict:
+ """
+ Disconnect a Git repository from a WordPress site.
+
+ Args:
+ site_id: ID of the WordPressSite
+
+ Returns:
+ Dict with success status
+ """
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ try:
+ # Remove git tracking from wp-content
+ if site.application and site.application.root_path:
+ wp_content_path = os.path.join(site.application.root_path, 'wp-content')
+ git_dir = os.path.join(wp_content_path, '.git')
+ if os.path.exists(git_dir):
+ shutil.rmtree(git_dir)
+
+ # Clear git settings
+ site.git_repo_url = None
+ site.git_branch = None
+ site.git_paths = None
+ site.auto_deploy = False
+ site.last_deploy_commit = None
+ site.last_deploy_at = None
+
+ db.session.commit()
+
+ return {'success': True, 'message': 'Repository disconnected'}
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def deploy_from_commit(cls, site_id: int, commit_sha: str = None,
+ branch: str = None, create_snapshot: bool = True) -> Dict:
+ """
+ Deploy a specific commit or branch to the WordPress site.
+
+ Args:
+ site_id: ID of the WordPressSite
+ commit_sha: Specific commit SHA to deploy (optional)
+ branch: Branch name to deploy latest from (optional)
+ create_snapshot: Create a database snapshot before deploying
+
+ Returns:
+ Dict with success status and deployment info
+ """
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.git_repo_url:
+ return {'success': False, 'error': 'No repository connected'}
+
+ if not site.application or not site.application.root_path:
+ return {'success': False, 'error': 'Site application path not found'}
+
+ wp_content_path = os.path.join(site.application.root_path, 'wp-content')
+
+ try:
+ # Create pre-deploy snapshot
+ if create_snapshot:
+ snapshot_result = DatabaseSyncService.create_snapshot(
+ db_name=site.db_name,
+ name=f"pre_deploy_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
+ tag='pre-deploy',
+ commit_sha=site.last_deploy_commit,
+ host=site.db_host,
+ user=site.db_user,
+ password=WordPressEnvService._get_db_password(site)
+ )
+
+ if snapshot_result['success']:
+ # Save snapshot to database
+ snapshot = DatabaseSnapshot(
+ site_id=site.id,
+ name=snapshot_result['snapshot']['name'],
+ tag='pre-deploy',
+ file_path=snapshot_result['snapshot']['file_path'],
+ size_bytes=snapshot_result['snapshot']['size_bytes'],
+ compressed=snapshot_result['snapshot']['compressed'],
+ commit_sha=site.last_deploy_commit,
+ tables_included=json.dumps(snapshot_result['snapshot'].get('tables', [])),
+ row_count=snapshot_result['snapshot'].get('row_count', 0),
+ status='completed'
+ )
+ db.session.add(snapshot)
+
+ # Fetch latest from remote
+ fetch_result = cls._run_git(wp_content_path, ['fetch', 'origin'])
+ if not fetch_result['success']:
+ return fetch_result
+
+ # Determine what to checkout
+ if commit_sha:
+ target = commit_sha
+ elif branch:
+ target = f'origin/{branch}'
+ else:
+ target = f'origin/{site.git_branch}'
+
+ # Checkout the target
+ checkout_result = cls._run_git(wp_content_path, ['checkout', target, '--force'])
+ if not checkout_result['success']:
+ return checkout_result
+
+ # Get the actual commit SHA we deployed
+ rev_result = cls._run_git(wp_content_path, ['rev-parse', 'HEAD'])
+ deployed_sha = rev_result['output'].strip() if rev_result['success'] else commit_sha
+
+ # Get commit message
+ msg_result = cls._run_git(wp_content_path, ['log', '-1', '--format=%s'])
+ commit_message = msg_result['output'].strip() if msg_result['success'] else ''
+
+ # Update site record
+ site.last_deploy_commit = deployed_sha
+ site.last_deploy_at = datetime.utcnow()
+
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': 'Deployment successful',
+ 'commit_sha': deployed_sha,
+ 'commit_message': commit_message,
+ 'pre_deploy_snapshot': snapshot_result.get('snapshot', {}).get('file_path') if create_snapshot else None
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def create_dev_for_commit(cls, production_site_id: int, commit_sha: str,
+ config: Dict, user_id: int) -> Dict:
+ """
+ Create a development environment for a specific commit.
+
+ This creates a full dev environment with:
+ - Database snapshot from nearest point in time (or current)
+ - Code checked out at the specified commit
+ - URL search-replace applied
+
+ Args:
+ production_site_id: ID of the production WordPressSite
+ commit_sha: Git commit SHA to create dev for
+ config: Environment configuration (name, domain, etc.)
+ user_id: User ID creating the environment
+
+ Returns:
+ Dict with success status and dev environment info
+ """
+ prod_site = WordPressSite.query.get(production_site_id)
+ if not prod_site:
+ return {'success': False, 'error': 'Production site not found'}
+
+ if not prod_site.is_production:
+ return {'success': False, 'error': 'Source site is not a production site'}
+
+ if not prod_site.git_repo_url:
+ return {'success': False, 'error': 'No repository connected to production site'}
+
+ try:
+ # Get short SHA for naming
+ short_sha = commit_sha[:7]
+
+ # Set defaults in config
+ if not config.get('name'):
+ config['name'] = f"{prod_site.application.name} @ {short_sha}"
+
+ if not config.get('domain'):
+ # Try to create subdomain from production domain
+ if prod_site.application.domains:
+ prod_domain = prod_site.application.domains[0].domain
+ config['domain'] = f"{short_sha}.dev.{prod_domain}"
+
+ # Create the environment using WordPressEnvService
+ env_result = WordPressEnvService.create_environment(
+ production_site_id=production_site_id,
+ env_type='development',
+ config=config,
+ user_id=user_id
+ )
+
+ if not env_result['success']:
+ return env_result
+
+ env_site_id = env_result['environment']['id']
+ env_site = WordPressSite.query.get(env_site_id)
+
+ # Checkout the specific commit
+ if env_site and env_site.application:
+ wp_content_path = os.path.join(env_site.application.root_path, 'wp-content')
+
+ # Initialize git in the new environment
+ init_result = cls._init_git_tracking(
+ wp_content_path,
+ prod_site.git_repo_url,
+ prod_site.git_branch
+ )
+
+ if init_result['success']:
+ # Fetch and checkout specific commit
+ cls._run_git(wp_content_path, ['fetch', 'origin'])
+ checkout_result = cls._run_git(wp_content_path, ['checkout', commit_sha, '--force'])
+
+ if checkout_result['success']:
+ env_site.last_deploy_commit = commit_sha
+ env_site.last_deploy_at = datetime.utcnow()
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': f'Development environment created for commit {short_sha}',
+ 'environment': env_site.to_dict() if env_site else env_result['environment'],
+ 'commit_sha': commit_sha,
+ 'url': f"https://{config.get('domain')}" if config.get('domain') else None
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_recent_commits(cls, site_id: int, limit: int = 20) -> Dict:
+ """
+ Get recent commits from the repository.
+
+ Args:
+ site_id: ID of the WordPressSite
+ limit: Maximum number of commits to return
+
+ Returns:
+ Dict with list of commits
+ """
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.git_repo_url:
+ return {'success': False, 'error': 'No repository connected'}
+
+ if not site.application or not site.application.root_path:
+ return {'success': False, 'error': 'Site application path not found'}
+
+ wp_content_path = os.path.join(site.application.root_path, 'wp-content')
+
+ try:
+ # Fetch latest
+ cls._run_git(wp_content_path, ['fetch', 'origin'])
+
+ # Get commit log
+ log_format = '%H|%h|%s|%an|%ae|%ai'
+ log_result = cls._run_git(wp_content_path, [
+ 'log',
+ f'origin/{site.git_branch}',
+ f'-{limit}',
+ f'--format={log_format}'
+ ])
+
+ if not log_result['success']:
+ return log_result
+
+ commits = []
+ for line in log_result['output'].strip().split('\n'):
+ if not line:
+ continue
+ parts = line.split('|')
+ if len(parts) >= 6:
+ commits.append({
+ 'sha': parts[0],
+ 'short_sha': parts[1],
+ 'message': parts[2],
+ 'author_name': parts[3],
+ 'author_email': parts[4],
+ 'date': parts[5],
+ 'is_deployed': parts[0] == site.last_deploy_commit
+ })
+
+ return {
+ 'success': True,
+ 'commits': commits,
+ 'current_deploy': site.last_deploy_commit
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def rollback_to_commit(cls, site_id: int, commit_sha: str) -> Dict:
+ """
+ Rollback a site to a previous commit.
+
+ Args:
+ site_id: ID of the WordPressSite
+ commit_sha: Commit SHA to rollback to
+
+ Returns:
+ Dict with success status
+ """
+ # This is essentially the same as deploy_from_commit
+ return cls.deploy_from_commit(site_id, commit_sha=commit_sha, create_snapshot=True)
+
+ @classmethod
+ def get_git_status(cls, site_id: int) -> Dict:
+ """
+ Get the Git status for a site.
+
+ Args:
+ site_id: ID of the WordPressSite
+
+ Returns:
+ Dict with Git status information
+ """
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ result = {
+ 'success': True,
+ 'connected': bool(site.git_repo_url),
+ 'repo_url': site.git_repo_url,
+ 'branch': site.git_branch,
+ 'auto_deploy': site.auto_deploy,
+ 'last_deploy_commit': site.last_deploy_commit,
+ 'last_deploy_at': site.last_deploy_at.isoformat() if site.last_deploy_at else None,
+ 'paths': json.loads(site.git_paths) if site.git_paths else None
+ }
+
+ if site.git_repo_url and site.application and site.application.root_path:
+ wp_content_path = os.path.join(site.application.root_path, 'wp-content')
+
+ # Check if there are uncommitted changes
+ status_result = cls._run_git(wp_content_path, ['status', '--porcelain'])
+ if status_result['success']:
+ result['has_local_changes'] = bool(status_result['output'].strip())
+
+ # Check if behind remote
+ cls._run_git(wp_content_path, ['fetch', 'origin'])
+ behind_result = cls._run_git(wp_content_path, [
+ 'rev-list',
+ '--count',
+ f'HEAD..origin/{site.git_branch}'
+ ])
+ if behind_result['success']:
+ result['commits_behind'] = int(behind_result['output'].strip() or 0)
+
+ return result
+
+ @classmethod
+ def _validate_repo_url(cls, url: str) -> bool:
+ """Validate a Git repository URL."""
+ if not url:
+ return False
+
+ # Accept HTTPS URLs
+ if url.startswith('https://'):
+ return True
+
+ # Accept SSH URLs
+ if url.startswith('git@') or url.startswith('ssh://'):
+ return True
+
+ return False
+
+ @classmethod
+ def _test_repo_access(cls, repo_url: str) -> Dict:
+ """Test if we can access the repository."""
+ try:
+ result = subprocess.run(
+ ['git', 'ls-remote', '--exit-code', repo_url],
+ capture_output=True,
+ text=True,
+ timeout=30
+ )
+
+ if result.returncode == 0:
+ return {'success': True}
+ else:
+ return {
+ 'success': False,
+ 'error': f'Cannot access repository: {result.stderr or "Authentication failed or repository not found"}'
+ }
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Connection to repository timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _init_git_tracking(cls, path: str, repo_url: str, branch: str) -> Dict:
+ """Initialize Git tracking in a directory."""
+ try:
+ git_dir = os.path.join(path, '.git')
+
+ if os.path.exists(git_dir):
+ # Already initialized, just update remote
+ cls._run_git(path, ['remote', 'set-url', 'origin', repo_url])
+ else:
+ # Initialize new repo
+ init_result = cls._run_git(path, ['init'])
+ if not init_result['success']:
+ return init_result
+
+ # Add remote
+ remote_result = cls._run_git(path, ['remote', 'add', 'origin', repo_url])
+ if not remote_result['success']:
+ return remote_result
+
+ # Fetch from remote
+ fetch_result = cls._run_git(path, ['fetch', 'origin'])
+ if not fetch_result['success']:
+ return fetch_result
+
+ return {'success': True}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _run_git(cls, cwd: str, args: List[str]) -> Dict:
+ """Run a Git command."""
+ try:
+ cmd = ['git'] + args
+ result = subprocess.run(
+ cmd,
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ timeout=120
+ )
+
+ return {
+ 'success': result.returncode == 0,
+ 'output': result.stdout,
+ 'error': result.stderr if result.returncode != 0 else None
+ }
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Git command timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
diff --git a/backend/app/services/wordpress_env_service.py b/backend/app/services/wordpress_env_service.py
new file mode 100644
index 00000000..ffb0b0b3
--- /dev/null
+++ b/backend/app/services/wordpress_env_service.py
@@ -0,0 +1,486 @@
+"""
+WordPress Environment Service
+
+Manage WordPress production/development/staging environments.
+Handles environment creation, database cloning, and synchronization.
+"""
+
+import os
+import json
+import secrets
+import string
+import shutil
+from datetime import datetime
+from typing import Dict, List, Optional
+
+from app import db
+from app.models.application import Application
+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob
+from app.services.db_sync_service import DatabaseSyncService
+from app.services.wordpress_service import WordPressService
+from app.services.database_service import DatabaseService
+
+
+class WordPressEnvService:
+ """Manage WordPress production/development/staging environments."""
+
+ @classmethod
+ def create_environment(cls, production_site_id: int, env_type: str,
+ config: Dict, user_id: int) -> Dict:
+ """
+ Create a new environment linked to production.
+
+ Args:
+ production_site_id: ID of the production WordPressSite
+ env_type: 'development' or 'staging'
+ config: Dict with:
+ - name: Environment name (e.g., 'My Site Dev')
+ - domain: Domain for the environment (e.g., 'dev.mysite.com')
+ - port: Optional custom port
+ - clone_db: Whether to clone the production database
+ - sync_schedule: Optional cron schedule for auto-sync
+ user_id: User ID creating the environment
+
+ Returns:
+ Dict with success status and environment info
+ """
+ # Validate environment type
+ if env_type not in ['development', 'staging']:
+ return {'success': False, 'error': 'Invalid environment type. Must be development or staging.'}
+
+ # Get production site
+ prod_site = WordPressSite.query.get(production_site_id)
+ if not prod_site:
+ return {'success': False, 'error': 'Production site not found'}
+
+ if not prod_site.is_production:
+ return {'success': False, 'error': 'Source site is not a production site'}
+
+ prod_app = prod_site.application
+ if not prod_app:
+ return {'success': False, 'error': 'Production application not found'}
+
+ try:
+ # Generate names
+ env_name = config.get('name', f"{prod_app.name} ({env_type.title()})")
+ env_domain = config.get('domain')
+
+ # Generate unique database name and prefix
+ short_id = secrets.token_hex(4)
+ env_db_name = f"{prod_site.db_name}_{env_type[:3]}_{short_id}"
+ env_db_prefix = f"wp_{env_type[:3]}_"
+
+ # Determine root path for new environment
+ prod_path = prod_app.root_path
+ base_path = os.path.dirname(prod_path)
+ env_path = os.path.join(base_path, f"{os.path.basename(prod_path)}_{env_type}")
+
+ # Step 1: Clone the database if requested
+ if config.get('clone_db', True):
+ # First create a snapshot
+ snapshot_result = DatabaseSyncService.create_snapshot(
+ db_name=prod_site.db_name,
+ name=f"pre_env_create_{env_type}",
+ tag=f"env-create-{env_type}",
+ host=prod_site.db_host,
+ user=prod_site.db_user,
+ password=cls._get_db_password(prod_site)
+ )
+
+ if not snapshot_result['success']:
+ return {'success': False, 'error': f"Failed to create snapshot: {snapshot_result.get('error')}"}
+
+ # Clone with transformations
+ clone_options = {
+ 'table_prefix': env_db_prefix,
+ 'truncate_tables': config.get('truncate_tables', [
+ 'actionscheduler_actions',
+ 'actionscheduler_logs',
+ ])
+ }
+
+ # Add search-replace for domain if provided
+ if env_domain and prod_app.domains:
+ prod_domain = prod_app.domains[0].domain if prod_app.domains else None
+ if prod_domain:
+ clone_options['search_replace'] = {
+ f'https://{prod_domain}': f'https://{env_domain}',
+ f'http://{prod_domain}': f'http://{env_domain}',
+ prod_domain: env_domain
+ }
+
+ clone_result = DatabaseSyncService.clone_database(
+ source_db=prod_site.db_name,
+ target_db=env_db_name,
+ source_host=prod_site.db_host,
+ target_host=prod_site.db_host,
+ source_user=prod_site.db_user,
+ target_user=prod_site.db_user,
+ source_password=cls._get_db_password(prod_site),
+ target_password=cls._get_db_password(prod_site),
+ options=clone_options
+ )
+
+ if not clone_result['success']:
+ return {'success': False, 'error': f"Failed to clone database: {clone_result.get('error')}"}
+
+ # Step 2: Create the Application record
+ env_app = Application(
+ name=env_name,
+ app_type='wordpress',
+ status='deploying',
+ php_version=prod_app.php_version,
+ port=config.get('port'),
+ root_path=env_path,
+ environment_type=env_type,
+ linked_app_id=prod_app.id,
+ user_id=user_id
+ )
+ db.session.add(env_app)
+ db.session.flush() # Get the ID
+
+ # Step 3: Create the WordPressSite record
+ env_site = WordPressSite(
+ application_id=env_app.id,
+ wp_version=prod_site.wp_version,
+ multisite=prod_site.multisite,
+ admin_user=prod_site.admin_user,
+ admin_email=prod_site.admin_email,
+ db_name=env_db_name,
+ db_user=prod_site.db_user,
+ db_host=prod_site.db_host,
+ db_prefix=env_db_prefix,
+ git_repo_url=prod_site.git_repo_url,
+ git_branch=config.get('git_branch', prod_site.git_branch),
+ git_paths=prod_site.git_paths,
+ auto_deploy=config.get('auto_deploy', False),
+ is_production=False,
+ production_site_id=production_site_id
+ )
+ db.session.add(env_site)
+
+ # Step 4: Copy WordPress files
+ copy_result = cls._copy_wordpress_files(prod_path, env_path)
+ if not copy_result['success']:
+ db.session.rollback()
+ return copy_result
+
+ # Step 5: Update wp-config.php for new environment
+ config_result = cls._update_wp_config(
+ env_path,
+ db_name=env_db_name,
+ db_prefix=env_db_prefix,
+ site_url=f"https://{env_domain}" if env_domain else None
+ )
+
+ if not config_result['success']:
+ db.session.rollback()
+ return config_result
+
+ # Step 6: Create sync job if schedule provided
+ if config.get('sync_schedule'):
+ sync_job = SyncJob(
+ source_site_id=production_site_id,
+ target_site_id=env_site.id,
+ name=f"Auto-sync {prod_app.name} to {env_name}",
+ schedule=config['sync_schedule'],
+ enabled=True,
+ config=json.dumps({
+ 'search_replace': clone_options.get('search_replace', {}),
+ 'truncate_tables': clone_options.get('truncate_tables', [])
+ })
+ )
+ db.session.add(sync_job)
+
+ # Update application status
+ env_app.status = 'running'
+
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': f'{env_type.title()} environment created successfully',
+ 'environment': env_site.to_dict(),
+ 'application': env_app.to_dict()
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def sync_environment(cls, env_site_id: int, options: Dict = None) -> Dict:
+ """
+ Sync an environment from its production source.
+
+ Args:
+ env_site_id: ID of the environment WordPressSite to sync
+ options: Optional override options for sync
+
+ Returns:
+ Dict with success status
+ """
+ options = options or {}
+
+ env_site = WordPressSite.query.get(env_site_id)
+ if not env_site:
+ return {'success': False, 'error': 'Environment not found'}
+
+ if env_site.is_production:
+ return {'success': False, 'error': 'Cannot sync a production site'}
+
+ prod_site = env_site.production_site
+ if not prod_site:
+ return {'success': False, 'error': 'Production site not found'}
+
+ try:
+ # Get sync config
+ sync_config = json.loads(env_site.sync_config) if env_site.sync_config else {}
+ sync_config.update(options)
+
+ # Create snapshot before sync
+ snapshot_result = DatabaseSyncService.create_snapshot(
+ db_name=env_site.db_name,
+ name=f"pre_sync_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
+ tag='pre-sync',
+ host=env_site.db_host,
+ user=env_site.db_user,
+ password=cls._get_db_password(env_site)
+ )
+
+ # Clone production to environment
+ clone_options = {
+ 'table_prefix': env_site.db_prefix,
+ 'search_replace': sync_config.get('search_replace', {}),
+ 'truncate_tables': sync_config.get('truncate_tables', []),
+ 'anonymize': sync_config.get('anonymize', False)
+ }
+
+ clone_result = DatabaseSyncService.clone_database(
+ source_db=prod_site.db_name,
+ target_db=env_site.db_name,
+ source_host=prod_site.db_host,
+ target_host=env_site.db_host,
+ source_user=prod_site.db_user,
+ target_user=env_site.db_user,
+ source_password=cls._get_db_password(prod_site),
+ target_password=cls._get_db_password(env_site),
+ options=clone_options
+ )
+
+ if not clone_result['success']:
+ return clone_result
+
+ # Update sync timestamp
+ env_site.updated_at = datetime.utcnow()
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'message': 'Environment synced successfully',
+ 'pre_sync_snapshot': snapshot_result.get('snapshot', {}).get('file_path')
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_environment_status(cls, production_site_id: int) -> Dict:
+ """
+ Get status of all environments for a production site.
+
+ Args:
+ production_site_id: ID of the production WordPressSite
+
+ Returns:
+ Dict with production site and all environments
+ """
+ prod_site = WordPressSite.query.get(production_site_id)
+ if not prod_site:
+ return {'success': False, 'error': 'Production site not found'}
+
+ environments = []
+ for env in prod_site.environments:
+ env_data = env.to_dict()
+
+ # Get last sync info
+ last_sync_job = SyncJob.query.filter_by(
+ target_site_id=env.id
+ ).order_by(SyncJob.last_run.desc()).first()
+
+ if last_sync_job:
+ env_data['last_sync'] = {
+ 'time': last_sync_job.last_run.isoformat() if last_sync_job.last_run else None,
+ 'status': last_sync_job.last_run_status,
+ 'next_scheduled': last_sync_job.next_run.isoformat() if last_sync_job.next_run else None
+ }
+
+ environments.append(env_data)
+
+ return {
+ 'success': True,
+ 'production': prod_site.to_dict(),
+ 'environments': environments
+ }
+
+ @classmethod
+ def delete_environment(cls, env_site_id: int, delete_files: bool = True,
+ delete_database: bool = True) -> Dict:
+ """
+ Delete an environment.
+
+ Args:
+ env_site_id: ID of the environment WordPressSite
+ delete_files: Whether to delete WordPress files
+ delete_database: Whether to drop the database
+
+ Returns:
+ Dict with success status
+ """
+ env_site = WordPressSite.query.get(env_site_id)
+ if not env_site:
+ return {'success': False, 'error': 'Environment not found'}
+
+ if env_site.is_production:
+ return {'success': False, 'error': 'Cannot delete a production site this way'}
+
+ env_app = env_site.application
+
+ try:
+ # Delete database
+ if delete_database and env_site.db_name:
+ DatabaseService.mysql_execute(
+ f"DROP DATABASE IF EXISTS `{env_site.db_name}`"
+ )
+
+ # Delete files
+ if delete_files and env_app and env_app.root_path:
+ if os.path.exists(env_app.root_path):
+ shutil.rmtree(env_app.root_path)
+
+ # Delete related sync jobs
+ SyncJob.query.filter(
+ (SyncJob.source_site_id == env_site_id) |
+ (SyncJob.target_site_id == env_site_id)
+ ).delete()
+
+ # Delete snapshots
+ for snapshot in env_site.snapshots:
+ if os.path.exists(snapshot.file_path):
+ os.remove(snapshot.file_path)
+
+ # Delete records
+ db.session.delete(env_site)
+ if env_app:
+ db.session.delete(env_app)
+
+ db.session.commit()
+
+ return {'success': True, 'message': 'Environment deleted successfully'}
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _copy_wordpress_files(cls, source_path: str, target_path: str) -> Dict:
+ """Copy WordPress files from source to target."""
+ try:
+ if os.path.exists(target_path):
+ shutil.rmtree(target_path)
+
+ shutil.copytree(source_path, target_path)
+
+ # Set permissions
+ import subprocess
+ subprocess.run(['sudo', 'chown', '-R', 'www-data:www-data', target_path], capture_output=True)
+
+ return {'success': True}
+
+ except Exception as e:
+ return {'success': False, 'error': f'Failed to copy files: {str(e)}'}
+
+ @classmethod
+ def _update_wp_config(cls, wp_path: str, db_name: str = None,
+ db_prefix: str = None, site_url: str = None) -> Dict:
+ """Update wp-config.php for the new environment."""
+ config_path = os.path.join(wp_path, 'wp-config.php')
+
+ if not os.path.exists(config_path):
+ return {'success': False, 'error': 'wp-config.php not found'}
+
+ try:
+ with open(config_path, 'r') as f:
+ content = f.read()
+
+ # Update database name
+ if db_name:
+ content = cls._replace_define(content, 'DB_NAME', db_name)
+
+ # Update table prefix
+ if db_prefix:
+ content = cls._replace_table_prefix(content, db_prefix)
+
+ # Update site URL if provided
+ if site_url:
+ content = cls._replace_define(content, 'WP_HOME', site_url)
+ content = cls._replace_define(content, 'WP_SITEURL', site_url)
+
+ # Add debug mode for non-production
+ if "define( 'WP_DEBUG'" not in content and "define('WP_DEBUG'" not in content:
+ content = content.replace(
+ "/* That's all",
+ "define('WP_DEBUG', true);\ndefine('WP_DEBUG_LOG', true);\n\n/* That's all"
+ )
+
+ with open(config_path, 'w') as f:
+ f.write(content)
+
+ return {'success': True}
+
+ except Exception as e:
+ return {'success': False, 'error': f'Failed to update wp-config.php: {str(e)}'}
+
+ @staticmethod
+ def _replace_define(content: str, constant: str, value: str) -> str:
+ """Replace a define() statement in wp-config.php."""
+ import re
+ # Match both styles: define('CONST', 'value') and define( 'CONST', 'value' )
+ pattern = rf"define\s*\(\s*['\"]({constant})['\"]\s*,\s*['\"]([^'\"]*)['\"]"
+ replacement = f"define('{constant}', '{value}'"
+ return re.sub(pattern, replacement, content)
+
+ @staticmethod
+ def _replace_table_prefix(content: str, prefix: str) -> str:
+ """Replace the table prefix in wp-config.php."""
+ import re
+ pattern = r"\$table_prefix\s*=\s*['\"]([^'\"]*)['\"]"
+ replacement = f"$table_prefix = '{prefix}'"
+ return re.sub(pattern, replacement, content)
+
+ @staticmethod
+ def _get_db_password(site: WordPressSite) -> Optional[str]:
+ """Get database password for a site from wp-config.php."""
+ if not site.application or not site.application.root_path:
+ return None
+
+ config_path = os.path.join(site.application.root_path, 'wp-config.php')
+ if not os.path.exists(config_path):
+ return None
+
+ try:
+ with open(config_path, 'r') as f:
+ content = f.read()
+
+ import re
+ match = re.search(r"define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]*)['\"]", content)
+ return match.group(1) if match else None
+
+ except Exception:
+ return None
+
+ @staticmethod
+ def _generate_password(length: int = 16) -> str:
+ """Generate a secure random password."""
+ alphabet = string.ascii_letters + string.digits + '!@#$%^&*'
+ return ''.join(secrets.choice(alphabet) for _ in range(length))
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index b62f2c23..b762641b 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -29,6 +29,8 @@ import WorkflowBuilder from './pages/WorkflowBuilder';
import Servers from './pages/Servers';
import ServerDetail from './pages/ServerDetail';
import Downloads from './pages/Downloads';
+import WordPress from './pages/WordPress';
+import WordPressDetail from './pages/WordPressDetail';
// Page title mapping
const PAGE_TITLES = {
@@ -37,6 +39,7 @@ const PAGE_TITLES = {
'/register': 'Register',
'/setup': 'Setup',
'/apps': 'Applications',
+ '/wordpress': 'WordPress Sites',
'/templates': 'Templates',
'/workflow': 'Workflow Builder',
'/domains': 'Domains',
@@ -67,6 +70,7 @@ function PageTitleUpdater() {
if (!title) {
if (path.startsWith('/apps/')) title = 'Application Details';
else if (path.startsWith('/servers/')) title = 'Server Details';
+ else if (path.startsWith('/wordpress/')) title = 'WordPress Site';
else title = 'ServerKit';
}
@@ -151,6 +155,8 @@ function AppRoutes() {
<Route index element={<Dashboard />} />
<Route path="apps" element={<Applications />} />
<Route path="apps/:id" element={<ApplicationDetail />} />
+ <Route path="wordpress" element={<WordPress />} />
+ <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/components/ConfirmDialog.jsx b/frontend/src/components/ConfirmDialog.jsx
index 1fcb123c..3e2e4b59 100644
--- a/frontend/src/components/ConfirmDialog.jsx
+++ b/frontend/src/components/ConfirmDialog.jsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useState, useEffect } from 'react';
import { AlertTriangle, Info, AlertCircle } from 'lucide-react';
const iconMap = {
@@ -11,15 +11,40 @@ export function ConfirmDialog({
isOpen,
title,
message,
+ details,
confirmText = 'Confirm',
cancelText = 'Cancel',
variant = 'danger',
+ requireConfirmation,
+ confirmationPlaceholder,
onConfirm,
onCancel
}) {
+ const [inputValue, setInputValue] = useState('');
+
+ // Reset input when dialog opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setInputValue('');
+ }
+ }, [isOpen]);
+
if (!isOpen) return null;
const Icon = iconMap[variant] || AlertTriangle;
+ const isConfirmDisabled = requireConfirmation && inputValue !== requireConfirmation;
+
+ function handleConfirm() {
+ if (!isConfirmDisabled) {
+ onConfirm();
+ }
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Enter' && !isConfirmDisabled) {
+ handleConfirm();
+ }
+ }
return (
<div className="modal-overlay" onClick={onCancel}>
@@ -30,6 +55,26 @@ export function ConfirmDialog({
</div>
<h2 className="confirm-dialog-title">{title}</h2>
<p className="confirm-dialog-message">{message}</p>
+ {details && (
+ <div className="confirm-dialog-details">
+ {details}
+ </div>
+ )}
+ {requireConfirmation && (
+ <div className="confirm-dialog-input">
+ <label>
+ Type <strong>{requireConfirmation}</strong> to confirm:
+ </label>
+ <input
+ type="text"
+ value={inputValue}
+ onChange={(e) => setInputValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder={confirmationPlaceholder || requireConfirmation}
+ autoFocus
+ />
+ </div>
+ )}
</div>
<div className="confirm-dialog-actions">
<button
@@ -40,7 +85,8 @@ export function ConfirmDialog({
</button>
<button
className={`btn btn-${variant === 'danger' ? 'danger' : 'primary'}`}
- onClick={onConfirm}
+ onClick={handleConfirm}
+ disabled={isConfirmDisabled}
>
{confirmText}
</button>
diff --git a/frontend/src/components/ErrorBoundary.jsx b/frontend/src/components/ErrorBoundary.jsx
new file mode 100644
index 00000000..35773ee0
--- /dev/null
+++ b/frontend/src/components/ErrorBoundary.jsx
@@ -0,0 +1,89 @@
+import React, { Component } from 'react';
+import { AlertTriangle, RefreshCw } from 'lucide-react';
+
+// Class-based Error Boundary for catching React errors
+export class ErrorBoundary extends Component {
+ constructor(props) {
+ super(props);
+ this.state = { hasError: false, error: null, errorInfo: null };
+ }
+
+ static getDerivedStateFromError(error) {
+ return { hasError: true, error };
+ }
+
+ componentDidCatch(error, errorInfo) {
+ this.setState({ errorInfo });
+ console.error('ErrorBoundary caught an error:', error, errorInfo);
+ }
+
+ handleRetry = () => {
+ this.setState({ hasError: false, error: null, errorInfo: null });
+ this.props.onRetry?.();
+ };
+
+ render() {
+ if (this.state.hasError) {
+ return (
+ <div className="error-boundary">
+ <div className="error-boundary-icon">
+ <AlertTriangle size={32} />
+ </div>
+ <h3>Something went wrong</h3>
+ <p className="error-boundary-message">
+ {this.state.error?.message || 'An unexpected error occurred'}
+ </p>
+ <button className="btn btn-primary" onClick={this.handleRetry}>
+ <RefreshCw size={14} />
+ Try Again
+ </button>
+ </div>
+ );
+ }
+
+ return this.props.children;
+ }
+}
+
+// Functional component for displaying API/fetch errors
+export function ErrorState({
+ title = 'Failed to load',
+ message,
+ error,
+ onRetry,
+ compact = false
+}) {
+ const errorMessage = message || error?.message || 'An error occurred while loading data';
+
+ if (compact) {
+ return (
+ <div className="error-state-compact">
+ <AlertTriangle size={16} />
+ <span>{errorMessage}</span>
+ {onRetry && (
+ <button className="btn btn-ghost btn-sm" onClick={onRetry}>
+ <RefreshCw size={14} /> Retry
+ </button>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="error-state">
+ <div className="error-state-icon">
+ <AlertTriangle size={32} />
+ </div>
+ <h3 className="error-state-title">{title}</h3>
+ <p className="error-state-message">{errorMessage}</p>
+ {onRetry && (
+ <button className="btn btn-primary" onClick={onRetry}>
+ <RefreshCw size={14} />
+ Try Again
+ </button>
+ )}
+ </div>
+ );
+}
+
+export default ErrorBoundary;
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 5afbe9d7..a4fd9d27 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -58,6 +58,14 @@ const Sidebar = () => {
</svg>
Applications
</NavLink>
+ <NavLink to="/wordpress" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
+ <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="M3.5 9h17M3.5 15h17"/>
+ </svg>
+ WordPress
+ </NavLink>
<NavLink to="/templates" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<rect x="3" y="3" width="7" height="9"/>
diff --git a/frontend/src/components/wordpress/CommitList.jsx b/frontend/src/components/wordpress/CommitList.jsx
new file mode 100644
index 00000000..ad8c47ba
--- /dev/null
+++ b/frontend/src/components/wordpress/CommitList.jsx
@@ -0,0 +1,197 @@
+import React, { useState } from 'react';
+import { GitCommit, Rocket, Copy, CheckCircle } from 'lucide-react';
+
+const CommitList = ({ commits, currentCommit, onDeploy, onCreateDev, loading = false }) => {
+ const [actionLoading, setActionLoading] = useState({});
+ const [showDevModal, setShowDevModal] = useState(null);
+
+ function formatDate(dateString) {
+ if (!dateString) return '-';
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
+ const diffDays = Math.floor(diffHours / 24);
+
+ if (diffHours < 1) return 'Just now';
+ if (diffHours < 24) return `${diffHours}h ago`;
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return date.toLocaleDateString();
+ }
+
+ async function handleDeploy(commit) {
+ if (!confirm(`Deploy commit ${commit.sha.substring(0, 7)} to production?`)) {
+ return;
+ }
+ setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: true }));
+ try {
+ await onDeploy?.({ commit_sha: commit.sha });
+ } finally {
+ setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: false }));
+ }
+ }
+
+ async function handleCreateDev(commit, config) {
+ setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: true }));
+ try {
+ await onCreateDev?.({
+ commit_sha: commit.sha,
+ config
+ });
+ setShowDevModal(null);
+ } finally {
+ setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: false }));
+ }
+ }
+
+ if (loading) {
+ return <div className="loading">Loading commits...</div>;
+ }
+
+ if (!commits || commits.length === 0) {
+ return (
+ <div className="empty-state-small">
+ <p>No commits found.</p>
+ <p className="hint">Push changes to your repository to see commits here.</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="commit-list">
+ {commits.map(commit => {
+ const isCurrent = currentCommit === commit.sha;
+ const isDeploying = actionLoading[`deploy-${commit.sha}`];
+ const isCreatingDev = actionLoading[`dev-${commit.sha}`];
+
+ return (
+ <div key={commit.sha} className={`commit-item ${isCurrent ? 'current' : ''}`}>
+ <div className="commit-icon">
+ {isCurrent ? (
+ <CheckCircle size={16} className="current-icon" />
+ ) : (
+ <GitCommit size={16} />
+ )}
+ </div>
+
+ <div className="commit-info">
+ <div className="commit-header">
+ <span className="commit-sha mono">{commit.sha.substring(0, 7)}</span>
+ {isCurrent && <span className="current-badge">Deployed</span>}
+ <span className="commit-date">{formatDate(commit.date)}</span>
+ </div>
+ <p className="commit-message">{commit.message}</p>
+ {commit.author && (
+ <span className="commit-author">{commit.author}</span>
+ )}
+ </div>
+
+ <div className="commit-actions">
+ {!isCurrent && (
+ <button
+ className="btn btn-primary btn-sm"
+ onClick={() => handleDeploy(commit)}
+ disabled={isDeploying}
+ title="Deploy this commit"
+ >
+ <Rocket size={12} />
+ {isDeploying ? 'Deploying...' : 'Deploy'}
+ </button>
+ )}
+ <button
+ className="btn btn-secondary btn-sm"
+ onClick={() => setShowDevModal(commit)}
+ disabled={isCreatingDev}
+ title="Create dev environment from this commit"
+ >
+ <Copy size={12} />
+ {isCreatingDev ? 'Creating...' : 'Create Dev'}
+ </button>
+ </div>
+ </div>
+ );
+ })}
+
+ {showDevModal && (
+ <CreateDevModal
+ commit={showDevModal}
+ onClose={() => setShowDevModal(null)}
+ onCreate={(config) => handleCreateDev(showDevModal, config)}
+ loading={actionLoading[`dev-${showDevModal.sha}`]}
+ />
+ )}
+ </div>
+ );
+};
+
+const CreateDevModal = ({ commit, onClose, onCreate, loading }) => {
+ const [formData, setFormData] = useState({
+ name: `dev-${commit.sha.substring(0, 7)}`,
+ domain: ''
+ });
+
+ function handleChange(e) {
+ const { name, value } = e.target;
+ setFormData(prev => ({ ...prev, [name]: value }));
+ }
+
+ function handleSubmit(e) {
+ e.preventDefault();
+ onCreate(formData);
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create Dev Environment</h2>
+ <button className="modal-close" onClick={onClose}>&times;</button>
+ </div>
+
+ <div className="modal-body">
+ <p className="hint">
+ Create a development environment with code from commit{' '}
+ <code>{commit.sha.substring(0, 7)}</code>
+ </p>
+ <p className="commit-message-preview">"{commit.message}"</p>
+
+ <form onSubmit={handleSubmit}>
+ <div className="form-group">
+ <label>Environment Name</label>
+ <input
+ type="text"
+ name="name"
+ value={formData.name}
+ onChange={handleChange}
+ placeholder="dev-abc1234"
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Domain (optional)</label>
+ <input
+ type="text"
+ name="domain"
+ value={formData.domain}
+ onChange={handleChange}
+ placeholder="dev.example.com"
+ />
+ <span className="form-hint">Leave empty to auto-generate</span>
+ </div>
+
+ <div className="modal-actions">
+ <button type="button" className="btn btn-secondary" onClick={onClose}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary" disabled={loading}>
+ {loading ? 'Creating...' : 'Create Environment'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default CommitList;
diff --git a/frontend/src/components/wordpress/CreateSiteModal.jsx b/frontend/src/components/wordpress/CreateSiteModal.jsx
new file mode 100644
index 00000000..b645d255
--- /dev/null
+++ b/frontend/src/components/wordpress/CreateSiteModal.jsx
@@ -0,0 +1,159 @@
+import React, { useState } from 'react';
+import { X } from 'lucide-react';
+
+const CreateSiteModal = ({ onClose, onCreate }) => {
+ const [formData, setFormData] = useState({
+ name: '',
+ domain: '',
+ adminUser: 'admin',
+ adminEmail: '',
+ dbName: '',
+ createDatabase: true
+ });
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState('');
+
+ function handleChange(e) {
+ const { name, value, type, checked } = e.target;
+ setFormData(prev => ({
+ ...prev,
+ [name]: type === 'checkbox' ? checked : value
+ }));
+ }
+
+ function generateDbName(siteName) {
+ return `wp_${siteName.toLowerCase().replace(/[^a-z0-9]/g, '_').substring(0, 20)}`;
+ }
+
+ function handleNameChange(e) {
+ const name = e.target.value;
+ setFormData(prev => ({
+ ...prev,
+ name,
+ dbName: prev.dbName || generateDbName(name)
+ }));
+ }
+
+ async function handleSubmit(e) {
+ e.preventDefault();
+ setError('');
+ setLoading(true);
+
+ try {
+ await onCreate({
+ name: formData.name,
+ domain: formData.domain,
+ admin_user: formData.adminUser,
+ admin_email: formData.adminEmail,
+ db_name: formData.dbName,
+ create_database: formData.createDatabase
+ });
+ onClose();
+ } catch (err) {
+ setError(err.message || 'Failed to create WordPress site');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create WordPress Site</h2>
+ <button className="modal-close" onClick={onClose}>
+ <X size={20} />
+ </button>
+ </div>
+
+ {error && <div className="error-message">{error}</div>}
+
+ <form onSubmit={handleSubmit}>
+ <div className="form-group">
+ <label>Site Name *</label>
+ <input
+ type="text"
+ name="name"
+ value={formData.name}
+ onChange={handleNameChange}
+ placeholder="My WordPress Site"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Domain</label>
+ <input
+ type="text"
+ name="domain"
+ value={formData.domain}
+ onChange={handleChange}
+ placeholder="example.com"
+ />
+ <span className="form-hint">Leave empty to use a local development URL</span>
+ </div>
+
+ <div className="form-row">
+ <div className="form-group">
+ <label>Admin Username *</label>
+ <input
+ type="text"
+ name="adminUser"
+ value={formData.adminUser}
+ onChange={handleChange}
+ placeholder="admin"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Admin Email *</label>
+ <input
+ type="email"
+ name="adminEmail"
+ value={formData.adminEmail}
+ onChange={handleChange}
+ placeholder="[email protected]"
+ required
+ />
+ </div>
+ </div>
+
+ <div className="form-group">
+ <label>Database Name</label>
+ <input
+ type="text"
+ name="dbName"
+ value={formData.dbName}
+ onChange={handleChange}
+ placeholder="wp_mysite"
+ />
+ </div>
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ name="createDatabase"
+ checked={formData.createDatabase}
+ onChange={handleChange}
+ />
+ <span>Create database automatically</span>
+ </label>
+ </div>
+
+ <div className="modal-actions">
+ <button type="button" className="btn btn-secondary" onClick={onClose}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary" disabled={loading}>
+ {loading ? 'Creating...' : 'Create Site'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+export default CreateSiteModal;
diff --git a/frontend/src/components/wordpress/EnvironmentCard.jsx b/frontend/src/components/wordpress/EnvironmentCard.jsx
new file mode 100644
index 00000000..08d0d582
--- /dev/null
+++ b/frontend/src/components/wordpress/EnvironmentCard.jsx
@@ -0,0 +1,239 @@
+import React, { useState } from 'react';
+import { ExternalLink, RefreshCw, Trash2, GitBranch, Clock, AlertTriangle, Calendar, FileText } from 'lucide-react';
+import { ConfirmDialog } from '../ConfirmDialog';
+
+const EnvironmentCard = ({ environment, productionUrl, onSync, onDelete, onViewLogs, isProduction = false }) => {
+ const [syncing, setSyncing] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const [showSyncConfirm, setShowSyncConfirm] = useState(false);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+
+ const isRunning = environment.status === 'running';
+ const envType = environment.type || (isProduction ? 'production' : 'development');
+
+ // Helper functions
+ function formatDate(dateString) {
+ if (!dateString) return null;
+ return new Date(dateString).toLocaleDateString();
+ }
+
+ function formatRelativeTime(dateString) {
+ if (!dateString) return null;
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+
+ if (diffDays === 0) return 'Today';
+ if (diffDays === 1) return 'Yesterday';
+ if (diffDays < 7) return `${diffDays} days ago`;
+ if (diffDays < 30) return `${Math.floor(diffDays / 7)} week(s) ago`;
+ return `${Math.floor(diffDays / 30)} month(s) ago`;
+ }
+
+ function isStale() {
+ if (!environment.last_sync || isProduction) return false;
+ const lastSync = new Date(environment.last_sync);
+ const now = new Date();
+ const diffDays = Math.floor((now - lastSync) / (1000 * 60 * 60 * 24));
+ return diffDays > 7; // Consider stale if not synced in 7 days
+ }
+
+ function formatSchedule(schedule) {
+ if (!schedule) return null;
+ const scheduleMap = {
+ '0 3 * * 0': 'Weekly (Sunday 3am)',
+ '0 3 * * *': 'Daily (3am)',
+ '0 0 * * 0': 'Weekly (Sunday midnight)',
+ '0 0 * * *': 'Daily (midnight)'
+ };
+ return scheduleMap[schedule] || schedule;
+ }
+
+ const stale = isStale();
+
+ async function handleSync() {
+ setShowSyncConfirm(false);
+ setSyncing(true);
+ try {
+ await onSync?.(environment.id);
+ } finally {
+ setSyncing(false);
+ }
+ }
+
+ async function handleDelete() {
+ setShowDeleteConfirm(false);
+ setDeleting(true);
+ try {
+ await onDelete?.(environment.id);
+ } finally {
+ setDeleting(false);
+ }
+ }
+
+ function handleVisit() {
+ if (environment.url) {
+ window.open(environment.url, '_blank');
+ }
+ }
+
+ function getEnvBadgeClass() {
+ switch (envType) {
+ case 'production': return 'env-production';
+ case 'staging': return 'env-staging';
+ default: return 'env-development';
+ }
+ }
+
+ return (
+ <div className={`wp-env-card ${isProduction ? 'production' : ''} ${stale ? 'stale' : ''}`}>
+ <div className="wp-env-header">
+ <div className="wp-env-info">
+ <span className={`wp-env-badge ${getEnvBadgeClass()}`}>
+ {envType.toUpperCase()}
+ </span>
+ <h4 className="wp-env-name">{environment.name}</h4>
+ </div>
+ <div className="wp-env-status-group">
+ {stale && (
+ <span className="wp-env-stale-badge" title="Environment hasn't been synced in over 7 days">
+ <AlertTriangle size={12} />
+ Stale
+ </span>
+ )}
+ <span className={`wp-env-status ${isRunning ? 'running' : 'stopped'}`}>
+ <span className="status-dot" />
+ {isRunning ? 'Running' : 'Stopped'}
+ </span>
+ </div>
+ </div>
+
+ <div className="wp-env-body">
+ {environment.url && (
+ <div className="wp-env-url">
+ <a href={environment.url} target="_blank" rel="noopener noreferrer">
+ {environment.url}
+ </a>
+ </div>
+ )}
+
+ <div className="wp-env-meta">
+ {environment.db_name && (
+ <div className="wp-env-meta-item">
+ <span className="meta-label">Database</span>
+ <span className="meta-value mono">{environment.db_name}</span>
+ </div>
+ )}
+ {environment.commit_sha && (
+ <div className="wp-env-meta-item">
+ <span className="meta-label">
+ <GitBranch size={12} /> Commit
+ </span>
+ <span className="meta-value mono">{environment.commit_sha.substring(0, 7)}</span>
+ </div>
+ )}
+ {!isProduction && environment.last_sync && (
+ <div className="wp-env-meta-item">
+ <span className="meta-label">
+ <Clock size={12} /> Last Sync
+ </span>
+ <span className={`meta-value ${stale ? 'text-warning' : ''}`}>
+ {formatRelativeTime(environment.last_sync)}
+ </span>
+ </div>
+ )}
+ {!isProduction && environment.sync_schedule && (
+ <div className="wp-env-meta-item">
+ <span className="meta-label">
+ <Calendar size={12} /> Schedule
+ </span>
+ <span className="meta-value">
+ {formatSchedule(environment.sync_schedule)}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div className="wp-env-footer">
+ <button
+ className="btn btn-ghost btn-sm"
+ onClick={handleVisit}
+ disabled={!environment.url}
+ >
+ <ExternalLink size={14} />
+ Visit
+ </button>
+
+ {!isProduction && (
+ <>
+ <button
+ className="btn btn-ghost btn-sm"
+ onClick={() => setShowSyncConfirm(true)}
+ disabled={syncing || !productionUrl}
+ title="Sync from production"
+ >
+ <RefreshCw size={14} className={syncing ? 'spinning' : ''} />
+ {syncing ? 'Syncing...' : 'Sync'}
+ </button>
+ {onViewLogs && (
+ <button
+ className="btn btn-ghost btn-sm"
+ onClick={() => onViewLogs?.(environment.id)}
+ title="View sync logs"
+ >
+ <FileText size={14} />
+ Logs
+ </button>
+ )}
+ <button
+ className="btn btn-ghost btn-sm btn-danger"
+ onClick={() => setShowDeleteConfirm(true)}
+ disabled={deleting}
+ >
+ <Trash2 size={14} />
+ {deleting ? 'Deleting...' : 'Delete'}
+ </button>
+ </>
+ )}
+ </div>
+
+ <ConfirmDialog
+ isOpen={showSyncConfirm}
+ title="Sync from Production"
+ message={`Sync "${environment.name}" from production?`}
+ details={
+ <ul>
+ <li><strong>Warning:</strong> This will overwrite the current database</li>
+ <li>All data in this environment will be replaced with production data</li>
+ <li>URLs will be automatically updated for this environment</li>
+ </ul>
+ }
+ confirmText="Sync Now"
+ variant="warning"
+ onConfirm={handleSync}
+ onCancel={() => setShowSyncConfirm(false)}
+ />
+
+ <ConfirmDialog
+ isOpen={showDeleteConfirm}
+ title={`Delete ${envType.charAt(0).toUpperCase() + envType.slice(1)} Environment`}
+ message={`Are you sure you want to delete "${environment.name}"?`}
+ details={
+ <ul>
+ <li>All environment files will be permanently deleted</li>
+ <li>Database <code>{environment.db_name || 'associated database'}</code> will be removed</li>
+ <li>This action cannot be undone</li>
+ </ul>
+ }
+ confirmText="Delete Environment"
+ variant="danger"
+ onConfirm={handleDelete}
+ onCancel={() => setShowDeleteConfirm(false)}
+ />
+ </div>
+ );
+};
+
+export default EnvironmentCard;
diff --git a/frontend/src/components/wordpress/GitConnectForm.jsx b/frontend/src/components/wordpress/GitConnectForm.jsx
new file mode 100644
index 00000000..109fd8ec
--- /dev/null
+++ b/frontend/src/components/wordpress/GitConnectForm.jsx
@@ -0,0 +1,188 @@
+import React, { useState } from 'react';
+import { GitBranch, Link, Unlink } from 'lucide-react';
+
+const GitConnectForm = ({ gitStatus, onConnect, onDisconnect }) => {
+ const [formData, setFormData] = useState({
+ repoUrl: '',
+ branch: 'main',
+ paths: ['wp-content/themes', 'wp-content/plugins'],
+ autoDeploy: false
+ });
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState('');
+
+ const isConnected = gitStatus?.connected;
+
+ function handleChange(e) {
+ const { name, value, type, checked } = e.target;
+ setFormData(prev => ({
+ ...prev,
+ [name]: type === 'checkbox' ? checked : value
+ }));
+ }
+
+ function handlePathsChange(e) {
+ const paths = e.target.value.split('\n').filter(p => p.trim());
+ setFormData(prev => ({ ...prev, paths }));
+ }
+
+ async function handleConnect(e) {
+ e.preventDefault();
+ setError('');
+ setLoading(true);
+
+ try {
+ await onConnect({
+ repo_url: formData.repoUrl,
+ branch: formData.branch,
+ paths: formData.paths,
+ auto_deploy: formData.autoDeploy
+ });
+ } catch (err) {
+ setError(err.message || 'Failed to connect repository');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleDisconnect() {
+ if (!confirm('Disconnect Git repository? This will not delete any files.')) {
+ return;
+ }
+ setLoading(true);
+ try {
+ await onDisconnect();
+ } catch (err) {
+ setError(err.message || 'Failed to disconnect repository');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ if (isConnected) {
+ return (
+ <div className="git-connected-card">
+ <div className="git-connected-header">
+ <GitBranch size={20} />
+ <div className="git-connected-info">
+ <h4>Repository Connected</h4>
+ <a
+ href={gitStatus.repo_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="git-repo-url"
+ >
+ {gitStatus.repo_url}
+ </a>
+ </div>
+ </div>
+
+ <div className="git-connected-meta">
+ <div className="git-meta-item">
+ <span className="meta-label">Branch</span>
+ <span className="meta-value">{gitStatus.branch}</span>
+ </div>
+ <div className="git-meta-item">
+ <span className="meta-label">Auto Deploy</span>
+ <span className="meta-value">{gitStatus.auto_deploy ? 'Enabled' : 'Disabled'}</span>
+ </div>
+ {gitStatus.last_deploy_commit && (
+ <div className="git-meta-item">
+ <span className="meta-label">Last Deploy</span>
+ <span className="meta-value mono">{gitStatus.last_deploy_commit.substring(0, 7)}</span>
+ </div>
+ )}
+ {gitStatus.last_deploy_at && (
+ <div className="git-meta-item">
+ <span className="meta-label">Deployed At</span>
+ <span className="meta-value">
+ {new Date(gitStatus.last_deploy_at).toLocaleString()}
+ </span>
+ </div>
+ )}
+ </div>
+
+ <div className="git-connected-actions">
+ <button
+ className="btn btn-danger-outline"
+ onClick={handleDisconnect}
+ disabled={loading}
+ >
+ <Unlink size={14} />
+ {loading ? 'Disconnecting...' : 'Disconnect'}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="git-connect-form">
+ <h4>Connect Git Repository</h4>
+ <p className="hint">
+ Connect a Git repository to manage themes and plugins via version control.
+ </p>
+
+ {error && <div className="error-message">{error}</div>}
+
+ <form onSubmit={handleConnect}>
+ <div className="form-group">
+ <label>Repository URL *</label>
+ <input
+ type="text"
+ name="repoUrl"
+ value={formData.repoUrl}
+ onChange={handleChange}
+ placeholder="https://github.com/user/repo.git"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Branch</label>
+ <input
+ type="text"
+ name="branch"
+ value={formData.branch}
+ onChange={handleChange}
+ placeholder="main"
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Tracked Paths (one per line)</label>
+ <textarea
+ value={formData.paths.join('\n')}
+ onChange={handlePathsChange}
+ placeholder="wp-content/themes&#10;wp-content/plugins"
+ rows={3}
+ />
+ <span className="form-hint">
+ Paths relative to WordPress root that should be tracked
+ </span>
+ </div>
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ name="autoDeploy"
+ checked={formData.autoDeploy}
+ onChange={handleChange}
+ />
+ <span>Enable auto-deploy on push</span>
+ </label>
+ </div>
+
+ <div className="form-actions">
+ <button type="submit" className="btn btn-primary" disabled={loading}>
+ <Link size={14} />
+ {loading ? 'Connecting...' : 'Connect Repository'}
+ </button>
+ </div>
+ </form>
+ </div>
+ );
+};
+
+export default GitConnectForm;
diff --git a/frontend/src/components/wordpress/SnapshotTable.jsx b/frontend/src/components/wordpress/SnapshotTable.jsx
new file mode 100644
index 00000000..b831a675
--- /dev/null
+++ b/frontend/src/components/wordpress/SnapshotTable.jsx
@@ -0,0 +1,168 @@
+import React, { useState } from 'react';
+import { Download, RotateCcw, Trash2, GitCommit, Tag } from 'lucide-react';
+import { ConfirmDialog } from '../ConfirmDialog';
+
+const SnapshotTable = ({ snapshots, onRestore, onDelete, loading = false }) => {
+ const [actionLoading, setActionLoading] = useState({});
+ const [confirmRestore, setConfirmRestore] = useState(null);
+ const [confirmDelete, setConfirmDelete] = useState(null);
+
+ function formatBytes(bytes) {
+ if (!bytes || bytes === 0) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
+ }
+
+ function formatDate(dateString) {
+ if (!dateString) return '-';
+ return new Date(dateString).toLocaleString();
+ }
+
+ async function handleRestore(snapshot) {
+ setConfirmRestore(null);
+ setActionLoading(prev => ({ ...prev, [`restore-${snapshot.id}`]: true }));
+ try {
+ await onRestore?.(snapshot.id);
+ } finally {
+ setActionLoading(prev => ({ ...prev, [`restore-${snapshot.id}`]: false }));
+ }
+ }
+
+ async function handleDelete(snapshot) {
+ setConfirmDelete(null);
+ setActionLoading(prev => ({ ...prev, [`delete-${snapshot.id}`]: true }));
+ try {
+ await onDelete?.(snapshot.id);
+ } finally {
+ setActionLoading(prev => ({ ...prev, [`delete-${snapshot.id}`]: false }));
+ }
+ }
+
+ if (loading) {
+ return <div className="loading">Loading snapshots...</div>;
+ }
+
+ if (!snapshots || snapshots.length === 0) {
+ return (
+ <div className="empty-state-small">
+ <p>No database snapshots yet.</p>
+ <p className="hint">Create a snapshot to backup your database.</p>
+ </div>
+ );
+ }
+
+ return (
+ <table className="docker-table wp-snapshot-table">
+ <thead>
+ <tr>
+ <th>Snapshot</th>
+ <th>Size</th>
+ <th>Created</th>
+ <th>Git Context</th>
+ <th style={{ textAlign: 'right' }}>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {snapshots.map(snapshot => (
+ <tr key={snapshot.id}>
+ <td>
+ <div className="snapshot-name-cell">
+ <span className="snapshot-name">{snapshot.name}</span>
+ {snapshot.tag && (
+ <span className="snapshot-tag">
+ <Tag size={10} /> {snapshot.tag}
+ </span>
+ )}
+ {snapshot.description && (
+ <span className="snapshot-desc">{snapshot.description}</span>
+ )}
+ </div>
+ </td>
+ <td>
+ <span className="mono">{formatBytes(snapshot.size_bytes)}</span>
+ {snapshot.compressed && (
+ <span className="compressed-badge" title="Compressed">gz</span>
+ )}
+ </td>
+ <td>{formatDate(snapshot.created_at)}</td>
+ <td>
+ {snapshot.commit_sha ? (
+ <div className="git-context">
+ <GitCommit size={12} />
+ <span className="mono">{snapshot.commit_sha.substring(0, 7)}</span>
+ {snapshot.commit_message && (
+ <span className="commit-msg" title={snapshot.commit_message}>
+ {snapshot.commit_message.substring(0, 30)}
+ {snapshot.commit_message.length > 30 && '...'}
+ </span>
+ )}
+ </div>
+ ) : (
+ <span className="text-muted">-</span>
+ )}
+ </td>
+ <td className="docker-actions-cell">
+ <button
+ className="docker-icon-action"
+ title="Restore"
+ onClick={() => setConfirmRestore(snapshot)}
+ disabled={actionLoading[`restore-${snapshot.id}`]}
+ >
+ <RotateCcw size={14} />
+ </button>
+ <button
+ className="docker-icon-action"
+ title="Delete"
+ onClick={() => setConfirmDelete(snapshot)}
+ disabled={actionLoading[`delete-${snapshot.id}`]}
+ style={{ color: '#EF4444' }}
+ >
+ <Trash2 size={14} />
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+
+ <ConfirmDialog
+ isOpen={!!confirmRestore}
+ title="Restore Database Snapshot"
+ message={`Restore database from "${confirmRestore?.name}"?`}
+ details={
+ <ul>
+ <li><strong>Warning:</strong> This will overwrite your current database</li>
+ <li>Snapshot size: <code>{formatBytes(confirmRestore?.size_bytes)}</code></li>
+ <li>Created: {formatDate(confirmRestore?.created_at)}</li>
+ {confirmRestore?.commit_sha && (
+ <li>Git commit: <code>{confirmRestore.commit_sha.substring(0, 7)}</code></li>
+ )}
+ </ul>
+ }
+ confirmText="Restore Snapshot"
+ variant="warning"
+ onConfirm={() => handleRestore(confirmRestore)}
+ onCancel={() => setConfirmRestore(null)}
+ />
+
+ <ConfirmDialog
+ isOpen={!!confirmDelete}
+ title="Delete Snapshot"
+ message={`Delete snapshot "${confirmDelete?.name}"?`}
+ details={
+ <ul>
+ <li>This snapshot will be permanently deleted</li>
+ <li>This action cannot be undone</li>
+ </ul>
+ }
+ confirmText="Delete Snapshot"
+ variant="danger"
+ onConfirm={() => handleDelete(confirmDelete)}
+ onCancel={() => setConfirmDelete(null)}
+ />
+ </table>
+ );
+};
+
+export default SnapshotTable;
diff --git a/frontend/src/components/wordpress/WordPressSiteCard.jsx b/frontend/src/components/wordpress/WordPressSiteCard.jsx
new file mode 100644
index 00000000..9711113c
--- /dev/null
+++ b/frontend/src/components/wordpress/WordPressSiteCard.jsx
@@ -0,0 +1,148 @@
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { ExternalLink, Settings, Copy, Trash2 } from 'lucide-react';
+import { ConfirmDialog } from '../ConfirmDialog';
+
+const WordPressSiteCard = ({ site, onDelete }) => {
+ const navigate = useNavigate();
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+ const isRunning = site.status === 'running';
+
+ function getEnvironmentCount() {
+ return site.environments?.length || 0;
+ }
+
+ function handleVisitSite(e) {
+ e.stopPropagation();
+ if (site.url) {
+ window.open(site.url, '_blank');
+ }
+ }
+
+ function handleOpenDashboard(e) {
+ e.stopPropagation();
+ if (site.url) {
+ window.open(`${site.url}/wp-admin`, '_blank');
+ }
+ }
+
+ function handleManage() {
+ navigate(`/wordpress/${site.id}`);
+ }
+
+ function handleDelete(e) {
+ e.stopPropagation();
+ setShowDeleteConfirm(true);
+ }
+
+ function confirmDelete() {
+ setShowDeleteConfirm(false);
+ onDelete?.(site.id);
+ }
+
+ return (
+ <div className="wp-site-card" onClick={handleManage}>
+ <div className="wp-site-card-header">
+ <div className="wp-site-icon">
+ <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
+ <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 19.542c-5.261 0-9.542-4.281-9.542-9.542S6.739 2.458 12 2.458 21.542 6.739 21.542 12 17.261 21.542 12 21.542z"/>
+ </svg>
+ </div>
+ <div className="wp-site-info">
+ <h3 className="wp-site-name">{site.name}</h3>
+ {site.url && (
+ <span className="wp-site-url">{site.url}</span>
+ )}
+ </div>
+ <span className={`wp-site-status ${isRunning ? 'running' : 'stopped'}`}>
+ <span className="status-dot" />
+ {isRunning ? 'Running' : 'Stopped'}
+ </span>
+ </div>
+
+ <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 || 'Unknown'}</span>
+ </div>
+ <div className="wp-site-meta-item">
+ <span className="meta-label">Environments</span>
+ <span className="meta-value">{getEnvironmentCount() + 1}</span>
+ </div>
+ {site.git_repo_url && (
+ <div className="wp-site-meta-item">
+ <span className="meta-label">Git</span>
+ <span className="meta-value git-connected">Connected</span>
+ </div>
+ )}
+ </div>
+
+ {site.is_production && (
+ <span className="wp-site-badge production">Production</span>
+ )}
+ {!site.is_production && site.production_site_id && (
+ <span className="wp-site-badge development">Development</span>
+ )}
+ </div>
+
+ <div className="wp-site-card-footer">
+ <button
+ className="btn btn-ghost btn-sm"
+ onClick={handleVisitSite}
+ disabled={!site.url}
+ title="Visit Site"
+ >
+ <ExternalLink size={14} />
+ Visit
+ </button>
+ <button
+ className="btn btn-ghost btn-sm"
+ onClick={handleOpenDashboard}
+ disabled={!site.url}
+ title="Open Dashboard"
+ >
+ <Settings size={14} />
+ Dashboard
+ </button>
+ <button
+ className="btn btn-ghost btn-sm"
+ onClick={handleManage}
+ title="Manage Site"
+ >
+ <Copy size={14} />
+ Manage
+ </button>
+ <button
+ className="btn btn-ghost btn-sm btn-danger"
+ onClick={handleDelete}
+ title="Delete Site"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+
+ <ConfirmDialog
+ isOpen={showDeleteConfirm}
+ title="Delete WordPress Site"
+ message={`Are you sure you want to delete "${site.name}"? This action cannot be undone.`}
+ details={
+ <ul>
+ <li>All site files will be permanently deleted</li>
+ <li>Database <code>{site.db_name || 'associated database'}</code> will be removed</li>
+ {site.environments?.length > 0 && (
+ <li>{site.environments.length} linked environment(s) will also be deleted</li>
+ )}
+ </ul>
+ }
+ confirmText="Delete Site"
+ variant="danger"
+ requireConfirmation={site.name}
+ onConfirm={confirmDelete}
+ onCancel={() => setShowDeleteConfirm(false)}
+ />
+ </div>
+ );
+};
+
+export default WordPressSiteCard;
diff --git a/frontend/src/components/wordpress/index.js b/frontend/src/components/wordpress/index.js
new file mode 100644
index 00000000..5a81f25b
--- /dev/null
+++ b/frontend/src/components/wordpress/index.js
@@ -0,0 +1,6 @@
+export { default as WordPressSiteCard } from './WordPressSiteCard';
+export { default as CreateSiteModal } from './CreateSiteModal';
+export { default as EnvironmentCard } from './EnvironmentCard';
+export { default as SnapshotTable } from './SnapshotTable';
+export { default as GitConnectForm } from './GitConnectForm';
+export { default as CommitList } from './CommitList';
diff --git a/frontend/src/pages/Applications.jsx b/frontend/src/pages/Applications.jsx
index fe0c554c..a58de4a1 100644
--- a/frontend/src/pages/Applications.jsx
+++ b/frontend/src/pages/Applications.jsx
@@ -29,7 +29,8 @@ const Applications = () => {
setLoading(true);
try {
const data = await api.getApps();
- const appList = data.apps || [];
+ // Filter out WordPress apps - they have their own dedicated page at /wordpress
+ const appList = (data.apps || []).filter(a => a.app_type !== 'wordpress');
setApps(appList);
// Calculate stats
diff --git a/frontend/src/pages/WordPress.jsx b/frontend/src/pages/WordPress.jsx
new file mode 100644
index 00000000..22bd5311
--- /dev/null
+++ b/frontend/src/pages/WordPress.jsx
@@ -0,0 +1,237 @@
+import React, { useState, useEffect } from 'react';
+import { Plus, RefreshCw } from 'lucide-react';
+import wordpressApi from '../services/wordpress';
+import { useToast } from '../contexts/ToastContext';
+import { WordPressSiteCard, CreateSiteModal } from '../components/wordpress';
+
+const WordPress = () => {
+ const toast = useToast();
+ const [sites, setSites] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [showCreateModal, setShowCreateModal] = useState(false);
+ const [searchTerm, setSearchTerm] = useState('');
+ const [stats, setStats] = useState({
+ total: 0,
+ running: 0,
+ production: 0,
+ development: 0
+ });
+
+ useEffect(() => {
+ loadSites();
+ }, []);
+
+ async function loadSites() {
+ setLoading(true);
+ try {
+ const data = await wordpressApi.getSites();
+ const siteList = data.sites || [];
+ setSites(siteList);
+
+ // Calculate stats
+ const running = siteList.filter(s => s.status === 'running').length;
+ const production = siteList.filter(s => s.is_production).length;
+ const development = siteList.filter(s => !s.is_production).length;
+
+ setStats({
+ total: siteList.length,
+ running,
+ production,
+ development
+ });
+ } catch (err) {
+ console.error('Failed to load WordPress sites:', err);
+ toast.error('Failed to load WordPress sites');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleCreateSite(data) {
+ const result = await wordpressApi.createSite(data);
+ toast.success('WordPress site created successfully');
+ loadSites();
+ return result;
+ }
+
+ async function handleDeleteSite(siteId) {
+ try {
+ await wordpressApi.deleteSite(siteId);
+ toast.success('WordPress site deleted');
+ loadSites();
+ } catch (err) {
+ console.error('Failed to delete site:', err);
+ toast.error(err.message || 'Failed to delete site');
+ }
+ }
+
+ const filteredSites = sites.filter(site => {
+ if (!searchTerm) return true;
+ const search = searchTerm.toLowerCase();
+ return site.name?.toLowerCase().includes(search) ||
+ site.url?.toLowerCase().includes(search) ||
+ site.domain?.toLowerCase().includes(search);
+ });
+
+ // Skeleton Card Component for loading state
+ const SiteCardSkeleton = () => (
+ <div 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 className="wp-site-card-skeleton-footer">
+ <div className="wp-site-card-skeleton-btn" />
+ <div className="wp-site-card-skeleton-btn" />
+ <div className="wp-site-card-skeleton-btn" />
+ </div>
+ </div>
+ );
+
+ const StatCardSkeleton = () => (
+ <div className="docker-stat-card-skeleton">
+ <div className="docker-stat-card-skeleton-label" />
+ <div className="docker-stat-card-skeleton-value" />
+ <div className="docker-stat-card-skeleton-meta" />
+ </div>
+ );
+
+ return (
+ <div className="docker-page-new wordpress-page">
+ <div className="docker-page-header">
+ <div className="docker-page-title">
+ <h2>WordPress Sites</h2>
+ <div className="docker-page-subtitle">
+ Manage your WordPress installations
+ </div>
+ </div>
+ <div className="docker-page-actions">
+ <button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
+ <Plus size={16} /> New Site
+ </button>
+ </div>
+ </div>
+
+ <div className="docker-stats-row">
+ {loading ? (
+ <>
+ <StatCardSkeleton />
+ <StatCardSkeleton />
+ <StatCardSkeleton />
+ <StatCardSkeleton />
+ </>
+ ) : (
+ <>
+ <div className="docker-stat-card">
+ <div className="docker-stat-label">Total Sites</div>
+ <div className="docker-stat-value">{stats.total}</div>
+ <div className="docker-stat-meta">
+ <span className="docker-stat-running">{stats.running} Running</span>
+ </div>
+ </div>
+ <div className="docker-stat-card">
+ <div className="docker-stat-label">Production</div>
+ <div className="docker-stat-value">{stats.production}</div>
+ <div className="docker-stat-meta">Live sites</div>
+ </div>
+ <div className="docker-stat-card">
+ <div className="docker-stat-label">Development</div>
+ <div className="docker-stat-value">{stats.development}</div>
+ <div className="docker-stat-meta">Dev/staging environments</div>
+ </div>
+ <div className="docker-stat-card">
+ <div className="docker-stat-label">Running</div>
+ <div className="docker-stat-value">{stats.running}</div>
+ <div className="docker-stat-meta">Active sites</div>
+ </div>
+ </>
+ )}
+ </div>
+
+ <div className="docker-panel">
+ <div className="docker-panel-header">
+ <div className="docker-panel-tabs">
+ <div className="docker-panel-tab active">All Sites</div>
+ </div>
+ <div className="docker-panel-actions">
+ <button className="btn btn-secondary btn-sm" onClick={loadSites}>
+ <RefreshCw size={14} /> Refresh
+ </button>
+ </div>
+ </div>
+
+ <div className="docker-panel-content">
+ <div className="docker-table-header">
+ <div />
+ <input
+ type="text"
+ className="docker-search"
+ placeholder="Search sites..."
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ />
+ </div>
+
+ {loading ? (
+ <div className="wp-sites-grid">
+ <SiteCardSkeleton />
+ <SiteCardSkeleton />
+ <SiteCardSkeleton />
+ </div>
+ ) : filteredSites.length === 0 ? (
+ <div className="docker-empty">
+ <div className="wp-empty-icon">
+ <svg viewBox="0 0 24 24" width="48" height="48" fill="none" stroke="currentColor" strokeWidth="1.5">
+ <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>
+ <h3>No WordPress sites</h3>
+ <p>Create your first WordPress site to get started.</p>
+ <button
+ className="btn btn-primary"
+ onClick={() => setShowCreateModal(true)}
+ >
+ <Plus size={16} /> Create Site
+ </button>
+ </div>
+ ) : (
+ <div className="wp-sites-grid">
+ {filteredSites.map(site => (
+ <WordPressSiteCard
+ key={site.id}
+ site={site}
+ onDelete={handleDeleteSite}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {showCreateModal && (
+ <CreateSiteModal
+ onClose={() => setShowCreateModal(false)}
+ onCreate={handleCreateSite}
+ />
+ )}
+ </div>
+ );
+};
+
+export default WordPress;
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
new file mode 100644
index 00000000..23c86545
--- /dev/null
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -0,0 +1,1359 @@
+import React, { useState, useEffect } from 'react';
+import { useParams, useNavigate, Link } from 'react-router-dom';
+import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive } from 'lucide-react';
+import wordpressApi from '../services/wordpress';
+import { useToast } from '../contexts/ToastContext';
+import { EnvironmentCard, SnapshotTable, GitConnectForm, CommitList } from '../components/wordpress';
+import { ErrorBoundary, ErrorState } from '../components/ErrorBoundary';
+
+// Detail Page Skeleton for initial loading
+const DetailPageSkeleton = () => (
+ <div className="app-detail-page wp-detail-page">
+ <div className="app-detail-topbar">
+ <div className="app-detail-breadcrumbs">
+ <span className="skeleton" style={{ width: 80, height: 16 }} />
+ <span>/</span>
+ <span className="skeleton" style={{ width: 120, height: 16 }} />
+ </div>
+ </div>
+ <div className="app-detail-header">
+ <div className="skeleton" style={{ width: 48, height: 48, borderRadius: 8 }} />
+ <div className="app-detail-title-block">
+ <div className="skeleton" style={{ width: 200, height: 28, marginBottom: 8 }} />
+ <div className="skeleton" style={{ width: 300, height: 16 }} />
+ </div>
+ </div>
+ <div className="app-detail-tabs" style={{ display: 'flex', gap: 8 }}>
+ {[1, 2, 3, 4, 5, 6, 7].map(i => (
+ <div key={i} className="skeleton" style={{ width: 80, height: 32, borderRadius: 4 }} />
+ ))}
+ </div>
+ <div className="app-detail-content">
+ <div className="tab-loading">
+ <div className="tab-loading-header">
+ <div className="tab-loading-title" />
+ <div className="tab-loading-btn" />
+ </div>
+ <div className="environments-grid">
+ <div className="wp-env-card-skeleton">
+ <div className="wp-env-card-skeleton-header">
+ <div className="wp-env-card-skeleton-badge" />
+ <div className="wp-env-card-skeleton-status" />
+ </div>
+ <div className="wp-env-card-skeleton-body">
+ <div className="wp-env-card-skeleton-url" />
+ </div>
+ </div>
+ <div className="wp-env-card-skeleton">
+ <div className="wp-env-card-skeleton-header">
+ <div className="wp-env-card-skeleton-badge" />
+ <div className="wp-env-card-skeleton-status" />
+ </div>
+ <div className="wp-env-card-skeleton-body">
+ <div className="wp-env-card-skeleton-url" />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+);
+
+const WordPressDetail = () => {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const toast = useToast();
+ const [site, setSite] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [activeTab, setActiveTab] = useState('overview');
+
+ useEffect(() => {
+ loadSite();
+ }, [id]);
+
+ async function loadSite() {
+ try {
+ const data = await wordpressApi.getSite(id);
+ setSite(data.site || data);
+ } catch (err) {
+ console.error('Failed to load site:', err);
+ toast.error('Failed to load WordPress site');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ if (loading) {
+ return <DetailPageSkeleton />;
+ }
+
+ if (!site) {
+ return (
+ <div className="empty-state">
+ <h3>Site not found</h3>
+ <button className="btn btn-primary" onClick={() => navigate('/wordpress')}>
+ Back to WordPress Sites
+ </button>
+ </div>
+ );
+ }
+
+ const isRunning = site.status === 'running';
+
+ return (
+ <div className="app-detail-page wp-detail-page">
+ {/* Top Bar */}
+ <div className="app-detail-topbar">
+ <div className="app-detail-breadcrumbs">
+ <Link to="/wordpress">WordPress</Link>
+ <span>/</span>
+ <span className="current">{site.name}</span>
+ </div>
+ <div className="app-detail-actions">
+ {site.url && (
+ <>
+ <a
+ href={site.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="btn btn-ghost"
+ >
+ <ExternalLink size={16} />
+ Visit Site
+ </a>
+ <a
+ href={`${site.url}/wp-admin`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="btn btn-ghost"
+ >
+ <Settings size={16} />
+ Dashboard
+ </a>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Header */}
+ <div className="app-detail-header">
+ <div className="app-detail-icon wp-icon">
+ <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor">
+ <path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm0 19.542c-5.261 0-9.542-4.281-9.542-9.542S6.739 2.458 12 2.458 21.542 6.739 21.542 12 17.261 21.542 12 21.542z"/>
+ </svg>
+ </div>
+ <div className="app-detail-title-block">
+ <h1>
+ {site.name}
+ <span className={`app-status-badge ${isRunning ? 'running' : 'stopped'}`}>
+ <span className="pulse-dot" />
+ {isRunning ? 'Running' : 'Stopped'}
+ </span>
+ {site.is_production && (
+ <span className="env-badge env-production">PROD</span>
+ )}
+ {!site.is_production && site.production_site_id && (
+ <span className="env-badge env-development">DEV</span>
+ )}
+ </h1>
+ <div className="app-detail-subtitle">
+ <span>WordPress {site.wp_version || ''}</span>
+ {site.url && (
+ <>
+ <span className="separator">•</span>
+ <span className="mono">{site.url}</span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Tabs */}
+ <div className="app-detail-tabs">
+ <div
+ className={`app-detail-tab ${activeTab === 'overview' ? 'active' : ''}`}
+ onClick={() => setActiveTab('overview')}
+ >
+ Overview
+ </div>
+ <div
+ className={`app-detail-tab ${activeTab === 'environments' ? 'active' : ''}`}
+ onClick={() => setActiveTab('environments')}
+ >
+ Environments
+ </div>
+ <div
+ className={`app-detail-tab ${activeTab === 'database' ? 'active' : ''}`}
+ onClick={() => setActiveTab('database')}
+ >
+ <Database size={14} /> Database
+ </div>
+ <div
+ className={`app-detail-tab ${activeTab === 'plugins' ? 'active' : ''}`}
+ onClick={() => setActiveTab('plugins')}
+ >
+ <Package size={14} /> Plugins
+ </div>
+ <div
+ className={`app-detail-tab ${activeTab === 'themes' ? 'active' : ''}`}
+ onClick={() => setActiveTab('themes')}
+ >
+ <Palette size={14} /> Themes
+ </div>
+ <div
+ className={`app-detail-tab ${activeTab === 'git' ? 'active' : ''}`}
+ onClick={() => setActiveTab('git')}
+ >
+ <GitBranch size={14} /> Git
+ </div>
+ <div
+ className={`app-detail-tab ${activeTab === 'backups' ? 'active' : ''}`}
+ onClick={() => setActiveTab('backups')}
+ >
+ <Archive size={14} /> Backups
+ </div>
+ </div>
+
+ {/* Tab Content */}
+ <div className="app-detail-content">
+ <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 === 'plugins' && <PluginsTab siteId={site.id} />}
+ {activeTab === 'themes' && <ThemesTab siteId={site.id} />}
+ {activeTab === 'git' && <GitTab siteId={site.id} site={site} onUpdate={loadSite} />}
+ {activeTab === 'backups' && <BackupsTab siteId={site.id} />}
+ </ErrorBoundary>
+ </div>
+ </div>
+ );
+};
+
+// Overview Tab
+const OverviewTab = ({ site, onUpdate }) => {
+ const toast = useToast();
+ const [creatingSnapshot, setCreatingSnapshot] = useState(false);
+ const [showEnvModal, setShowEnvModal] = useState(false);
+ const [syncingAll, setSyncingAll] = useState(false);
+
+ async function handleQuickSnapshot() {
+ setCreatingSnapshot(true);
+ toast.info('Creating snapshot...', { duration: 2000 });
+ try {
+ await wordpressApi.createSnapshot(site.id, {
+ name: `Quick Snapshot ${new Date().toLocaleDateString()}`,
+ tag: 'quick',
+ description: 'Created from Overview quick action'
+ });
+ toast.success('Snapshot created successfully');
+ } catch (err) {
+ toast.error(err.message || 'Failed to create snapshot');
+ } finally {
+ setCreatingSnapshot(false);
+ }
+ }
+
+ async function handleSyncAll() {
+ if (!site.environments?.length) return;
+ setSyncingAll(true);
+ toast.info(`Syncing ${site.environments.length} environment(s)...`, { duration: 3000 });
+ try {
+ // Sync each environment sequentially
+ for (let i = 0; i < site.environments.length; i++) {
+ const env = site.environments[i];
+ await wordpressApi.syncEnvironment(site.id, { environment_id: env.id });
+ }
+ toast.success(`Synced ${site.environments.length} environment(s) from production`);
+ onUpdate?.();
+ } catch (err) {
+ toast.error(err.message || 'Failed to sync environments');
+ } finally {
+ setSyncingAll(false);
+ }
+ }
+
+ async function handleCreateEnvironment(data) {
+ toast.info('Creating environment... This may take a moment.', { duration: 5000 });
+ try {
+ await wordpressApi.createEnvironment(site.id, data);
+ toast.success('Environment created successfully');
+ setShowEnvModal(false);
+ onUpdate?.();
+ } catch (err) {
+ toast.error(err.message || 'Failed to create environment');
+ }
+ }
+
+ return (
+ <div className="app-overview-grid">
+ <div className="app-overview-left">
+ <div className="app-panel">
+ <div className="app-panel-header">Site Information</div>
+ <div className="app-panel-body">
+ <div className="app-info-grid">
+ <div className="app-info-item">
+ <span className="app-info-label">WordPress Version</span>
+ <span className="app-info-value">{site.wp_version || 'Unknown'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Multisite</span>
+ <span className="app-info-value">{site.multisite ? 'Yes' : 'No'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Admin User</span>
+ <span className="app-info-value">{site.admin_user || '-'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Admin Email</span>
+ <span className="app-info-value">{site.admin_email || '-'}</span>
+ </div>
+ <div className="app-info-item full-width">
+ <span className="app-info-label">Site URL</span>
+ <span className="app-info-value">
+ {site.url ? (
+ <a href={site.url} target="_blank" rel="noopener noreferrer">
+ {site.url}
+ </a>
+ ) : '-'}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="app-panel">
+ <div className="app-panel-header">Database Configuration</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 || '-'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Database User</span>
+ <span className="app-info-value mono">{site.db_user || '-'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Database Host</span>
+ <span className="app-info-value mono">{site.db_host || 'localhost'}</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>
+ </div>
+ </div>
+
+ {site.git_repo_url && (
+ <div className="app-panel">
+ <div className="app-panel-header">Git Integration</div>
+ <div className="app-panel-body">
+ <div className="app-info-grid">
+ <div className="app-info-item full-width">
+ <span className="app-info-label">Repository</span>
+ <span className="app-info-value mono">{site.git_repo_url}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Branch</span>
+ <span className="app-info-value">{site.git_branch || 'main'}</span>
+ </div>
+ <div className="app-info-item">
+ <span className="app-info-label">Auto Deploy</span>
+ <span className="app-info-value">{site.auto_deploy ? 'Enabled' : 'Disabled'}</span>
+ </div>
+ {site.last_deploy_commit && (
+ <div className="app-info-item">
+ <span className="app-info-label">Last Deploy</span>
+ <span className="app-info-value mono">{site.last_deploy_commit.substring(0, 7)}</span>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="app-overview-right">
+ <div className="app-panel">
+ <div className="app-panel-header">Quick Actions</div>
+ <div className="app-panel-body">
+ <div className="quick-actions-grid">
+ {site.url && (
+ <>
+ <a
+ href={site.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="quick-action-btn"
+ >
+ <ExternalLink size={16} />
+ Visit Site
+ </a>
+ <a
+ href={`${site.url}/wp-admin`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="quick-action-btn"
+ >
+ <Settings size={16} />
+ WP Admin
+ </a>
+ </>
+ )}
+ {site.is_production && (
+ <button
+ className="quick-action-btn"
+ onClick={() => setShowEnvModal(true)}
+ >
+ <Plus size={16} />
+ Create Dev Env
+ </button>
+ )}
+ <button
+ className="quick-action-btn"
+ onClick={handleQuickSnapshot}
+ disabled={creatingSnapshot}
+ >
+ <Database size={16} />
+ {creatingSnapshot ? 'Creating...' : 'Create Snapshot'}
+ </button>
+ {site.environments?.length > 0 && (
+ <button
+ className="quick-action-btn"
+ onClick={handleSyncAll}
+ disabled={syncingAll}
+ >
+ <RefreshCw size={16} className={syncingAll ? 'spinning' : ''} />
+ {syncingAll ? 'Syncing...' : 'Sync All Envs'}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {showEnvModal && (
+ <CreateEnvironmentModal
+ onClose={() => setShowEnvModal(false)}
+ onCreate={handleCreateEnvironment}
+ productionDomain={site.url}
+ />
+ )}
+ </div>
+ );
+};
+
+// Reusable Skeleton Components for Tabs
+const EnvironmentCardSkeleton = () => (
+ <div className="wp-env-card-skeleton">
+ <div className="wp-env-card-skeleton-header">
+ <div className="wp-env-card-skeleton-badge" />
+ <div className="wp-env-card-skeleton-status" />
+ </div>
+ <div className="wp-env-card-skeleton-body">
+ <div className="wp-env-card-skeleton-url" />
+ <div className="wp-env-card-skeleton-meta">
+ <div className="wp-env-card-skeleton-meta-item">
+ <div className="skeleton-label" />
+ <div className="skeleton-value" />
+ </div>
+ <div className="wp-env-card-skeleton-meta-item">
+ <div className="skeleton-label" />
+ <div className="skeleton-value" />
+ </div>
+ </div>
+ </div>
+ <div className="wp-env-card-skeleton-footer">
+ <div className="skeleton" style={{ flex: 1, height: 28, borderRadius: 4 }} />
+ <div className="skeleton" style={{ flex: 1, height: 28, borderRadius: 4 }} />
+ </div>
+ </div>
+);
+
+const TableRowSkeleton = () => (
+ <div className="skeleton-table-row">
+ <div className="skeleton-cell cell-name" />
+ <div className="skeleton-cell cell-tag" />
+ <div className="skeleton-cell cell-size" />
+ <div className="skeleton-cell cell-date" />
+ <div className="skeleton-cell cell-actions" />
+ </div>
+);
+
+const ListItemSkeleton = () => (
+ <div className="skeleton" style={{ height: 48, borderRadius: 6, marginBottom: 8 }} />
+);
+
+// Environments Tab
+const EnvironmentsTab = ({ siteId, site, onUpdate }) => {
+ const toast = useToast();
+ const [environments, setEnvironments] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [showCreateModal, setShowCreateModal] = useState(false);
+
+ useEffect(() => {
+ loadEnvironments();
+ }, [siteId]);
+
+ async function loadEnvironments() {
+ setLoading(true);
+ setError(null);
+ try {
+ const data = await wordpressApi.getEnvironments(siteId);
+ setEnvironments(data.environments || []);
+ } catch (err) {
+ console.error('Failed to load environments:', err);
+ setError(err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleCreateEnvironment(data) {
+ toast.info('Creating environment... This may take a moment.', { duration: 5000 });
+ try {
+ await wordpressApi.createEnvironment(siteId, data);
+ toast.success('Environment created successfully');
+ loadEnvironments();
+ setShowCreateModal(false);
+ } catch (err) {
+ toast.error(err.message || 'Failed to create environment');
+ }
+ }
+
+ async function handleSync(envId) {
+ toast.info('Syncing from production...', { duration: 3000 });
+ try {
+ await wordpressApi.syncEnvironment(siteId, { environment_id: envId });
+ toast.success('Environment synced from production');
+ loadEnvironments();
+ } catch (err) {
+ toast.error(err.message || 'Failed to sync environment');
+ }
+ }
+
+ async function handleDelete(envId) {
+ toast.info('Deleting environment...', { duration: 2000 });
+ try {
+ await wordpressApi.deleteEnvironment(siteId, envId);
+ toast.success('Environment deleted');
+ loadEnvironments();
+ } catch (err) {
+ toast.error(err.message || 'Failed to delete environment');
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="environments-tab">
+ <div className="section-header">
+ <div className="skeleton" style={{ width: 120, height: 24 }} />
+ <div className="skeleton" style={{ width: 160, height: 36, borderRadius: 6 }} />
+ </div>
+ <div className="environments-grid">
+ <EnvironmentCardSkeleton />
+ <EnvironmentCardSkeleton />
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Failed to load environments"
+ error={error}
+ onRetry={loadEnvironments}
+ />
+ );
+ }
+
+ return (
+ <div className="environments-tab">
+ <div className="section-header">
+ <h3>Environments</h3>
+ {site.is_production && (
+ <button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
+ <Plus size={14} /> Create Environment
+ </button>
+ )}
+ </div>
+
+ <div className="environments-grid">
+ {/* Production environment (the current site) */}
+ <EnvironmentCard
+ environment={{
+ id: site.id,
+ name: site.name,
+ url: site.url,
+ status: site.status,
+ db_name: site.db_name,
+ type: 'production'
+ }}
+ isProduction={true}
+ />
+
+ {/* Dev/staging environments */}
+ {environments.map(env => (
+ <EnvironmentCard
+ key={env.id}
+ environment={env}
+ productionUrl={site.url}
+ onSync={handleSync}
+ onDelete={handleDelete}
+ />
+ ))}
+ </div>
+
+ {environments.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>
+ </div>
+ )}
+
+ {showCreateModal && (
+ <CreateEnvironmentModal
+ onClose={() => setShowCreateModal(false)}
+ onCreate={handleCreateEnvironment}
+ productionDomain={site.url}
+ />
+ )}
+ </div>
+ );
+};
+
+// Create Environment Modal
+const CreateEnvironmentModal = ({ onClose, onCreate, productionDomain }) => {
+ const [formData, setFormData] = useState({
+ type: 'development',
+ name: '',
+ domain: '',
+ cloneDb: true,
+ syncSchedule: ''
+ });
+ const [loading, setLoading] = useState(false);
+
+ // Generate suggested domain based on production domain
+ function getSuggestedDomain() {
+ if (!productionDomain) return '';
+ try {
+ const url = new URL(productionDomain);
+ const prefix = formData.type === 'staging' ? 'staging' : 'dev';
+ return `${prefix}.${url.hostname}`;
+ } catch {
+ return '';
+ }
+ }
+
+ const suggestedDomain = getSuggestedDomain();
+ const displayDomain = formData.domain || suggestedDomain;
+
+ function handleChange(e) {
+ const { name, value, type, checked } = e.target;
+ setFormData(prev => ({
+ ...prev,
+ [name]: type === 'checkbox' ? checked : value
+ }));
+ }
+
+ async function handleSubmit(e) {
+ e.preventDefault();
+ setLoading(true);
+ try {
+ await onCreate({
+ type: formData.type,
+ name: formData.name,
+ domain: formData.domain || suggestedDomain,
+ clone_db: formData.cloneDb,
+ sync_schedule: formData.syncSchedule || null
+ });
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create Environment</h2>
+ <button className="modal-close" onClick={onClose}>&times;</button>
+ </div>
+
+ <form onSubmit={handleSubmit}>
+ <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>
+ </select>
+ </div>
+
+ <div className="form-group">
+ <label>Environment Name *</label>
+ <input
+ type="text"
+ name="name"
+ value={formData.name}
+ onChange={handleChange}
+ placeholder="My Site Dev"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Domain</label>
+ <input
+ type="text"
+ name="domain"
+ value={formData.domain}
+ onChange={handleChange}
+ placeholder={suggestedDomain || 'dev.example.com'}
+ />
+ {suggestedDomain && !formData.domain && (
+ <span className="form-hint form-hint-domain">
+ Will use: <code>{suggestedDomain}</code>
+ </span>
+ )}
+ {!suggestedDomain && !formData.domain && (
+ <span className="form-hint">Enter a domain or leave empty to auto-generate</span>
+ )}
+ </div>
+
+ {displayDomain && (
+ <div className="env-preview-url">
+ <span className="preview-label">Environment URL:</span>
+ <span className="preview-url">https://{displayDomain}</span>
+ </div>
+ )}
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ name="cloneDb"
+ checked={formData.cloneDb}
+ onChange={handleChange}
+ />
+ <span>Clone production database</span>
+ </label>
+ </div>
+
+ <div className="form-group">
+ <label>Sync Schedule (optional)</label>
+ <select name="syncSchedule" value={formData.syncSchedule} onChange={handleChange}>
+ <option value="">No automatic sync</option>
+ <option value="0 3 * * 0">Weekly (Sunday 3am)</option>
+ <option value="0 3 * * *">Daily (3am)</option>
+ </select>
+ <span className="form-hint">Automatically sync database from production</span>
+ </div>
+
+ <div className="modal-actions">
+ <button type="button" className="btn btn-secondary" onClick={onClose}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary" disabled={loading}>
+ {loading ? 'Creating...' : 'Create Environment'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+// Database Tab
+const DatabaseTab = ({ siteId }) => {
+ const toast = useToast();
+ const [snapshots, setSnapshots] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [showCreateModal, setShowCreateModal] = useState(false);
+
+ useEffect(() => {
+ loadSnapshots();
+ }, [siteId]);
+
+ async function loadSnapshots() {
+ setLoading(true);
+ setError(null);
+ try {
+ const data = await wordpressApi.getSnapshots(siteId);
+ setSnapshots(data.snapshots || []);
+ } catch (err) {
+ console.error('Failed to load snapshots:', err);
+ setError(err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleCreateSnapshot(data) {
+ toast.info('Creating snapshot...', { duration: 3000 });
+ try {
+ await wordpressApi.createSnapshot(siteId, data);
+ toast.success('Snapshot created successfully');
+ loadSnapshots();
+ setShowCreateModal(false);
+ } catch (err) {
+ toast.error(err.message || 'Failed to create snapshot');
+ }
+ }
+
+ async function handleRestore(snapId) {
+ toast.info('Restoring database... This may take a moment.', { duration: 5000 });
+ try {
+ await wordpressApi.restoreSnapshot(siteId, snapId);
+ toast.success('Database restored from snapshot');
+ } catch (err) {
+ toast.error(err.message || 'Failed to restore snapshot');
+ }
+ }
+
+ async function handleDelete(snapId) {
+ try {
+ await wordpressApi.deleteSnapshot(siteId, snapId);
+ toast.success('Snapshot deleted');
+ loadSnapshots();
+ } catch (err) {
+ toast.error(err.message || 'Failed to delete snapshot');
+ }
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Failed to load snapshots"
+ error={error}
+ onRetry={loadSnapshots}
+ />
+ );
+ }
+
+ return (
+ <div className="database-tab">
+ <div className="section-header">
+ <h3>Database Snapshots</h3>
+ <button className="btn btn-primary" onClick={() => setShowCreateModal(true)}>
+ <Plus size={14} /> Create Snapshot
+ </button>
+ </div>
+
+ <SnapshotTable
+ snapshots={snapshots}
+ loading={loading}
+ onRestore={handleRestore}
+ onDelete={handleDelete}
+ />
+
+ {showCreateModal && (
+ <CreateSnapshotModal
+ onClose={() => setShowCreateModal(false)}
+ onCreate={handleCreateSnapshot}
+ />
+ )}
+ </div>
+ );
+};
+
+// Create Snapshot Modal
+const CreateSnapshotModal = ({ onClose, onCreate }) => {
+ const [formData, setFormData] = useState({
+ name: `Snapshot ${new Date().toLocaleDateString()}`,
+ description: '',
+ tag: ''
+ });
+ const [loading, setLoading] = useState(false);
+
+ function handleChange(e) {
+ const { name, value } = e.target;
+ setFormData(prev => ({ ...prev, [name]: value }));
+ }
+
+ async function handleSubmit(e) {
+ e.preventDefault();
+ setLoading(true);
+ try {
+ await onCreate(formData);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create Snapshot</h2>
+ <button className="modal-close" onClick={onClose}>&times;</button>
+ </div>
+
+ <form onSubmit={handleSubmit}>
+ <div className="form-group">
+ <label>Snapshot Name *</label>
+ <input
+ type="text"
+ name="name"
+ value={formData.name}
+ onChange={handleChange}
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Description</label>
+ <textarea
+ name="description"
+ value={formData.description}
+ onChange={handleChange}
+ placeholder="Optional description..."
+ rows={3}
+ />
+ </div>
+
+ <div className="form-group">
+ <label>Tag</label>
+ <input
+ type="text"
+ name="tag"
+ value={formData.tag}
+ onChange={handleChange}
+ placeholder="e.g., v1.0.0, before-update"
+ />
+ </div>
+
+ <div className="modal-actions">
+ <button type="button" className="btn btn-secondary" onClick={onClose}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary" disabled={loading}>
+ {loading ? 'Creating...' : 'Create Snapshot'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+// Plugins Tab
+const PluginsTab = ({ siteId }) => {
+ const toast = useToast();
+ const [plugins, setPlugins] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [installing, setInstalling] = useState(false);
+ const [newPlugin, setNewPlugin] = useState('');
+
+ useEffect(() => {
+ loadPlugins();
+ }, [siteId]);
+
+ async function loadPlugins() {
+ setLoading(true);
+ setError(null);
+ try {
+ const data = await wordpressApi.getPlugins(siteId);
+ setPlugins(data.plugins || []);
+ } catch (err) {
+ console.error('Failed to load plugins:', err);
+ setError(err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleInstall(e) {
+ e.preventDefault();
+ if (!newPlugin.trim()) return;
+
+ setInstalling(true);
+ try {
+ await wordpressApi.installPlugin(siteId, { slug: newPlugin.trim() });
+ toast.success('Plugin installed successfully');
+ setNewPlugin('');
+ loadPlugins();
+ } catch (err) {
+ toast.error(err.message || 'Failed to install plugin');
+ } finally {
+ setInstalling(false);
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="plugins-tab">
+ <div className="section-header">
+ <div className="skeleton" style={{ width: 80, height: 24 }} />
+ </div>
+ <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 16 }} />
+ <div className="plugins-list">
+ <ListItemSkeleton />
+ <ListItemSkeleton />
+ <ListItemSkeleton />
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Failed to load plugins"
+ error={error}
+ onRetry={loadPlugins}
+ />
+ );
+ }
+
+ return (
+ <div className="plugins-tab">
+ <div className="section-header">
+ <h3>Plugins</h3>
+ </div>
+
+ <form className="install-form" onSubmit={handleInstall}>
+ <input
+ type="text"
+ value={newPlugin}
+ onChange={(e) => setNewPlugin(e.target.value)}
+ placeholder="Plugin slug (e.g., akismet, woocommerce)"
+ />
+ <button type="submit" className="btn btn-primary" disabled={installing}>
+ {installing ? 'Installing...' : 'Install Plugin'}
+ </button>
+ </form>
+
+ <div className="plugins-list">
+ {plugins.length === 0 ? (
+ <p className="hint">No plugins installed.</p>
+ ) : (
+ plugins.map(plugin => (
+ <div key={plugin.name} className={`plugin-item ${plugin.status === 'active' ? 'active' : ''}`}>
+ <div className="plugin-info">
+ <span className="plugin-name">{plugin.title || plugin.name}</span>
+ <span className="plugin-version">{plugin.version}</span>
+ </div>
+ <span className={`plugin-status ${plugin.status}`}>
+ {plugin.status === 'active' ? 'Active' : 'Inactive'}
+ </span>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ );
+};
+
+// Themes Tab
+const ThemesTab = ({ siteId }) => {
+ const toast = useToast();
+ const [themes, setThemes] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [installing, setInstalling] = useState(false);
+ const [newTheme, setNewTheme] = useState('');
+
+ useEffect(() => {
+ loadThemes();
+ }, [siteId]);
+
+ async function loadThemes() {
+ setLoading(true);
+ setError(null);
+ try {
+ const data = await wordpressApi.getThemes(siteId);
+ setThemes(data.themes || []);
+ } catch (err) {
+ console.error('Failed to load themes:', err);
+ setError(err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleInstall(e) {
+ e.preventDefault();
+ if (!newTheme.trim()) return;
+
+ setInstalling(true);
+ try {
+ await wordpressApi.installTheme(siteId, { slug: newTheme.trim() });
+ toast.success('Theme installed successfully');
+ setNewTheme('');
+ loadThemes();
+ } catch (err) {
+ toast.error(err.message || 'Failed to install theme');
+ } finally {
+ setInstalling(false);
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="themes-tab">
+ <div className="section-header">
+ <div className="skeleton" style={{ width: 80, height: 24 }} />
+ </div>
+ <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 16 }} />
+ <div className="themes-list">
+ <ListItemSkeleton />
+ <ListItemSkeleton />
+ <ListItemSkeleton />
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Failed to load themes"
+ error={error}
+ onRetry={loadThemes}
+ />
+ );
+ }
+
+ return (
+ <div className="themes-tab">
+ <div className="section-header">
+ <h3>Themes</h3>
+ </div>
+
+ <form className="install-form" onSubmit={handleInstall}>
+ <input
+ type="text"
+ value={newTheme}
+ onChange={(e) => setNewTheme(e.target.value)}
+ placeholder="Theme slug (e.g., twentytwentyfour)"
+ />
+ <button type="submit" className="btn btn-primary" disabled={installing}>
+ {installing ? 'Installing...' : 'Install Theme'}
+ </button>
+ </form>
+
+ <div className="themes-list">
+ {themes.length === 0 ? (
+ <p className="hint">No themes found.</p>
+ ) : (
+ themes.map(theme => (
+ <div key={theme.name} className={`theme-item ${theme.status === 'active' ? 'active' : ''}`}>
+ <div className="theme-info">
+ <span className="theme-name">{theme.title || theme.name}</span>
+ <span className="theme-version">{theme.version}</span>
+ </div>
+ {theme.status === 'active' && (
+ <span className="active-badge">Active</span>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ );
+};
+
+// Git Tab
+const GitTab = ({ siteId, site, onUpdate }) => {
+ const toast = useToast();
+ const [gitStatus, setGitStatus] = useState(null);
+ const [commits, setCommits] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ loadGitData();
+ }, [siteId]);
+
+ async function loadGitData() {
+ setLoading(true);
+ setError(null);
+ try {
+ const statusData = await wordpressApi.getGitStatus(siteId);
+ setGitStatus(statusData);
+
+ if (statusData.connected) {
+ const commitsData = await wordpressApi.getCommits(siteId);
+ setCommits(commitsData.commits || []);
+ }
+ } catch (err) {
+ console.error('Failed to load git data:', err);
+ setError(err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleConnect(data) {
+ await wordpressApi.connectRepo(siteId, data);
+ toast.success('Repository connected');
+ loadGitData();
+ onUpdate?.();
+ }
+
+ async function handleDisconnect() {
+ await wordpressApi.disconnectRepo(siteId);
+ toast.success('Repository disconnected');
+ loadGitData();
+ onUpdate?.();
+ }
+
+ async function handleDeploy(data) {
+ try {
+ await wordpressApi.deployCommit(siteId, data);
+ toast.success('Deployment completed');
+ loadGitData();
+ onUpdate?.();
+ } catch (err) {
+ toast.error(err.message || 'Deployment failed');
+ }
+ }
+
+ async function handleCreateDev(data) {
+ try {
+ await wordpressApi.createDevFromCommit(siteId, data);
+ toast.success('Development environment created');
+ } catch (err) {
+ toast.error(err.message || 'Failed to create environment');
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="git-tab">
+ <div className="git-connect-form">
+ <div className="skeleton" style={{ width: 200, height: 24, marginBottom: 16 }} />
+ <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 12 }} />
+ <div className="skeleton" style={{ height: 44, borderRadius: 6, marginBottom: 12 }} />
+ <div className="skeleton" style={{ width: 140, height: 36, borderRadius: 6 }} />
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Failed to load Git information"
+ error={error}
+ onRetry={loadGitData}
+ />
+ );
+ }
+
+ return (
+ <div className="git-tab">
+ <GitConnectForm
+ gitStatus={gitStatus}
+ onConnect={handleConnect}
+ onDisconnect={handleDisconnect}
+ />
+
+ {gitStatus?.connected && (
+ <div className="git-commits-section">
+ <div className="section-header">
+ <h3>Recent Commits</h3>
+ <button className="btn btn-secondary btn-sm" onClick={loadGitData}>
+ <RefreshCw size={14} /> Refresh
+ </button>
+ </div>
+
+ <CommitList
+ commits={commits}
+ currentCommit={site.last_deploy_commit}
+ onDeploy={handleDeploy}
+ onCreateDev={handleCreateDev}
+ />
+ </div>
+ )}
+ </div>
+ );
+};
+
+// Backups Tab
+const BackupsTab = ({ siteId }) => {
+ const toast = useToast();
+ const [snapshots, setSnapshots] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ loadSnapshots();
+ }, [siteId]);
+
+ async function loadSnapshots() {
+ try {
+ const data = await wordpressApi.getSnapshots(siteId);
+ // Filter for backup-tagged snapshots
+ setSnapshots((data.snapshots || []).filter(s => s.tag?.includes('backup')));
+ } catch (err) {
+ console.error('Failed to load backups:', err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleCreateBackup() {
+ try {
+ await wordpressApi.createSnapshot(siteId, {
+ name: `Backup ${new Date().toISOString().split('T')[0]}`,
+ tag: 'backup',
+ description: 'Full site backup'
+ });
+ toast.success('Backup created');
+ loadSnapshots();
+ } catch (err) {
+ toast.error(err.message || 'Failed to create backup');
+ }
+ }
+
+ async function handleRestore(snapId) {
+ try {
+ await wordpressApi.restoreSnapshot(siteId, snapId);
+ toast.success('Backup restored');
+ } catch (err) {
+ toast.error(err.message || 'Failed to restore backup');
+ }
+ }
+
+ async function handleDelete(snapId) {
+ try {
+ await wordpressApi.deleteSnapshot(siteId, snapId);
+ toast.success('Backup deleted');
+ loadSnapshots();
+ } catch (err) {
+ toast.error(err.message || 'Failed to delete backup');
+ }
+ }
+
+ return (
+ <div className="backups-tab">
+ <div className="section-header">
+ <h3>Backups</h3>
+ <button className="btn btn-primary" onClick={handleCreateBackup}>
+ <Plus size={14} /> Create Backup
+ </button>
+ </div>
+
+ <SnapshotTable
+ snapshots={snapshots}
+ loading={loading}
+ onRestore={handleRestore}
+ onDelete={handleDelete}
+ />
+
+ {snapshots.length === 0 && !loading && (
+ <div className="hint-box">
+ <p>No backups yet. Create a backup to protect your site data.</p>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default WordPressDetail;
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
new file mode 100644
index 00000000..cf267e05
--- /dev/null
+++ b/frontend/src/services/wordpress.js
@@ -0,0 +1,105 @@
+import api from './api';
+
+const BASE_PATH = '/wordpress/sites';
+
+const wordpressApi = {
+ // Site Management
+ getSites: () => api.request(BASE_PATH),
+
+ createSite: (data) => api.request(BASE_PATH, {
+ method: 'POST',
+ body: data
+ }),
+
+ getSite: (id) => api.request(`${BASE_PATH}/${id}`),
+
+ deleteSite: (id) => api.request(`${BASE_PATH}/${id}`, {
+ method: 'DELETE'
+ }),
+
+ // Environment Management
+ getEnvironments: (siteId) => api.request(`${BASE_PATH}/${siteId}/environments`),
+
+ createEnvironment: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/environments`, {
+ method: 'POST',
+ body: data
+ }),
+
+ deleteEnvironment: (siteId, envId) => api.request(`${BASE_PATH}/${siteId}/environments/${envId}`, {
+ method: 'DELETE'
+ }),
+
+ syncEnvironment: (siteId, data = {}) => api.request(`${BASE_PATH}/${siteId}/sync`, {
+ method: 'POST',
+ body: data
+ }),
+
+ // Database Snapshots
+ getSnapshots: (siteId) => api.request(`${BASE_PATH}/${siteId}/snapshots`),
+
+ createSnapshot: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/snapshots`, {
+ method: 'POST',
+ body: data
+ }),
+
+ restoreSnapshot: (siteId, snapId) => api.request(`${BASE_PATH}/${siteId}/snapshots/${snapId}/restore`, {
+ method: 'POST'
+ }),
+
+ deleteSnapshot: (siteId, snapId) => api.request(`${BASE_PATH}/${siteId}/snapshots/${snapId}`, {
+ method: 'DELETE'
+ }),
+
+ // Git Integration
+ getGitStatus: (siteId) => api.request(`${BASE_PATH}/${siteId}/git`),
+
+ connectRepo: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/git`, {
+ method: 'POST',
+ body: data
+ }),
+
+ disconnectRepo: (siteId) => api.request(`${BASE_PATH}/${siteId}/git`, {
+ method: 'DELETE'
+ }),
+
+ getCommits: (siteId, limit = 20) => api.request(`${BASE_PATH}/${siteId}/git/commits?limit=${limit}`),
+
+ deployCommit: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/git/deploy`, {
+ method: 'POST',
+ body: data
+ }),
+
+ createDevFromCommit: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/git/dev-from-commit`, {
+ method: 'POST',
+ body: data
+ }),
+
+ // Plugins
+ getPlugins: (siteId) => api.request(`${BASE_PATH}/${siteId}/plugins`),
+
+ installPlugin: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/plugins`, {
+ method: 'POST',
+ body: data
+ }),
+
+ // Themes
+ getThemes: (siteId) => api.request(`${BASE_PATH}/${siteId}/themes`),
+
+ installTheme: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/themes`, {
+ method: 'POST',
+ body: data
+ }),
+
+ // WordPress Core Update
+ updateCore: (siteId) => api.request(`${BASE_PATH}/${siteId}/update`, {
+ method: 'POST'
+ }),
+
+ // Clone Database (for advanced use)
+ cloneDatabase: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/clone-db`, {
+ method: 'POST',
+ body: data
+ })
+};
+
+export default wordpressApi;
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index 5f2b1a24..e08a404f 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -75,3 +75,4 @@
@import 'pages/_git';
@import 'pages/_servers';
@import 'pages/_downloads';
+@import 'pages/_wordpress';
diff --git a/frontend/src/styles/pages/_wordpress.less b/frontend/src/styles/pages/_wordpress.less
new file mode 100644
index 00000000..a6f6c1e6
--- /dev/null
+++ b/frontend/src/styles/pages/_wordpress.less
@@ -0,0 +1,1134 @@
+// ============================================
+// WORDPRESS PAGE STYLES
+// ============================================
+
+// WordPress Page Layout (extends Docker page styles)
+.wordpress-page {
+ .docker-empty {
+ .wp-empty-icon {
+ color: @text-tertiary;
+ margin-bottom: @space-4;
+
+ svg {
+ stroke: currentColor;
+ }
+ }
+ }
+}
+
+// Sites Grid
+.wp-sites-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
+ gap: @space-4;
+ padding: @space-4;
+}
+
+// Site Card
+.wp-site-card {
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+ cursor: pointer;
+ transition: all 0.15s ease;
+
+ &:hover {
+ border-color: @border-hover;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
+ }
+}
+
+.wp-site-card-header {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ padding: @space-4;
+ border-bottom: 1px solid @border-subtle;
+}
+
+.wp-site-icon {
+ width: 40px;
+ height: 40px;
+ background: linear-gradient(135deg, #21759b 0%, #1a5f7f 100%);
+ border-radius: @radius-md;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ flex-shrink: 0;
+}
+
+.wp-site-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.wp-site-name {
+ font-size: @font-size-base;
+ font-weight: @font-weight-semibold;
+ color: @text-primary;
+ margin: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.wp-site-url {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ font-family: @font-family-mono;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: block;
+}
+
+.wp-site-status {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: @font-size-xs;
+ padding: 4px 10px;
+ border-radius: @radius-full;
+ font-weight: @font-weight-medium;
+
+ .status-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ }
+
+ &.running {
+ background: fade(@color-success, 12%);
+ color: @color-success;
+
+ .status-dot {
+ background: @color-success;
+ }
+ }
+
+ &.stopped {
+ background: fade(@text-tertiary, 12%);
+ color: @text-tertiary;
+
+ .status-dot {
+ background: @text-tertiary;
+ }
+ }
+}
+
+.wp-site-card-body {
+ padding: @space-4;
+}
+
+.wp-site-meta {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: @space-3;
+}
+
+.wp-site-meta-item {
+ .meta-label {
+ display: block;
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-bottom: 2px;
+ }
+
+ .meta-value {
+ font-size: @font-size-sm;
+ color: @text-primary;
+ font-weight: @font-weight-medium;
+
+ &.git-connected {
+ color: @color-success;
+ }
+ }
+}
+
+.wp-site-badge {
+ display: inline-block;
+ font-size: @font-size-xs;
+ font-weight: @font-weight-medium;
+ padding: 2px 8px;
+ border-radius: @radius-sm;
+ margin-top: @space-3;
+
+ &.production {
+ background: fade(@color-danger, 12%);
+ color: @color-danger;
+ }
+
+ &.development {
+ background: fade(@color-info, 12%);
+ color: @color-info;
+ }
+}
+
+.wp-site-card-footer {
+ display: flex;
+ gap: @space-2;
+ padding: @space-3 @space-4;
+ border-top: 1px solid @border-subtle;
+ background: @bg-tertiary;
+ border-radius: 0 0 @radius-lg @radius-lg;
+
+ .btn {
+ flex: 1;
+ justify-content: center;
+
+ &.btn-danger {
+ flex: 0;
+ color: @color-danger;
+
+ &:hover {
+ background: fade(@color-danger, 10%);
+ }
+ }
+ }
+}
+
+// WordPress Detail Page
+.wp-detail-page {
+ .wp-icon {
+ background: linear-gradient(135deg, #21759b 0%, #1a5f7f 100%) !important;
+ }
+}
+
+// Environment Cards
+.environments-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: @space-4;
+ margin-top: @space-4;
+}
+
+.wp-env-card {
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+
+ &.production {
+ border-color: fade(@color-danger, 30%);
+ border-left: 3px solid @color-danger;
+ }
+
+ &.stale {
+ border-color: fade(@color-warning, 40%);
+ background: fade(@color-warning, 3%);
+ }
+}
+
+.wp-env-status-group {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+}
+
+.wp-env-stale-badge {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: @font-size-xs;
+ font-weight: @font-weight-medium;
+ padding: 2px 8px;
+ border-radius: @radius-sm;
+ background: fade(@color-warning, 15%);
+ color: @color-warning;
+
+ svg {
+ flex-shrink: 0;
+ }
+}
+
+.text-warning {
+ color: @color-warning !important;
+}
+
+.wp-env-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: @space-4;
+ border-bottom: 1px solid @border-subtle;
+}
+
+.wp-env-info {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+}
+
+.wp-env-badge {
+ font-size: @font-size-xs;
+ font-weight: @font-weight-bold;
+ padding: 2px 8px;
+ border-radius: @radius-sm;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+
+ &.env-production {
+ background: fade(@color-danger, 12%);
+ color: @color-danger;
+ }
+
+ &.env-staging {
+ background: fade(@color-warning, 12%);
+ color: @color-warning;
+ }
+
+ &.env-development {
+ background: fade(@color-info, 12%);
+ color: @color-info;
+ }
+}
+
+.wp-env-name {
+ font-size: @font-size-base;
+ font-weight: @font-weight-semibold;
+ color: @text-primary;
+ margin: 0;
+}
+
+.wp-env-status {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: @font-size-xs;
+ font-weight: @font-weight-medium;
+
+ .status-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ }
+
+ &.running {
+ color: @color-success;
+
+ .status-dot {
+ background: @color-success;
+ }
+ }
+
+ &.stopped {
+ color: @text-tertiary;
+
+ .status-dot {
+ background: @text-tertiary;
+ }
+ }
+}
+
+.wp-env-body {
+ padding: @space-4;
+}
+
+.wp-env-url {
+ margin-bottom: @space-3;
+
+ a {
+ font-size: @font-size-sm;
+ color: @color-primary;
+ font-family: @font-family-mono;
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+}
+
+.wp-env-meta {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: @space-2;
+}
+
+.wp-env-meta-item {
+ .meta-label {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-bottom: 2px;
+ }
+
+ .meta-value {
+ font-size: @font-size-sm;
+ color: @text-primary;
+
+ &.mono {
+ font-family: @font-family-mono;
+ }
+ }
+}
+
+.wp-env-footer {
+ display: flex;
+ gap: @space-2;
+ padding: @space-3 @space-4;
+ border-top: 1px solid @border-subtle;
+ background: @bg-tertiary;
+ border-radius: 0 0 @radius-lg @radius-lg;
+}
+
+// Snapshot Table
+.wp-snapshot-table {
+ .snapshot-name-cell {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+
+ .snapshot-name {
+ font-weight: @font-weight-medium;
+ color: @text-primary;
+ }
+
+ .snapshot-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-size: @font-size-xs;
+ color: @color-info;
+ background: fade(@color-info, 10%);
+ padding: 2px 6px;
+ border-radius: @radius-sm;
+ width: fit-content;
+ }
+
+ .snapshot-desc {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ }
+
+ .compressed-badge {
+ display: inline-block;
+ font-size: 10px;
+ background: fade(@color-success, 10%);
+ color: @color-success;
+ padding: 1px 4px;
+ border-radius: 3px;
+ margin-left: @space-2;
+ }
+
+ .git-context {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: @text-secondary;
+
+ svg {
+ color: @text-tertiary;
+ }
+
+ .commit-msg {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-left: @space-2;
+ }
+ }
+}
+
+// Git Connect Form
+.git-connect-form {
+ max-width: 600px;
+
+ h4 {
+ margin: 0 0 @space-2;
+ }
+
+ .hint {
+ color: @text-tertiary;
+ margin-bottom: @space-4;
+ }
+}
+
+.git-connected-card {
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+ padding: @space-5;
+ max-width: 600px;
+}
+
+.git-connected-header {
+ display: flex;
+ align-items: flex-start;
+ gap: @space-4;
+ margin-bottom: @space-4;
+
+ > svg {
+ color: @color-success;
+ flex-shrink: 0;
+ }
+
+ h4 {
+ margin: 0 0 @space-1;
+ font-size: @font-size-base;
+ }
+}
+
+.git-repo-url {
+ font-size: @font-size-sm;
+ font-family: @font-family-mono;
+ color: @text-secondary;
+
+ &:hover {
+ color: @color-primary;
+ }
+}
+
+.git-connected-meta {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: @space-3;
+ padding: @space-4;
+ background: @bg-tertiary;
+ border-radius: @radius-md;
+ margin-bottom: @space-4;
+}
+
+.git-meta-item {
+ .meta-label {
+ display: block;
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-bottom: 2px;
+ }
+
+ .meta-value {
+ font-size: @font-size-sm;
+ color: @text-primary;
+
+ &.mono {
+ font-family: @font-family-mono;
+ }
+ }
+}
+
+.git-connected-actions {
+ display: flex;
+ justify-content: flex-end;
+}
+
+// Commit List
+.commit-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-1;
+ max-width: 800px;
+}
+
+.commit-item {
+ display: flex;
+ align-items: flex-start;
+ gap: @space-3;
+ padding: @space-3 @space-4;
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-md;
+ transition: all 0.15s ease;
+
+ &:hover {
+ border-color: @border-hover;
+ }
+
+ &.current {
+ border-color: fade(@color-success, 40%);
+ background: fade(@color-success, 4%);
+ }
+}
+
+.commit-icon {
+ color: @text-tertiary;
+ margin-top: 2px;
+
+ .current-icon {
+ color: @color-success;
+ }
+}
+
+.commit-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.commit-header {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ margin-bottom: @space-1;
+}
+
+.commit-sha {
+ font-size: @font-size-sm;
+ font-weight: @font-weight-medium;
+ color: @text-secondary;
+}
+
+.current-badge {
+ font-size: @font-size-xs;
+ background: @color-success;
+ color: #fff;
+ padding: 1px 6px;
+ border-radius: @radius-sm;
+}
+
+.commit-date {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-left: auto;
+}
+
+.commit-message {
+ font-size: @font-size-sm;
+ color: @text-primary;
+ margin: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.commit-author {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+}
+
+.commit-actions {
+ display: flex;
+ gap: @space-2;
+ flex-shrink: 0;
+}
+
+.commit-message-preview {
+ font-style: italic;
+ color: @text-secondary;
+ padding: @space-3;
+ background: @bg-tertiary;
+ border-radius: @radius-md;
+ margin: @space-3 0;
+}
+
+// Git Commits Section
+.git-commits-section {
+ margin-top: @space-6;
+ padding-top: @space-6;
+ border-top: 1px solid @border-subtle;
+}
+
+// Quick Actions
+.quick-actions-grid {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: @space-2;
+}
+
+.quick-action-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: @space-2;
+ padding: @space-3;
+ background: @bg-tertiary;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-md;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ font-weight: @font-weight-medium;
+ text-decoration: none;
+ transition: all 0.15s ease;
+
+ &:hover {
+ background: @bg-hover;
+ border-color: @border-hover;
+ color: @text-primary;
+ }
+}
+
+// Hint Box
+.hint-box {
+ padding: @space-4;
+ background: @bg-tertiary;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-md;
+ margin-top: @space-4;
+
+ p {
+ margin: 0;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+
+ &:not(:last-child) {
+ margin-bottom: @space-2;
+ }
+ }
+}
+
+// Empty State Small
+.empty-state-small {
+ padding: @space-6;
+ text-align: center;
+ color: @text-tertiary;
+
+ p {
+ margin: 0;
+
+ &:not(:last-child) {
+ margin-bottom: @space-2;
+ }
+ }
+
+ .hint {
+ font-size: @font-size-sm;
+ }
+}
+
+// Spinning animation for sync button
+@keyframes spin {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.spinning {
+ animation: spin 1s linear infinite;
+}
+
+// ============================================
+// SKELETON LOADING STATES
+// ============================================
+
+@keyframes shimmer {
+ 0% {
+ background-position: -200% 0;
+ }
+ 100% {
+ background-position: 200% 0;
+ }
+}
+
+.skeleton {
+ background: linear-gradient(
+ 90deg,
+ @bg-tertiary 25%,
+ fade(@border-subtle, 50%) 50%,
+ @bg-tertiary 75%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.5s infinite;
+ border-radius: @radius-md;
+}
+
+// Skeleton Site Card
+.wp-site-card-skeleton {
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+}
+
+.wp-site-card-skeleton-header {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ padding: @space-4;
+ border-bottom: 1px solid @border-subtle;
+}
+
+.wp-site-card-skeleton-icon {
+ width: 40px;
+ height: 40px;
+ border-radius: @radius-md;
+ .skeleton();
+}
+
+.wp-site-card-skeleton-info {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: @space-2;
+}
+
+.wp-site-card-skeleton-name {
+ width: 60%;
+ height: 16px;
+ .skeleton();
+}
+
+.wp-site-card-skeleton-url {
+ width: 80%;
+ height: 12px;
+ .skeleton();
+}
+
+.wp-site-card-skeleton-status {
+ width: 64px;
+ height: 24px;
+ border-radius: @radius-full;
+ .skeleton();
+}
+
+.wp-site-card-skeleton-body {
+ padding: @space-4;
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: @space-3;
+}
+
+.wp-site-card-skeleton-meta {
+ display: flex;
+ flex-direction: column;
+ gap: @space-1;
+}
+
+.wp-site-card-skeleton-label {
+ width: 50%;
+ height: 10px;
+ .skeleton();
+}
+
+.wp-site-card-skeleton-value {
+ width: 70%;
+ height: 14px;
+ .skeleton();
+}
+
+.wp-site-card-skeleton-footer {
+ display: flex;
+ gap: @space-2;
+ padding: @space-3 @space-4;
+ border-top: 1px solid @border-subtle;
+ background: @bg-tertiary;
+ border-radius: 0 0 @radius-lg @radius-lg;
+}
+
+.wp-site-card-skeleton-btn {
+ flex: 1;
+ height: 32px;
+ .skeleton();
+}
+
+// Skeleton Environment Card
+.wp-env-card-skeleton {
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+}
+
+.wp-env-card-skeleton-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: @space-4;
+ border-bottom: 1px solid @border-subtle;
+}
+
+.wp-env-card-skeleton-badge {
+ width: 60px;
+ height: 20px;
+ border-radius: @radius-sm;
+ .skeleton();
+}
+
+.wp-env-card-skeleton-status {
+ width: 64px;
+ height: 20px;
+ border-radius: @radius-sm;
+ .skeleton();
+}
+
+.wp-env-card-skeleton-body {
+ padding: @space-4;
+}
+
+.wp-env-card-skeleton-url {
+ width: 70%;
+ height: 14px;
+ margin-bottom: @space-3;
+ .skeleton();
+}
+
+.wp-env-card-skeleton-meta {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: @space-2;
+}
+
+.wp-env-card-skeleton-meta-item {
+ .skeleton-label {
+ width: 40%;
+ height: 10px;
+ margin-bottom: 4px;
+ .skeleton();
+ }
+
+ .skeleton-value {
+ width: 60%;
+ height: 14px;
+ .skeleton();
+ }
+}
+
+.wp-env-card-skeleton-footer {
+ display: flex;
+ gap: @space-2;
+ padding: @space-3 @space-4;
+ border-top: 1px solid @border-subtle;
+ background: @bg-tertiary;
+ border-radius: 0 0 @radius-lg @radius-lg;
+}
+
+// Skeleton Stat Card
+.docker-stat-card-skeleton {
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+ padding: @space-4;
+ display: flex;
+ flex-direction: column;
+ gap: @space-2;
+}
+
+.docker-stat-card-skeleton-label {
+ width: 60%;
+ height: 12px;
+ .skeleton();
+}
+
+.docker-stat-card-skeleton-value {
+ width: 40%;
+ height: 28px;
+ .skeleton();
+}
+
+.docker-stat-card-skeleton-meta {
+ width: 80%;
+ height: 12px;
+ .skeleton();
+}
+
+// Skeleton Table Row
+.skeleton-table-row {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ padding: @space-3 @space-4;
+ border-bottom: 1px solid @border-subtle;
+
+ .skeleton-cell {
+ height: 16px;
+ .skeleton();
+
+ &.cell-name { width: 25%; }
+ &.cell-tag { width: 15%; }
+ &.cell-size { width: 10%; }
+ &.cell-date { width: 15%; }
+ &.cell-actions { width: 20%; margin-left: auto; }
+ }
+}
+
+// Tab Content Loading
+.tab-loading {
+ display: flex;
+ flex-direction: column;
+ gap: @space-4;
+ padding: @space-4;
+}
+
+.tab-loading-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: @space-2;
+}
+
+.tab-loading-title {
+ width: 120px;
+ height: 24px;
+ .skeleton();
+}
+
+.tab-loading-btn {
+ width: 140px;
+ height: 36px;
+ border-radius: @radius-md;
+ .skeleton();
+}
+
+// ============================================
+// ERROR STATES
+// ============================================
+
+.error-boundary,
+.error-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: @space-8;
+ text-align: center;
+ min-height: 200px;
+}
+
+.error-boundary-icon,
+.error-state-icon {
+ color: @color-danger;
+ margin-bottom: @space-4;
+ padding: @space-3;
+ background: fade(@color-danger, 10%);
+ border-radius: 50%;
+}
+
+.error-boundary h3,
+.error-state-title {
+ font-size: @font-size-lg;
+ font-weight: @font-weight-semibold;
+ color: @text-primary;
+ margin: 0 0 @space-2;
+}
+
+.error-boundary-message,
+.error-state-message {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ margin: 0 0 @space-4;
+ max-width: 400px;
+}
+
+.error-state-compact {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ padding: @space-3 @space-4;
+ background: fade(@color-danger, 8%);
+ border: 1px solid fade(@color-danger, 20%);
+ border-radius: @radius-md;
+ color: @color-danger;
+ font-size: @font-size-sm;
+
+ svg {
+ flex-shrink: 0;
+ }
+
+ span {
+ flex: 1;
+ }
+
+ .btn {
+ flex-shrink: 0;
+ }
+}
+
+// ============================================
+// CONFIRM DIALOG ENHANCEMENTS
+// ============================================
+
+.confirm-dialog-details {
+ margin-top: @space-3;
+ padding: @space-3;
+ background: @bg-tertiary;
+ border-radius: @radius-md;
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ text-align: left;
+
+ ul {
+ margin: 0;
+ padding-left: @space-4;
+
+ li {
+ margin-bottom: @space-1;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+ }
+
+ strong {
+ color: @text-primary;
+ }
+
+ code {
+ background: @bg-code;
+ padding: 2px 6px;
+ border-radius: 3px;
+ font-family: @font-family-mono;
+ font-size: 0.9em;
+ }
+}
+
+// Environment Preview URL in Create Modal
+.env-preview-url {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ padding: @space-3;
+ background: fade(@color-success, 8%);
+ border: 1px solid fade(@color-success, 20%);
+ border-radius: @radius-md;
+ margin-bottom: @space-4;
+
+ .preview-label {
+ font-size: @font-size-xs;
+ color: @text-secondary;
+ }
+
+ .preview-url {
+ font-family: @font-family-mono;
+ font-size: @font-size-sm;
+ color: @color-success;
+ font-weight: @font-weight-medium;
+ }
+}
+
+.form-hint-domain {
+ code {
+ background: @bg-code;
+ padding: 2px 6px;
+ border-radius: 3px;
+ font-family: @font-family-mono;
+ font-size: 0.9em;
+ }
+}
+
+.confirm-dialog-input {
+ margin-top: @space-4;
+ text-align: left;
+
+ label {
+ display: block;
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ margin-bottom: @space-2;
+
+ strong {
+ color: @text-primary;
+ font-family: @font-family-mono;
+ }
+ }
+
+ input {
+ width: 100%;
+ padding: @space-3;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-md;
+ font-size: @font-size-base;
+ background: @bg-input;
+ color: @text-primary;
+
+ &:focus {
+ outline: none;
+ border-color: @color-primary;
+ box-shadow: 0 0 0 3px fade(@color-primary, 15%);
+ }
+
+ &::placeholder {
+ color: @text-tertiary;
+ }
+ }
+}