"""프로젝트 관리 — 현재 접근 권한의 공통 기준(서버). 라우터·마감 알림이 같은 규칙을 쓰도록 한 곳에 모은다. 모든 판단은 "지금" 기준이다 — 예전에 멤버였거나 담당자·멘션·협업자로 기록돼 있어도, 지금 권한이 없으면 보이지도 바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다). 프로젝트 관리(=보기·작업 CRUD) : 프로젝트 owner · 배정 멤버 · 슈퍼관리자. 모두 `project` 모듈 권한이 있어야 한다. (2026-10-07 — 관리자(is_admin)도 멤버가 아닌 프로젝트는 보이지 않는다. 예외는 슈퍼관리자 한 명뿐. 멤버 배정은 Pro user 이상(2026-10-12) — 라우터의 _require_pro, 아래 등급 표.) 등급(2026-10-12, app.store.ROLES) — 수퍼관리자 > admin > pro > user is_project_admin : 수퍼관리자·admin — 남이 만든 프로젝트·섹션도 삭제. is_pro : 수퍼관리자·admin·pro — 새 프로젝트 만들기, 프로젝트 이름·색·아이콘·소유자 수정, 멤버 배정·제외(자기가 멤버인 프로젝트), 사이드바 순서, 남의 댓글 수정·삭제, 휴지통 보기·복구, 전체 보기, 대시보드 담당자별 합계, 전체 멤버 메뉴, 목표 표 입력·구조 변경·주차별 목표·연도 추가/삭제, 회의 완료·완료 해제·회의록 삭제. user : 멤버인 프로젝트의 작업·섹션·서브프로젝트·작업 삭제, 회의록 작성(완료 전까지). 프로젝트 단위 권한은 등급과 상관없이 멤버(owner)여야 한다 — 위 is_pro 권한도 멤버인 프로젝트 안에서만. 작업 FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(작업 삭제는 멤버 누구나, 2026-10-12) READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음 → 그 작업의 상세·세부 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다. 연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용. None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외 """ from __future__ import annotations from typing import Any, Callable, Iterable from . import store FULL = "full" READ = "read" UserLookup = Callable[[str], "dict[str, Any] | None"] def default_user_lookup(email: str) -> dict[str, Any] | None: """등록 사용자 레코드(app.main.user_store). 지연 import — 테스트는 lookup 을 직접 넘긴다.""" from app.main import user_store # noqa: WPS433 return user_store.get(store.norm_str(email, lower=True)) def _is_super(user: dict[str, Any] | None) -> bool: """슈퍼관리자(app.store.SUPER_ADMIN_EMAIL) — 모든 프로젝트를 보는 유일한 예외.""" from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433 return bool(user) and email_of(user) == SUPER_ADMIN_EMAIL def role_of(user: dict[str, Any] | None) -> str: """등급 — 'super' · 'admin' · 'pro' · 'user'. 모르는 role 값은 user 로 본다.""" if _is_super(user): return "super" role = (user or {}).get("role") return role if role in ("admin", "pro") else "user" def is_project_admin(user: dict[str, Any] | None) -> bool: """수퍼관리자·admin — 만든 사람이 아니어도 프로젝트·섹션을 지운다.""" return role_of(user) in ("super", "admin") def is_pro(user: dict[str, Any] | None) -> bool: """수퍼관리자·admin·pro — 프로젝트 관리·목표 입력 등 운영 권한(모듈 docstring 의 등급 표).""" return role_of(user) in ("super", "admin", "pro") def can_all_view(user: dict[str, Any] | None, allowed: list[str] | None) -> bool: """왼쪽 "전체 보기" 메뉴를 보는가 — Project 옵션 all_view_users(목록에 든 사람만), 설정 전(None)이면 Pro user 이상. 메뉴 표시만 정한다 — 전체 보기도 멤버인 프로젝트 범위라 데이터 권한은 그대로(모듈 권한은 화면 진입에서 이미 확인).""" if allowed is None: return is_pro(user) return str((user or {}).get("email") or "").strip().lower() in allowed def sees_all_projects(user: dict[str, Any] | None) -> bool: """멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야).""" return can_use_module(user) and _is_super(user) def can_use_module(user: dict[str, Any] | None) -> bool: from app.store import has_module # noqa: WPS433 return bool(user) and has_module(user, "project") def email_of(user: dict[str, Any] | None) -> str: return store.norm_str((user or {}).get("email", ""), lower=True) def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool: """프로젝트 관리(=보기·작업 CRUD) — owner/멤버(관리자도 마찬가지), 슈퍼관리자는 전부. 모듈 권한이 없으면 False.""" if not can_use_module(user): return False if _is_super(user): return True try: pid = int(project_id) except (TypeError, ValueError): return False return bool(st.is_member(project_id=pid, user_email=email_of(user))) def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None: """관리할 수 있는 프로젝트 id 집합. 슈퍼관리자는 None(=전체), 그 밖(관리자 포함)은 owner·멤버인 프로젝트만.""" if not can_use_module(user): return set() if _is_super(user): return None return { int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user)) } def task_access(st: Any, user: dict[str, Any] | None, task: dict[str, Any] | None) -> str | None: """작업 하나에 대한 지금 권한: FULL / READ / None.""" if not task or not can_use_module(user): return None if can_manage_project(st, user, task.get("project_id")): return FULL for pid in link_scope(st, [int(task["id"])]).get(int(task["id"]), set()): if can_manage_project(st, user, pid): return READ return None def link_scope(st: Any, task_ids: Iterable[int]) -> dict[int, set[int]]: """작업 id → 이 작업 또는 상위 작업이 연결된 프로젝트 id 들. 연결 표가 없으면 빈 값.""" ids = [int(i) for i in task_ids] if not ids: return {} try: return st.task_link_scope(task_ids=ids) except Exception: # noqa: BLE001 - 003 미적용(연결 기능 없음) → 연결로 보이는 작업 없음 return {} def filter_visible_tasks(st: Any, user: dict[str, Any], tasks: list[dict[str, Any]], *, key: str = "id") -> list[dict[str, Any]]: """목록에서 지금 볼 수 있는(FULL 또는 READ) 작업만 남긴다 — 내 작업·수신함·알림 공용.""" allowed = visible_project_ids(st, user) if allowed is None: return list(tasks) ids = [int(t[key]) for t in tasks if t.get(key) is not None] scope = link_scope(st, ids) out = [] for t in tasks: tid = t.get(key) pid = t.get("project_id") if pid is not None and int(pid) in allowed: out.append(t) elif tid is not None and scope.get(int(tid), set()) & allowed: out.append(t) return out def email_task_access(st: Any, email: str, task: dict[str, Any], lookup: UserLookup | None = None) -> str | None: """이메일(알림·멘션 대상)이 지금 이 작업을 볼 수 있는지. 등록 안 된 사람·모듈 권한 없는 사람은 None.""" rec = (lookup or default_user_lookup)(email) if not rec: return None rec = {**rec, "email": rec.get("email") or email} return task_access(st, rec, task) def filter_recipients(st: Any, task: dict[str, Any], emails: Iterable[str], lookup: UserLookup | None = None) -> list[str]: """알림·메일·멘션 대상 중 지금 이 작업을 볼 수 있는 사람만(순서 유지, 중복 제거).""" out: list[str] = [] seen: set[str] = set() for e in emails: em = store.norm_str(e, lower=True) if not em or em in seen: continue seen.add(em) if email_task_access(st, em, task, lookup) is not None: out.append(em) return out def can_assign(st: Any, email: str, project_id: Any, lookup: UserLookup | None = None) -> bool: """담당자·소유자 후보 — 등록된 사용자이고 project 모듈 권한이 있으며, 그 프로젝트를 관리할 수 있어야 한다(관리자 포함). 권한 없는 사람에게 작업 정보가 담긴 알림이 가지 않게.""" rec = (lookup or default_user_lookup)(email) if not rec: return False rec = {**rec, "email": rec.get("email") or email} return can_manage_project(st, rec, project_id)