Coverage for app / router / app / organisations / router.py: 100%
86 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1from uuid import UUID
2from typing import List
4from fastapi import APIRouter, Depends, HTTPException, status
5from sqlalchemy.orm import Session
6from sqlalchemy.exc import SQLAlchemyError
8from app.dependency.base import get_db
9from app.dependency.resource_access import verify_organisation_access
10from app.dependency.user.context import get_current_user
11from app.db.postgres.enums import HistoryEnum, PermissionEnum
12from app.db.postgres.models import Organisation, Role, User, UserOrganisation
13from app.db.postgres.crud_schemas import Schema
14from app.router.app.history.router import register_history_routes
15from app.router.app.membership_routes import register_membership_routes
16from app.router.app.organisations.schemas import OrganisationListItem
17from app.services import access as access_service
18from app.services import membership
19from app.services.membership import ORGANISATION, MemberRole
20from app.common import exceptions
21import logging
23logger = logging.getLogger(__name__)
25organisation_router = APIRouter(
26 prefix="/organisations",
27 tags=["App - Organisations"],
28)
31# --------------------
32# READ (list)
33# --------------------
34@organisation_router.get("", response_model=List[OrganisationListItem])
35async def organisation_list(
36 db: Session = Depends(get_db),
37 current_user: User = Depends(get_current_user),
38):
39 """The caller's organisations, each with their role in it — so a form
40 can offer an organisation as an owner only where the caller may write
41 what it would create (an organisation's rules are its admins')."""
42 query = (
43 db.query(Organisation, Role.name, UserOrganisation.access)
44 .outerjoin(
45 UserOrganisation,
46 (UserOrganisation.organisation_id == Organisation.id)
47 & (UserOrganisation.user_id == current_user.id),
48 )
49 .outerjoin(Role, Role.id == UserOrganisation.role_id)
50 )
51 if not current_user.is_superuser:
52 query = query.filter(UserOrganisation.user_id == current_user.id)
53 # Validated whole, never ``model_copy(update=…)``: that skips validation,
54 # so ``access`` kept its plain-string keys and every response warned
55 # that its ``AccessArea`` keys were not what the schema says.
56 return [
57 OrganisationListItem.model_validate(
58 {
59 **Schema.Organisation.Read.model_validate(org).model_dump(),
60 "role": MemberRole(role) if role else None,
61 "access": _access_of(role, access),
62 }
63 )
64 for org, role, access in query.order_by(Organisation.name).all()
65 ]
68def _access_of(role: str | None, access: dict | None):
69 """The caller's level per area, or None where they are not a member."""
70 if role is None:
71 return None
72 effective = (
73 access_service.ADMIN_ACCESS
74 if role == MemberRole.admin.value
75 else access_service.normalise(access)
76 )
77 return access_service.to_json(effective)
80# --------------------
81# READ (by id)
82# --------------------
83@organisation_router.get("/id/{id}", response_model=Schema.Organisation.Read)
84async def organisation_id(
85 id: UUID,
86 db: Session = Depends(get_db),
87 current_user: User = Depends(get_current_user),
88):
89 organisation = db.query(Organisation).filter(Organisation.id == id).first()
91 if not organisation:
92 raise exceptions.OrganisationNotFoundException
94 if not current_user.is_superuser:
95 membership = (
96 db.query(UserOrganisation)
97 .filter(
98 UserOrganisation.user_id == current_user.id,
99 UserOrganisation.organisation_id == id,
100 )
101 .first()
102 )
103 if not membership:
104 raise HTTPException(
105 status_code=status.HTTP_403_FORBIDDEN,
106 detail="Forbidden",
107 )
109 return organisation
112# --------------------
113# CREATE
114# --------------------
115@organisation_router.post(
116 "/",
117 response_model=Schema.Organisation.Read,
118 status_code=status.HTTP_201_CREATED,
119)
120async def organisation_create(
121 payload: Schema.Organisation.Create,
122 db: Session = Depends(get_db),
123 current_user: User = Depends(get_current_user),
124):
125 logger.info("Creating organisation...")
126 try:
127 organisation = Organisation(**payload.model_dump())
128 db.add(organisation)
129 db.flush()
130 # Its creator is its first admin. Nothing used to add them, so they
131 # were refused on the organisation they had just made.
132 membership.add_member(
133 db, ORGANISATION, organisation.id, current_user.id, MemberRole.admin
134 )
135 membership.record_change(
136 db,
137 ORGANISATION,
138 organisation,
139 current_user,
140 action=HistoryEnum.Action.created,
141 )
142 db.commit()
143 db.refresh(organisation)
144 return organisation
146 except SQLAlchemyError as e:
147 db.rollback()
148 logger.exception("Failed to create organisation")
149 raise exceptions.OrganisationFailedToCreateException from e
152# --------------------
153# UPDATE
154# --------------------
155@organisation_router.put("/id/{id}", response_model=Schema.Organisation.Read)
156async def organisation_update(
157 id: UUID,
158 payload: Schema.Organisation.Update,
159 db: Session = Depends(get_db),
160 current_user: User = Depends(get_current_user),
161):
162 organisation = db.query(Organisation).filter(Organisation.id == id).first()
164 if not organisation:
165 raise exceptions.OrganisationNotFoundException
166 membership.require_permission(
167 db, ORGANISATION, organisation.id, current_user, PermissionEnum.Code.ORG_UPDATE
168 )
170 for field, value in payload.model_dump(exclude_unset=True).items():
171 setattr(organisation, field, value)
173 membership.record_change(db, ORGANISATION, organisation, current_user)
174 db.commit()
175 db.refresh(organisation)
177 logger.info("Updated organisation %s", id)
178 return organisation
181# --------------------
182# DELETE
183# --------------------
184@organisation_router.delete("/id/{id}", status_code=status.HTTP_204_NO_CONTENT)
185async def organisation_delete(
186 id: UUID,
187 db: Session = Depends(get_db),
188 current_user: User = Depends(get_current_user),
189):
190 organisation = db.query(Organisation).filter(Organisation.id == id).first()
192 if not organisation:
193 raise exceptions.OrganisationNotFoundException
194 membership.require_permission(
195 db, ORGANISATION, organisation.id, current_user, PermissionEnum.Code.ORG_DELETE
196 )
198 membership.record_change(
199 db, ORGANISATION, organisation, current_user, action=HistoryEnum.Action.deleted
200 )
201 from app.services import memory_lifecycle
203 agents = memory_lifecycle.agents_of(db, organisation_id=organisation.id)
204 db.delete(organisation)
205 db.commit()
206 # Its agents and its projects' went with it; what they remember is in
207 # svc-ai, where nothing cascades.
208 memory_lifecycle.forget_agents(agents)
210 logger.info("Deleted organisation %s", id)
213# Members and invites: the same routes projects mount.
214register_membership_routes(organisation_router, ORGANISATION, path_prefix="/id")
217# Organisations are membership-scoped, not owner-scoped — they carry no
218# owner_* columns, so the default ownership check would allow everyone.
219# verify_organisation_access is the same predicate GET /id/{id} already uses,
220# which keeps an organisation's history exactly as readable as the
221# organisation itself.
222register_history_routes(
223 organisation_router,
224 resource_type=HistoryEnum.ResourceType.organisation,
225 model=Organisation,
226 not_found_detail="Organisation not found",
227 access_check=verify_organisation_access,
228 path_prefix="/id",
229)