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.

feat(wordpress): monthly client reports — persisted per-month rollups (#33)

Juan Denis1926416f27f2
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index ef1cf849..38b3d9cb 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -712,6 +712,56 @@ def set_site_update_schedule(app_id):
}), 200
+# ---- Monthly client reports (#33 agency slice): persisted per-month rollups ----
+
+@wordpress_bp.route('/sites/<int:app_id>/reports', methods=['GET'])
+@jwt_required()
+def get_site_reports(app_id):
+ """Return all persisted monthly reports for a site (newest month first)."""
+ from app.services.wp_reports_service import WpReportsService
+ app, err = _owner_or_admin_app(app_id)
+ if err:
+ return err
+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
+ if not wp_site:
+ return jsonify({'error': 'Not a WordPress site'}), 400
+ return jsonify(WpReportsService.get_reports(wp_site)), 200
+
+
+@wordpress_bp.route('/sites/<int:app_id>/reports/generate', methods=['POST'])
+@jwt_required()
+@admin_required
+def generate_site_report(app_id):
+ """Generate (or regenerate) the monthly report for a site. Body may carry
+ {year, month}; defaults to the current UTC month."""
+ from app.services.wp_reports_service import WpReportsService
+ app = _resolve_app(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
+ if not wp_site:
+ return jsonify({'error': 'Not a WordPress site'}), 400
+ data = request.get_json() or {}
+ result = WpReportsService.generate(wp_site, year=data.get('year'), month=data.get('month'))
+ return jsonify(result), (200 if result.get('success') else 400)
+
+
+@wordpress_bp.route('/sites/<int:app_id>/reports/<int:report_id>', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def delete_site_report(app_id, report_id):
+ """Delete one persisted monthly report."""
+ from app.services.wp_reports_service import WpReportsService
+ app = _resolve_app(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
+ if not wp_site:
+ return jsonify({'error': 'Not a WordPress site'}), 400
+ result = WpReportsService.delete(wp_site, report_id)
+ return jsonify(result), (200 if result.get('success') else 404)
+
+
@wordpress_bp.route('/sites/<int:app_id>/info', methods=['GET'])
@jwt_required()
def get_wordpress_info(app_id):
diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py
index b601caa3..4653b394 100644
--- a/backend/app/models/wordpress_site.py
+++ b/backend/app/models/wordpress_site.py
@@ -103,6 +103,7 @@ class WordPressSite(db.Model):
snapshots = db.relationship('DatabaseSnapshot', backref='site', lazy='dynamic', cascade='all, delete-orphan')
vulnerabilities = db.relationship('WordPressVulnerability', backref='site', lazy='dynamic', cascade='all, delete-orphan')
update_runs = db.relationship('WordPressUpdateRun', backref='site', lazy='dynamic', cascade='all, delete-orphan')
+ reports = db.relationship('WordPressReport', backref='site', lazy='dynamic', cascade='all, delete-orphan')
sync_jobs_as_source = db.relationship(
'SyncJob',
foreign_keys='SyncJob.source_site_id',
@@ -389,3 +390,50 @@ class WordPressUpdateRun(db.Model):
def __repr__(self):
return f'<WordPressUpdateRun {self.id} site={self.site_id} {self.status}>'
+
+
+class WordPressReport(db.Model):
+ """A persisted monthly client report for a WordPress site (#33 — agency
+ reports slice): a point-in-time snapshot of the site's uptime, incidents,
+ update runs, backups, and security posture for one calendar month.
+
+ Why this is persisted rather than computed live on every view: some of the
+ underlying sources are point-in-time, not historical. Vulnerability findings
+ (#28) are deleted-and-replaced on each scan, and the live health/disk values
+ only reflect "now" — so a report regenerated months later would otherwise
+ show the wrong month's posture. Generating a report snapshots the computed
+ aggregates into `data` here, so the historical record stays truthful. The
+ true-historical sources (HealthCheck uptime samples #26, WordPressUpdateRun
+ #29, DatabaseSnapshot backups) are re-aggregated from their own tables for
+ the month at generation time.
+ """
+
+ __tablename__ = 'wordpress_reports'
+
+ id = db.Column(db.Integer, primary_key=True)
+ site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False, index=True)
+
+ # Calendar-month window (naive UTC, matching every other timestamp in the app).
+ # period_label is "YYYY-MM" and is unique per site (regenerating replaces the row).
+ period_label = db.Column(db.String(7), nullable=False) # e.g. "2026-05"
+ period_start = db.Column(db.DateTime, nullable=False) # first of month, 00:00 UTC
+ period_end = db.Column(db.DateTime, nullable=False) # first of next month (exclusive)
+
+ # The full aggregated payload (JSON). Schema is owned by WpReportsService.
+ data = db.Column(db.Text)
+
+ generated_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'site_id': self.site_id,
+ 'period_label': self.period_label,
+ 'period_start': self.period_start.isoformat() if self.period_start else None,
+ 'period_end': self.period_end.isoformat() if self.period_end else None,
+ 'data': json.loads(self.data) if self.data else {},
+ 'generated_at': self.generated_at.isoformat() if self.generated_at else None,
+ }
+
+ def __repr__(self):
+ return f'<WordPressReport {self.id} site={self.site_id} {self.period_label}>'
diff --git a/backend/app/services/wp_reports_service.py b/backend/app/services/wp_reports_service.py
new file mode 100644
index 00000000..86bd0c1d
--- /dev/null
+++ b/backend/app/services/wp_reports_service.py
@@ -0,0 +1,363 @@
+"""Monthly client reports for managed WordPress sites (#33 — agency-scale slice).
+
+Aggregates the per-site signals that already accrue elsewhere in the panel into
+a single, client-presentable monthly report and persists it (see the docstring
+on the WordPressReport model for *why* it's persisted rather than computed live).
+
+Data-source honesty (this is the whole point of the feature):
+ * Uptime % + incidents (#26) -> TRUE month history, re-aggregated from the
+ retained HealthCheck samples (90-day retention) for the exact month.
+ * Update runs (#29) -> TRUE month history (WordPressUpdateRun rows).
+ * Database snapshots/backups -> TRUE month history (DatabaseSnapshot rows).
+ * Vulnerabilities (#28) -> CURRENT posture only (findings are
+ deleted-and-replaced each scan), captured as-of generation time.
+ * Health / disk -> CURRENT values, captured as-of generation.
+ * Traffic (#25) / on-demand security scans (#30) -> point-in-time, omitted
+ from monthly history (and a note says so).
+
+Generation is synchronous: it is pure DB aggregation (no WP-CLI, no external
+HTTP), so unlike the scan/update services it needs no background thread.
+"""
+
+import calendar
+import json
+from datetime import datetime, timedelta
+
+
+class WpReportsService:
+ """Build + persist + fetch monthly client reports for a WordPress site."""
+
+ # ---- public API -------------------------------------------------------
+
+ @classmethod
+ def get_reports(cls, site):
+ """Return all persisted reports for a site, newest month first."""
+ from app.models.wordpress_site import WordPressReport
+ rows = (WordPressReport.query
+ .filter_by(site_id=site.id)
+ .order_by(WordPressReport.period_start.desc())
+ .all())
+ return {'success': True, 'reports': [r.to_dict() for r in rows]}
+
+ @classmethod
+ def generate(cls, site, year=None, month=None):
+ """Compute + upsert the report for one calendar month (default: the
+ current UTC month). Regenerating the same month replaces its row so the
+ latest posture is captured. Returns {'success', 'report'} or an error."""
+ from app import db
+ from app.models.wordpress_site import WordPressReport
+
+ now = datetime.utcnow()
+ year = int(year) if year else now.year
+ month = int(month) if month else now.month
+ if month < 1 or month > 12:
+ return {'success': False, 'error': 'Invalid month'}
+ # Guard against generating a report for a future month (no data exists).
+ if (year, month) > (now.year, now.month):
+ return {'success': False, 'error': 'Cannot generate a report for a future month'}
+
+ start, end = cls._month_bounds(year, month)
+ label = f'{year:04d}-{month:02d}'
+ data = cls._build(site, start, end, label)
+
+ row = WordPressReport.query.filter_by(site_id=site.id, period_label=label).first()
+ if row is None:
+ row = WordPressReport(site_id=site.id, period_label=label,
+ period_start=start, period_end=end)
+ db.session.add(row)
+ row.period_start = start
+ row.period_end = end
+ row.data = json.dumps(data)
+ row.generated_at = now
+ db.session.commit()
+ return {'success': True, 'report': row.to_dict()}
+
+ @classmethod
+ def delete(cls, site, report_id):
+ """Delete one persisted report belonging to this site."""
+ from app import db
+ from app.models.wordpress_site import WordPressReport
+ row = WordPressReport.query.filter_by(id=report_id, site_id=site.id).first()
+ if row is None:
+ return {'success': False, 'error': 'Report not found'}
+ db.session.delete(row)
+ db.session.commit()
+ return {'success': True}
+
+ # ---- report builder ---------------------------------------------------
+
+ @classmethod
+ def _build(cls, site, start, end, label):
+ now = datetime.utcnow()
+ tags = []
+ try:
+ tags = json.loads(site.tags) if site.tags else []
+ except (ValueError, TypeError):
+ tags = []
+
+ uptime, daily, incidents = cls._uptime_and_incidents(site, start, end, now)
+ report = {
+ 'period': {
+ 'label': label,
+ 'start': start.isoformat(),
+ 'end': end.isoformat(),
+ 'month_name': f'{calendar.month_name[start.month]} {start.year}',
+ },
+ 'generated_at': now.isoformat(),
+ 'site': {
+ 'id': site.id,
+ 'name': site.application.name if site.application else f'site-{site.id}',
+ 'url': cls._site_url(site),
+ 'wp_version': site.wp_version,
+ 'multisite': bool(site.multisite),
+ 'tags': tags,
+ 'client': cls._client_from_tags(tags),
+ },
+ 'uptime': uptime,
+ 'uptime_daily': daily,
+ 'incidents': incidents,
+ 'incident_count': len(incidents),
+ 'updates': cls._updates(site, start, end),
+ 'backups': cls._backups(site, start, end),
+ 'vulnerabilities': cls._vuln_posture(site),
+ 'health': cls._health(site),
+ 'notes': cls._notes(uptime),
+ }
+ return report
+
+ # ---- sections ---------------------------------------------------------
+
+ @classmethod
+ def _uptime_and_incidents(cls, site, start, end, now):
+ """Re-aggregate the month's uptime % + a daily series + the incidents that
+ overlapped the month, from the bound status-page component's samples (#26).
+ Returns (uptime_dict, daily_list, incidents_list)."""
+ from app.models.status_page import StatusComponent, HealthCheck, StatusIncident
+ from sqlalchemy import or_
+
+ comp = StatusComponent.query.filter_by(wordpress_site_id=site.id).first()
+ if comp is None:
+ return ({'bound': False, 'percent': None, 'samples': 0,
+ 'checks_up': 0, 'checks_down': 0, 'checks_degraded': 0,
+ 'rolling_30d': None}, [], [])
+
+ checks = (HealthCheck.query
+ .filter(HealthCheck.component_id == comp.id,
+ HealthCheck.checked_at >= start,
+ HealthCheck.checked_at < end)
+ .all())
+ total = len(checks)
+ up = sum(1 for c in checks if c.status == 'up')
+ down = sum(1 for c in checks if c.status == 'down')
+ degraded = sum(1 for c in checks if c.status == 'degraded')
+ uptime = {
+ 'bound': True,
+ 'percent': round(up / total * 100, 2) if total else None,
+ 'samples': total,
+ 'checks_up': up,
+ 'checks_down': down,
+ 'checks_degraded': degraded,
+ 'rolling_30d': comp.uptime_30d,
+ }
+
+ # Daily uptime series — only the up/total ratio per calendar day. Uses the
+ # same "only 'up' counts" rule as recompute_uptime, so degraded reduces it.
+ buckets = {}
+ for c in checks:
+ key = c.checked_at.date().isoformat()
+ b = buckets.setdefault(key, {'up': 0, 'total': 0})
+ b['total'] += 1
+ if c.status == 'up':
+ b['up'] += 1
+ daily = []
+ day = start
+ # Stop at the end of *today* (today is included as a partial day) and never
+ # emit a future day. Truncate `now` to its date first — otherwise its
+ # time-of-day pushes the bound past tomorrow's midnight for a to-date month.
+ today_end = datetime(now.year, now.month, now.day) + timedelta(days=1)
+ last = min(end, today_end)
+ while day < last:
+ key = day.date().isoformat()
+ b = buckets.get(key)
+ daily.append({
+ 'date': key,
+ 'percent': round(b['up'] / b['total'] * 100, 2) if b and b['total'] else None,
+ 'samples': b['total'] if b else 0,
+ })
+ day += timedelta(days=1)
+
+ incident_rows = (StatusIncident.query
+ .filter(StatusIncident.component_id == comp.id,
+ StatusIncident.created_at < end,
+ or_(StatusIncident.resolved_at.is_(None),
+ StatusIncident.resolved_at >= start))
+ .order_by(StatusIncident.created_at.desc())
+ .all())
+ incidents = []
+ for inc in incident_rows:
+ resolved = inc.resolved_at
+ # Attribute only the in-month portion of the incident to this report:
+ # clamp the window to [start, min(end, now)] so a still-open or
+ # cross-month incident doesn't bleed its full elapsed time into the
+ # month it's reported under. created_at/resolved_at below stay raw.
+ if inc.created_at:
+ ref_start = max(inc.created_at, start)
+ ref_end = min(resolved or now, end, now)
+ minutes = max(0, int((ref_end - ref_start).total_seconds() // 60))
+ else:
+ minutes = 0
+ incidents.append({
+ 'id': inc.id,
+ 'title': inc.title,
+ 'impact': inc.impact,
+ 'status': inc.status,
+ 'ongoing': resolved is None,
+ 'created_at': inc.created_at.isoformat() if inc.created_at else None,
+ 'resolved_at': resolved.isoformat() if resolved else None,
+ 'duration_minutes': minutes,
+ })
+ return uptime, daily, incidents
+
+ @classmethod
+ def _updates(cls, site, start, end):
+ from app.models.wordpress_site import WordPressUpdateRun
+ runs = (WordPressUpdateRun.query
+ .filter(WordPressUpdateRun.site_id == site.id,
+ WordPressUpdateRun.started_at >= start,
+ WordPressUpdateRun.started_at < end)
+ .order_by(WordPressUpdateRun.started_at.desc())
+ .all())
+ out = {'total_runs': len(runs), 'completed': 0, 'rolled_back': 0,
+ 'failed': 0, 'components_updated': 0, 'runs': []}
+ for r in runs:
+ if r.status in out:
+ out[r.status] += 1
+ try:
+ details = json.loads(r.details) if r.details else {}
+ except (ValueError, TypeError):
+ details = {}
+ updated = details.get('updated') or []
+ out['components_updated'] += len(updated)
+ out['runs'].append({
+ 'id': r.id,
+ 'status': r.status,
+ 'trigger': r.trigger,
+ 'started_at': r.started_at.isoformat() if r.started_at else None,
+ 'finished_at': r.finished_at.isoformat() if r.finished_at else None,
+ 'updated': updated,
+ 'rolled_back': bool(details.get('rolled_back')),
+ 'error': r.error,
+ })
+ return out
+
+ @classmethod
+ def _backups(cls, site, start, end):
+ from app.models.wordpress_site import DatabaseSnapshot
+ snaps = (DatabaseSnapshot.query
+ .filter(DatabaseSnapshot.site_id == site.id,
+ DatabaseSnapshot.created_at >= start,
+ DatabaseSnapshot.created_at < end)
+ .order_by(DatabaseSnapshot.created_at.desc())
+ .all())
+ total_bytes = sum((s.size_bytes or 0) for s in snaps)
+ return {
+ 'count': len(snaps),
+ 'total_bytes': total_bytes,
+ 'total_bytes_human': DatabaseSnapshot._format_size(total_bytes),
+ 'snapshots': [{
+ 'id': s.id,
+ 'name': s.name,
+ 'tag': s.tag,
+ 'status': s.status,
+ 'size_bytes': s.size_bytes,
+ 'size_human': DatabaseSnapshot._format_size(s.size_bytes),
+ 'created_at': s.created_at.isoformat() if s.created_at else None,
+ } for s in snaps],
+ }
+
+ @classmethod
+ def _vuln_posture(cls, site):
+ """Current open-vulnerability posture as-of the last scan. NOT month
+ history — findings are overwritten on each scan (see #28)."""
+ from app.models.wordpress_site import WordPressVulnerability
+ vulns = WordPressVulnerability.query.filter_by(site_id=site.id).all()
+ by_sev = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'unknown': 0}
+ items = []
+ for v in vulns:
+ sev = v.severity if v.severity in by_sev else 'unknown'
+ by_sev[sev] += 1
+ items.append({
+ 'source': v.source,
+ 'slug': v.slug,
+ 'name': v.name,
+ 'installed_version': v.installed_version,
+ 'severity': v.severity,
+ 'advisory_id': v.advisory_id,
+ 'fixed_in': v.fixed_in,
+ 'reference_url': v.reference_url,
+ })
+ return {
+ 'as_of': site.last_vuln_scan_at.isoformat() if site.last_vuln_scan_at else None,
+ 'total': len(items),
+ 'by_severity': by_sev,
+ 'items': items,
+ }
+
+ @classmethod
+ def _health(cls, site):
+ from app.models.wordpress_site import DatabaseSnapshot
+ return {
+ 'status': site.health_status,
+ 'checked_at': site.last_health_check.isoformat() if site.last_health_check else None,
+ 'disk_usage_bytes': site.disk_usage_bytes,
+ 'disk_usage_human': (DatabaseSnapshot._format_size(site.disk_usage_bytes)
+ if site.disk_usage_bytes else None),
+ }
+
+ @classmethod
+ def _notes(cls, uptime):
+ notes = [
+ 'Vulnerability posture is the current snapshot as of the last scan, '
+ 'not month-historical — findings are overwritten on each scan.',
+ 'Traffic analytics and on-demand security scans are point-in-time and '
+ 'are not included in monthly history.',
+ ]
+ if not uptime.get('bound'):
+ notes.append('Uptime history is unavailable for this period — attach the '
+ 'site to a status page (Uptime tab) so uptime % can accrue.')
+ return notes
+
+ # ---- helpers ----------------------------------------------------------
+
+ @staticmethod
+ def _month_bounds(year, month):
+ """First-of-month .. first-of-next-month (exclusive), naive UTC."""
+ start = datetime(year, month, 1)
+ if month == 12:
+ end = datetime(year + 1, 1, 1)
+ else:
+ end = datetime(year, month + 1, 1)
+ return start, end
+
+ @staticmethod
+ def _client_from_tags(tags):
+ """Derive a client name from a `client-<name>` / `client:<name>` tag (#20)."""
+ for t in tags or []:
+ if not isinstance(t, str):
+ continue
+ low = t.lower()
+ if low.startswith('client-'):
+ return t[len('client-'):] or None
+ if low.startswith('client:'):
+ return t[len('client:'):] or None
+ return None
+
+ @staticmethod
+ def _site_url(site):
+ app = site.application
+ domains = list(getattr(app, 'domains', None) or []) if app else []
+ if not domains:
+ return None
+ primary = next((d for d in domains if getattr(d, 'is_primary', False)), domains[0])
+ scheme = 'https' if getattr(primary, 'ssl_enabled', False) else 'http'
+ return f'{scheme}://{primary.name}'
diff --git a/backend/migrations/versions/014_wordpress_reports.py b/backend/migrations/versions/014_wordpress_reports.py
new file mode 100644
index 00000000..7a9c4882
--- /dev/null
+++ b/backend/migrations/versions/014_wordpress_reports.py
@@ -0,0 +1,45 @@
+"""Monthly client reports (#33 — agency-scale reports slice).
+
+Adds:
+- table wordpress_reports (one persisted report per site per calendar month,
+ FK site_id -> wordpress_sites.id)
+
+Idempotent: MigrationService._fix_missing_columns runs db.create_all() on boot
+before Alembic, so the table may already exist — guard on the live schema
+exactly like 009/010/011/012/013.
+
+Revision ID: 014_wordpress_reports
+Revises: 013_ai_assistant
+Create Date: 2026-06-01
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '014_wordpress_reports'
+down_revision = '013_ai_assistant'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+
+ if 'wordpress_reports' not in inspector.get_table_names():
+ op.create_table(
+ 'wordpress_reports',
+ sa.Column('id', sa.Integer(), primary_key=True),
+ sa.Column('site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False, index=True),
+ sa.Column('period_label', sa.String(length=7), nullable=False),
+ sa.Column('period_start', sa.DateTime(), nullable=False),
+ sa.Column('period_end', sa.DateTime(), nullable=False),
+ sa.Column('data', sa.Text()),
+ sa.Column('generated_at', sa.DateTime()),
+ )
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'wordpress_reports' in inspector.get_table_names():
+ op.drop_table('wordpress_reports')
diff --git a/backend/tests/test_wp_reports.py b/backend/tests/test_wp_reports.py
new file mode 100644
index 00000000..db983fda
--- /dev/null
+++ b/backend/tests/test_wp_reports.py
@@ -0,0 +1,261 @@
+"""Tests for the WordPress monthly client reports service + API (#33 slice)."""
+from datetime import datetime, timedelta
+
+import pytest
+
+
+def _mk_user(db, username='owner'):
+ from app.models import User
+ from werkzeug.security import generate_password_hash
+ u = User(email=f'{username}@test.local', username=username,
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _mk_site(db, user_id, name='acme-prod', tags=None):
+ import json
+ from app.models import Application, WordPressSite
+ app_row = Application(name=name, app_type='wordpress', user_id=user_id, root_path='/srv/x')
+ db.session.add(app_row)
+ db.session.commit()
+ site = WordPressSite(application_id=app_row.id, wp_version='6.4',
+ tags=json.dumps(tags) if tags else None,
+ health_status='healthy', last_health_check=datetime.utcnow())
+ db.session.add(site)
+ db.session.commit()
+ return app_row, site
+
+
+def _current_month():
+ now = datetime.utcnow()
+ return now.year, now.month, now
+
+
+# ---- pure helpers ---------------------------------------------------------
+
+def test_month_bounds_normal_and_december():
+ from app.services.wp_reports_service import WpReportsService
+ start, end = WpReportsService._month_bounds(2026, 5)
+ assert start == datetime(2026, 5, 1)
+ assert end == datetime(2026, 6, 1)
+ # December must roll over the year, not crash.
+ start, end = WpReportsService._month_bounds(2026, 12)
+ assert start == datetime(2026, 12, 1)
+ assert end == datetime(2027, 1, 1)
+
+
+def test_client_from_tags():
+ from app.services.wp_reports_service import WpReportsService
+ assert WpReportsService._client_from_tags(['retainer', 'client-acme']) == 'acme'
+ assert WpReportsService._client_from_tags(['client:Globex']) == 'Globex'
+ assert WpReportsService._client_from_tags(['php8', 'retainer']) is None
+ assert WpReportsService._client_from_tags(None) is None
+
+
+# ---- end-to-end aggregation ----------------------------------------------
+
+def test_generate_aggregates_bound_site(app):
+ import json
+ from app import db
+ from app.services.wp_reports_service import WpReportsService
+ from app.models.status_page import StatusPage, StatusComponent, HealthCheck
+ from app.models.wordpress_site import WordPressUpdateRun, DatabaseSnapshot, WordPressVulnerability
+
+ user = _mk_user(db)
+ _, site = _mk_site(db, user.id, tags=['client-acme', 'retainer'])
+ year, month, now = _current_month()
+
+ # Bound status-page component + 10 health checks (8 up, 1 degraded, 1 down) -> 80% uptime.
+ page = StatusPage(name='Status', slug='status')
+ db.session.add(page)
+ db.session.commit()
+ comp = StatusComponent(page_id=page.id, name='acme', wordpress_site_id=site.id, uptime_30d=88.5)
+ db.session.add(comp)
+ db.session.commit()
+ statuses = ['up'] * 8 + ['degraded', 'down']
+ for s in statuses:
+ db.session.add(HealthCheck(component_id=comp.id, status=s, checked_at=now))
+ # Update runs in-month: 1 completed (2 comps), 1 rolled_back (1 comp), 1 failed.
+ db.session.add(WordPressUpdateRun(site_id=site.id, status='completed', trigger='manual',
+ started_at=now, details=json.dumps({'updated': [{'type': 'plugin', 'slug': 'a', 'from': '1', 'to': '2'}, {'type': 'theme', 'slug': 'b', 'from': '1', 'to': '2'}]})))
+ db.session.add(WordPressUpdateRun(site_id=site.id, status='rolled_back', trigger='scheduled',
+ started_at=now, details=json.dumps({'updated': [{'type': 'plugin', 'slug': 'c', 'from': '1', 'to': '2'}], 'rolled_back': True})))
+ db.session.add(WordPressUpdateRun(site_id=site.id, status='failed', trigger='manual',
+ started_at=now, details=None, error='boom'))
+ # Backups in-month.
+ db.session.add(DatabaseSnapshot(site_id=site.id, name='snap1', file_path='/x/1.sql', size_bytes=100, tag='pre-deploy', created_at=now))
+ db.session.add(DatabaseSnapshot(site_id=site.id, name='snap2', file_path='/x/2.sql', size_bytes=200, created_at=now))
+ # Current vuln posture.
+ db.session.add(WordPressVulnerability(site_id=site.id, source='plugin', slug='a', name='Plugin A', severity='high'))
+ db.session.add(WordPressVulnerability(site_id=site.id, source='core', slug='', name='WP', severity='medium'))
+ site.last_vuln_scan_at = now
+ db.session.commit()
+
+ res = WpReportsService.generate(site, year=year, month=month)
+ assert res['success'] is True
+ data = res['report']['data']
+
+ assert data['site']['client'] == 'acme'
+ assert data['uptime']['bound'] is True
+ assert data['uptime']['samples'] == 10
+ assert data['uptime']['percent'] == 80.0
+ assert data['uptime']['rolling_30d'] == 88.5
+
+ u = data['updates']
+ assert u['total_runs'] == 3
+ assert u['completed'] == 1 and u['rolled_back'] == 1 and u['failed'] == 1
+ assert u['components_updated'] == 3
+
+ assert data['backups']['count'] == 2
+ assert data['backups']['total_bytes'] == 300
+
+ assert data['vulnerabilities']['total'] == 2
+ assert data['vulnerabilities']['by_severity']['high'] == 1
+ assert data['vulnerabilities']['by_severity']['medium'] == 1
+ assert data['vulnerabilities']['as_of'] is not None
+
+ # A daily series spanning the month, with at least one populated day.
+ assert any(d['samples'] > 0 for d in data['uptime_daily'])
+
+
+def test_generate_unbound_site_has_no_uptime_history(app):
+ from app import db
+ from app.services.wp_reports_service import WpReportsService
+
+ user = _mk_user(db, 'owner2')
+ _, site = _mk_site(db, user.id, name='nobound')
+ year, month, _ = _current_month()
+
+ res = WpReportsService.generate(site, year=year, month=month)
+ assert res['success'] is True
+ data = res['report']['data']
+ assert data['uptime']['bound'] is False
+ assert data['uptime']['percent'] is None
+ # The "attach to a status page" note must be present so the gap is explained.
+ assert any('Uptime history is unavailable' in n for n in data['notes'])
+
+
+def test_generate_is_upsert(app):
+ from app import db
+ from app.services.wp_reports_service import WpReportsService
+ from app.models.wordpress_site import WordPressReport
+
+ user = _mk_user(db, 'owner3')
+ _, site = _mk_site(db, user.id, name='upsert')
+ year, month, _ = _current_month()
+
+ WpReportsService.generate(site, year=year, month=month)
+ WpReportsService.generate(site, year=year, month=month)
+ rows = WordPressReport.query.filter_by(site_id=site.id).all()
+ assert len(rows) == 1 # regenerating the same month replaces, not duplicates
+
+
+def test_generate_rejects_future_month(app):
+ from app import db
+ from app.services.wp_reports_service import WpReportsService
+
+ user = _mk_user(db, 'owner4')
+ _, site = _mk_site(db, user.id, name='future')
+ now = datetime.utcnow()
+ res = WpReportsService.generate(site, year=now.year + 1, month=1)
+ assert res['success'] is False
+ assert 'future' in res['error'].lower()
+
+
+def test_daily_series_never_emits_a_future_day(app):
+ """Regression: the to-date daily series must stop at today, not tomorrow."""
+ from app import db
+ from app.services.wp_reports_service import WpReportsService
+ from app.models.status_page import StatusPage, StatusComponent
+
+ user = _mk_user(db, 'owner5')
+ _, site = _mk_site(db, user.id, name='daily')
+ page = StatusPage(name='S', slug='s-daily')
+ db.session.add(page)
+ db.session.commit()
+ db.session.add(StatusComponent(page_id=page.id, name='c', wordpress_site_id=site.id))
+ db.session.commit()
+
+ year, month, now = _current_month()
+ res = WpReportsService.generate(site, year=year, month=month)
+ daily = res['report']['data']['uptime_daily']
+ assert daily, 'a bound site should produce a daily series'
+ today = now.date().isoformat()
+ assert all(d['date'] <= today for d in daily)
+ assert daily[-1]['date'] == today # today is included as a partial day
+
+
+def test_ongoing_incident_duration_is_clamped_to_the_month(app):
+ """Regression: a still-open incident in a PAST-month report must not bleed
+ its full elapsed time (up to now) into that month's attributed duration."""
+ from datetime import datetime, timedelta
+ from app import db
+ from app.services.wp_reports_service import WpReportsService
+ from app.models.status_page import StatusPage, StatusComponent, StatusIncident
+
+ now = datetime.utcnow()
+ first_this = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ prev_start = (first_this - timedelta(days=1)).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ prev_end = first_this
+
+ user = _mk_user(db, 'owner6')
+ _, site = _mk_site(db, user.id, name='inc')
+ page = StatusPage(name='S', slug='s-inc')
+ db.session.add(page)
+ db.session.commit()
+ comp = StatusComponent(page_id=page.id, name='c', wordpress_site_id=site.id)
+ db.session.add(comp)
+ db.session.commit()
+ # An incident opened early in the previous month and never resolved.
+ created = prev_start + timedelta(days=1)
+ db.session.add(StatusIncident(page_id=page.id, component_id=comp.id, title='down',
+ impact='major', created_at=created, resolved_at=None))
+ db.session.commit()
+
+ res = WpReportsService.generate(site, year=prev_start.year, month=prev_start.month)
+ incidents = res['report']['data']['incidents']
+ assert len(incidents) == 1
+ inc = incidents[0]
+ assert inc['ongoing'] is True
+ # Duration is capped at the month boundary, NOT (now - created).
+ in_month_cap = int((prev_end - created).total_seconds() // 60)
+ full_elapsed = int((now - created).total_seconds() // 60)
+ assert inc['duration_minutes'] <= in_month_cap
+ assert inc['duration_minutes'] < full_elapsed
+
+
+# ---- API route ------------------------------------------------------------
+
+def test_reports_api_roundtrip(app, client, auth_headers):
+ from app import db
+ from app.models import User
+
+ admin = User.query.filter_by(username='testadmin').first()
+ _, site = _mk_site(db, admin.id, name='api-site')
+ year, month, _ = _current_month()
+
+ # Empty before generation.
+ r = client.get(f'/api/v1/wordpress/sites/{site.id}/reports', headers=auth_headers)
+ assert r.status_code == 200
+ assert r.get_json()['reports'] == []
+
+ # Generate the current month.
+ r = client.post(f'/api/v1/wordpress/sites/{site.id}/reports/generate',
+ json={'year': year, 'month': month}, headers=auth_headers)
+ assert r.status_code == 200
+ body = r.get_json()
+ assert body['success'] is True
+ report_id = body['report']['id']
+
+ # Now listed.
+ r = client.get(f'/api/v1/wordpress/sites/{site.id}/reports', headers=auth_headers)
+ assert len(r.get_json()['reports']) == 1
+
+ # Delete it.
+ r = client.delete(f'/api/v1/wordpress/sites/{site.id}/reports/{report_id}', headers=auth_headers)
+ assert r.status_code == 200
+ r = client.get(f'/api/v1/wordpress/sites/{site.id}/reports', headers=auth_headers)
+ assert r.get_json()['reports'] == []
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 82887a77..96bbbfd6 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -291,12 +291,13 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c
- **Done when:** Each site exposes scoped SFTP credentials.
- **Assessment / why deferred:** The roadmap's host-sshd-chroot approach doesn't fit the Docker model — a managed site's files live in the `wordpress_html` **named volume**, not a host path, so a host-level chroot would target the wrong place. The **Docker-correct** design is a per-site **SFTP sidecar container** (e.g. `atmoz/sftp`) mounting `wordpress_html`, injected into the compose stack exactly like #23's redis (`_ensure_*_in_stack` + additive `compose up -d`), with a generated credential surfaced once and a new mapped port (via the template's port-allocation). That is genuinely implementable on the proven pattern — but it (a) opens a **publicly-exposed, security-sensitive file-access surface** that should be firewalled and that I cannot runtime-verify from the dev host, and (b) consumes a port + a container per site. Shipping security-sensitive infra blind violates the quality bar, so this is deferred for a focused pass on a real Docker host (where the sidecar, chroot perms, and firewall can be exercised). No code shipped.
-### #33 — Agency scale (workspaces, RBAC, white-label, reports) `[XL]` 🟡 — ⏸️ Deferred (XL epic — split into its own milestone; touches cross-cutting models + RBAC + reports)
+### #33 — Agency scale (workspaces, RBAC, white-label, reports) `[XL]` 🟡 — 🟡 In progress (reports slice ✅ shipped; `workspace_id` FKs + per-site ACL + server-side branding still deferred as a milestone)
- **Today:** No `workspace_id` FK on `Application`/`WordPressSite`/`Server`; permissions are global with no per-site ACL; white-label lives in `localStorage` and never reads `Workspace.logo_url`/`primary_color`.
- **Do:** Add `workspace_id` FKs + per-site ACL rows + environment-tier RBAC in promote/sync/bulk endpoints; server-side branding scoped to workspace; monthly client reports aggregating uptime/updates/backups/security.
- **Reuse:** `workspace_service`, `permission_service`, `audit_service`.
- **Done when:** A site/environment can be scoped to a workspace with per-site roles and branded reports.
-- **Assessment / why deferred:** A genuine **`XL`** multi-day epic (the roadmap's own guidance is "split before starting"), and it cuts across the whole system rather than the WordPress object: (1) `workspace_id` FK migrations on `Application`/`WordPressSite`/`Server` + backfill + scoping *every* list/query; (2) a per-site **ACL** model + enforcement woven through promote/sync/bulk endpoints; (3) moving white-label from `localStorage` to server-rendered, workspace-scoped branding; (4) a monthly **reports** generator aggregating the now-existing uptime (#26) / updates (#29) / backups / security (#28/#30) signals. Each sub-part is its own feature; done together they're a milestone, not a single change — and the cross-cutting FK + RBAC rework is high-blast-radius. **Foundation now in place from this session:** the report's data sources (per-site uptime/incidents #26, update history #29, vuln findings #28) all exist, so the reports sub-feature is the most self-contained slice to start with. Deferred to a dedicated milestone. No code shipped.
+- **Assessment / why deferred:** A genuine **`XL`** multi-day epic (the roadmap's own guidance is "split before starting"), and it cuts across the whole system rather than the WordPress object: (1) `workspace_id` FK migrations on `Application`/`WordPressSite`/`Server` + backfill + scoping *every* list/query; (2) a per-site **ACL** model + enforcement woven through promote/sync/bulk endpoints; (3) moving white-label from `localStorage` to server-rendered, workspace-scoped branding; (4) a monthly **reports** generator aggregating the now-existing uptime (#26) / updates (#29) / backups / security (#28/#30) signals. Each sub-part is its own feature; done together they're a milestone, not a single change — and the cross-cutting FK + RBAC rework is high-blast-radius. **Foundation now in place from this session:** the report's data sources (per-site uptime/incidents #26, update history #29, vuln findings #28) all exist, so the reports sub-feature is the most self-contained slice to start with. Deferred to a dedicated milestone.
+- **Landed (reports slice):** the self-contained **monthly client reports** sub-feature shipped — the milestone's first slice, deliberately built *without* the high-blast-radius `workspace_id` rework. New `WpReportsService` aggregates a calendar month's signals into a single persisted, printable report: **uptime % + a daily series + incidents** re-aggregated from the bound status component's `HealthCheck` samples for the exact month (#26), **update runs** (counts + components-updated, #29), **DatabaseSnapshot backups** (count + bytes), and the **current vulnerability posture** (#28) + health/disk — each section honestly labelled PERSISTED-history vs point-in-time (vulns are snapshot-replaced each scan, so they're captured *as-of* generation; traffic/on-demand security scans are noted as excluded). **Why persisted, not live:** generation snapshots the point-in-time sources so a report regenerated months later still shows the right month's posture; the true-historical sources are re-queried per month. Generation is **synchronous** (pure DB aggregation — no WP-CLI/HTTP, so no background thread), and **upserts** per `(site, YYYY-MM)` so regenerating replaces. Client grouping is derived from the **`client-*` / `client:*` tag** (#20) — *no* `workspace_id` FK needed. New `WordPressReport` model (Alembic **014**, chains off `013_ai_assistant`; defined in `wordpress_site.py` + imported lazily in the service so the concurrent AI agent's `models/__init__.py` is never touched), routes `GET /sites/<id>/reports`, `POST …/reports/generate` (`@admin_required`), `DELETE …/reports/<rid>`, client `getReports`/`generateReport`/`deleteReport`, and a new **Reports tab** (month picker → generate, per-month selector, a recharts daily-uptime chart, summary stat cards, incident/update/backup/vuln sections) with a **Print → Save-as-PDF** path (scoped `@media print` isolation, no PDF dependency) and a **Download JSON** export. Verified: backend `py_compile`, **9 new pytest tests** (helpers, bound + unbound aggregation, upsert, future-month guard, API round-trip, + 2 regression tests for review fixes), frontend lint-clean + production build, and a 3-lens adversarial review (5 findings; 4 fixed — daily-series future-day off-by-one, ongoing-incident duration clamped to the in-month window, dead error branch, robust print-cleanup; the 5th — admin-only buttons shown to non-admin owners — left for parity with #28/#29/#30 which do the same). *(Still deferred for the dedicated milestone: cross-cutting `workspace_id` FKs + per-site ACL + server-side workspace-scoped branding. The report already inherits the operator's existing client-side white-label in-app; server-side branding upgrades cleanly later by feeding the same `{name, logo, color}` triplet into the print view.)* Not runtime-exercised on a real Docker host (Windows dev).
### #34 — Horizontal scaling `[XL]` ❌ — ⏸️ Deferred (XL + blocked on the same per-site reverse-proxy/upstream layer as #21)
- **Today:** `nginx_advanced_service` has load-balancing primitives (round-robin/least-conn/IP-hash) but WP containers are stateful (local uploads, no shared object cache).
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
index 22f54f01..d5a288e5 100644
--- a/frontend/src/pages/WordPressDetail.jsx
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
-import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy, Zap, Activity, Globe, Layers, BarChart3 } from 'lucide-react';
+import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy, Zap, Activity, Globe, Layers, BarChart3, FileBarChart, Printer, Download } from 'lucide-react';
import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import useTabParam from '../hooks/useTabParam';
import wordpressApi from '../services/wordpress';
@@ -73,7 +73,7 @@ const DetailPageSkeleton = () => (
</div>
);
-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates'];
+const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates', 'reports'];
const WordPressDetail = () => {
const { id } = useParams();
@@ -374,6 +374,12 @@ const WordPressDetail = () => {
>
<RefreshCw size={14} /> Updates
</div>
+ <div
+ className={`app-detail-tab ${activeTab === 'reports' ? 'active' : ''}`}
+ onClick={() => setActiveTab('reports')}
+ >
+ <FileBarChart size={14} /> Reports
+ </div>
</div>
{/* Clone Site Modal */}
@@ -422,6 +428,7 @@ const WordPressDetail = () => {
{activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}
{activeTab === 'security' && <SecurityTab siteId={site.id} />}
{activeTab === 'updates' && <UpdatesTab siteId={site.id} />}
+ {activeTab === 'reports' && <ReportsTab siteId={site.id} />}
</ErrorBoundary>
</div>
</div>
@@ -1139,6 +1146,356 @@ const AnalyticsTab = ({ siteId }) => {
);
};
+// Reports Tab — monthly client reports (#33 agency slice). Aggregates the
+// per-site signals that already accrue (uptime/incidents #26, update runs #29,
+// backups, vulnerability posture #28) into a persisted, printable monthly report.
+const ReportsTab = ({ siteId }) => {
+ const toast = useToast();
+ const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();
+ const [reports, setReports] = useState([]);
+ const [selectedId, setSelectedId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+
+ // Last 12 months (current first) as {value:'YYYY-MM', label, year, month}.
+ const monthOptions = React.useMemo(() => {
+ const opts = [];
+ const d = new Date();
+ d.setDate(1);
+ for (let i = 0; i < 12; i++) {
+ const year = d.getFullYear();
+ const month = d.getMonth() + 1;
+ opts.push({
+ value: `${year}-${String(month).padStart(2, '0')}`,
+ label: d.toLocaleString([], { month: 'long', year: 'numeric' }),
+ year, month,
+ });
+ d.setMonth(d.getMonth() - 1);
+ }
+ return opts;
+ }, []);
+ const [genMonth, setGenMonth] = useState(monthOptions[0].value);
+
+ const load = React.useCallback(async (preferLabel) => {
+ try {
+ const res = await wordpressApi.getReports(siteId);
+ const list = res.reports || [];
+ setReports(list);
+ setSelectedId(prev => {
+ if (preferLabel) {
+ const match = list.find(r => r.period_label === preferLabel);
+ if (match) return match.id;
+ }
+ if (prev && list.some(r => r.id === prev)) return prev;
+ return list.length ? list[0].id : null;
+ });
+ } catch (err) {
+ toast.error(err.message || 'Failed to load reports');
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ async function handleGenerate() {
+ const opt = monthOptions.find(o => o.value === genMonth) || monthOptions[0];
+ setBusy(true);
+ try {
+ // The API client throws on a non-2xx (e.g. the future-month guard's 400),
+ // so a resolved call means success; failures surface via catch.
+ await wordpressApi.generateReport(siteId, { year: opt.year, month: opt.month });
+ toast.success(`Report generated for ${opt.label}`);
+ await load(opt.value);
+ } catch (err) {
+ toast.error(err.message || 'Failed to generate report');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function handleDelete(report) {
+ const ok = await confirm({
+ title: 'Delete report',
+ message: `Delete the report for ${report.data?.period?.month_name || report.period_label}? This cannot be undone.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ });
+ if (!ok) return;
+ try {
+ await wordpressApi.deleteReport(siteId, report.id);
+ toast.success('Report deleted');
+ await load();
+ } catch (err) {
+ toast.error(err.message || 'Failed to delete report');
+ }
+ }
+
+ function handleDownload(report) {
+ const blob = new Blob([JSON.stringify(report.data, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `wp-report-${siteId}-${report.period_label}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }
+
+ function handlePrint() {
+ document.body.classList.add('wp-report-printing');
+ // Clean up on whichever signal fires first: `afterprint` (most engines) or
+ // the window regaining focus when the dialog closes (fallback for webviews
+ // that don't dispatch afterprint). cleanup is idempotent.
+ const cleanup = () => {
+ document.body.classList.remove('wp-report-printing');
+ window.removeEventListener('afterprint', cleanup);
+ window.removeEventListener('focus', cleanup);
+ };
+ window.addEventListener('afterprint', cleanup);
+ window.addEventListener('focus', cleanup, { once: true });
+ window.print();
+ }
+
+ if (loading) return <div className="tab-loading"><p className="hint">Loading reports...</p></div>;
+
+ const selected = reports.find(r => r.id === selectedId) || null;
+
+ return (
+ <div className="app-overview-grid">
+ <div className="app-overview-left">
+ <div className="app-panel wp-report-no-print">
+ <div className="app-panel-header">Generate monthly report</div>
+ <div className="app-panel-body">
+ <p className="hint">Snapshots this site&apos;s uptime, incidents, update runs, backups, and current security posture for a calendar month into a printable client report.</p>
+ <div className="app-detail-actions">
+ <select value={genMonth} onChange={e => setGenMonth(e.target.value)} disabled={busy}>
+ {monthOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
+ </select>
+ <Button size="sm" onClick={handleGenerate} disabled={busy}>
+ {busy ? 'Generating…' : 'Generate'}
+ </Button>
+ </div>
+ {reports.length > 0 && (
+ <div className="app-detail-actions wp-report-month-list">
+ {reports.map(r => (
+ <Button
+ key={r.id}
+ variant={r.id === selectedId ? 'default' : 'outline'}
+ size="sm"
+ onClick={() => setSelectedId(r.id)}
+ >
+ {r.data?.period?.month_name || r.period_label}
+ </Button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {!selected ? (
+ <div className="app-panel wp-report-no-print">
+ <div className="app-panel-body">
+ <p className="hint">No reports yet — pick a month above and click Generate.</p>
+ </div>
+ </div>
+ ) : (
+ <ReportView report={selected} onPrint={handlePrint} onDownload={() => handleDownload(selected)} onDelete={() => handleDelete(selected)} />
+ )}
+ </div>
+ <ConfirmDialog {...confirmState} onConfirm={handleConfirm} onCancel={handleCancel} />
+ </div>
+ );
+};
+
+// The printable rendering of a single monthly report. Wrapped in
+// .wp-report-printable so the print stylesheet can isolate it from the app chrome.
+const ReportView = ({ report, onPrint, onDownload, onDelete }) => {
+ const d = report.data || {};
+ const period = d.period || {};
+ const site = d.site || {};
+ const uptime = d.uptime || {};
+ const updates = d.updates || {};
+ const backups = d.backups || {};
+ const vulns = d.vulnerabilities || {};
+ const health = d.health || {};
+ const sev = vulns.by_severity || {};
+ const sevVariant = (s) => ({ critical: 'destructive', high: 'destructive', medium: 'warning', low: 'info' }[s] || 'secondary');
+ const impactVariant = (i) => ({ critical: 'destructive', major: 'destructive', minor: 'warning' }[i] || 'secondary');
+ const fmt = (iso) => (iso ? new Date(iso).toLocaleString() : '—');
+ const fmtDay = (key) => {
+ if (!key) return '';
+ const parts = key.split('-');
+ return parts.length === 3 ? Number(parts[2]).toString() : key;
+ };
+ const dailyHasData = (d.uptime_daily || []).some(x => x.percent !== null);
+
+ return (
+ <div className="wp-report-printable">
+ <div className="app-panel">
+ <div className="app-panel-header">
+ Report — {period.month_name || report.period_label}
+ <span className="wp-report-actions wp-report-no-print">
+ <Button variant="outline" size="sm" onClick={onPrint}><Printer size={14} /> Print</Button>
+ <Button variant="outline" size="sm" onClick={onDownload}><Download size={14} /> JSON</Button>
+ <Button variant="outline" size="sm" onClick={onDelete}><Trash2 size={14} /> Delete</Button>
+ </span>
+ </div>
+ <div className="app-panel-body">
+ <div className="app-info-grid">
+ <div className="app-info-item"><span className="app-info-label">Site</span><span className="app-info-value">{site.name || '—'}</span></div>
+ {site.client && <div className="app-info-item"><span className="app-info-label">Client</span><span className="app-info-value">{site.client}</span></div>}
+ <div className="app-info-item"><span className="app-info-label">URL</span><span className="app-info-value">{site.url ? <a href={site.url} target="_blank" rel="noopener noreferrer">{site.url}</a> : '—'}</span></div>
+ <div className="app-info-item"><span className="app-info-label">WordPress</span><span className="app-info-value">{site.wp_version || '—'}{site.multisite ? ' · multisite' : ''}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Generated</span><span className="app-info-value">{fmt(d.generated_at)}</span></div>
+ </div>
+ </div>
+ </div>
+
+ <div className="app-panel">
+ <div className="app-panel-header">Summary</div>
+ <div className="app-panel-body">
+ <div className="app-info-grid">
+ <div className="app-info-item"><span className="app-info-label">Uptime</span><span className="app-info-value">{uptime.percent !== null && uptime.percent !== undefined ? `${uptime.percent}%` : 'N/A'}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Incidents</span><span className="app-info-value">{d.incident_count ?? 0}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Update runs</span><span className="app-info-value">{updates.total_runs ?? 0}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Components updated</span><span className="app-info-value">{updates.components_updated ?? 0}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Backups</span><span className="app-info-value">{backups.count ?? 0}{backups.count ? ` · ${backups.total_bytes_human}` : ''}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Open vulnerabilities</span><span className="app-info-value">{vulns.total ?? 0}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Current health</span><span className="app-info-value">{health.status || 'unknown'}</span></div>
+ <div className="app-info-item"><span className="app-info-label">Disk usage</span><span className="app-info-value">{health.disk_usage_human || '—'}</span></div>
+ </div>
+ {(updates.rolled_back > 0 || updates.failed > 0) && (
+ <div className="app-detail-actions">
+ {updates.completed > 0 && <Badge variant="success">{updates.completed} completed</Badge>}
+ {updates.rolled_back > 0 && <Badge variant="warning">{updates.rolled_back} rolled back</Badge>}
+ {updates.failed > 0 && <Badge variant="destructive">{updates.failed} failed</Badge>}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {uptime.bound && dailyHasData && (
+ <div className="app-panel">
+ <div className="app-panel-header">Daily uptime</div>
+ <div className="app-panel-body">
+ <ResponsiveContainer width="100%" height={200}>
+ <AreaChart data={d.uptime_daily || []} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
+ <defs>
+ <linearGradient id="wpUptime" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.4} />
+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
+ <XAxis dataKey="date" tickFormatter={fmtDay} tick={{ fontSize: 11, fill: '#888' }} minTickGap={16} />
+ <YAxis domain={[0, 100]} tick={{ fontSize: 11, fill: '#888' }} width={36} />
+ <Tooltip formatter={(v) => (v === null ? 'no data' : `${v}%`)} />
+ <Area connectNulls type="monotone" dataKey="percent" name="Uptime %" stroke="#10b981" fill="url(#wpUptime)" strokeWidth={2} />
+ </AreaChart>
+ </ResponsiveContainer>
+ <p className="hint">Uptime recomputed from recorded health-check samples ({uptime.samples} this month). Rolling 30-day: {uptime.rolling_30d ?? '—'}%.</p>
+ </div>
+ </div>
+ )}
+
+ {(d.incidents || []).length > 0 && (
+ <div className="app-panel">
+ <div className="app-panel-header">Incidents</div>
+ <div className="app-panel-body">
+ {d.incidents.map(inc => (
+ <div className="form-group" key={inc.id}>
+ <div>
+ <Badge variant={impactVariant(inc.impact)}>{inc.impact}</Badge>{' '}
+ <strong>{inc.title}</strong>
+ </div>
+ <span className="form-hint">
+ {fmt(inc.created_at)} → {inc.ongoing ? 'ongoing' : fmt(inc.resolved_at)} · {inc.duration_minutes} min · {inc.status}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {(updates.runs || []).length > 0 && (
+ <div className="app-panel">
+ <div className="app-panel-header">Update runs</div>
+ <div className="app-panel-body">
+ {updates.runs.map(r => {
+ const n = (r.updated || []).length;
+ const sv = ({ completed: 'success', rolled_back: 'warning', failed: 'destructive', running: 'info' }[r.status] || 'secondary');
+ return (
+ <div className="form-group" key={r.id}>
+ <div>
+ <Badge variant={sv}>{r.status.replace('_', ' ')}</Badge>{' '}
+ <span className="form-hint">{fmt(r.started_at)} · {r.trigger}</span>
+ </div>
+ <span className="form-hint">
+ {n === 0 ? 'No components needed updating' : `${n} component${n === 1 ? '' : 's'} updated`}
+ {r.rolled_back ? ' · auto-rolled back' : ''}
+ {r.error ? ` · ${r.error}` : ''}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {(backups.snapshots || []).length > 0 && (
+ <div className="app-panel">
+ <div className="app-panel-header">Backups</div>
+ <div className="app-panel-body">
+ {backups.snapshots.map(s => (
+ <div className="app-info-item" key={s.id}>
+ <span className="app-info-label">{fmt(s.created_at)}{s.tag ? ` · ${s.tag}` : ''}</span>
+ <span className="app-info-value">{s.size_human} · {s.status}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div className="app-panel">
+ <div className="app-panel-header">Security posture {vulns.as_of ? `(as of ${fmt(vulns.as_of)})` : ''}</div>
+ <div className="app-panel-body">
+ {vulns.total > 0 ? (
+ <>
+ <div className="app-detail-actions">
+ {sev.critical > 0 && <Badge variant="destructive">{sev.critical} critical</Badge>}
+ {sev.high > 0 && <Badge variant="destructive">{sev.high} high</Badge>}
+ {sev.medium > 0 && <Badge variant="warning">{sev.medium} medium</Badge>}
+ {sev.low > 0 && <Badge variant="info">{sev.low} low</Badge>}
+ {sev.unknown > 0 && <Badge variant="secondary">{sev.unknown} unrated</Badge>}
+ </div>
+ {(vulns.items || []).map((v, i) => (
+ <div className="form-group" key={i}>
+ <div><Badge variant={sevVariant(v.severity)}>{v.severity}</Badge>{' '}<strong>{v.name}</strong></div>
+ <span className="form-hint">
+ {v.source}{v.slug ? ` · ${v.slug}` : ''} · installed {v.installed_version}
+ {v.fixed_in ? ` · fixed in ${v.fixed_in}` : ' · no fix yet'}
+ {v.advisory_id ? ` · ${v.advisory_id}` : ''}
+ </span>
+ </div>
+ ))}
+ </>
+ ) : (
+ <p className="hint">{vulns.as_of ? 'No known vulnerabilities at last scan.' : 'No vulnerability scan has run for this site yet.'}</p>
+ )}
+ </div>
+ </div>
+
+ {(d.notes || []).length > 0 && (
+ <div className="app-panel">
+ <div className="app-panel-body">
+ {d.notes.map((n, i) => <p className="hint" key={i}>{n}</p>)}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
// Overview Tab
const OverviewTab = ({ site, onUpdate }) => {
const toast = useToast();
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index 4b300527..ed9c42c1 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -203,6 +203,11 @@ const wordpressApi = {
runCron: (siteId) => api.request(`${BASE_PATH}/${siteId}/cron/run`, { method: 'POST' }),
setCronDisabled: (siteId, disabled) => api.request(`${BASE_PATH}/${siteId}/cron`, { method: 'POST', body: { disabled } }),
+ // Monthly client reports (#33): persisted per-month uptime/updates/backups/vuln rollups
+ getReports: (siteId) => api.request(`${BASE_PATH}/${siteId}/reports`),
+ generateReport: (siteId, body = {}) => api.request(`${BASE_PATH}/${siteId}/reports/generate`, { method: 'POST', body }),
+ deleteReport: (siteId, reportId) => api.request(`${BASE_PATH}/${siteId}/reports/${reportId}`, { method: 'DELETE' }),
+
// Mint a one-time passwordless wp-admin login URL for the current operator.
autoLogin: (siteId) => api.request(`${BASE_PATH}/${siteId}/login`, {
method: 'POST'
diff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scss
index e3d4a0db..77b0cad1 100644
--- a/frontend/src/styles/pages/_wordpress.scss
+++ b/frontend/src/styles/pages/_wordpress.scss
@@ -1340,6 +1340,47 @@
text-align: center;
}
+// ---- Monthly client reports (#33) ----
+.wp-report-month-list {
+ flex-wrap: wrap;
+ margin-top: $space-3;
+}
+
+.wp-report-actions {
+ margin-left: auto;
+ display: inline-flex;
+ gap: $space-2;
+}
+
+// Print isolation: when the report's "Print" button toggles
+// `body.wp-report-printing`, hide all app chrome and lay out only the report.
+// Uses the classic visibility trick so it doesn't depend on enumerating every
+// layout class, and only applies inside @media print so the screen is untouched.
+@media print {
+ body.wp-report-printing {
+ * {
+ visibility: hidden !important;
+ }
+
+ .wp-report-printable,
+ .wp-report-printable * {
+ visibility: visible !important;
+ }
+
+ .wp-report-printable {
+ position: absolute;
+ inset: 0 auto auto 0;
+ width: 100%;
+ padding: 0;
+ margin: 0;
+ }
+
+ .wp-report-no-print {
+ display: none !important;
+ }
+ }
+}
+
.resource-gate-icon {
display: inline-flex;
align-items: center;