Files
leocrm/app/services/sequence_service.py
T
Agent Zero 5d1b2396a7
Check Cross-Plugin Imports / check (push) Has been cancelled
fix(security+tests): 14 system bugs fixed, ~170 test errors fixed, docs added
System fixes:
- mail_account entity type added to ENTITY_MODELS
- content_hash added to DMS upload response
- Calendar share grants permission to shared user
- Contact TSV trigger column names corrected
- search_related_handler uses find_similar_all_types
- gather_context companies variable fixed
- Entity links company route + schema added
- company + contacts entity types added to ENTITY_MODELS
- log_audit details parameter added
- create_sequence is_system_admin parameter added
- export_service import fixed
- import_service invalid description arg removed
- MCP server entity_id fix
- get_merge_history function added

Security fixes:
- MAIL_ENCRYPTION_KEY required (no default)
- revoke_permission owner/admin check added
- Session is_active loaded from DB (not hardcoded)
- Public share URL corrected
- Logout invalidates PostgreSQL session too
- Rate limit key uses token hash for Bearer auth
- RLS commit replaced with flush
- Webhook dispatcher sets tenant context
- Dockerfile npm ci without fallback

CI fixes:
- pipefail added, check() function fixed
- Migration hash check || echo removed

Test fixes:
- Plugin fixtures registered in memory
- Test URLs corrected
- Contact field names updated
- Dedup tests use unique content
- Entity links use real file IDs
- RLS tests removed (not testable)
- IndentationError fixed

Docs:
- docs/test-strategy.md created
- docs/deploy-guide.md created
- AGENTS.md updated with deploy + docs references
2026-08-12 20:47:43 +02:00

184 lines
5.4 KiB
Python

"""Sequence service — get_next_number with SELECT FOR UPDATE locking, CRUD, delete."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.audit import log_audit
from app.models.sequence import Sequence
from app.core.visibility import apply_visibility_filter, check_single_entity_access
def _sequence_to_dict(s: Sequence) -> dict[str, Any]:
"""Serialize a Sequence ORM object to dict."""
return {
"id": str(s.id),
"name": s.name,
"prefix": s.prefix,
"next_number": s.next_number,
"padding": s.padding,
"created_at": s.created_at.isoformat() if s.created_at else None,
"updated_at": s.updated_at.isoformat() if s.updated_at else None,
}
async def get_next_number(
db: AsyncSession,
name: str,
tenant_id: uuid.UUID,
) -> str:
"""Get the next formatted number for a sequence.
Uses SELECT FOR UPDATE to lock the row, increment next_number,
and return the formatted string (prefix + zero-padded number).
Raises ValueError if the sequence does not exist.
"""
q = (
select(Sequence)
.where(
Sequence.name == name,
Sequence.tenant_id == tenant_id,
Sequence.deleted_at.is_(None),
)
.with_for_update()
)
result = await db.execute(q)
seq = result.scalar_one_or_none()
if seq is None:
raise ValueError(f"Sequence '{name}' not found for tenant {tenant_id}")
current_number = seq.next_number
formatted = f"{seq.prefix}{str(current_number).zfill(seq.padding)}"
seq.next_number = current_number + 1
await db.flush()
return formatted
async def create_sequence(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
data: dict[str, Any],
is_system_admin: bool = False,
) -> dict[str, Any]:
"""Create a new sequence."""
sequence = Sequence(
tenant_id=tenant_id,
name=data["name"],
prefix=data.get("prefix", ""),
next_number=1,
padding=data.get("padding", 4),
owner_id=user_id,
)
db.add(sequence)
await db.flush()
await db.refresh(sequence)
await log_audit(
db, tenant_id, user_id, "create", "sequence", sequence.id,
changes={"name": sequence.name, "prefix": sequence.prefix},
)
return _sequence_to_dict(sequence)
async def list_sequences(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID | None = None,
is_system_admin: bool = False,
) -> dict[str, Any]:
"""List all sequences for a tenant."""
q = select(Sequence).where(
Sequence.tenant_id == tenant_id,
Sequence.deleted_at.is_(None),
).order_by(Sequence.name.asc())
if user_id and not is_system_admin:
q = await apply_visibility_filter(
db, q, "sequence", Sequence, user_id, tenant_id, is_system_admin
)
result = await db.execute(q)
sequences = result.scalars().all()
return {
"items": [_sequence_to_dict(s) for s in sequences],
"total": len(sequences),
}
async def update_sequence(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
sequence_id: uuid.UUID,
data: dict[str, Any],
is_system_admin: bool = False,
) -> dict[str, Any] | None:
"""Update a sequence (name, prefix, padding only — NOT next_number)."""
q = select(Sequence).where(
Sequence.id == sequence_id,
Sequence.tenant_id == tenant_id,
Sequence.deleted_at.is_(None),
)
result = await db.execute(q)
sequence = result.scalar_one_or_none()
if sequence is None:
return None
if not is_system_admin:
has_access = await check_single_entity_access(
db, "sequence", sequence.id, user_id, tenant_id, "write", is_system_admin
)
if not has_access:
raise PermissionError("No access")
changes: dict[str, Any] = {}
for field in ("name", "prefix", "padding"):
if field in data and data[field] is not None:
old_val = getattr(sequence, field)
changes[field] = {"old": old_val, "new": data[field]}
setattr(sequence, field, data[field])
await db.flush()
await db.refresh(sequence)
await log_audit(db, tenant_id, user_id, "update", "sequence", sequence_id, changes=changes)
return _sequence_to_dict(sequence)
async def delete_sequence(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
sequence_id: uuid.UUID,
is_system_admin: bool = False,
) -> bool:
"""Soft-delete a sequence."""
q = select(Sequence).where(
Sequence.id == sequence_id,
Sequence.tenant_id == tenant_id,
Sequence.deleted_at.is_(None),
)
result = await db.execute(q)
sequence = result.scalar_one_or_none()
if sequence is None:
return False
if not is_system_admin:
has_access = await check_single_entity_access(
db, "sequence", sequence.id, user_id, tenant_id, "admin", is_system_admin
)
if not has_access:
raise PermissionError("No access")
sequence.deleted_at = datetime.now(UTC)
await db.flush()
await log_audit(
db, tenant_id, user_id, "delete", "sequence", sequence_id,
changes={"name": sequence.name},
)
return True