Files
celtic-life-science/app/common/master_edit.py
Shubhankar45 0d30c58bf0 Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
2026-11-07 05:43:12 +00:00

70 lines
2.3 KiB
Python

"""Shared rules for an administrator editing a doctor, chemist or stockist."""
import uuid
from datetime import date
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import assert_can_view_hq
from app.common.exceptions import ConflictError, NotFoundError
from app.organization.models import Headquarters
from app.users.models import User
async def move_headquarters(
db: AsyncSession,
actor: User,
item,
new_hq_id: uuid.UUID,
assignment_model=None,
fk_field: str | None = None,
) -> None:
"""Move ``item`` to another headquarters. A current MR assignment ends when that MR does not
work the new headquarters, since an MR may only hold masters of the headquarters they cover."""
if new_hq_id == item.headquarters_id:
return
if await db.get(Headquarters, new_hq_id) is None:
raise NotFoundError("Headquarters not found")
await assert_can_view_hq(db, actor, new_hq_id)
item.headquarters_id = new_hq_id
if assignment_model is None:
return
current = (
await db.execute(
select(assignment_model).where(
getattr(assignment_model, fk_field) == item.id,
assignment_model.effective_to.is_(None),
)
)
).scalars().all()
for row in current:
mr = await db.get(User, row.mr_user_id)
if mr is None or new_hq_id not in mr.covered_headquarter_ids:
row.effective_to = date.today()
async def end_assignments(db: AsyncSession, assignment_model, fk_field: str, item_id: uuid.UUID) -> int:
"""Close every current MR assignment of one master; returns how many were closed."""
current = (
await db.execute(
select(assignment_model).where(
getattr(assignment_model, fk_field) == item_id,
assignment_model.effective_to.is_(None),
)
)
).scalars().all()
for row in current:
row.effective_to = date.today()
return len(current)
async def commit_unique(db: AsyncSession, message: str) -> None:
"""Commit, turning a unique-constraint clash (same name and address in a headquarters) into a 409."""
try:
await db.commit()
except IntegrityError as exc:
await db.rollback()
raise ConflictError(message) from exc