feat(settings): Features tab + sidebar reorg with feature-flag gating

Reorganises the admin sidebar around what users actually do, and adds a
single Features page that gates which feature surfaces appear in the
nav. Shrinks the main sidebar from 11 items to 4-6 (depending on
feature flags) and groups configuration screens into a single Settings
home with six logical sections.

Why
---
The current sidebar mixes three concerns: workspaces (Dashboard, Events,
Archives), feature surfaces (Analytics, Users), and configuration
screens that get touched maybe once a month (Email Settings, Branding,
Event Types, Backup, CMS Pages). That's 11 items, half of them config.

Backend
-------
- New `feature_flags` table (key, value, updated_at, updated_by).
  Migration 088 detects existing-vs-fresh installs from the events
  table:
    * Existing install (events>0)  → all 9 flags TRUE so nothing
      vanishes from an admin's UI on upgrade.
    * Fresh install      (events=0) → spec defaults: galleries,
      reminderEmails, analytics, userManagement TRUE; calendar,
      calendarBooking, quotes, bills, messaging FALSE.

- New `/api/admin/feature-flags` (GET/PUT) under `settings.view` and
  `settings.edit`. Server enforces the same dependency rules the
  frontend does (galleries always TRUE, quotes=false → bills=false,
  calendar=false → calendarBooking=false). PUT writes one
  `feature_flags_updated` activity log row with the diff.

Frontend
--------
- `FeatureFlagsContext` provides `useFeatureFlags()` (with staged/save/
  reset/isDirty) and `useFeatureEnabled(key)`. Mounted inside
  AdminLayout so flag fetches carry the auth cookie. Source of truth
  is the server response; staged is a local copy that the Features tab
  edits and the Save button PUTs.

- `RequireFeature` route guard for /admin/analytics and /admin/users —
  redirects to /admin/dashboard when the corresponding flag is OFF.

- AdminSidebar dropped from 11 to 6 items. Removed: Email Settings,
  Branding, Event Types, Backup, CMS Pages (now Settings tabs).
  Feature-gated: Analytics, Users.

- Old top-level routes (/admin/email, /admin/branding, /admin/event-
  types, /admin/backup, /admin/cms) kept as <Navigate> redirects to
  /admin/settings?tab=<key> so existing bookmarks don't 404.

- SettingsPage rewritten with a 6-group inner-nav (General /
  Content & Appearance / Communication / Privacy & Security /
  Integrations / System) and 19 tabs. New Features tab is the
  default landing tab. URL ?tab=<key> roundtrips with state — deep
  links and the back button work.

