Deploy Development / deploy (push) Successful in 44s
Prüfstufen hier, darin, Umfeld stehen als Kontoeinstellung bereit. Der Server antwortet bei einem sicheren Treffer mit 409 und bindet auf Wunsch das vorhandene Element zusätzlich ein. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1726 lines
56 KiB
Python
1726 lines
56 KiB
Python
"""HTTP routes for the first usable delivery."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from uuid import UUID
|
|
|
|
from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile
|
|
from fastapi.responses import JSONResponse
|
|
from psycopg import Connection
|
|
|
|
from app.access.policy import (
|
|
Ctx,
|
|
account_by_email,
|
|
audit,
|
|
case_rights,
|
|
deadline_rights,
|
|
element_rights,
|
|
ensure_member_or_personal,
|
|
get_case,
|
|
get_deadline,
|
|
get_element,
|
|
get_matter,
|
|
get_task,
|
|
list_cases,
|
|
list_matters,
|
|
room_name,
|
|
matter_rights,
|
|
parse_context,
|
|
parse_query_context,
|
|
require_case,
|
|
require_matter,
|
|
task_rights,
|
|
)
|
|
from app.access.limits import ensure_can_add_member
|
|
from app.api.deps import Principal, get_conn, get_principal, get_session
|
|
from app.api.externals import place_external
|
|
from app.api.schemas import (
|
|
AcceptInviteIn,
|
|
AnnotationIn,
|
|
BootstrapIn,
|
|
AssigneeIn,
|
|
BindingIn,
|
|
CaseIn,
|
|
CaseLinkIn,
|
|
CasePatch,
|
|
ChapterDateIn,
|
|
ChapterDeleteIn,
|
|
ChapterParentIn,
|
|
BindingChaptersIn,
|
|
ChapterTitleIn,
|
|
CommunicationIn,
|
|
MatterMoveIn,
|
|
RecordDeleteIn,
|
|
ChapterIn,
|
|
ChapterOrderIn,
|
|
CrossLinkIn,
|
|
DeadlineIn,
|
|
DeadlinePatch,
|
|
DeleteElementIn,
|
|
ExceptionIn,
|
|
ExternalIn,
|
|
FulfillIn,
|
|
GrantIn,
|
|
LoginIn,
|
|
MatterIn,
|
|
MatterPatch,
|
|
BindingOrderIn,
|
|
ContentOrderIn,
|
|
ChapterMoveIn,
|
|
DatesPatch,
|
|
NoteIn,
|
|
NotePatch,
|
|
ScopeIn,
|
|
TaskDeadlineIn,
|
|
ElementReferenceIn,
|
|
TaskDependencyIn,
|
|
TaskElementsIn,
|
|
SummaryPatch,
|
|
TitlePatch,
|
|
TaskIn,
|
|
TaskPatch,
|
|
)
|
|
from app.auth.accounts import (
|
|
clear_login_attempts,
|
|
create_account,
|
|
initial_scope,
|
|
list_rooms,
|
|
login_blocked,
|
|
normalize_email,
|
|
record_failed_login,
|
|
start_session,
|
|
)
|
|
from app.auth.security import (
|
|
clear_session_cookie,
|
|
device_label,
|
|
hash_secret,
|
|
login_bucket,
|
|
new_secret,
|
|
session_expiry,
|
|
set_session_cookie,
|
|
verify_password,
|
|
verify_unknown_account,
|
|
)
|
|
from app.core.errors import DOWNLOAD_REFUSED, Problem, forbidden, not_found, too_many, unprocessable
|
|
from app.core.timeutil import dump_date, dump_dt, utcnow
|
|
from app.media.port import read_clear_bytes
|
|
from app.media.storage import content_disposition
|
|
from app.ops import (
|
|
add_annotation,
|
|
assign_task,
|
|
bind_element,
|
|
create_case,
|
|
create_chapter,
|
|
create_cross_link,
|
|
create_deadline,
|
|
create_file,
|
|
create_matter,
|
|
create_note,
|
|
create_task,
|
|
delete_case,
|
|
delete_chapter,
|
|
delete_cross_link,
|
|
delete_element,
|
|
delete_matter,
|
|
detach_binding,
|
|
fulfill_deadline,
|
|
grant_access,
|
|
link_matter_to_case,
|
|
link_task_deadline,
|
|
link_element_reference,
|
|
link_task_dependency,
|
|
set_task_elements,
|
|
unlink_element_reference,
|
|
unlink_task_dependency,
|
|
patch_case,
|
|
patch_deadline,
|
|
patch_matter,
|
|
patch_task,
|
|
revoke_grant,
|
|
move_binding_chapter,
|
|
move_bindings_chapter,
|
|
move_chapter_parent,
|
|
move_matter,
|
|
reorder_bindings,
|
|
rename_chapter,
|
|
reorder_chapters,
|
|
set_chapter_date,
|
|
set_communication_direction,
|
|
set_content_order,
|
|
set_exception,
|
|
unlink_matter_case,
|
|
update_dates,
|
|
update_note,
|
|
update_summary,
|
|
update_title,
|
|
)
|
|
from app.present import (
|
|
LABELS,
|
|
binding_payload,
|
|
case_detail,
|
|
case_summary,
|
|
deadline_payload,
|
|
course_items,
|
|
matter_detail,
|
|
matter_summary,
|
|
note_update_payload,
|
|
task_payload,
|
|
)
|
|
from app.library import case_items, matter_items
|
|
from app.ops import share_with_room as _share_with_room
|
|
from app.seed import demo_public
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def _chosen_home(conn, principal: Principal, requested: UUID | None) -> UUID:
|
|
scope_id = requested or principal.scope_id
|
|
room = conn.execute("SELECT id, kind FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
|
if room is None:
|
|
raise not_found()
|
|
ensure_member_or_personal(conn, principal.account_id, room["kind"], room["id"])
|
|
return room["id"]
|
|
|
|
|
|
def _created(path: str, payload: dict) -> JSONResponse:
|
|
return JSONResponse(status_code=201, content=payload, headers={"Location": path})
|
|
|
|
|
|
def _ctx_model(value) -> Ctx | None:
|
|
return None if value is None else Ctx(value.kind, value.id)
|
|
|
|
|
|
def _chapter_payload(row) -> dict:
|
|
return {
|
|
"id": str(row["id"]),
|
|
"title": row["title"],
|
|
"position": row["position"],
|
|
"document_on": dump_date(row["document_on"]),
|
|
"parent_chapter_id": str(row["parent_chapter_id"]) if row["parent_chapter_id"] else None,
|
|
}
|
|
|
|
|
|
def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf: str, epoch: int) -> dict:
|
|
account = conn.execute(
|
|
"SELECT id, email, display_name, is_superadmin, must_change_password, account_kind FROM auth_accounts WHERE id = %s",
|
|
(account_id,),
|
|
).fetchone()
|
|
room = conn.execute("SELECT id, kind, name FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
|
return {
|
|
"account": {
|
|
"id": str(account["id"]),
|
|
"email": account["email"],
|
|
"display_name": account["display_name"],
|
|
"is_superadmin": account["is_superadmin"],
|
|
"must_change_password": account["must_change_password"],
|
|
"account_kind": account["account_kind"],
|
|
},
|
|
"scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]},
|
|
"rooms": list_rooms(conn, account_id),
|
|
"csrf_token": csrf,
|
|
"epoch": epoch,
|
|
}
|
|
|
|
|
|
@router.post("/api/v1/auth/login")
|
|
def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn)):
|
|
email = normalize_email(body.email)
|
|
bucket = login_bucket(request.client.host if request.client else "local", email)
|
|
if login_blocked(conn, bucket):
|
|
raise too_many()
|
|
account = conn.execute(
|
|
"SELECT * FROM auth_accounts WHERE email = %s",
|
|
(email,),
|
|
).fetchone()
|
|
if account is None or account["status"] != "active":
|
|
# Same time and same answer as a wrong password.
|
|
verify_unknown_account(body.password)
|
|
valid = False
|
|
else:
|
|
valid = verify_password(body.password, account["password_hash"])
|
|
if not valid:
|
|
record_failed_login(conn, bucket)
|
|
raise Problem(401, "Anmeldung fehlgeschlagen", "E-Mail oder Passwort ist nicht richtig.", "unauthorized")
|
|
clear_login_attempts(conn, bucket)
|
|
settings = request.app.state.settings
|
|
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
|
scope_kind, scope_id = initial_scope(conn, account["id"])
|
|
payload = _session_body(conn, account["id"], scope_kind, scope_id, csrf, 1)
|
|
response = JSONResponse(payload)
|
|
set_session_cookie(response, request, settings, token)
|
|
return response
|
|
|
|
|
|
@router.post("/api/v1/auth/logout", status_code=204)
|
|
def logout(request: Request, session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
|
conn.execute("UPDATE auth_sessions SET revoked_at = now() WHERE id = %s", (session["id"],))
|
|
audit(conn, session["account_id"], None, "session_ended", "session", session["id"])
|
|
response = Response(status_code=204)
|
|
clear_session_cookie(response, request, request.app.state.settings)
|
|
return response
|
|
|
|
|
|
@router.get("/api/v1/auth/session")
|
|
def session_view(session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
|
return _session_body(
|
|
conn,
|
|
session["account_id"],
|
|
session["scope_kind"],
|
|
session["scope_id"],
|
|
session["csrf_token"],
|
|
session["epoch"],
|
|
)
|
|
|
|
|
|
@router.post("/api/v1/auth/session/scope")
|
|
def choose_scope(
|
|
body: ScopeIn,
|
|
request: Request,
|
|
session: dict = Depends(get_session),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
from app.access.policy import ensure_member_or_personal
|
|
|
|
room = ensure_member_or_personal(conn, session["account_id"], body.kind, body.id)
|
|
row = conn.execute(
|
|
"""
|
|
UPDATE auth_sessions
|
|
SET scope_kind = %s, scope_id = %s, epoch = epoch + 1
|
|
WHERE id = %s
|
|
RETURNING epoch, csrf_token
|
|
""",
|
|
(body.kind, room["id"], session["id"]),
|
|
).fetchone()
|
|
return _session_body(conn, session["account_id"], body.kind, room["id"], row["csrf_token"], row["epoch"])
|
|
|
|
|
|
@router.get("/api/v1/auth/demo")
|
|
def demo(request: Request):
|
|
return demo_public(request.app.state.settings)
|
|
|
|
|
|
def _superadmin_exists(conn: Connection) -> bool:
|
|
return conn.execute("SELECT 1 FROM auth_accounts WHERE is_superadmin LIMIT 1").fetchone() is not None
|
|
|
|
|
|
@router.get("/api/v1/auth/bootstrap")
|
|
def bootstrap_available(conn: Connection = Depends(get_conn)):
|
|
if _superadmin_exists(conn):
|
|
raise not_found()
|
|
return {"available": True}
|
|
|
|
|
|
@router.post("/api/v1/auth/bootstrap")
|
|
def bootstrap(body: BootstrapIn, request: Request, conn: Connection = Depends(get_conn)):
|
|
conn.execute("LOCK TABLE auth_accounts IN EXCLUSIVE MODE")
|
|
if _superadmin_exists(conn):
|
|
raise not_found()
|
|
account = create_account(conn, body.email, body.display_name, body.password, is_superadmin=True)
|
|
settings = request.app.state.settings
|
|
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
|
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
|
response = JSONResponse(status_code=201, content=payload)
|
|
set_session_cookie(response, request, settings, token)
|
|
return response
|
|
|
|
|
|
@router.post("/api/v1/invitations/{invitation_id}/accept")
|
|
def accept_invite(
|
|
invitation_id: UUID,
|
|
body: AcceptInviteIn,
|
|
request: Request,
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
row = conn.execute("SELECT * FROM auth_invitations WHERE id = %s", (invitation_id,)).fetchone()
|
|
if (
|
|
row is None
|
|
or row["accepted_at"] is not None
|
|
or row["revoked_at"] is not None
|
|
or row["expires_at"] <= utcnow()
|
|
):
|
|
raise not_found()
|
|
if row["token_hash"] != hash_secret(body.token):
|
|
raise not_found()
|
|
room = conn.execute("SELECT owner_id FROM data_rooms WHERE id = %s AND status = 'active'", (row["room_id"],)).fetchone()
|
|
if room is None:
|
|
raise not_found()
|
|
ensure_can_add_member(conn, room["owner_id"], row["room_id"])
|
|
# An invitation creates an employee account. The owner of the room is the sponsor.
|
|
account = create_account(
|
|
conn,
|
|
row["email"],
|
|
body.display_name,
|
|
body.password,
|
|
account_kind="employee",
|
|
sponsor_id=room["owner_id"],
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO room_memberships (room_id, subject_id, role)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(row["room_id"], account["id"], row["role"]),
|
|
)
|
|
conn.execute("UPDATE auth_invitations SET accepted_at = now() WHERE id = %s", (invitation_id,))
|
|
audit(conn, account["id"], row["room_id"], "invitation_accepted", "invitation", invitation_id)
|
|
settings = request.app.state.settings
|
|
token, csrf = start_session(conn, settings, account["id"], device_label(request.headers.get("user-agent")))
|
|
scope_kind, scope_id = initial_scope(conn, account["id"])
|
|
payload = _session_body(conn, account["id"], scope_kind, scope_id, csrf, 1)
|
|
response = JSONResponse(status_code=201, content=payload)
|
|
set_session_cookie(response, request, settings, token)
|
|
return response
|
|
|
|
|
|
@router.get("/api/v1/principals")
|
|
def find_principal(email: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
account = account_by_email(conn, email)
|
|
if account is None or account["status"] != "active":
|
|
raise not_found()
|
|
return {"id": str(account["id"]), "email": account["email"], "display_name": account["display_name"]}
|
|
|
|
|
|
@router.get("/api/v1/cases")
|
|
def cases(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
return {"items": case_items(conn, principal.account_id, list_cases(conn, principal.account_id)), "next_cursor": None}
|
|
|
|
|
|
@router.post("/api/v1/cases")
|
|
def post_case(body: CaseIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
case = create_case(
|
|
conn,
|
|
principal.account_id,
|
|
_chosen_home(conn, principal, body.home_scope_id),
|
|
body.title,
|
|
body.parent_case_id,
|
|
body.rights_mode,
|
|
)
|
|
if body.share_with_room_id is not None:
|
|
_share_with_room(conn, principal.account_id, "case", case["id"], body.share_with_room_id, "edit")
|
|
rights = case_rights(conn, principal.account_id, case)
|
|
return _created(f"/api/v1/cases/{case['id']}", case_summary(case, rights))
|
|
|
|
|
|
@router.get("/api/v1/cases/{case_id}")
|
|
def get_one_case(case_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
case, rights = require_case(conn, principal.account_id, case_id, "read")
|
|
return case_detail(conn, principal.account_id, case, rights)
|
|
|
|
|
|
@router.patch("/api/v1/cases/{case_id}")
|
|
def patch_one_case(
|
|
case_id: UUID,
|
|
body: CasePatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
case = patch_case(conn, principal.account_id, case_id, body.expected_version, body.title, body.status)
|
|
rights = case_rights(conn, principal.account_id, case)
|
|
return case_summary(case, rights)
|
|
|
|
|
|
@router.post("/api/v1/cases/{case_id}/chapters")
|
|
def post_case_chapter(
|
|
case_id: UUID,
|
|
body: ChapterIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
row = create_chapter(
|
|
conn,
|
|
principal.account_id,
|
|
"case",
|
|
case_id,
|
|
body.title,
|
|
body.position,
|
|
None,
|
|
body.document_on,
|
|
body.parent_chapter_id,
|
|
)
|
|
return _created(
|
|
f"/api/v1/cases/{case_id}/chapters/{row['id']}",
|
|
_chapter_payload(row),
|
|
)
|
|
|
|
|
|
@router.post("/api/v1/cases/{case_id}/chapters/order")
|
|
def post_case_chapter_order(
|
|
case_id: UUID,
|
|
body: ChapterOrderIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = reorder_chapters(conn, principal.account_id, "case", case_id, body.expected_version, body.chapter_ids, None)
|
|
return {"version": version}
|
|
|
|
|
|
@router.post("/api/v1/cases/{case_id}/grants")
|
|
def post_case_grant(
|
|
case_id: UUID,
|
|
body: GrantIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
account = account_by_email(conn, body.email)
|
|
if account is None:
|
|
raise not_found()
|
|
grant = grant_access(
|
|
conn,
|
|
principal.account_id,
|
|
"case",
|
|
case_id,
|
|
account["id"],
|
|
body.can_read,
|
|
body.can_edit,
|
|
body.can_share,
|
|
None,
|
|
body.use_owner_sources,
|
|
)
|
|
return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])})
|
|
|
|
|
|
@router.get("/api/v1/matters")
|
|
def matters(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
return {"items": matter_items(conn, principal.account_id, list_matters(conn, principal.account_id)), "next_cursor": None}
|
|
|
|
|
|
@router.post("/api/v1/matters")
|
|
def post_matter(body: MatterIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
matter = create_matter(
|
|
conn,
|
|
principal.account_id,
|
|
_chosen_home(conn, principal, body.home_scope_id),
|
|
body.title,
|
|
body.parent_matter_id,
|
|
_ctx_model(body.context),
|
|
)
|
|
if body.share_with_room_id is not None:
|
|
_share_with_room(conn, principal.account_id, "matter", matter["id"], body.share_with_room_id, "edit")
|
|
return _created(f"/api/v1/matters/{matter['id']}", matter_summary(conn, principal.account_id, matter))
|
|
|
|
|
|
@router.get("/api/v1/matters/{matter_id}")
|
|
def get_one_matter(
|
|
matter_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
context = parse_query_context(context_kind, context_id)
|
|
matter, rights = require_matter(conn, principal.account_id, matter_id, context, "read")
|
|
return matter_detail(conn, principal.account_id, matter, rights, context)
|
|
|
|
|
|
@router.patch("/api/v1/matters/{matter_id}")
|
|
def patch_one_matter(
|
|
matter_id: UUID,
|
|
body: MatterPatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
matter = patch_matter(
|
|
conn, principal.account_id, matter_id, body.expected_version, body.title, body.status, _ctx_model(body.context)
|
|
)
|
|
return matter_summary(conn, principal.account_id, matter)
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/chapters")
|
|
def post_matter_chapter(
|
|
matter_id: UUID,
|
|
body: ChapterIn,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
context = parse_query_context(context_kind, context_id)
|
|
row = create_chapter(
|
|
conn,
|
|
principal.account_id,
|
|
"matter",
|
|
matter_id,
|
|
body.title,
|
|
body.position,
|
|
context,
|
|
body.document_on,
|
|
body.parent_chapter_id,
|
|
)
|
|
return _created(
|
|
f"/api/v1/matters/{matter_id}/chapters/{row['id']}",
|
|
_chapter_payload(row),
|
|
)
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/chapters/order")
|
|
def post_matter_chapter_order(
|
|
matter_id: UUID,
|
|
body: ChapterOrderIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = reorder_chapters(
|
|
conn, principal.account_id, "matter", matter_id, body.expected_version, body.chapter_ids, _ctx_model(body.context)
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.patch("/api/v1/chapters/{chapter_id}/title")
|
|
def patch_chapter_title(
|
|
chapter_id: UUID,
|
|
body: ChapterTitleIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = rename_chapter(
|
|
conn, principal.account_id, chapter_id, body.expected_version, body.title, _ctx_model(body.context)
|
|
)
|
|
return {"version": version, "title": body.title}
|
|
|
|
|
|
@router.post("/api/v1/chapters/{chapter_id}/delete")
|
|
def post_delete_chapter(
|
|
chapter_id: UUID,
|
|
body: ChapterDeleteIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = delete_chapter(
|
|
conn, principal.account_id, chapter_id, body.expected_version, _ctx_model(body.context)
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.post("/api/v1/chapters/{chapter_id}/parent")
|
|
def post_chapter_parent(
|
|
chapter_id: UUID,
|
|
body: ChapterParentIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = move_chapter_parent(
|
|
conn,
|
|
principal.account_id,
|
|
chapter_id,
|
|
body.expected_version,
|
|
body.parent_chapter_id,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"version": version, "parent_chapter_id": str(body.parent_chapter_id) if body.parent_chapter_id else None}
|
|
|
|
|
|
@router.post("/api/v1/cases/{case_id}/delete")
|
|
def post_delete_case(
|
|
case_id: UUID,
|
|
body: RecordDeleteIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
delete_case(conn, principal.account_id, case_id, body.expected_version)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/delete")
|
|
def post_delete_matter(
|
|
matter_id: UUID,
|
|
body: RecordDeleteIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
delete_matter(conn, principal.account_id, matter_id, body.expected_version, _ctx_model(body.context))
|
|
return {"ok": True}
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/move")
|
|
def post_move_matter(
|
|
matter_id: UUID,
|
|
body: MatterMoveIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
matter = move_matter(
|
|
conn,
|
|
principal.account_id,
|
|
matter_id,
|
|
body.expected_version,
|
|
_ctx_model(body.context),
|
|
body.case_id,
|
|
body.parent_matter_id,
|
|
body.clear_parent,
|
|
)
|
|
return matter_summary(conn, principal.account_id, matter)
|
|
|
|
|
|
@router.patch("/api/v1/bindings/{binding_id}/communication")
|
|
def patch_communication(
|
|
binding_id: UUID,
|
|
body: CommunicationIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
element = set_communication_direction(
|
|
conn,
|
|
principal.account_id,
|
|
binding_id,
|
|
body.expected_version,
|
|
body.direction,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"version": element["version"], "direction": body.direction}
|
|
|
|
|
|
@router.patch("/api/v1/chapters/{chapter_id}")
|
|
def patch_chapter_date(
|
|
chapter_id: UUID,
|
|
body: ChapterDateIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = set_chapter_date(
|
|
conn, principal.account_id, chapter_id, body.expected_version, body.document_on, _ctx_model(body.context)
|
|
)
|
|
return {"version": version, "document_on": dump_date(body.document_on)}
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/case-links")
|
|
def post_case_link(
|
|
matter_id: UUID,
|
|
body: CaseLinkIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
link = link_matter_to_case(conn, principal.account_id, matter_id, body.case_id, _ctx_model(body.context))
|
|
return _created(f"/api/v1/matter-case-links/{link['id']}", {"id": str(link["id"]), "case_id": str(body.case_id)})
|
|
|
|
|
|
@router.delete("/api/v1/matter-case-links/{link_id}", status_code=204)
|
|
def delete_case_link(link_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
unlink_matter_case(conn, principal.account_id, link_id)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/cross-links")
|
|
def post_cross_link(
|
|
matter_id: UUID,
|
|
body: CrossLinkIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
row = create_cross_link(
|
|
conn,
|
|
principal.account_id,
|
|
matter_id,
|
|
body.target_matter_id,
|
|
_ctx_model(body.source_context),
|
|
Ctx(body.target_context.kind, body.target_context.id),
|
|
)
|
|
return _created(f"/api/v1/matter-cross-links/{row['id']}", {"id": str(row["id"])})
|
|
|
|
|
|
@router.delete("/api/v1/matter-cross-links/{link_id}", status_code=204)
|
|
def remove_cross_link(
|
|
link_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
delete_cross_link(conn, principal.account_id, link_id, parse_query_context(context_kind, context_id))
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/grants")
|
|
def post_matter_grant(
|
|
matter_id: UUID,
|
|
body: GrantIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
account = account_by_email(conn, body.email)
|
|
if account is None:
|
|
raise not_found()
|
|
grant = grant_access(
|
|
conn,
|
|
principal.account_id,
|
|
"matter",
|
|
matter_id,
|
|
account["id"],
|
|
body.can_read,
|
|
body.can_edit,
|
|
body.can_share,
|
|
None,
|
|
body.use_owner_sources,
|
|
)
|
|
return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])})
|
|
|
|
|
|
@router.delete("/api/v1/grants/{grant_id}", status_code=204)
|
|
def delete_grant(grant_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
revoke_grant(conn, principal.account_id, grant_id)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.put("/api/v1/exceptions")
|
|
def put_exception(body: ExceptionIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
set_exception(
|
|
conn,
|
|
principal.account_id,
|
|
body.resource_kind,
|
|
body.resource_id,
|
|
Ctx(body.context.kind, body.context.id),
|
|
body.remove_read,
|
|
body.remove_edit,
|
|
body.remove_share,
|
|
)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.post("/api/v1/notes")
|
|
def post_note(body: NoteIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
created = create_note(
|
|
conn,
|
|
principal.account_id,
|
|
principal.scope_id,
|
|
body.title,
|
|
body.document.model_dump(),
|
|
Ctx(body.context.kind, body.context.id),
|
|
_ctx_model(body.placement),
|
|
body.chapter_id,
|
|
body.dates.document_on if body.dates else None,
|
|
body.dates.sent_on if body.dates else None,
|
|
body.dates.received_on if body.dates else None,
|
|
body.communication_direction,
|
|
)
|
|
element = created["element"]
|
|
return _created(
|
|
f"/api/v1/notes/{element['id']}",
|
|
note_update_payload(conn, principal.account_id, element, created["document"]),
|
|
)
|
|
|
|
|
|
@router.patch("/api/v1/notes/{element_id}")
|
|
def patch_note(
|
|
element_id: UUID,
|
|
body: NotePatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
updated = update_note(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
body.expected_version,
|
|
body.document.model_dump(),
|
|
_ctx_model(body.context),
|
|
)
|
|
return note_update_payload(conn, principal.account_id, updated["element"], updated["document"])
|
|
|
|
|
|
@router.post("/api/v1/bindings")
|
|
def post_binding(body: BindingIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
binding = bind_element(
|
|
conn,
|
|
principal.account_id,
|
|
body.element_id,
|
|
Ctx(body.source_context.kind, body.source_context.id),
|
|
Ctx(body.target.kind, body.target.id),
|
|
_ctx_model(body.target_context),
|
|
body.chapter_id,
|
|
)
|
|
return _created(f"/api/v1/bindings/{binding['id']}", {"id": str(binding["id"])})
|
|
|
|
|
|
@router.delete("/api/v1/bindings/{binding_id}", status_code=204)
|
|
def delete_binding(
|
|
binding_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
detach_binding(conn, principal.account_id, binding_id, parse_query_context(context_kind, context_id))
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/api/v1/bindings/{binding_id}/annotations")
|
|
def post_annotation(
|
|
binding_id: UUID,
|
|
body: AnnotationIn,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
row = add_annotation(
|
|
conn, principal.account_id, binding_id, body.body, parse_query_context(context_kind, context_id)
|
|
)
|
|
return _created(f"/api/v1/bindings/{binding_id}/annotations/{row['id']}", {"id": str(row["id"]), "body": row["body"]})
|
|
|
|
|
|
@router.post("/api/v1/external-refs")
|
|
def post_external(body: ExternalIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
element = place_external(conn, principal, body)
|
|
return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]})
|
|
|
|
|
|
@router.post("/api/v1/files")
|
|
def post_file(
|
|
request: Request,
|
|
title: str = Form(),
|
|
context_kind: str = Form(),
|
|
context_id: UUID = Form(),
|
|
upload: UploadFile = File(),
|
|
placement_kind: str | None = Form(default=None),
|
|
placement_id: UUID | None = Form(default=None),
|
|
chapter_id: UUID | None = Form(default=None),
|
|
document_on: str | None = Form(default=None),
|
|
sent_on: str | None = Form(default=None),
|
|
received_on: str | None = Form(default=None),
|
|
communication_direction: str | None = Form(default=None),
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
settings = request.app.state.settings
|
|
cleaned_title = title.strip()
|
|
if not cleaned_title or len(cleaned_title) > 200:
|
|
raise unprocessable("Der Titel fehlt oder ist zu lang.")
|
|
data = upload.file.read(settings.upload_max_bytes + 1)
|
|
context = parse_context({"kind": context_kind, "id": str(context_id)}, required=True)
|
|
placement = None
|
|
if placement_kind or placement_id:
|
|
placement = parse_context({"kind": placement_kind, "id": str(placement_id)}, required=True)
|
|
request.state.cleanup_files = []
|
|
element = create_file(
|
|
conn,
|
|
principal.account_id,
|
|
principal.scope_id,
|
|
cleaned_title,
|
|
upload.filename or "datei",
|
|
data,
|
|
context,
|
|
placement,
|
|
chapter_id,
|
|
_parse_date(document_on),
|
|
_parse_date(sent_on),
|
|
_parse_date(received_on),
|
|
settings.media_root,
|
|
settings.upload_max_bytes,
|
|
request.state.cleanup_files,
|
|
communication_direction if communication_direction in {"in", "out", "local"} else None,
|
|
)
|
|
return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]})
|
|
|
|
|
|
@router.get("/api/v1/files/{element_id}/content")
|
|
def download_file(
|
|
element_id: UUID,
|
|
request: Request,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
save: bool = False,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
context = parse_query_context(context_kind, context_id)
|
|
element = get_element(conn, element_id)
|
|
if element is None or element["kind"] != "file":
|
|
raise not_found()
|
|
rights = element_rights(conn, principal.account_id, element, context)
|
|
if not rights.read:
|
|
raise not_found()
|
|
if save and not rights.download:
|
|
raise forbidden(DOWNLOAD_REFUSED)
|
|
asset = conn.execute(
|
|
"""
|
|
SELECT id, original_filename, content_type, sha256, status,
|
|
storage_instance_id, storage_generation, object_key, protection_profile
|
|
FROM media_assets WHERE element_id = %s
|
|
""",
|
|
(element_id,),
|
|
).fetchone()
|
|
if asset is None or asset["status"] != "active":
|
|
raise not_found()
|
|
payload = read_clear_bytes(
|
|
conn,
|
|
instance_id=asset["storage_instance_id"],
|
|
generation=asset["storage_generation"],
|
|
object_key=asset["object_key"] or str(asset["id"]),
|
|
media_root=request.app.state.settings.media_root,
|
|
protection_profile=asset["protection_profile"],
|
|
expected_sha256=asset["sha256"],
|
|
)
|
|
return Response(
|
|
content=payload,
|
|
media_type=asset["content_type"],
|
|
headers={
|
|
"Content-Disposition": content_disposition(asset["original_filename"]),
|
|
"X-Content-Type-Options": "nosniff",
|
|
"Cache-Control": "private, no-store",
|
|
},
|
|
)
|
|
|
|
|
|
@router.post("/api/v1/elements/{element_id}/delete", status_code=204)
|
|
def destroy_element(
|
|
element_id: UUID,
|
|
body: DeleteElementIn,
|
|
request: Request,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
request.state.delete_after_commit = []
|
|
delete_element(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
body.expected_version,
|
|
request.app.state.settings.media_root,
|
|
request.state.delete_after_commit,
|
|
)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.get("/api/v1/elements")
|
|
def elements(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM elements
|
|
WHERE owner_subject_id = %s AND deleted_at IS NULL
|
|
AND NOT EXISTS (SELECT 1 FROM bindings b WHERE b.element_id = elements.id)
|
|
ORDER BY updated_at DESC, id DESC
|
|
LIMIT 100
|
|
""",
|
|
(principal.account_id,),
|
|
).fetchall()
|
|
return {
|
|
"items": [{"id": str(row["id"]), "kind": row["kind"], "title": row["title"], "version": row["version"]} for row in rows],
|
|
"next_cursor": None,
|
|
}
|
|
|
|
|
|
@router.post("/api/v1/tasks")
|
|
def post_task(body: TaskIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
task = create_task(
|
|
conn, principal.account_id, principal.scope_id, body.title, body.due_on, body.matter_id, _ctx_model(body.context)
|
|
)
|
|
rights = task_rights(conn, principal.account_id, task, _ctx_model(body.context))
|
|
return _created(f"/api/v1/tasks/{task['id']}", task_payload(conn, principal.account_id, task, rights))
|
|
|
|
|
|
@router.patch("/api/v1/tasks/{task_id}")
|
|
def patch_one_task(
|
|
task_id: UUID,
|
|
body: TaskPatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
task = patch_task(
|
|
conn,
|
|
principal.account_id,
|
|
task_id,
|
|
body.expected_version,
|
|
body.title,
|
|
body.due_on,
|
|
body.clear_due_on,
|
|
body.status,
|
|
_ctx_model(body.context),
|
|
)
|
|
rights = task_rights(conn, principal.account_id, task, _ctx_model(body.context))
|
|
return task_payload(conn, principal.account_id, task, rights)
|
|
|
|
|
|
@router.post("/api/v1/tasks/{task_id}/assignee")
|
|
def post_assignee(
|
|
task_id: UUID,
|
|
body: AssigneeIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
assignee = None
|
|
if body.email:
|
|
account = account_by_email(conn, body.email)
|
|
if account is None:
|
|
raise not_found()
|
|
assignee = account["id"]
|
|
task = assign_task(conn, principal.account_id, task_id, assignee, _ctx_model(body.context))
|
|
rights = task_rights(conn, principal.account_id, task, _ctx_model(body.context))
|
|
return task_payload(conn, principal.account_id, task, rights)
|
|
|
|
|
|
@router.post("/api/v1/tasks/{task_id}/deadline-links", status_code=204)
|
|
def post_task_deadline(
|
|
task_id: UUID,
|
|
body: TaskDeadlineIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
link_task_deadline(conn, principal.account_id, task_id, body.deadline_id, _ctx_model(body.context))
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.put("/api/v1/tasks/{task_id}/elements", status_code=204)
|
|
def put_task_elements(
|
|
task_id: UUID,
|
|
body: TaskElementsIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
set_task_elements(conn, principal.account_id, task_id, body.element_ids, _ctx_model(body.context))
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/api/v1/tasks/{task_id}/dependencies", status_code=204)
|
|
def post_task_dependency(
|
|
task_id: UUID,
|
|
body: TaskDependencyIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
link_task_dependency(conn, principal.account_id, task_id, body.depends_on_task_id, _ctx_model(body.context))
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.delete("/api/v1/tasks/{task_id}/dependencies/{depends_on_task_id}", status_code=204)
|
|
def delete_task_dependency(
|
|
task_id: UUID,
|
|
depends_on_task_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
unlink_task_dependency(
|
|
conn,
|
|
principal.account_id,
|
|
task_id,
|
|
depends_on_task_id,
|
|
parse_query_context(context_kind, context_id),
|
|
)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/api/v1/elements/{element_id}/references", status_code=204)
|
|
def post_element_reference(
|
|
element_id: UUID,
|
|
body: ElementReferenceIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
link_element_reference(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
body.refers_to_element_id,
|
|
_ctx_model(body.context),
|
|
)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.delete("/api/v1/elements/{element_id}/references/{refers_to_element_id}", status_code=204)
|
|
def delete_element_reference(
|
|
element_id: UUID,
|
|
refers_to_element_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
unlink_element_reference(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
refers_to_element_id,
|
|
parse_query_context(context_kind, context_id),
|
|
)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/api/v1/deadlines")
|
|
def post_deadline(body: DeadlineIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
deadline = create_deadline(
|
|
conn, principal.account_id, principal.scope_id, body.title, body.due_on, body.matter_id, _ctx_model(body.context)
|
|
)
|
|
return _created(f"/api/v1/deadlines/{deadline['id']}", deadline_payload(conn, principal.account_id, deadline))
|
|
|
|
|
|
@router.patch("/api/v1/deadlines/{deadline_id}")
|
|
def patch_one_deadline(
|
|
deadline_id: UUID,
|
|
body: DeadlinePatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
deadline = patch_deadline(
|
|
conn, principal.account_id, deadline_id, body.expected_version, body.title, body.due_on, _ctx_model(body.context)
|
|
)
|
|
return deadline_payload(conn, principal.account_id, deadline)
|
|
|
|
|
|
@router.post("/api/v1/deadlines/{deadline_id}/fulfill")
|
|
def post_fulfill(
|
|
deadline_id: UUID,
|
|
body: FulfillIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
deadline = fulfill_deadline(conn, principal.account_id, deadline_id, body.expected_version, _ctx_model(body.context))
|
|
return deadline_payload(conn, principal.account_id, deadline)
|
|
|
|
|
|
VIEW_LIMIT = 200
|
|
SEARCH_LIMIT = 50
|
|
SCAN_BATCH = 200
|
|
SCAN_CAP = 20000
|
|
|
|
|
|
def _scan(conn, sql: str, params: tuple = ()):
|
|
"""Rows in the order of the query, read in batches.
|
|
|
|
The rights are checked per row after reading. A fixed LIMIT in the query would count rows
|
|
of other people too, so the own ones could fall off the end. The reader stops once it has
|
|
enough. `SCAN_CAP` bounds the work on very large data sets.
|
|
"""
|
|
offset = 0
|
|
while offset < SCAN_CAP:
|
|
rows = conn.execute(f"{sql} LIMIT %s OFFSET %s", (*params, SCAN_BATCH, offset)).fetchall()
|
|
yield from rows
|
|
if len(rows) < SCAN_BATCH:
|
|
return
|
|
offset += SCAN_BATCH
|
|
|
|
|
|
@router.get("/api/v1/views/open-tasks")
|
|
def open_tasks(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
items = []
|
|
for task in _scan(
|
|
conn,
|
|
"""
|
|
SELECT * FROM tasks
|
|
WHERE deleted_at IS NULL AND task_status = 'open'
|
|
ORDER BY due_on NULLS LAST, created_at, id
|
|
""",
|
|
):
|
|
if _task_visible(conn, principal.account_id, task):
|
|
items.append(task_payload(conn, principal.account_id, task))
|
|
if len(items) >= VIEW_LIMIT:
|
|
break
|
|
return {"items": items, "next_cursor": None}
|
|
|
|
|
|
@router.get("/api/v1/views/open-deadlines")
|
|
def open_deadlines(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
items = []
|
|
for deadline in _scan(
|
|
conn,
|
|
"""
|
|
SELECT * FROM deadlines
|
|
WHERE deleted_at IS NULL AND deadline_status = 'open'
|
|
ORDER BY due_on, created_at, id
|
|
""",
|
|
):
|
|
if _deadline_visible(conn, principal.account_id, deadline):
|
|
items.append(deadline_payload(conn, principal.account_id, deadline))
|
|
if len(items) >= VIEW_LIMIT:
|
|
break
|
|
return {"items": items, "next_cursor": None}
|
|
|
|
|
|
@router.get("/api/v1/placement-targets")
|
|
def placement_targets(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
items = []
|
|
for case, rights in list_cases(conn, principal.account_id):
|
|
if rights.edit:
|
|
items.append({"kind": "case", "id": str(case["id"]), "title": case["title"]})
|
|
for matter, contexts in list_matters(conn, principal.account_id):
|
|
editable = [item for item in contexts if item["rights"]["edit"]]
|
|
if editable:
|
|
items.append(
|
|
{
|
|
"kind": "matter",
|
|
"id": str(matter["id"]),
|
|
"title": matter["title"],
|
|
"contexts": [
|
|
{
|
|
"kind": "direct" if item["kind"] == "matter" else item["kind"],
|
|
"id": item["id"],
|
|
"title": item["title"],
|
|
}
|
|
for item in editable
|
|
],
|
|
}
|
|
)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/api/v1/search")
|
|
def search(q: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
term = q.strip()
|
|
if len(term) < 2:
|
|
raise unprocessable("Bitte mindestens zwei Zeichen suchen.")
|
|
pattern = "%" + term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
|
items = []
|
|
for case, rights in list_cases(conn, principal.account_id):
|
|
if rights.read and term.casefold() in case["title"].casefold():
|
|
items.append({"kind": "case", "id": str(case["id"]), "title": case["title"], "contexts": []})
|
|
for matter, contexts in list_matters(conn, principal.account_id):
|
|
if term.casefold() in matter["title"].casefold():
|
|
items.append(
|
|
{
|
|
"kind": "matter",
|
|
"id": str(matter["id"]),
|
|
"title": matter["title"],
|
|
"contexts": [
|
|
{"kind": "direct" if item["kind"] == "matter" else item["kind"], "id": item["id"], "title": item["title"]}
|
|
for item in contexts
|
|
],
|
|
}
|
|
)
|
|
elements = _scan(
|
|
conn,
|
|
"""
|
|
SELECT e.*
|
|
FROM elements e
|
|
LEFT JOIN note_bodies n ON n.element_id = e.id
|
|
WHERE e.deleted_at IS NULL
|
|
AND (e.title ILIKE %s ESCAPE '\\' OR COALESCE(n.document_json::text, '') ILIKE %s ESCAPE '\\')
|
|
ORDER BY e.updated_at DESC, e.id
|
|
""",
|
|
(pattern, pattern),
|
|
)
|
|
for element in elements:
|
|
if len(items) >= SEARCH_LIMIT:
|
|
break
|
|
from app.access.policy import visible_bindings_for_element
|
|
|
|
bindings = visible_bindings_for_element(conn, principal.account_id, element)
|
|
owner = element["owner_subject_id"] == principal.account_id
|
|
if not bindings and not owner:
|
|
continue
|
|
if not bindings and owner:
|
|
direct = element_rights(conn, principal.account_id, element, None)
|
|
if not direct.read:
|
|
continue
|
|
items.append(
|
|
{
|
|
"kind": element["kind"],
|
|
"id": str(element["id"]),
|
|
"title": element["title"],
|
|
"contexts": [
|
|
{
|
|
"kind": item["context_kind"],
|
|
"id": item["context_id"],
|
|
"title": item["context_title"],
|
|
"binding_id": item["id"],
|
|
"chapter_id": item.get("chapter_id"),
|
|
}
|
|
for item in bindings
|
|
],
|
|
}
|
|
)
|
|
return {"items": items[:SEARCH_LIMIT], "next_cursor": None}
|
|
|
|
|
|
@router.patch("/api/v1/cases/{case_id}/content-order")
|
|
def patch_case_order(
|
|
case_id: UUID,
|
|
body: ContentOrderIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = set_content_order(
|
|
conn,
|
|
principal.account_id,
|
|
"case",
|
|
case_id,
|
|
body.expected_version,
|
|
body.mode,
|
|
body.direction,
|
|
None,
|
|
body.view,
|
|
)
|
|
return {"version": version, "mode": body.mode, "direction": body.direction, "view": body.view}
|
|
|
|
|
|
@router.post("/api/v1/cases/{case_id}/bindings/order")
|
|
def post_case_binding_order(
|
|
case_id: UUID,
|
|
body: BindingOrderIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = reorder_bindings(
|
|
conn, principal.account_id, "case", case_id, body.expected_version, body.binding_ids, None
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.post("/api/v1/cases/{case_id}/bindings/chapters")
|
|
def post_case_binding_chapters(
|
|
case_id: UUID,
|
|
body: BindingChaptersIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = move_bindings_chapter(
|
|
conn,
|
|
principal.account_id,
|
|
"case",
|
|
case_id,
|
|
body.expected_version,
|
|
body.binding_ids,
|
|
body.chapter_id,
|
|
None,
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.patch("/api/v1/matters/{matter_id}/content-order")
|
|
def patch_matter_order(
|
|
matter_id: UUID,
|
|
body: ContentOrderIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = set_content_order(
|
|
conn,
|
|
principal.account_id,
|
|
"matter",
|
|
matter_id,
|
|
body.expected_version,
|
|
body.mode,
|
|
body.direction,
|
|
_ctx_model(body.context),
|
|
body.view,
|
|
)
|
|
return {"version": version, "mode": body.mode, "direction": body.direction, "view": body.view}
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/bindings/order")
|
|
def post_matter_binding_order(
|
|
matter_id: UUID,
|
|
body: BindingOrderIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = reorder_bindings(
|
|
conn,
|
|
principal.account_id,
|
|
"matter",
|
|
matter_id,
|
|
body.expected_version,
|
|
body.binding_ids,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.post("/api/v1/matters/{matter_id}/bindings/chapters")
|
|
def post_matter_binding_chapters(
|
|
matter_id: UUID,
|
|
body: BindingChaptersIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = move_bindings_chapter(
|
|
conn,
|
|
principal.account_id,
|
|
"matter",
|
|
matter_id,
|
|
body.expected_version,
|
|
body.binding_ids,
|
|
body.chapter_id,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.patch("/api/v1/elements/{element_id}/dates")
|
|
def patch_element_dates(
|
|
element_id: UUID,
|
|
body: DatesPatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
element = update_dates(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
body.expected_version,
|
|
body.document_on,
|
|
body.sent_on,
|
|
body.received_on,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"id": str(element["id"]), "version": element["version"]}
|
|
|
|
|
|
@router.patch("/api/v1/elements/{element_id}/summary")
|
|
def patch_element_summary(
|
|
element_id: UUID,
|
|
body: SummaryPatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
element = update_summary(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
body.expected_version,
|
|
body.summary,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"id": str(element["id"]), "version": element["version"], "summary": element["summary"]}
|
|
|
|
|
|
@router.patch("/api/v1/elements/{element_id}/title")
|
|
def patch_element_title(
|
|
element_id: UUID,
|
|
body: TitlePatch,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
element = update_title(
|
|
conn,
|
|
principal.account_id,
|
|
element_id,
|
|
body.expected_version,
|
|
body.title,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"id": str(element["id"]), "version": element["version"], "title": element["title"]}
|
|
|
|
|
|
@router.patch("/api/v1/bindings/{binding_id}/chapter")
|
|
def patch_binding_chapter(
|
|
binding_id: UUID,
|
|
body: ChapterMoveIn,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
version = move_binding_chapter(
|
|
conn,
|
|
principal.account_id,
|
|
binding_id,
|
|
body.expected_version,
|
|
body.chapter_id,
|
|
_ctx_model(body.context),
|
|
)
|
|
return {"version": version}
|
|
|
|
|
|
@router.get("/api/v1/cases/{case_id}/course")
|
|
def case_course(case_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
case, rights = require_case(conn, principal.account_id, case_id, "read")
|
|
detail = case_detail(conn, principal.account_id, case, rights)
|
|
return {"items": course_items(detail["bindings"]), "next_cursor": None}
|
|
|
|
|
|
@router.get("/api/v1/matters/{matter_id}/course")
|
|
def matter_course(
|
|
matter_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
context = parse_query_context(context_kind, context_id)
|
|
matter, rights = require_matter(conn, principal.account_id, matter_id, context, "read")
|
|
detail = matter_detail(conn, principal.account_id, matter, rights, context)
|
|
return {"items": course_items(detail["bindings"]), "next_cursor": None}
|
|
|
|
|
|
@router.get("/api/v1/views/recent-matters")
|
|
def recent_matters(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
|
rows = [matter for matter, _contexts in list_matters(conn, principal.account_id)]
|
|
rows.sort(key=lambda item: (item["updated_at"], str(item["id"])), reverse=True)
|
|
items = [matter_summary(conn, principal.account_id, matter) for matter in rows[:8]]
|
|
return {"items": items, "next_cursor": None}
|
|
|
|
|
|
@router.get("/api/v1/cases/{case_id}/chronology")
|
|
def case_chronology(
|
|
case_id: UUID,
|
|
cursor: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
case, _rights = require_case(conn, principal.account_id, case_id, "read")
|
|
page = Ctx("case", case["id"])
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT *
|
|
FROM domain_events
|
|
WHERE (resource_kind = 'case' AND resource_id = %(case)s)
|
|
OR (context_kind = 'case' AND context_id = %(case)s)
|
|
OR resource_id IN (SELECT matter_id FROM matter_case_links WHERE case_id = %(case)s)
|
|
OR resource_id IN (
|
|
SELECT element_id FROM bindings WHERE context_kind = 'case' AND context_id = %(case)s
|
|
UNION
|
|
SELECT b.element_id
|
|
FROM bindings b
|
|
JOIN matter_case_links l ON b.context_kind = 'matter' AND b.context_id = l.matter_id
|
|
WHERE l.case_id = %(case)s
|
|
)
|
|
ORDER BY COALESCE(occurred_on, occurred_at::date), occurred_at, id
|
|
""",
|
|
{"case": case_id},
|
|
).fetchall()
|
|
return _event_page(_visible_events(conn, principal.account_id, rows, page), cursor)
|
|
|
|
|
|
@router.get("/api/v1/matters/{matter_id}/chronology")
|
|
def matter_chronology(
|
|
matter_id: UUID,
|
|
context_kind: str | None = None,
|
|
context_id: str | None = None,
|
|
cursor: str | None = None,
|
|
principal: Principal = Depends(get_principal),
|
|
conn: Connection = Depends(get_conn),
|
|
):
|
|
context = parse_query_context(context_kind, context_id)
|
|
matter, _rights = require_matter(conn, principal.account_id, matter_id, context, "read")
|
|
page = context or Ctx("matter", matter["id"])
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT *
|
|
FROM domain_events
|
|
WHERE resource_id = %(matter)s
|
|
OR (context_kind = 'matter' AND context_id = %(matter)s)
|
|
OR resource_id IN (
|
|
SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %(matter)s
|
|
)
|
|
OR resource_id IN (
|
|
SELECT id FROM tasks WHERE matter_id = %(matter)s
|
|
UNION
|
|
SELECT id FROM deadlines WHERE matter_id = %(matter)s
|
|
)
|
|
ORDER BY COALESCE(occurred_on, occurred_at::date), occurred_at, id
|
|
""",
|
|
{"matter": matter_id},
|
|
).fetchall()
|
|
return _event_page(_visible_events(conn, principal.account_id, rows, page), cursor)
|
|
|
|
|
|
def _parse_date(value: str | None) -> date | None:
|
|
if value is None or value == "":
|
|
return None
|
|
try:
|
|
return date.fromisoformat(value)
|
|
except ValueError as exc:
|
|
raise unprocessable("Ein Datum ist ungültig.") from exc
|
|
|
|
|
|
def _task_visible(conn, actor: UUID, task: dict) -> bool:
|
|
if task_rights(conn, actor, task, None).read:
|
|
return True
|
|
matter = get_matter(conn, task["matter_id"]) if task["matter_id"] else None
|
|
if matter is None:
|
|
return False
|
|
return any(task_rights(conn, actor, task, Ctx(item["kind"], UUID(item["id"]))).read for item in _case_contexts(conn, actor, matter))
|
|
|
|
|
|
def _deadline_visible(conn, actor: UUID, deadline: dict) -> bool:
|
|
if deadline_rights(conn, actor, deadline, None).read:
|
|
return True
|
|
matter = get_matter(conn, deadline["matter_id"]) if deadline["matter_id"] else None
|
|
if matter is None:
|
|
return False
|
|
return any(
|
|
deadline_rights(conn, actor, deadline, Ctx(item["kind"], UUID(item["id"]))).read
|
|
for item in _case_contexts(conn, actor, matter)
|
|
)
|
|
|
|
|
|
def _case_contexts(conn, actor, matter) -> list[dict]:
|
|
from app.access.policy import readable_matter_contexts
|
|
|
|
return [item for item in readable_matter_contexts(conn, actor, matter) if item["kind"] == "case"]
|
|
|
|
|
|
def _event_page(items: list[dict], cursor: str | None, limit: int = 40) -> dict:
|
|
start = 0
|
|
if cursor:
|
|
ids = [item["id"] for item in items]
|
|
if cursor not in ids:
|
|
return {"items": [], "next_cursor": None}
|
|
start = ids.index(cursor) + 1
|
|
chunk = items[start:start + limit]
|
|
next_cursor = chunk[-1]["id"] if chunk and start + limit < len(items) else None
|
|
return {"items": chunk, "next_cursor": next_cursor}
|
|
|
|
|
|
def _visible_events(conn, actor: UUID, rows: list[dict], page: Ctx) -> list[dict]:
|
|
names: dict = {}
|
|
items = []
|
|
for event in rows:
|
|
if event["result"] != "ok":
|
|
continue
|
|
title = _event_title(conn, actor, event, page)
|
|
if title is None:
|
|
continue
|
|
actor_id = event["actor_subject_id"]
|
|
if actor_id not in names:
|
|
row = None
|
|
if actor_id is not None:
|
|
row = conn.execute(
|
|
"SELECT display_name FROM auth_accounts WHERE id = %s",
|
|
(actor_id,),
|
|
).fetchone()
|
|
names[actor_id] = row["display_name"] if row else None
|
|
items.append(
|
|
{
|
|
"id": str(event["id"]),
|
|
"action": event["action"],
|
|
"label": LABELS.get(event["action"], "Ereignis"),
|
|
"title": title,
|
|
"actor_display_name": names[actor_id],
|
|
"occurred_on": event["occurred_on"].isoformat() if event["occurred_on"] else None,
|
|
"occurred_at": event["occurred_at"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"resource_kind": event["resource_kind"],
|
|
"resource_id": str(event["resource_id"]),
|
|
}
|
|
)
|
|
return items
|
|
|
|
|
|
def _event_title(conn, actor: UUID, event: dict, page: Ctx) -> str | None:
|
|
kind = event["resource_kind"]
|
|
resource_id = event["resource_id"]
|
|
if kind == "case":
|
|
case = get_case(conn, resource_id)
|
|
if case is None or not case_rights(conn, actor, case).read:
|
|
return None
|
|
return case["title"]
|
|
if kind == "matter":
|
|
matter = get_matter(conn, resource_id)
|
|
if matter is None:
|
|
return None
|
|
context = page if page.kind == "case" else None
|
|
if not matter_rights(conn, actor, matter, context).read and not matter_rights(conn, actor, matter, None).read:
|
|
return None
|
|
if page.kind == "case" and not matter_rights(conn, actor, matter, page).read:
|
|
return None
|
|
return matter["title"]
|
|
if kind == "element":
|
|
element = get_element(conn, resource_id)
|
|
if element is None or not element_rights(conn, actor, element, page).read:
|
|
return None
|
|
return element["title"]
|
|
if kind == "task":
|
|
task = get_task(conn, resource_id)
|
|
if task is None or not task_rights(conn, actor, task, None if page.kind == "matter" else page).read:
|
|
if task is None or not task_rights(conn, actor, task, page).read:
|
|
return None
|
|
return task["title"] if task else None
|
|
if kind == "deadline":
|
|
deadline = get_deadline(conn, resource_id)
|
|
if deadline is None:
|
|
return None
|
|
direct = deadline_rights(conn, actor, deadline, None)
|
|
via = deadline_rights(conn, actor, deadline, page)
|
|
if not direct.read and not via.read:
|
|
return None
|
|
return deadline["title"]
|
|
return None
|