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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(recycle-bin): soft delete for records, with restore and purge
Juan Denisf49a3e6cfcc8
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex c8ed93e2..1132ebcf 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -504,6 +504,13 @@ def create_app(config_name=None):from app.api.views import views_bpapp.register_blueprint(views_bp, url_prefix='/api/v1/views')+ from app.api.recycle_bin import recycle_bin_bp+ app.register_blueprint(recycle_bin_bp, url_prefix='/api/v1/recycle-bin')+ # Teach the bin which models it can restore. Import-time registration keeps+ # the API type-agnostic: adding a soft-deletable model touches only this list.+ from app.services import recycle_bin_service+ recycle_bin_service.register_builtin_types()+# Register blueprints - Dashboard boards (plan 62, per-user widget grid)from app.api.dashboards import dashboards_bpapp.register_blueprint(dashboards_bp, url_prefix='/api/v1/dashboards')diff --git a/backend/app/api/domains.py b/backend/app/api/domains.pyindex a6469e79..6317dbc0 100644--- a/backend/app/api/domains.py+++ b/backend/app/api/domains.py@@ -93,7 +93,7 @@ def get_domains():Application.query, Application, user,workspace_id=ws_id, owner_attr='user_id', grant_resource_type='application')app_ids = [row[0] for row in app_q.with_entities(Application.id).all()]- domains = (Domain.query.filter(Domain.application_id.in_(app_ids)).all()+ domains = (Domain.query_active().filter(Domain.application_id.in_(app_ids)).all()if app_ids else [])return jsonify({@@ -143,7 +143,7 @@ def create_domain():name = sanitized_name# Check if domain already exists- if Domain.query.filter_by(name=name).first():+ if Domain.query_active().filter_by(name=name).first():return jsonify({'error': 'Domain already exists'}), 409# Check if application exists and user has access@@ -173,7 +173,7 @@ def create_domain():is_primary = data.get('is_primary', False)if is_primary:# Unset any existing primary domain for this app- Domain.query.filter_by(application_id=application_id, is_primary=True).update({'is_primary': False})+ Domain.query_active().filter_by(application_id=application_id, is_primary=True).update({'is_primary': False}, synchronize_session=False)domain = Domain(name=name,@@ -190,7 +190,7 @@ def create_domain():nginx_result = Noneif app.app_type == 'docker' and app.port:# Get all domains for this app to include in nginx config- all_domains = [d.name for d in Domain.query.filter_by(application_id=application_id).all()]+ all_domains = [d.name for d in Domain.query_active().filter_by(application_id=application_id).all()]# Create nginx site confignginx_result = NginxService.create_site(@@ -295,7 +295,7 @@ def update_domain(domain_id):if 'is_primary' in data and data['is_primary']:# Unset any existing primary domain for this app- Domain.query.filter_by(application_id=domain.application_id, is_primary=True).update({'is_primary': False})+ Domain.query_active().filter_by(application_id=domain.application_id, is_primary=True).update({'is_primary': False}, synchronize_session=False)domain.is_primary = Trueif 'ssl_enabled' in data:@@ -326,13 +326,17 @@ def delete_domain(domain_id):return jsonify({'error': 'Access denied'}), 403application_id = domain.application_id- db.session.delete(domain)+ # Soft delete: the vhost teardown below still happens, but the record keeps+ # a tombstone so the Recycle Bin can hand it back. Purging for real is a+ # separate, admin-only action.+ domain.soft_delete(user_id=current_user_id)db.session.commit()# Update nginx config for Docker appsnginx_result = Noneif app.app_type == 'docker' and app.port:- remaining_domains = [d.name for d in Domain.query.filter_by(application_id=application_id).all()]+ remaining_domains = [d.name for d in+ Domain.query_active().filter_by(application_id=application_id).all()]if remaining_domains:# Update nginx config with remaining domainsdiff --git a/backend/app/api/recycle_bin.py b/backend/app/api/recycle_bin.pynew file mode 100644index 00000000..b0d6ee6d--- /dev/null+++ b/backend/app/api/recycle_bin.py@@ -0,0 +1,71 @@+"""Recycle Bin — list, restore and purge soft-deleted records.++Type-agnostic on purpose: every route works off a `kind` registered in+recycle_bin_service, so adding a soft-deletable model needs no change here.+"""+from flask import Blueprint, jsonify, request+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.middleware.rbac import admin_required+from app.services import recycle_bin_service++recycle_bin_bp = Blueprint('recycle_bin', __name__)+++@recycle_bin_bp.route('', methods=['GET'])+@jwt_required()+def list_deleted():+ """Everything currently in the bin, newest deletion first."""+ kind = request.args.get('kind', '').strip() or None+ if kind and kind not in recycle_bin_service.registered_kinds():+ return jsonify({'error': f'Unknown kind: {kind}'}), 400+ try:+ limit = min(int(request.args.get('limit', 200)), 500)+ except (TypeError, ValueError):+ limit = 200+ return jsonify({+ 'items': recycle_bin_service.list_deleted(kind=kind, limit=limit),+ 'kinds': recycle_bin_service.registered_kinds(),+ 'retention_days': recycle_bin_service.DEFAULT_RETENTION_DAYS,+ })+++@recycle_bin_bp.route('/<kind>/<int:record_id>/restore', methods=['POST'])+@jwt_required()+def restore(kind, record_id):+ try:+ item, err = recycle_bin_service.restore(kind, record_id)+ except KeyError:+ return jsonify({'error': f'Unknown kind: {kind}'}), 400+ if item is None:+ return jsonify({'error': err or 'not found'}), 404+ # A non-null err with an item means the row came back but a side effect+ # (re-writing a vhost, say) failed — a warning, not a failure.+ return jsonify({'item': item, 'warning': err}), 200+++@recycle_bin_bp.route('/<kind>/<int:record_id>', methods=['DELETE'])+@jwt_required()+@admin_required+def purge(kind, record_id):+ """Delete for real. Admin-only: this is the one irreversible action."""+ try:+ ok, err = recycle_bin_service.purge(kind, record_id)+ except KeyError:+ return jsonify({'error': f'Unknown kind: {kind}'}), 400+ if not ok:+ return jsonify({'error': err}), 404 if err == 'not found' else 400+ return jsonify({'success': True})+++@recycle_bin_bp.route('/purge-expired', methods=['POST'])+@jwt_required()+@admin_required+def purge_expired():+ body = request.get_json(silent=True) or {}+ days = body.get('retention_days', recycle_bin_service.DEFAULT_RETENTION_DAYS)+ try:+ days = max(1, int(days))+ except (TypeError, ValueError):+ days = recycle_bin_service.DEFAULT_RETENTION_DAYS+ return jsonify({'purged': recycle_bin_service.purge_expired(days)})diff --git a/backend/app/models/domain.py b/backend/app/models/domain.pyindex 590eff29..1b9f9444 100644--- a/backend/app/models/domain.py+++ b/backend/app/models/domain.py@@ -1,12 +1,18 @@from datetime import datetimefrom app import db+from app.models.mixins import SoftDeleteMixin-class Domain(db.Model):+class Domain(SoftDeleteMixin, db.Model):__tablename__ = 'domains'id = db.Column(db.Integer, primary_key=True)- name = db.Column(db.String(255), unique=True, nullable=False, index=True)+ # NOT unique=True any more. A deleted domain keeps its tombstone, and a+ # table-level UNIQUE would then refuse to let you re-add the same name --+ # deleting a domain would permanently burn it. Migration 083 replaces the+ # constraint with a PARTIAL unique index over rows where deleted_at IS NULL,+ # so live names stay unique and tombstones stay out of the way.+ name = db.Column(db.String(255), nullable=False, index=True)is_primary = db.Column(db.Boolean, default=False)# SSL@@ -33,7 +39,8 @@ class Domain(db.Model):'ssl_auto_renew': self.ssl_auto_renew,'created_at': self.created_at.isoformat(),'updated_at': self.updated_at.isoformat(),- 'application_id': self.application_id+ 'application_id': self.application_id,+ **self.soft_delete_dict(),}def __repr__(self):diff --git a/backend/app/models/mixins.py b/backend/app/models/mixins.pynew file mode 100644index 00000000..c03883ac--- /dev/null+++ b/backend/app/models/mixins.py@@ -0,0 +1,81 @@+"""Shared model mixins.++SoftDeleteMixin is the app's one answer to "delete" for records a person can+destroy by hand. Deleting is the only action in a control panel that cannot be+undone by repeating it, so records that took effort to create keep a tombstone+instead of vanishing, and the Recycle Bin gives them back.++Adopting it on a model is three steps:++ class Domain(SoftDeleteMixin, db.Model):+ ...++ # 2. an Alembic migration adding deleted_at / deleted_by_id+ # 3. register it so the Recycle Bin can see it:+ # recycle_bin_service.register('domain', Domain, label=lambda d: d.name)++WHAT DOES NOT COME FREE: every existing query still sees deleted rows. Use+`Model.query_active()` in place of `Model.query` on the read paths that should+hide them — the mixin cannot do this for you without a global query filter,+which would silently change behaviour everywhere including the Recycle Bin's+own lookups.++UNIQUE CONSTRAINTS: a column that is `unique=True` will block re-creating a+record whose tombstone still holds the value (you could not re-add a domain you+just deleted). Those constraints have to become PARTIAL unique indexes with a+`deleted_at IS NULL` predicate — supported by both SQLite (3.8+) and Postgres.+See migration 083 for the pattern.+"""+from datetime import datetime++from app import db+++class SoftDeleteMixin:+ """Adds a tombstone (`deleted_at`) plus who did it, and restore/purge."""++ @db.declared_attr+ def deleted_at(cls): # noqa: N805+ return db.Column(db.DateTime, nullable=True, index=True)++ @db.declared_attr+ def deleted_by_id(cls): # noqa: N805+ # No FK: the actor may be removed later, and losing the user must not+ # cascade into losing the tombstone.+ return db.Column(db.Integer, nullable=True)++ @property+ def is_deleted(self):+ return self.deleted_at is not None++ # `is_active` reads better at call sites and matches the vocabulary already+ # used across the app (api_key.is_active, workspace status filters).+ @property+ def is_active(self):+ return self.deleted_at is None++ def soft_delete(self, user_id=None):+ if self.deleted_at is None:+ self.deleted_at = datetime.utcnow()+ self.deleted_by_id = user_id+ return self++ def restore(self):+ self.deleted_at = None+ self.deleted_by_id = None+ return self++ @classmethod+ def query_active(cls):+ return cls.query.filter(cls.deleted_at.is_(None))++ @classmethod+ def query_deleted(cls):+ return cls.query.filter(cls.deleted_at.isnot(None))++ def soft_delete_dict(self):+ return {+ 'deleted_at': self.deleted_at.isoformat() if self.deleted_at else None,+ 'deleted_by_id': self.deleted_by_id,+ 'is_active': self.is_active,+ }diff --git a/backend/app/models/saved_view.py b/backend/app/models/saved_view.pyindex 2999a8d8..1cdaf5e9 100644--- a/backend/app/models/saved_view.py+++ b/backend/app/models/saved_view.py@@ -1,8 +1,9 @@from datetime import datetimefrom app import db+from app.models.mixins import SoftDeleteMixin-class SavedView(db.Model):+class SavedView(SoftDeleteMixin, db.Model):"""A user's saved table view for a list page (Services, Domains, …).Captures the page's table state — filter, search, sort levels, hidden@@ -17,14 +18,19 @@ class SavedView(db.Model):user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)page = db.Column(db.String(80), nullable=False)name = db.Column(db.String(120), nullable=False)+ # URL-safe handle so a view can be linked: /domains?view=ssl-expiring-soon.+ # Unique per (user, page) among LIVE rows; derived from the name on create.+ slug = db.Column(db.String(140), nullable=True, index=True)state = db.Column(db.JSON, nullable=False, default=dict)is_default = db.Column(db.Boolean, nullable=False, default=False)created_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)- __table_args__ = (- db.UniqueConstraint('user_id', 'page', 'name', name='uq_saved_views_user_page_name'),- )+ # No table-level UNIQUE on (user_id, page, name): a deleted view keeps its+ # row, and the constraint would then refuse to let you re-create a view by+ # the same name. Migration 083 makes it a PARTIAL unique index restricted to+ # rows where deleted_at IS NULL.+ __table_args__ = ()user = db.relationship('User', backref=db.backref('saved_views', cascade='all, delete-orphan'))@@ -34,7 +40,9 @@ class SavedView(db.Model):'user_id': self.user_id,'page': self.page,'name': self.name,+ 'slug': self.slug,'state': self.state or {},+ **self.soft_delete_dict(),'is_default': self.is_default,'created_at': self.created_at.isoformat() if self.created_at else None,'updated_at': self.updated_at.isoformat() if self.updated_at else None,diff --git a/backend/app/services/recycle_bin_service.py b/backend/app/services/recycle_bin_service.pynew file mode 100644index 00000000..1729ee25--- /dev/null+++ b/backend/app/services/recycle_bin_service.py@@ -0,0 +1,148 @@+"""The Recycle Bin: one place that lists, restores and purges soft-deleted+records across every model that opted into SoftDeleteMixin.++A model registers itself with a label function and (optionally) a restore hook,+so the bin can present "domain · shop.example.com, deleted 2 days ago by admin"+without knowing anything about domains. Adding a new type is one register()+call — the API, the listing and the restore flow do not change.++ register('domain', Domain, label=lambda d: d.name,+ description=lambda d: f'app #{d.application_id}',+ on_restore=nginx_service.rewrite_site)++RESTORE IS NOT ALWAYS FREE. Soft-deleting a record does not undo the side+effects that went with it — a deleted domain still had its nginx vhost and its+certificate torn down. `on_restore` is where a type re-does that work; a type+without one restores the ROW only, which is the honest default.+"""+from datetime import datetime, timedelta++from app import db++# name -> {model, label, description, on_restore, verb}+_REGISTRY = {}++# How long a tombstone survives before `purge_expired` may reap it. Long enough+# that "I deleted the wrong thing last week" is still recoverable.+DEFAULT_RETENTION_DAYS = 30+++def register(kind, model, *, label, description=None, on_restore=None, noun=None):+ """Make a soft-deletable model visible to the Recycle Bin."""+ if not hasattr(model, 'deleted_at'):+ raise TypeError(f'{model.__name__} does not use SoftDeleteMixin')+ _REGISTRY[kind] = {+ 'model': model,+ 'label': label,+ 'description': description,+ 'on_restore': on_restore,+ 'noun': noun or kind.replace('_', ' '),+ }+++def registered_kinds():+ return sorted(_REGISTRY.keys())+++def _entry(kind):+ entry = _REGISTRY.get(kind)+ if not entry:+ raise KeyError(kind)+ return entry+++def _serialize(kind, entry, row):+ return {+ 'kind': kind,+ 'noun': entry['noun'],+ 'id': row.id,+ 'label': entry['label'](row),+ 'description': entry['description'](row) if entry['description'] else None,+ 'deleted_at': row.deleted_at.isoformat() if row.deleted_at else None,+ 'deleted_by_id': row.deleted_by_id,+ 'restorable': True,+ }+++def list_deleted(kind=None, limit=200):+ """Everything currently in the bin, newest deletion first."""+ kinds = [kind] if kind else registered_kinds()+ items = []+ for k in kinds:+ entry = _REGISTRY.get(k)+ if not entry:+ continue+ rows = (entry['model'].query_deleted()+ .order_by(entry['model'].deleted_at.desc())+ .limit(limit).all())+ items.extend(_serialize(k, entry, r) for r in rows)+ items.sort(key=lambda i: i['deleted_at'] or '', reverse=True)+ return items[:limit]+++def restore(kind, record_id):+ entry = _entry(kind)+ row = entry['model'].query.filter_by(id=record_id).first()+ if row is None:+ return None, 'not found'+ if row.deleted_at is None:+ return _serialize(kind, entry, row), None # already active; idempotent+ row.restore()+ db.session.commit()+ if entry['on_restore']:+ try:+ entry['on_restore'](row)+ except Exception as exc: # noqa: BLE001+ # The row IS back; the side effect is what failed. Say so rather+ # than rolling back a restore the user asked for.+ return _serialize(kind, entry, row), f'restored, but re-applying config failed: {exc}'+ return _serialize(kind, entry, row), None+++def purge(kind, record_id):+ """Delete for real. The only irreversible action in this module."""+ entry = _entry(kind)+ row = entry['model'].query.filter_by(id=record_id).first()+ if row is None:+ return False, 'not found'+ if row.deleted_at is None:+ return False, 'record is not in the recycle bin'+ db.session.delete(row)+ db.session.commit()+ return True, None+++def purge_expired(retention_days=DEFAULT_RETENTION_DAYS):+ """Reap tombstones older than the retention window. Returns a per-kind count."""+ cutoff = datetime.utcnow() - timedelta(days=retention_days)+ counts = {}+ for kind, entry in _REGISTRY.items():+ rows = entry['model'].query.filter(+ entry['model'].deleted_at.isnot(None),+ entry['model'].deleted_at < cutoff,+ ).all()+ for row in rows:+ db.session.delete(row)+ if rows:+ counts[kind] = len(rows)+ if counts:+ db.session.commit()+ return counts+++def register_builtin_types():+ """Wire the models that ship with the panel. Called from create_app."""+ from app.models.domain import Domain+ from app.models.saved_view import SavedView++ register(+ 'domain', Domain, noun='domain',+ label=lambda d: d.name,+ description=lambda d: (f'linked to app #{d.application_id}'+ if d.application_id else None),+ )+ register(+ 'saved_view', SavedView, noun='saved view',+ label=lambda v: v.name,+ description=lambda v: f'{v.page} view',+ )diff --git a/backend/app/services/saved_view_service.py b/backend/app/services/saved_view_service.pyindex 2d5b6162..0d0f2d9a 100644--- a/backend/app/services/saved_view_service.py+++ b/backend/app/services/saved_view_service.py@@ -1,4 +1,5 @@import logging+import refrom app import dbfrom app.models.saved_view import SavedView@@ -8,9 +9,42 @@ logger = logging.getLogger(__name__)MAX_VIEWS_PER_PAGE = 50+def slugify(value):+ """URL handle for a view name: 'SSL expiring ≤ 30d' -> 'ssl-expiring-30d'."""+ slug = re.sub(r'[^a-z0-9]+', '-', (value or '').lower()).strip('-')+ return slug[:140] or 'view'+++def _unique_slug(user_id, page, name, exclude_id=None):+ """A slug unique among that user's LIVE views on the page.++ Scoped to live rows only: a tombstoned view must not reserve its handle+ forever, or deleting a view would burn the link name with it.+ """+ base = slugify(name)+ slug, n = base, 2+ while True:+ q = (SavedView.query_active()+ .filter_by(user_id=user_id, page=page, slug=slug))+ if exclude_id is not None:+ q = q.filter(SavedView.id != exclude_id)+ if not q.first():+ return slug+ slug = f'{base}-{n}'+ n += 1+++def get_by_slug(user_id, page, slug):+ """Resolve ?view=<slug> back to a saved view."""+ view = (SavedView.query_active()+ .filter_by(user_id=user_id, page=page, slug=slug)+ .first())+ return view.to_dict() if view else None++def list_views(user_id, page):"""All saved views a user has for one list page, defaults first."""- views = (SavedView.query+ views = (SavedView.query_active().filter_by(user_id=user_id, page=page).order_by(SavedView.is_default.desc(), SavedView.name.asc()).all())@@ -30,9 +64,9 @@ def _validate(page, name, state):def _clear_default(user_id, page):- (SavedView.query+ (SavedView.query_active().filter_by(user_id=user_id, page=page, is_default=True)- .update({'is_default': False}))+ .update({'is_default': False}, synchronize_session=False))def create_view(user_id, page, name, state, is_default=False):@@ -41,13 +75,15 @@ def create_view(user_id, page, name, state, is_default=False):if err:return None, errname = name.strip()- if SavedView.query.filter_by(user_id=user_id, page=page).count() >= MAX_VIEWS_PER_PAGE:+ if SavedView.query_active().filter_by(user_id=user_id, page=page).count() >= MAX_VIEWS_PER_PAGE:return None, f'You can save at most {MAX_VIEWS_PER_PAGE} views per page'- if SavedView.query.filter_by(user_id=user_id, page=page, name=name).first():+ if SavedView.query_active().filter_by(user_id=user_id, page=page, name=name).first():return None, f'You already have a "{name}" view on this page'if is_default:_clear_default(user_id, page)- view = SavedView(user_id=user_id, page=page, name=name, state=state, is_default=bool(is_default))+ view = SavedView(user_id=user_id, page=page, name=name, state=state,+ slug=_unique_slug(user_id, page, name),+ is_default=bool(is_default))db.session.add(view)db.session.commit()return view.to_dict(), None@@ -55,7 +91,7 @@ def create_view(user_id, page, name, state, is_default=False):def update_view(user_id, view_id, data):"""Rename / restate / (un)default a saved view. Returns ``(view_dict, error)``."""- view = SavedView.query.filter_by(id=view_id, user_id=user_id).first()+ view = SavedView.query_active().filter_by(id=view_id, user_id=user_id).first()if not view:return None, 'View not found'@@ -64,13 +100,14 @@ def update_view(user_id, view_id, data):if err:return None, errname = data['name'].strip()- clash = (SavedView.query+ clash = (SavedView.query_active().filter_by(user_id=user_id, page=view.page, name=name).filter(SavedView.id != view.id).first())if clash:return None, f'You already have a "{name}" view on this page'view.name = name+ view.slug = _unique_slug(user_id, view.page, name, exclude_id=view.id)if 'state' in data:if not isinstance(data['state'], dict):@@ -87,10 +124,14 @@ def update_view(user_id, view_id, data):def delete_view(user_id, view_id):- """Delete a saved view. Returns ``(True, error)``."""- view = SavedView.query.filter_by(id=view_id, user_id=user_id).first()+ """Send a saved view to the Recycle Bin. Returns ``(True, error)``.++ Soft, not destructive: a view is a piece of work someone tuned, and the+ only way to get it back used to be rebuilding it from memory.+ """+ view = SavedView.query_active().filter_by(id=view_id, user_id=user_id).first()if not view:return None, 'View not found'- db.session.delete(view)+ view.soft_delete(user_id=user_id)db.session.commit()return True, Nonediff --git a/backend/migrations/versions/083_soft_delete_recycle_bin.py b/backend/migrations/versions/083_soft_delete_recycle_bin.pynew file mode 100644index 00000000..bbbb0ee4--- /dev/null+++ b/backend/migrations/versions/083_soft_delete_recycle_bin.py@@ -0,0 +1,173 @@+"""Soft delete + recycle bin: tombstones on domains and saved_views, view slugs.++Two things need care here:++1. UNIQUE -> PARTIAL UNIQUE. Both tables had a plain UNIQUE that included what+ is now a tombstoned row, so deleting a domain would permanently burn its+ name and deleting a view would block re-creating one with the same name.+ Each becomes a unique INDEX with a `deleted_at IS NULL` predicate, which+ SQLite (3.8+) and PostgreSQL both support.++2. SQLite cannot drop a constraint in place, so the domains change runs inside+ a batch_alter_table (table rebuild). The saved_views UNIQUE was declared as+ a named constraint, so it is dropped the same way.++Revision ID: 083_soft_delete_recycle_bin+Revises: 082_saved_views+"""+import sqlalchemy as sa+from alembic import op++revision = '083_soft_delete_recycle_bin'+down_revision = '082_saved_views'+branch_labels = None+depends_on = None+++def _has_table(name):+ bind = op.get_bind()+ return name in sa.inspect(bind).get_table_names()+++def _columns(table):+ bind = op.get_bind()+ return {c['name'] for c in sa.inspect(bind).get_columns(table)}+++def _indexes(table):+ bind = op.get_bind()+ return {i['name'] for i in sa.inspect(bind).get_indexes(table)}+++def _unique_constraints(table):+ bind = op.get_bind()+ try:+ return {c['name'] for c in sa.inspect(bind).get_unique_constraints(table)}+ except NotImplementedError: # some dialects+ return set()+++def _mk_index(table, name, cols, unique=False, live_only=False):+ """create_index that tolerates the index already existing.++ `deleted_at` is declared index=True on the mixin, so a database built from+ the models rather than replayed through migrations already has it — and a+ bare create_index would abort the upgrade on exactly the installs we most+ want to keep working.+ """+ if name in _indexes(table):+ return+ kwargs = {}+ if live_only:+ kwargs = {+ 'sqlite_where': sa.text('deleted_at IS NULL'),+ 'postgresql_where': sa.text('deleted_at IS NULL'),+ }+ op.create_index(name, table, cols, unique=unique, **kwargs)+++def upgrade():+ # ---- domains -------------------------------------------------------+ if _has_table('domains'):+ existing = _columns('domains')+ with op.batch_alter_table('domains') as batch:+ if 'deleted_at' not in existing:+ batch.add_column(sa.Column('deleted_at', sa.DateTime(), nullable=True))+ if 'deleted_by_id' not in existing:+ batch.add_column(sa.Column('deleted_by_id', sa.Integer(), nullable=True))+ _mk_index('domains', 'ix_domains_deleted_at', ['deleted_at'])++ # Replace the plain UNIQUE on name with a live-rows-only unique index.+ # The old constraint may be an index or a table constraint depending on+ # how the table was first created, so try both and ignore misses.+ for drop in (+ lambda: op.drop_index('ix_domains_name', table_name='domains'),+ lambda: op.drop_constraint('uq_domains_name', 'domains', type_='unique'),+ ):+ try:+ drop()+ except Exception: # noqa: BLE001 - constraint shape varies by install age+ pass+ _mk_index('domains', 'ix_domains_name', ['name'])+ _mk_index('domains', 'uq_domains_name_live', ['name'], unique=True, live_only=True)++ # ---- saved_views ---------------------------------------------------+ if _has_table('saved_views'):+ existing = _columns('saved_views')+ # Batch mode validates the whole recipe when the block EXITS, so a+ # missing constraint raises there, not at the drop_constraint() call --+ # wrapping the call in try/except does nothing. Check first instead.+ drop_uq = 'uq_saved_views_user_page_name' in _unique_constraints('saved_views')+ with op.batch_alter_table('saved_views') as batch:+ if 'deleted_at' not in existing:+ batch.add_column(sa.Column('deleted_at', sa.DateTime(), nullable=True))+ if 'deleted_by_id' not in existing:+ batch.add_column(sa.Column('deleted_by_id', sa.Integer(), nullable=True))+ if 'slug' not in existing:+ batch.add_column(sa.Column('slug', sa.String(length=140), nullable=True))+ if drop_uq:+ batch.drop_constraint('uq_saved_views_user_page_name', type_='unique')+ _mk_index('saved_views', 'ix_saved_views_deleted_at', ['deleted_at'])+ _mk_index('saved_views', 'ix_saved_views_slug', ['slug'])+ _mk_index('saved_views', 'uq_saved_views_user_page_name_live',+ ['user_id', 'page', 'name'], unique=True, live_only=True)+ _mk_index('saved_views', 'uq_saved_views_user_page_slug_live',+ ['user_id', 'page', 'slug'], unique=True, live_only=True)+ # Backfill slugs for views that predate the column.+ _backfill_slugs()+++def _backfill_slugs():+ import re+ bind = op.get_bind()+ rows = bind.execute(sa.text(+ 'SELECT id, user_id, page, name FROM saved_views WHERE slug IS NULL'+ )).fetchall()+ seen = set()+ for row in rows:+ base = re.sub(r'[^a-z0-9]+', '-', (row.name or '').lower()).strip('-') or f'view-{row.id}'+ slug, n = base, 2+ while (row.user_id, row.page, slug) in seen:+ slug = f'{base}-{n}'+ n += 1+ seen.add((row.user_id, row.page, slug))+ bind.execute(+ sa.text('UPDATE saved_views SET slug = :slug WHERE id = :id'),+ {'slug': slug, 'id': row.id},+ )+++def downgrade():+ if _has_table('saved_views'):+ for name in ('uq_saved_views_user_page_slug_live', 'uq_saved_views_user_page_name_live',+ 'ix_saved_views_slug', 'ix_saved_views_deleted_at'):+ try:+ op.drop_index(name, table_name='saved_views')+ except Exception: # noqa: BLE001+ pass+ with op.batch_alter_table('saved_views') as batch:+ for col in ('slug', 'deleted_by_id', 'deleted_at'):+ try:+ batch.drop_column(col)+ except Exception: # noqa: BLE001+ pass+ batch.create_unique_constraint(+ 'uq_saved_views_user_page_name', ['user_id', 'page', 'name'])++ if _has_table('domains'):+ for name in ('uq_domains_name_live', 'ix_domains_deleted_at'):+ try:+ op.drop_index(name, table_name='domains')+ except Exception: # noqa: BLE001+ pass+ with op.batch_alter_table('domains') as batch:+ for col in ('deleted_by_id', 'deleted_at'):+ try:+ batch.drop_column(col)+ except Exception: # noqa: BLE001+ pass+ try:+ op.drop_index('ix_domains_name', table_name='domains')+ except Exception: # noqa: BLE001+ pass+ op.create_index('ix_domains_name', 'domains', ['name'], unique=True)diff --git a/backend/tests/test_recycle_bin.py b/backend/tests/test_recycle_bin.pynew file mode 100644index 00000000..7709aa25--- /dev/null+++ b/backend/tests/test_recycle_bin.py@@ -0,0 +1,153 @@+"""Soft delete + Recycle Bin.++Deleting is the one action in a control panel that repeating cannot undo, so+records a person destroys by hand now leave a tombstone and the bin hands them+back. These tests pin the parts that are easy to get subtly wrong: that the+tombstone stays out of every read path, that a deleted name can be REUSED (the+partial unique index), and that purge is the only thing that really destroys.+"""+import pytest++from app import db+from app.models import Application, Domain+from app.models.saved_view import SavedView+from app.services import recycle_bin_service, saved_view_service+++def app_with_domain(app):+ with app.app_context():+ application = Application(name='shop', app_type='docker', port=8001, user_id=1)+ db.session.add(application)+ db.session.flush()+ domain = Domain(name='shop.example.com', application_id=application.id)+ db.session.add(domain)+ db.session.commit()+ yield {'app_id': application.id, 'domain_id': domain.id}+++# ---- the mixin -------------------------------------------------------------++def test_soft_delete_keeps_the_row_but_hides_it(app, app_with_domain):+ with app.app_context():+ domain = Domain.query.get(app_with_domain['domain_id'])+ domain.soft_delete(user_id=7)+ db.session.commit()++ assert Domain.query.get(app_with_domain['domain_id']) is not None+ assert Domain.query_active().filter_by(name='shop.example.com').first() is None+ assert Domain.query_deleted().count() == 1+ assert domain.is_active is False+ assert domain.deleted_by_id == 7+++def test_a_deleted_name_can_be_reused(app, app_with_domain):+ """The partial unique index is the whole point: a plain UNIQUE would make+ deleting a domain permanently burn its name."""+ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ db.session.commit()++ again = Domain(name='shop.example.com', application_id=app_with_domain['app_id'])+ db.session.add(again)+ db.session.commit() # must not raise IntegrityError++ assert Domain.query_active().filter_by(name='shop.example.com').count() == 1+ assert Domain.query.filter_by(name='shop.example.com').count() == 2+++def test_restore_is_idempotent(app, app_with_domain):+ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ db.session.commit()++ item, err = recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ assert err is None and item['label'] == 'shop.example.com'+ # restoring an already-live record is a no-op, not an error+ item, err = recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ assert err is None+ assert Domain.query_active().count() == 1+++# ---- the bin ---------------------------------------------------------------++def test_bin_lists_across_types_newest_first(app, app_with_domain):+ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ view = SavedView(user_id=1, page='domains', name='Mine', slug='mine', state={})+ db.session.add(view)+ db.session.commit()+ view.soft_delete()+ db.session.commit()++ items = recycle_bin_service.list_deleted()+ kinds = {i['kind'] for i in items}+ assert kinds == {'domain', 'saved_view'}+ stamps = [i['deleted_at'] for i in items]+ assert stamps == sorted(stamps, reverse=True)+++def test_purge_is_the_only_destructive_path(app, app_with_domain):+ with app.app_context():+ domain_id = app_with_domain['domain_id']+ # not in the bin yet -> refuse+ ok, err = recycle_bin_service.purge('domain', domain_id)+ assert ok is False and 'not in the recycle bin' in err++ Domain.query.get(domain_id).soft_delete()+ db.session.commit()+ ok, err = recycle_bin_service.purge('domain', domain_id)+ assert ok is True and err is None+ assert Domain.query.get(domain_id) is None+++def test_purge_expired_respects_the_retention_window(app, app_with_domain):+ from datetime import datetime, timedelta+ with app.app_context():+ domain = Domain.query.get(app_with_domain['domain_id'])+ domain.soft_delete()+ domain.deleted_at = datetime.utcnow() - timedelta(days=45)+ db.session.commit()++ assert recycle_bin_service.purge_expired(retention_days=90) == {}+ assert recycle_bin_service.purge_expired(retention_days=30) == {'domain': 1}+++def test_unknown_kind_raises(app):+ with app.app_context():+ with pytest.raises(KeyError):+ recycle_bin_service.restore('nope', 1)+++# ---- saved views ------------------------------------------------------------++def test_deleting_a_view_sends_it_to_the_bin(app):+ with app.app_context():+ view, err = saved_view_service.create_view(1, 'domains', 'SSL expiring', {'sorts': []})+ assert err is None+ saved_view_service.delete_view(1, view['id'])++ assert saved_view_service.list_views(1, 'domains') == []+ assert any(i['kind'] == 'saved_view' for i in recycle_bin_service.list_deleted())+++def test_view_slug_is_derived_and_deduped(app):+ with app.app_context():+ a, _ = saved_view_service.create_view(1, 'domains', 'SSL expiring', {})+ b, _ = saved_view_service.create_view(1, 'services', 'SSL expiring', {})+ assert a['slug'] == 'ssl-expiring'+ assert b['slug'] == 'ssl-expiring' # different page, no clash++ assert saved_view_service.get_by_slug(1, 'domains', 'ssl-expiring')['id'] == a['id']+ assert saved_view_service.get_by_slug(1, 'domains', 'nope') is None+++def test_a_deleted_view_frees_its_name_and_slug(app):+ with app.app_context():+ first, _ = saved_view_service.create_view(1, 'domains', 'Triage', {})+ saved_view_service.delete_view(1, first['id'])++ again, err = saved_view_service.create_view(1, 'domains', 'Triage', {})+ assert err is None+ assert again['slug'] == 'triage' # not 'triage-2'+ assert saved_view_service.get_by_slug(1, 'domains', 'triage')['id'] == again['id']