- FeaturesTab renders 9 cards across 5 sections. Toggles enabled for
  Analytics + User Management (the two flags that gate sidebar items
  in this PR). All other toggles disabled with a "Not yet available"
  lockedReason — the cards still render so admins see the roadmap, but
  the flag has no UI effect until the surface ships in its own PR. The
  galleries card is locked TRUE per spec (foundation, can't be off).

- Live SidebarPreview reflects unsaved staged changes — admins see
  what their sidebar will look like before they save.

- New i18n keys across all 5 locales (en, de, nl, pt, ru) for the
  Features tab copy, the new Settings group labels, and the lifted
  tab titles.

Verified end-to-end
-------------------
- Migration on this dev DB (existing install, 977 events): all 9 flags
  set to TRUE.
- Migration on simulated fresh install (events table emptied): spec
  defaults applied (5 OFF, 4 ON).
- Backend round-trip: GET → PUT → audit-log entry written, dependency
  rule enforced (bills forced false when quotes=false even when bills=
  true requested).
- UI Playwright spec: sidebar dropped 5 items, old top-level routes
  redirect, Features tab is default, Galleries+Calendar+Quotes+Bills+
  Messaging+ReminderEmails toggles disabled, Analytics+Users toggles
  enabled, toggling Analytics off + saving updates the sidebar +
  redirects /admin/analytics to /admin/dashboard.
- Smoke 13/13 still green; no regressions on existing flows.
This commit is contained in:
Paul Nothaft
2026-05-10 20:36:32 +02:00
parent b6aaea21ca
commit 15e333681f
21 changed files with 1679 additions and 157 deletions
+148
View File
@@ -0,0 +1,148 @@
/**
* Feature flags admin endpoints (#feature-flags-settings-reorg).
*
* GET /api/admin/feature-flags → { [key]: boolean }
* PUT /api/admin/feature-flags → body { [key]: boolean }, replaces in tx
*
* Server-side dependency rules mirror the frontend:
* - quotes=false forces bills=false
* - calendar=false forces calendarBooking=false
* - galleries is hard-coded true regardless of input
*
* Audit log: every successful PUT writes one activity_logs row with the
* before/after diff so changes are traceable.
*/
const express = require('express');
const router = express.Router();
const { db, logActivity } = require('../database/db');
const { adminAuth } = require('../middleware/auth');
const { requirePermission } = require('../middleware/permissions');
const logger = require('../utils/logger');
// Canonical flag list. Keep in sync with frontend
// `FeatureKey` union in frontend/src/contexts/FeatureFlagsContext.tsx.
const KNOWN_FLAGS = [
'galleries',
'reminderEmails',
'calendar',
'calendarBooking',
'quotes',
'bills',
'messaging',
'analytics',
'userManagement',
];
// Spec defaults for any flag missing from the DB (e.g. a row added by a
// new release that hasn't run its migration yet on this instance).
const DEFAULT_FLAGS = {
galleries: true,
reminderEmails: true,
calendar: false,
calendarBooking: false,
quotes: false,
bills: false,
messaging: false,
analytics: true,
userManagement: true,
};
async function readAllFlags() {
const rows = await db('feature_flags').select('key', 'value');
const result = { ...DEFAULT_FLAGS };
for (const row of rows) {
if (KNOWN_FLAGS.includes(row.key)) {
result[row.key] = Boolean(row.value);
}
}
return result;
}
function applyDependencyRules(flags) {
const out = { ...flags };
// Galleries is the foundation — never off.
out.galleries = true;
// Sub-features can't outlive their parents.
if (out.quotes === false) out.bills = false;
if (out.calendar === false) out.calendarBooking = false;
return out;
}
router.get('/', adminAuth, requirePermission('settings.view'), async (req, res) => {
try {
const flags = await readAllFlags();
res.json(flags);
} catch (error) {
logger.error('Failed to read feature flags', { error: error.message });
res.status(500).json({ error: 'Failed to read feature flags' });
}
});
router.put('/', adminAuth, requirePermission('settings.edit'), async (req, res) => {
try {
const body = req.body || {};
if (typeof body !== 'object' || Array.isArray(body)) {
return res.status(400).json({ error: 'Body must be an object of { key: boolean } pairs' });
}
// Validate keys + types up front.
const cleaned = {};
for (const [key, value] of Object.entries(body)) {
if (!KNOWN_FLAGS.includes(key)) {
return res.status(400).json({ error: `Unknown feature flag: ${key}` });
}
if (typeof value !== 'boolean') {
return res.status(400).json({ error: `Flag ${key} must be boolean, got ${typeof value}` });
}
cleaned[key] = value;
}
const before = await readAllFlags();
const merged = applyDependencyRules({ ...before, ...cleaned });
// Compute diff for audit log.
const changed = {};
for (const key of KNOWN_FLAGS) {
if (merged[key] !== before[key]) {
changed[key] = { from: before[key], to: merged[key] };
}
}
if (Object.keys(changed).length === 0) {
// No-op write — return current state, skip audit log.
return res.json(merged);
}
const adminId = req.admin?.id || null;
const adminUsername = req.admin?.username || 'unknown';
await db.transaction(async (trx) => {
for (const key of KNOWN_FLAGS) {
const value = merged[key];
const existing = await trx('feature_flags').where({ key }).first();
if (existing) {
await trx('feature_flags')
.where({ key })
.update({ value, updated_at: trx.fn.now(), updated_by: adminId });
} else {
await trx('feature_flags').insert({ key, value, updated_by: adminId });
}
}
});
await logActivity(
'feature_flags_updated',
{ changed, actor: adminUsername },
null,
{ type: 'admin' }
);
res.json(merged);
} catch (error) {
logger.error('Failed to update feature flags', { error: error.message, stack: error.stack });
res.status(500).json({ error: 'Failed to update feature flags' });
}
});
module.exports = router;