Files
leocrm/app/plugins/builtins/contacts/jobs.py
T

65 lines
2.2 KiB
Python
Raw Normal View History

"""ARQ background jobs for the contacts plugin.
Registered via ``register_job()`` at import time; the worker discovers this
module through ``ContactsPlugin.get_job_modules()`` — the core worker must
not import contact models directly (audit P2: hidden core->contacts
coupling in the trash cleanup).
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import delete as sa_delete
from sqlalchemy import text as sa_text
from app.core.job_registry import register_job
logger = logging.getLogger(__name__)
_TRASH_RETENTION_DAYS = 90
async def cleanup_contacts_trash_job(ctx: dict[str, Any]) -> None:
"""Permanently delete soft-deleted contacts older than the retention window.
Runs daily. Iterates per-tenant for RLS compliance.
Moved from app.core.worker.cleanup_trash_job (audit P2) so the core
worker only handles core-owned entities (entity_attachments).
"""
from app.core.db import get_worker_session_factory
from app.models.contact import Contact
factory = get_worker_session_factory()
async with factory() as db:
try:
tenant_result = await db.execute(sa_text("SELECT id FROM tenants"))
tenant_ids = [row[0] for row in tenant_result]
cutoff = datetime.now(UTC) - timedelta(days=_TRASH_RETENTION_DAYS)
total_deleted = 0
for tenant_id in tenant_ids:
await db.execute(
sa_text("SELECT set_config('app.current_tenant_id', :tid, true)"),
{"tid": str(tenant_id)},
)
result = await db.execute(
sa_delete(Contact).where(
Contact.deleted_at.is_not(None),
Contact.deleted_at < cutoff,
)
)
total_deleted += result.rowcount
await db.commit()
if total_deleted:
logger.info("Contacts trash cleanup: permanently deleted %d old contacts", total_deleted)
except Exception:
logger.error("Contacts trash cleanup failed", exc_info=True)
await db.rollback()
register_job("cleanup_contacts_trash", cleanup_contacts_trash_job)