fix(project): review fixes — access leaks, open paths, save safety, concurrency
- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -36,7 +36,7 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
||||
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
||||
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
|
||||
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성/삭제·사용자 배정은 `is_admin` 만, 배정 멤버(또는 owner)는 서브프로젝트/업무/단계 CRUD. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 권한은 등급(수퍼관리자 > Admin > Pro user > User, 2026-10-12)과 멤버십 기준 — 표는 `docs/PROJECT_MODULE.md` 6-14, 공통 판단 `access.py`(관리자도 멤버가 아니면 프로젝트가 안 보임, 예외는 수퍼관리자). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
||||
|
||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
프로젝트 단위 권한은 등급과 상관없이 멤버(owner)여야 한다 — 위 is_pro 권한도 멤버인 프로젝트 안에서만.
|
||||
|
||||
작업
|
||||
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙)
|
||||
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(작업 삭제는 멤버 누구나, 2026-10-12)
|
||||
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
|
||||
→ 그 작업의 상세·세부 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
|
||||
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
|
||||
|
||||
+182
-85
@@ -98,7 +98,10 @@ class ProjectStore:
|
||||
created_by: str = "",
|
||||
seed_stages: bool = False,
|
||||
icon: str | None = None,
|
||||
member_emails: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""member_emails — 만들면서 같이 넣을 멤버(같은 트랜잭션). 남을 소유자로 지정해 만든 사람이
|
||||
만든 직후 자기 프로젝트를 못 여는 일이 없게 라우터가 만든 사람을 넣는다(일반 멤버 — 나중에 뺄 수 있다)."""
|
||||
nm = store.validate_project_name(name)
|
||||
col = store.validate_color(color)
|
||||
ic = store.validate_project_icon(icon)
|
||||
@@ -136,6 +139,12 @@ class ProjectStore:
|
||||
vals,
|
||||
).fetchone()
|
||||
pid = row["id"]
|
||||
for em in store.normalize_emails(member_emails or []):
|
||||
conn.execute(
|
||||
"INSERT INTO project_members (project_id, user_email, user_name, role) "
|
||||
"VALUES (%s,%s,'','member') ON CONFLICT (project_id, user_email) DO NOTHING",
|
||||
(pid, em),
|
||||
)
|
||||
if seed_stages:
|
||||
for i, (stage_name, is_done) in enumerate(store.DEFAULT_STAGES):
|
||||
conn.execute(
|
||||
@@ -174,17 +183,22 @@ class ProjectStore:
|
||||
if existing is None:
|
||||
raise KeyError(project_id)
|
||||
return existing
|
||||
params.append(project_id)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
if "start_date" in clean or "due_date" in clean:
|
||||
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다.
|
||||
existing = self.get_project(project_id=project_id)
|
||||
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다 — 그 행을 잠근 뒤 읽어서(FOR UPDATE)
|
||||
# 두 사람이 시작일·마감일을 동시에 바꿔도 각자 옛 값으로 검사해 역전되지 않게.
|
||||
existing = conn.execute(
|
||||
"SELECT start_date, due_date FROM projects WHERE id = %s FOR UPDATE", (project_id,)
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
raise KeyError(project_id)
|
||||
existing = self._serialize(existing)
|
||||
store.validate_date_range(
|
||||
clean["start_date"] if "start_date" in clean else existing.get("start_date"),
|
||||
clean["due_date"] if "due_date" in clean else existing.get("due_date"),
|
||||
)
|
||||
params.append(project_id)
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"UPDATE projects SET {', '.join(sets)} WHERE id = %s RETURNING *",
|
||||
params,
|
||||
@@ -334,9 +348,11 @@ class ProjectStore:
|
||||
return self._serialize(row) if row else None
|
||||
|
||||
@staticmethod
|
||||
def _stage_default_assignee(conn: Any, stage_id: Any, project_id: int) -> tuple[str, str]:
|
||||
def _stage_default_assignee(conn: Any, stage_id: Any, project_id: int,
|
||||
allowed: Any = None) -> tuple[str, str]:
|
||||
"""세션 기본 담당자(마이그레이션 009) → (email, name). 미지정·009 미적용·
|
||||
그 사람이 이제 프로젝트 멤버가 아니면 ('', '').
|
||||
그 사람이 이제 프로젝트 멤버가 아니면 ('', ''). allowed(email) 가 있으면 그것도 통과해야 한다 —
|
||||
삭제된 사용자·project 모듈 권한을 잃은 사람에게 자동 배정(과 배정 알림)이 가지 않게(라우터가 넘김).
|
||||
|
||||
컬럼이 없어도 에러가 나지 않게 to_jsonb(행) 에서 키로 읽는다."""
|
||||
if stage_id in (None, ""):
|
||||
@@ -360,8 +376,17 @@ class ProjectStore:
|
||||
).fetchone()
|
||||
if not m:
|
||||
return "", ""
|
||||
if allowed is not None and not allowed(email):
|
||||
return "", ""
|
||||
return email, m["user_name"] or ""
|
||||
|
||||
@staticmethod
|
||||
def _stage_is_done_conn(conn: Any, stage_id: Any) -> bool:
|
||||
if stage_id is None:
|
||||
return False
|
||||
row = conn.execute("SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)).fetchone()
|
||||
return bool(row and row["is_done_stage"])
|
||||
|
||||
@staticmethod
|
||||
def _check_stage_in_project(conn: Any, stage_id: Any, project_id: int) -> int | None:
|
||||
"""세션이 그 프로젝트 것인지 확인하고 int 로 돌려준다(None 은 그대로).
|
||||
@@ -587,11 +612,13 @@ class ProjectStore:
|
||||
).fetchone()
|
||||
return int(row["n"] or 0)
|
||||
|
||||
def list_my_tasks(self, *, assignee_email: str, limit: int = 1000) -> list[dict[str, Any]]:
|
||||
""""내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이
|
||||
전부 반환한다. 세부 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이
|
||||
붙여서, 부모가 내 업무가 아니어도(다른 사람 담당) 화면에서 트리로 묶어
|
||||
보여줄 수 있게 한다.
|
||||
def list_my_tasks(self, *, assignee_email: str, completed_limit: int = 1000) -> list[dict[str, Any]]:
|
||||
""""내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이 반환한다.
|
||||
세부 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이 붙여서, 부모가 내 업무가 아니어도
|
||||
(다른 사람 담당) 화면에서 트리로 묶어 보여줄 수 있게 한다.
|
||||
|
||||
미완료는 **전부**, 완료는 최근에 완료한 completed_limit 건까지 — 예전엔 전체를 1000건에서 잘라
|
||||
오래된 완료 업무가 새 미완료 업무를 목록 밖으로 밀어낼 수 있었다.
|
||||
"""
|
||||
email = store.norm_str(assignee_email, lower=True)
|
||||
with self._pool.connection() as conn:
|
||||
@@ -607,8 +634,11 @@ class ProjectStore:
|
||||
f"LEFT JOIN project_stages s ON s.id = t.stage_id "
|
||||
f"LEFT JOIN tasks pt ON pt.id = t.parent_task_id "
|
||||
f"WHERE t.assignee_email = %s "
|
||||
"ORDER BY t.sort_order ASC, t.id ASC LIMIT %s",
|
||||
(email, int(limit)),
|
||||
" AND (t.completed_at IS NULL OR t.id IN ("
|
||||
" SELECT d.id FROM tasks d WHERE d.assignee_email = %s AND d.completed_at IS NOT NULL "
|
||||
" ORDER BY d.completed_at DESC, d.id DESC LIMIT %s)) "
|
||||
"ORDER BY t.sort_order ASC, t.id ASC",
|
||||
(email, email, int(completed_limit)),
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
@@ -642,7 +672,9 @@ class ProjectStore:
|
||||
due_time: str | None = None,
|
||||
created_by: str = "",
|
||||
parent_task_id: int | None = None,
|
||||
assignee_allowed: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""assignee_allowed — update_task 와 같이 섹션 기본 담당자 자동 배정 전 지금 권한 확인(라우터가 넘김)."""
|
||||
ttl = store.validate_task_title(title)
|
||||
pr = store.validate_priority(priority)
|
||||
sd = store.validate_date(start_date)
|
||||
@@ -681,7 +713,8 @@ class ProjectStore:
|
||||
# 담당자 없이 만들면 그 세션의 기본 담당자를 배정(세부 업무는
|
||||
# 세션이 없어 해당 없음).
|
||||
if not assignee and stage_id is not None:
|
||||
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id)
|
||||
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id,
|
||||
allowed=assignee_allowed)
|
||||
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
|
||||
if stage_id is not None:
|
||||
done_row = conn.execute(
|
||||
@@ -767,28 +800,57 @@ class ProjectStore:
|
||||
return self.get_task(task_id=task_id)
|
||||
|
||||
def update_task(
|
||||
self, *, task_id: int, fields: dict[str, Any], actor: str = ""
|
||||
self, *, task_id: int, fields: dict[str, Any], actor: str = "",
|
||||
assignee_allowed: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""업무 수정. 반환에 알림 힌트를 담는다(라우터가 메일 발송 판단).
|
||||
|
||||
반환 dict 에 추가되는 키:
|
||||
_newly_assigned: 새 담당자 이메일 or None
|
||||
_newly_completed: 완료로 전환됐으면 True
|
||||
"""
|
||||
prev = self.get_task(task_id=task_id)
|
||||
if prev is None:
|
||||
raise KeyError(task_id)
|
||||
|
||||
sets: list[str] = []
|
||||
params: list[Any] = []
|
||||
동시성 — 기존 값 읽기·최종 날짜 검사·변경·이력을 **한 트랜잭션에서 그 작업 행을 잠그고**
|
||||
(SELECT … FOR UPDATE) 한다. 두 사람이 시작일·마감일을 동시에 바꿔도 각자 옛 값으로 검사해
|
||||
날짜가 역전되지 않고, 동시에 완료해도 완료 이력·알림 힌트는 실제로 완료로 바뀐 한 요청에서만 생긴다.
|
||||
섹션 확인·기본 담당자·완료 섹션 여부도 같은 연결로 읽는다(다른 연결을 다시 빌리지 않는다).
|
||||
|
||||
assignee_allowed(email) — 섹션 기본 담당자를 자동 배정하기 전에 그 사람이 지금 등록된 project
|
||||
권한 사용자인지(사용자 목록은 DB 밖이라 라우터가 넘긴다). 없으면 멤버·owner 여부만 본다.
|
||||
"""
|
||||
# 형식 검사는 잠그기 전에(잠금을 짧게) — 값이 틀리면 DB 에 가지 않는다.
|
||||
clean: dict[str, Any] = {}
|
||||
if "title" in fields:
|
||||
clean["title"] = store.validate_task_title(fields["title"])
|
||||
if "description" in fields:
|
||||
clean["description"] = store.norm_str(fields["description"])
|
||||
if "priority" in fields:
|
||||
clean["priority"] = store.validate_priority(fields["priority"])
|
||||
for k in ("start_date", "due_date"):
|
||||
if k in fields:
|
||||
clean[k] = store.validate_date(fields[k])
|
||||
for k in ("start_time", "due_time"):
|
||||
if k in fields:
|
||||
clean[k] = store.validate_time(fields[k])
|
||||
|
||||
newly_assigned: str | None = None
|
||||
newly_completed = False
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute("SELECT * FROM tasks WHERE id = %s FOR UPDATE", (task_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(task_id)
|
||||
prev = self._serialize(row)
|
||||
sets: list[str] = []
|
||||
params: list[Any] = []
|
||||
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"):
|
||||
if k in clean:
|
||||
sets.append(f"{k} = %s")
|
||||
params.append(clean[k])
|
||||
|
||||
assignee_fields = {k: fields[k] for k in ("assignee_email", "assignee_name") if k in fields}
|
||||
new_stage: Any = None
|
||||
if "stage_id" in fields:
|
||||
new_stage = self.stage_in_project(
|
||||
stage_id=fields["stage_id"], project_id=prev["project_id"]
|
||||
)
|
||||
new_stage = self._check_stage_in_project(conn, fields["stage_id"], prev["project_id"])
|
||||
# 다른 세션으로 옮겨왔고 (옮긴 뒤에도) 담당자가 비어 있으면 그 세션의
|
||||
# 기본 담당자를 배정한다. 이미 담당자가 있으면 그대로 둔다.
|
||||
if new_stage is not None and new_stage != prev.get("stage_id"):
|
||||
@@ -797,44 +859,23 @@ class ProjectStore:
|
||||
if "assignee_email" in fields else (prev.get("assignee_email") or "")
|
||||
)
|
||||
if not final_assignee:
|
||||
with self._pool.connection() as conn:
|
||||
dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"])
|
||||
dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"],
|
||||
allowed=assignee_allowed)
|
||||
if dae:
|
||||
fields = {**fields, "assignee_email": dae, "assignee_name": dan}
|
||||
assignee_fields = {"assignee_email": dae, "assignee_name": dan}
|
||||
|
||||
if "title" in fields:
|
||||
sets.append("title = %s")
|
||||
params.append(store.validate_task_title(fields["title"]))
|
||||
if "description" in fields:
|
||||
sets.append("description = %s")
|
||||
params.append(store.norm_str(fields["description"]))
|
||||
if "priority" in fields:
|
||||
sets.append("priority = %s")
|
||||
params.append(store.validate_priority(fields["priority"]))
|
||||
if "start_date" in fields:
|
||||
sets.append("start_date = %s")
|
||||
params.append(store.validate_date(fields["start_date"]))
|
||||
if "due_date" in fields:
|
||||
sets.append("due_date = %s")
|
||||
params.append(store.validate_date(fields["due_date"]))
|
||||
if "start_time" in fields:
|
||||
sets.append("start_time = %s")
|
||||
params.append(store.validate_time(fields["start_time"]))
|
||||
if "due_time" in fields:
|
||||
sets.append("due_time = %s")
|
||||
params.append(store.validate_time(fields["due_time"]))
|
||||
if "assignee_email" in fields:
|
||||
new_assignee = store.norm_str(fields["assignee_email"], lower=True)
|
||||
if "assignee_email" in assignee_fields:
|
||||
new_assignee = store.norm_str(assignee_fields["assignee_email"], lower=True)
|
||||
sets.append("assignee_email = %s")
|
||||
params.append(new_assignee)
|
||||
if "assignee_name" in fields:
|
||||
if "assignee_name" in assignee_fields:
|
||||
sets.append("assignee_name = %s")
|
||||
params.append(store.norm_str(fields["assignee_name"]))
|
||||
params.append(store.norm_str(assignee_fields["assignee_name"]))
|
||||
if new_assignee and new_assignee != (prev.get("assignee_email") or ""):
|
||||
newly_assigned = new_assignee
|
||||
elif "assignee_name" in fields:
|
||||
elif "assignee_name" in assignee_fields:
|
||||
sets.append("assignee_name = %s")
|
||||
params.append(store.norm_str(fields["assignee_name"]))
|
||||
params.append(store.norm_str(assignee_fields["assignee_name"]))
|
||||
|
||||
# 단계 변경 → 완료단계 진입 시 completed_at 자동 세팅. 단, 실제로 단계가
|
||||
# 바뀐 경우에만 판정한다 — 업무 편집 모달의 "저장"은 매번 현재 stage_id
|
||||
@@ -844,7 +885,7 @@ class ProjectStore:
|
||||
sets.append("stage_id = %s")
|
||||
params.append(new_stage)
|
||||
if new_stage != prev.get("stage_id"):
|
||||
done = self._stage_is_done(new_stage)
|
||||
done = self._stage_is_done_conn(conn, new_stage)
|
||||
if done and not prev.get("completed_at"):
|
||||
sets.append("completed_at = %s")
|
||||
params.append(now_kst())
|
||||
@@ -862,23 +903,16 @@ class ProjectStore:
|
||||
sets.append("completed_at = NULL")
|
||||
|
||||
if not sets:
|
||||
return {**prev, "_newly_assigned": None, "_newly_completed": False}
|
||||
|
||||
# 날짜 범위 — 한쪽만 바꾸거나 지워도 기존 값과 합친 최종 상태로 검사.
|
||||
if any(k in fields for k in ("start_date", "due_date", "start_time", "due_time")):
|
||||
def final(key: str, fn: Any) -> Any:
|
||||
return fn(fields[key]) if key in fields else prev.get(key)
|
||||
store.validate_date_range(
|
||||
final("start_date", store.validate_date), final("due_date", store.validate_date),
|
||||
final("start_time", store.validate_time), final("due_time", store.validate_time),
|
||||
)
|
||||
|
||||
params.append(task_id)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", params
|
||||
)
|
||||
changed = False
|
||||
else:
|
||||
changed = True
|
||||
# 날짜 범위 — 한쪽만 바꾸거나 지워도 (잠근) 기존 값과 합친 최종 상태로 검사.
|
||||
if any(k in clean for k in ("start_date", "due_date", "start_time", "due_time")):
|
||||
def final(key: str) -> Any:
|
||||
return clean[key] if key in clean else prev.get(key)
|
||||
store.validate_date_range(final("start_date"), final("due_date"),
|
||||
final("start_time"), final("due_time"))
|
||||
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
|
||||
if newly_assigned:
|
||||
self._log(conn, project_id=prev["project_id"], task_id=task_id,
|
||||
actor=actor, action=store.ACTION_ASSIGNED,
|
||||
@@ -888,8 +922,10 @@ class ProjectStore:
|
||||
actor=actor, action=store.ACTION_COMPLETED,
|
||||
detail=prev["title"])
|
||||
out = self.get_task(task_id=task_id)
|
||||
out["_newly_assigned"] = newly_assigned
|
||||
out["_newly_completed"] = newly_completed
|
||||
if out is None:
|
||||
raise KeyError(task_id)
|
||||
out["_newly_assigned"] = newly_assigned if changed else None
|
||||
out["_newly_completed"] = newly_completed if changed else False
|
||||
return out
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -1072,15 +1108,6 @@ class ProjectStore:
|
||||
conn.execute("DELETE FROM project_trash WHERE id = %s", (trash_id,))
|
||||
return {"task_id": int(root["id"]), "project_id": int(root["project_id"]), "task_ids": ids}
|
||||
|
||||
def _stage_is_done(self, stage_id: Any) -> bool:
|
||||
if stage_id is None:
|
||||
return False
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
|
||||
).fetchone()
|
||||
return bool(row and row["is_done_stage"])
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 멀티호밍 (task_project_links) — 업무 1개가 여러 프로젝트/세션에 동시 소속.
|
||||
# 원래 소속(tasks.project_id/stage_id)은 여기서 건드리지 않는다("기본 홈"은
|
||||
@@ -1548,6 +1575,31 @@ class ProjectStore:
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def list_unread_after(
|
||||
self, *, recipient_email: str, after_id: int, types: tuple[str, ...], limit: int = 200,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""큰 팝업 알림 후보 — 이 사람·읽지 않음·종류·id > after_id 를 DB 에서 먼저 걸러 **오래된 것(id)부터**.
|
||||
라우터가 지금 볼 수 있는 것만 남기며 마지막 id 를 다음 after_id 로 넘겨 끝까지 읽는다."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM project_notifications "
|
||||
"WHERE recipient_email = %s AND is_read = FALSE AND id > %s AND type = ANY(%s) "
|
||||
"ORDER BY id ASC LIMIT %s",
|
||||
(store.norm_str(recipient_email, lower=True), int(after_id), list(types), int(limit)),
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def list_unread_refs(self, *, recipient_email: str) -> list[dict[str, Any]]:
|
||||
"""읽지 않은 알림 전부의 (id, project_id, task_id) — 수신함 배지를 개수 제한 없이 정확히 세려고
|
||||
가벼운 열만 읽는다(지금 권한 거르기는 라우터)."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, project_id, task_id FROM project_notifications "
|
||||
"WHERE recipient_email = %s AND is_read = FALSE",
|
||||
(store.norm_str(recipient_email, lower=True),),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def count_unread(self, *, recipient_email: str) -> int:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
@@ -1766,6 +1818,27 @@ class ProjectStore:
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def list_unread_mention_refs(self, *, mentioned_email: str) -> list[dict[str, Any]]:
|
||||
"""미확인 태그가 있는 작업마다 (id, project_id, unread_mentions) — 배지를 제한 없이 세는 가벼운 조회."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT t.id, t.project_id, m.unread AS unread_mentions "
|
||||
"FROM (SELECT task_id, COUNT(*) AS unread FROM task_mentions "
|
||||
" WHERE mentioned_email = %s AND is_read = FALSE GROUP BY task_id) m "
|
||||
"JOIN tasks t ON t.id = m.task_id",
|
||||
(store.norm_str(mentioned_email, lower=True),),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def list_my_open_refs(self, *, assignee_email: str) -> list[dict[str, Any]]:
|
||||
"""내가 담당인 미완료 작업 전부의 (id, project_id) — "내 작업" 배지를 제한 없이 정확히 센다."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, project_id FROM tasks WHERE assignee_email = %s AND completed_at IS NULL",
|
||||
(store.norm_str(assignee_email, lower=True),),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def count_unread_mentions(self, *, mentioned_email: str) -> int:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
@@ -2735,6 +2808,25 @@ class ProjectStore:
|
||||
if row and row["completed_at"] is not None:
|
||||
raise store.MeetingLocked()
|
||||
|
||||
def _check_result_open(self, conn: Any, own_week: Any) -> None:
|
||||
"""결과 칸(result_*·status)만 고칠 때 — 그 주 결과는 다음 주 회의에서 리뷰하며 적는다(6-14 표).
|
||||
· 다음 주차 회의록이 있으면 그 회의록이 열려 있을 때만(완료되면 잠금 — 그 주 회의록 완료 여부와 무관)
|
||||
· 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있을 때만(예전엔 그 주가 완료돼도 다음 회의록이
|
||||
없으면 고칠 수 있었다)
|
||||
다음 주차 = 바로 다음 주차 시작일(store.week_period 끝 + 1일 — 달이 바뀌어도, 월요일이 아닌 시작일도
|
||||
get_meeting 이 "지난주"를 찾는 규칙과 같다). 다음 회의록 행도 잠근다(FOR SHARE) — 이미 그 주 회의록을
|
||||
잠근 뒤라 잠금 순서는 늘 주차 오름차순(교착 없음), 확인 뒤 다음 회의록이 완료돼도 끼어들지 못한다.
|
||||
022 전이면 잠금 없음."""
|
||||
if not self._meeting_v22(conn):
|
||||
return
|
||||
nxt = store.week_period(own_week)[1] + timedelta(days=1)
|
||||
row = conn.execute("SELECT completed_at FROM goal_meetings WHERE week_start = %s FOR SHARE",
|
||||
(nxt,)).fetchone()
|
||||
if row is None:
|
||||
self._check_meeting_open(conn, own_week)
|
||||
elif row["completed_at"] is not None:
|
||||
raise store.MeetingLocked()
|
||||
|
||||
def set_meeting_completed(self, *, week_start: date, done: bool, by: str = "") -> dict[str, Any]:
|
||||
"""회의 완료(잠금)·완료 해제 — 관리자만(라우터). 바뀐 상태를 돌려준다."""
|
||||
with self._pool.connection() as conn:
|
||||
@@ -2993,7 +3085,13 @@ class ProjectStore:
|
||||
if not sets:
|
||||
return
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
self._require_meetings(conn)
|
||||
# 완료 확인과 머리 변경을 한 트랜잭션에서 그 회의록 행을 잠그고 — [회의 완료](set_meeting_completed
|
||||
# 의 UPDATE 도 같은 행을 잠근다)와 동시에 와도 완료된 회의록이 바뀌지 않는다.
|
||||
if not conn.execute("SELECT week_start FROM goal_meetings WHERE week_start = %s FOR UPDATE",
|
||||
(week_start,)).fetchone():
|
||||
raise KeyError(str(week_start))
|
||||
self._check_meeting_open(conn, week_start)
|
||||
row = conn.execute(
|
||||
f"UPDATE goal_meetings SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
|
||||
@@ -3103,9 +3201,8 @@ class ProjectStore:
|
||||
raise ValueError(next(e for _c, t, e in texts if t)) # 021 전 — 예전처럼 숫자만
|
||||
rows = self._locked_meeting_items(conn, item_id, check_open=not result_only)
|
||||
if result_only:
|
||||
# 지난주 결과는 다음 주 회의에서 적는다 — 그 회의록(바로 다음 주차)이 완료됐으면 잠금
|
||||
own = next(r for r in rows if int(r["id"]) == item_id)["week_start"]
|
||||
self._check_meeting_open(conn, store.week_period(own)[1] + timedelta(days=1))
|
||||
self._check_result_open(conn, own)
|
||||
if "content" in fields:
|
||||
self._require_meeting_cell_visible(rows, item_id)
|
||||
if sets:
|
||||
|
||||
+214
-90
@@ -156,15 +156,15 @@ def _require_task(
|
||||
|
||||
|
||||
def _my_visible_tasks(st: Any, user: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""내가 담당인 작업 중 지금 볼 수 있는 것만 — 권한을 잃은 프로젝트의 작업은 빠진다."""
|
||||
return access.filter_visible_tasks(
|
||||
st, user, st.list_my_tasks(assignee_email=user["email"], limit=1000)
|
||||
)
|
||||
"""내가 담당인 작업 중 지금 볼 수 있는 것만 — 권한을 잃은 프로젝트의 작업은 빠진다.
|
||||
미완료는 전부, 완료는 최근 완료 1000건까지(db.list_my_tasks)."""
|
||||
return access.filter_visible_tasks(st, user, st.list_my_tasks(assignee_email=user["email"]))
|
||||
|
||||
|
||||
def _my_open_count(st: Any, user: dict[str, Any]) -> int:
|
||||
"""사이드바 "내 작업" 배지 — _my_visible_tasks 와 같은 기준."""
|
||||
return sum(1 for t in _my_visible_tasks(st, user) if not t.get("completed_at"))
|
||||
"""사이드바 "내 작업" 배지 — 지금 볼 수 있는 미완료 담당 작업 수(_my_visible_tasks 와 같은 권한 기준).
|
||||
목록 전체를 읽지 않고 (id, project_id) 만 읽어 개수 제한 없이 센다."""
|
||||
return len(access.filter_visible_tasks(st, user, st.list_my_open_refs(assignee_email=user["email"])))
|
||||
|
||||
|
||||
def _remove_task_dirs(request: Request, task_ids: list[int]) -> None:
|
||||
@@ -729,23 +729,34 @@ def task_permalink(request: Request, task_id: int):
|
||||
task = st.get_task(task_id=task_id)
|
||||
if task is None:
|
||||
return _denied("작업을 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
|
||||
level = access.task_access(st, user, task)
|
||||
if level is None:
|
||||
target = _task_open_project(st, user, task)
|
||||
if target is None:
|
||||
return _denied(
|
||||
"이 작업이 속한 프로젝트의 멤버만 볼 수 있습니다. "
|
||||
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
||||
403,
|
||||
)
|
||||
target = task["project_id"]
|
||||
if level != access.FULL:
|
||||
# 연결된 프로젝트에서만 볼 수 있는 작업 — 그 프로젝트 화면에서 읽기 전용으로 연다.
|
||||
target = next((pid for pid in sorted(access.link_scope(st, [task_id]).get(task_id, set()))
|
||||
if _can_manage(request, st, user, pid)), None)
|
||||
if target is None:
|
||||
return _denied("이 작업을 볼 권한이 없습니다.", 403)
|
||||
|
||||
# 세부 업무도 업무처럼 자기 팝업으로 연다(아사나식 — 제목 위에 상위 업무 경로).
|
||||
return RedirectResponse(url=f"/project/p/{target}?task={task_id}", status_code=303)
|
||||
# 수신함 오른쪽 작업 창(iframe, ?embed=1)은 옮겨 간 뒤에도 embed 화면이어야 한다.
|
||||
return RedirectResponse(url=_task_page_url(target, task_id, request), status_code=303)
|
||||
|
||||
|
||||
def _task_open_project(st: Any, user: dict[str, Any], task: dict[str, Any]) -> int | None:
|
||||
"""작업을 열 프로젝트 화면 — 지금 권한 기준. FULL 이면 원 소속, READ 면 내가 볼 수 있는 연결된
|
||||
프로젝트(id 가 작은 것부터), 권한이 없으면 None. 공유 링크·수신함·알림 팝업·PC 알림이 같이 쓴다."""
|
||||
level = access.task_access(st, user, task)
|
||||
if level is None:
|
||||
return None
|
||||
if level == access.FULL:
|
||||
return int(task["project_id"])
|
||||
tid = int(task["id"])
|
||||
return next((pid for pid in sorted(access.link_scope(st, [tid]).get(tid, set()))
|
||||
if access.can_manage_project(st, user, pid)), None)
|
||||
|
||||
|
||||
def _task_page_url(project_id: int, task_id: int, request: Request) -> str:
|
||||
embed = "&embed=1" if request.query_params.get("embed") == "1" else ""
|
||||
return f"/project/p/{int(project_id)}?task={int(task_id)}{embed}"
|
||||
|
||||
|
||||
@router.get("/p/{project_id}", response_class=HTMLResponse)
|
||||
@@ -767,6 +778,12 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
# 링크(/project/t/{id})와 같은 원칙. 예전엔 세션·멤버 목록이 그대로 보였다.
|
||||
can_manage = _can_manage(request, st, user, project_id)
|
||||
if not can_manage:
|
||||
# 예전 주소(/p/{원 소속}?task=)로 연결된 작업을 연 경우 — 읽기 권한이 있는 연결된 프로젝트 화면으로.
|
||||
# (옛 PC 알림 프로그램·북마크가 원 소속 주소를 쓴다. 새 주소는 /project/t/{id})
|
||||
target = _redirect_target_for_task(st, user, request.query_params.get("task"))
|
||||
if target is not None and target != project_id:
|
||||
return RedirectResponse(
|
||||
url=_task_page_url(target, int(request.query_params["task"]), request), status_code=303)
|
||||
return render_template(
|
||||
request,
|
||||
"denied.html",
|
||||
@@ -779,13 +796,8 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
},
|
||||
status_code=403,
|
||||
)
|
||||
all_projects = st.list_projects(
|
||||
include_archived=False,
|
||||
member_email=None if access.sees_all_projects(user) else user["email"],
|
||||
)
|
||||
members = st.list_members(project_id=project_id)
|
||||
top_projects = [p for p in all_projects if not p.get("parent_id")] # 과거 서브프로젝트 제외
|
||||
top_ids = [p["id"] for p in top_projects]
|
||||
top_projects, top_ids = _view_scope(st, user, project)
|
||||
|
||||
# 좌측 트리 + 전체 집계: 4개 뷰(달력/타임라인/보드/리스트)는 '전체 프로젝트'를 보여준다.
|
||||
# all_tasks : 접근 가능한 모든 프로젝트의 업무(뷰 데이터)
|
||||
@@ -806,20 +818,12 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
tasks_by_ctx.setdefault(t["context_project_id"], []).append(t)
|
||||
|
||||
nav_projects: list[dict[str, Any]] = []
|
||||
projects_meta: list[dict[str, Any]] = []
|
||||
projects_meta: list[dict[str, Any]] = [_project_meta(p) for p in top_projects]
|
||||
if project_id not in {int(p["id"]) for p in top_projects}:
|
||||
# 보관된 프로젝트·서브프로젝트를 직접 연 경우 — 화면용 메타에만 넣고 사이드바 목록엔 넣지 않는다.
|
||||
projects_meta.append({**_project_meta(project), "view_only": True})
|
||||
for p in top_projects:
|
||||
p_tasks = tasks_by_ctx.get(p["id"], [])
|
||||
projects_meta.append({
|
||||
"id": p["id"],
|
||||
"name": p["name"],
|
||||
"color": p.get("color") or "#4573d2",
|
||||
"icon": p.get("icon") or "",
|
||||
"start_date": p.get("start_date"),
|
||||
"due_date": p.get("due_date"),
|
||||
"created_by": p.get("created_by") or "",
|
||||
"description": p.get("description") or "",
|
||||
"status": p.get("status") or "active",
|
||||
})
|
||||
nav_projects.append({
|
||||
"id": p["id"],
|
||||
"name": p["name"],
|
||||
@@ -917,6 +921,28 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# JSON API — 프로젝트
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def _view_scope(st: Any, user: dict[str, Any], project: dict[str, Any]) -> tuple[list[dict[str, Any]], list[int]]:
|
||||
"""프로젝트 화면·스냅샷(scope=all)·담당자별 합계가 같이 쓰는 조회 범위.
|
||||
(내가 볼 수 있는 활성 최상위 프로젝트, 작업·섹션을 읽을 프로젝트 id). 지금 연 프로젝트가 보관됐거나
|
||||
서브프로젝트여서 목록에 없으면 그 프로젝트 하나만 더한다 — 다른 보관 프로젝트까지 읽지는 않는다."""
|
||||
top = [p for p in st.list_projects(
|
||||
include_archived=False,
|
||||
member_email=None if access.sees_all_projects(user) else user["email"],
|
||||
) if not p.get("parent_id")] # 과거 서브프로젝트 제외
|
||||
ids = [int(p["id"]) for p in top]
|
||||
if int(project["id"]) not in ids:
|
||||
ids.append(int(project["id"]))
|
||||
return top, ids
|
||||
|
||||
|
||||
def _redirect_target_for_task(st: Any, user: dict[str, Any], raw_task_id: Any) -> int | None:
|
||||
try:
|
||||
task = st.get_task(task_id=int(raw_task_id)) if raw_task_id else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return _task_open_project(st, user, task) if task else None
|
||||
|
||||
|
||||
def _db_or_503(request: Request) -> Any:
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
@@ -952,6 +978,13 @@ def _owner_for_create(user: dict[str, Any], payload: dict[str, Any]) -> str:
|
||||
return want
|
||||
|
||||
|
||||
def _creator_member(user: dict[str, Any], owner: str) -> list[str]:
|
||||
"""남을 소유자로 지정해 만들면 만든 사람을 일반 멤버로 같이 넣는다 — 만든 직후 자기 프로젝트를
|
||||
못 여는 일이 없게. created_by 로 권한을 주는 게 아니라 멤버 행이라, 나중에 멤버에서 빼면 권한도 없어진다."""
|
||||
me = store.norm_str(user["email"], lower=True)
|
||||
return [] if owner == me else [me]
|
||||
|
||||
|
||||
def _check_owner_candidate(email: str) -> None:
|
||||
rec = access.default_user_lookup(email)
|
||||
if not rec or not access.can_use_module({**rec, "email": email}):
|
||||
@@ -966,17 +999,19 @@ def api_create_project(
|
||||
"""최상위 프로젝트 생성 — Pro user 이상(만든 사람이 owner). User 는 서브프로젝트만."""
|
||||
user = _require_pro(request)
|
||||
st = _db_or_503(request)
|
||||
owner = _owner_for_create(user, payload)
|
||||
try:
|
||||
project = st.create_project(
|
||||
name=payload.get("name", ""),
|
||||
parent_id=None,
|
||||
description=payload.get("description", ""),
|
||||
color=payload.get("color", ""),
|
||||
owner_email=_owner_for_create(user, payload),
|
||||
owner_email=owner,
|
||||
start_date=payload.get("start_date"),
|
||||
due_date=payload.get("due_date"),
|
||||
created_by=user["email"],
|
||||
icon=payload.get("icon"),
|
||||
member_emails=_creator_member(user, owner),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
@@ -993,16 +1028,18 @@ def api_create_subproject(
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
_require_manage(request, st, user, project_id)
|
||||
owner = _owner_for_create(user, payload)
|
||||
try:
|
||||
project = st.create_project(
|
||||
name=payload.get("name", ""),
|
||||
parent_id=project_id,
|
||||
description=payload.get("description", ""),
|
||||
color=payload.get("color", ""),
|
||||
owner_email=_owner_for_create(user, payload),
|
||||
owner_email=owner,
|
||||
start_date=payload.get("start_date"),
|
||||
due_date=payload.get("due_date"),
|
||||
created_by=user["email"],
|
||||
member_emails=_creator_member(user, owner),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
@@ -1023,13 +1060,39 @@ def api_reorder_projects(
|
||||
"order" 가 project_id 로 매칭 시도되어(정수 변환 실패로 422) 이 라우트가
|
||||
영영 실행되지 않는다(경로 매칭은 등록 순서, path param 특이도 무관).
|
||||
"""
|
||||
_require_pro(request)
|
||||
user = _require_pro(request)
|
||||
st = _db_or_503(request)
|
||||
ids = payload.get("ordered_ids") or []
|
||||
ids = _ordered_ids_arg(payload)
|
||||
# 보낸 id 가 모두 지금 내가 관리할 수 있는 프로젝트여야 한다(없는 id 도 같은 403 — 다른 프로젝트가
|
||||
# 있는지 알려 주지 않는다). 하나라도 아니면 아무것도 바꾸지 않는다(UPDATE 는 한 문장이라 전부 아니면 전무).
|
||||
allowed = _accessible_project_ids(st, user)
|
||||
if allowed is None: # 수퍼관리자 — 있는 프로젝트인지만
|
||||
allowed = {int(p["id"]) for p in st.list_projects(include_archived=True)}
|
||||
if any(i not in allowed for i in ids):
|
||||
raise HTTPException(status_code=403, detail="순서를 바꿀 권한이 없는 프로젝트가 들어 있습니다.")
|
||||
st.reorder_projects(ordered_ids=ids)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
def _ordered_ids_arg(payload: Any) -> list[int]:
|
||||
"""{"ordered_ids": [정수, ...]} — 비었거나 정수가 아니거나(참/거짓·소수·글자) 겹치면 400."""
|
||||
ids = payload.get("ordered_ids") if isinstance(payload, dict) else None
|
||||
if not isinstance(ids, list) or not ids:
|
||||
raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.")
|
||||
st.reorder_projects(ordered_ids=[int(i) for i in ids])
|
||||
return JSONResponse({"ok": True})
|
||||
out: list[int] = []
|
||||
for v in ids:
|
||||
if isinstance(v, bool) or not isinstance(v, (int, str)):
|
||||
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
|
||||
try:
|
||||
n = int(v)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
|
||||
if n <= 0:
|
||||
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
|
||||
out.append(n)
|
||||
if len(set(out)) != len(out):
|
||||
raise HTTPException(status_code=400, detail="ordered_ids 에 같은 프로젝트가 두 번 들어 있습니다.")
|
||||
return out
|
||||
|
||||
|
||||
@router.put("/api/projects/{project_id}")
|
||||
@@ -1156,10 +1219,8 @@ def api_user_tasks(
|
||||
tasks = st.list_tasks(project_id=project_id, assignee_email=email, limit=500)
|
||||
else:
|
||||
tasks = st.list_tasks(assignee_email=email, limit=500)
|
||||
# 전체 대상이면 내가 볼 수 있는 프로젝트의 업무만 남긴다(비관리자).
|
||||
allowed = _accessible_project_ids(st, user)
|
||||
if allowed is not None:
|
||||
tasks = [t for t in tasks if t["project_id"] in allowed]
|
||||
# 전체 대상이면 내가 지금 볼 수 있는 업무만(원 소속 멤버 또는 연결된 프로젝트의 읽기 — 프로젝트 화면과 같은 기준).
|
||||
tasks = access.filter_visible_tasks(st, user, tasks)
|
||||
return JSONResponse({"tasks": tasks})
|
||||
|
||||
|
||||
@@ -1253,11 +1314,19 @@ def _stage_default_assignee_arg(st: Any, project_id: int, payload: dict[str, Any
|
||||
allowed = {m["user_email"] for m in st.list_members(project_id=project_id)}
|
||||
project = st.get_project(project_id=project_id) or {}
|
||||
allowed.add(store.norm_str(project.get("owner_email") or "", lower=True))
|
||||
if email not in allowed:
|
||||
# 담당자 지정(_check_assignee)과 같은 지금 권한 — 멤버이고, 등록된 project 권한 사용자
|
||||
if email not in allowed or not _registered_project_user(email):
|
||||
raise HTTPException(status_code=400, detail="기본 담당자는 이 프로젝트 멤버여야 합니다.")
|
||||
return email
|
||||
|
||||
|
||||
def _registered_project_user(email: str) -> bool:
|
||||
"""지금 등록돼 있고 project 모듈 권한이 있는 사용자인가 — 섹션 기본 담당자 자동 배정 전 확인(DB 밖,
|
||||
사용자 목록만 본다 — 작업 행을 잠근 트랜잭션 안에서 불려도 다른 DB 연결을 빌리지 않는다)."""
|
||||
rec = access.default_user_lookup(email)
|
||||
return bool(rec) and access.can_use_module({**rec, "email": rec.get("email") or email})
|
||||
|
||||
|
||||
def _stage_of_project(st: Any, stage_id: int, project_id: int) -> dict[str, Any]:
|
||||
"""URL 의 세션이 URL 의 프로젝트 것인지 확인. 권한 검사는 project_id 로
|
||||
하므로, 이걸 안 보면 아무 프로젝트 멤버나 남의 세션을 고칠 수 있다."""
|
||||
@@ -1295,7 +1364,9 @@ def api_list_tasks(request: Request, project_id: int) -> JSONResponse:
|
||||
st = _db_or_503(request)
|
||||
_require_manage(request, st, user, project_id)
|
||||
tasks = st.list_tasks(project_id=project_id, include_subprojects=True, limit=2000)
|
||||
return JSONResponse({"tasks": tasks})
|
||||
# 서브프로젝트는 프로젝트마다 멤버가 따로다 — 부모를 볼 수 있다고 자식 작업이 보이면 안 된다.
|
||||
# 각 작업을 지금 권한(원 소속 멤버 또는 연결된 프로젝트의 읽기)으로 다시 거른다.
|
||||
return JSONResponse({"tasks": access.filter_visible_tasks(st, user, tasks)})
|
||||
|
||||
|
||||
@router.get("/api/projects/{project_id}/snapshot")
|
||||
@@ -1317,18 +1388,18 @@ def api_project_snapshot(request: Request, project_id: int, scope: str = "projec
|
||||
"stages": st.list_stages(project_id=project_id),
|
||||
"members": st.list_members(project_id=project_id),
|
||||
})
|
||||
allowed = _accessible_project_ids(st, user)
|
||||
top = [
|
||||
p for p in st.list_projects(include_archived=False,
|
||||
member_email=None if allowed is None else user["email"])
|
||||
if not p.get("parent_id")
|
||||
]
|
||||
ids = [p["id"] for p in top]
|
||||
project = st.get_project(project_id=project_id)
|
||||
if project is None:
|
||||
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
||||
top, ids = _view_scope(st, user, project) # 첫 화면(project_page)과 같은 범위
|
||||
stages_by_project = st.list_stages_for_projects(project_ids=ids)
|
||||
metas = [_project_meta(p) for p in top]
|
||||
if project_id not in {int(p["id"]) for p in top}:
|
||||
metas.append({**_project_meta(project), "view_only": True})
|
||||
return JSONResponse({
|
||||
"scope": "all",
|
||||
"project": st.get_project(project_id=project_id),
|
||||
"projects": [_project_meta(p) for p in top],
|
||||
"project": project,
|
||||
"projects": metas,
|
||||
"tasks": st.list_tasks_for_projects(project_ids=ids),
|
||||
"stages_by_project": {str(k): v for k, v in stages_by_project.items()},
|
||||
"stages": stages_by_project.get(project_id) or st.list_stages(project_id=project_id),
|
||||
@@ -1345,10 +1416,10 @@ def api_subtasks_summary(request: Request, project_id: int, scope: str = "projec
|
||||
st = _db_or_503(request)
|
||||
_require_manage(request, st, user, project_id)
|
||||
if scope == "all":
|
||||
allowed = _accessible_project_ids(st, user)
|
||||
ids = [p["id"] for p in st.list_projects(include_archived=False,
|
||||
member_email=None if allowed is None else user["email"])
|
||||
if not p.get("parent_id")]
|
||||
project = st.get_project(project_id=project_id)
|
||||
if project is None:
|
||||
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
||||
ids = _view_scope(st, user, project)[1] # 화면·스냅샷과 같은 범위
|
||||
else:
|
||||
ids = [project_id]
|
||||
parents = [t["id"] for t in st.list_tasks_for_projects(project_ids=ids)]
|
||||
@@ -1414,6 +1485,7 @@ def api_create_task(
|
||||
due_time=payload.get("due_time"),
|
||||
created_by=user["email"],
|
||||
parent_task_id=payload.get("parent_task_id"),
|
||||
assignee_allowed=_registered_project_user,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
@@ -1486,7 +1558,8 @@ def api_update_task(
|
||||
if "description" in payload:
|
||||
payload["description"] = store.sanitize_description_html(payload["description"])
|
||||
try:
|
||||
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"])
|
||||
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"],
|
||||
assignee_allowed=_registered_project_user)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError:
|
||||
@@ -1655,22 +1728,15 @@ def api_list_followers(request: Request, task_id: int) -> JSONResponse:
|
||||
def api_add_follower(
|
||||
request: Request, task_id: int, payload: dict[str, Any] = Body(default={})
|
||||
) -> JSONResponse:
|
||||
"""팔로워 추가. email 을 안 주면 나 자신(팔로우). 다른 사람은 그 프로젝트를
|
||||
볼 수 있는 사람(멤버·owner·관리자)만 추가할 수 있다 — 못 보는 업무의 알림이
|
||||
가면 안 되므로."""
|
||||
from app.main import user_store # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
"""팔로워 추가. email 을 안 주면 나 자신(팔로우). 다른 사람은 그 프로젝트를 지금 볼 수 있는
|
||||
사람(멤버·owner, 수퍼관리자 — 담당자 후보와 같은 access.can_assign)만 — 못 보는 업무의 알림이 가면
|
||||
안 되므로. 관리자도 멤버가 아니면 안 된다(2026-10-07 — 예전엔 관리자는 멤버가 아니어도 넣을 수 있었다)."""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
task = _task_for_followers(request, st, user, task_id)
|
||||
email = store.norm_str(payload.get("email") or user["email"], lower=True)
|
||||
if email != store.norm_str(user["email"], lower=True):
|
||||
target = user_store.get(email)
|
||||
allowed = (target is not None and is_admin(target)) or st.is_member(
|
||||
project_id=task["project_id"], user_email=email
|
||||
)
|
||||
if not allowed:
|
||||
if not access.can_assign(st, email, task["project_id"]):
|
||||
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
|
||||
try:
|
||||
st.add_followers(task_id=task_id, emails=[email])
|
||||
@@ -1904,10 +1970,16 @@ def _after_comment(
|
||||
|
||||
# 같은 댓글이 두 번 등록되지 않게(더블클릭·Enter 연타·응답을 못 받은 재전송) — 화면이 댓글마다
|
||||
# 만든 client_token 으로 10분 동안 첫 결과를 돌려준다. 웹 프로세스 하나(uvicorn 단일 워커) 기준.
|
||||
#
|
||||
# 보장 범위: 이 기록은 **웹 프로세스 메모리**에 있다. 같은 프로세스 안에서는 동시 요청·응답 유실 후 재전송이
|
||||
# 한 번만 만든다. 웹 워커가 여럿이면(uvicorn --workers N·컨테이너 여러 개) 다른 워커로 간 재전송은 막지 못하고,
|
||||
# 프로세스를 다시 띄우면 기록도 사라진다(지금 운영은 web 컨테이너 1개·워커 1개).
|
||||
_ONCE_TTL_SEC = 600
|
||||
_once_lock = threading.Lock()
|
||||
_once_results: dict[tuple[str, int, str], tuple[float, dict[str, Any]]] = {}
|
||||
_once_key_locks: dict[tuple[str, int, str], threading.Lock] = {}
|
||||
# 키별 잠금 [잠금, 쓰는 요청 수]. 쓰는 요청이 0 이 되면 바로 뺀다 — 결과가 있으면 다음 요청은 결과로
|
||||
# 답하고(결과를 먼저 저장한 뒤 잠금을 푼다), 실패해 결과가 없으면 다음 요청이 새로 만든다(재시도).
|
||||
_once_key_locks: dict[tuple[str, int, str], list[Any]] = {}
|
||||
|
||||
|
||||
def _once(user: dict[str, Any], task_id: int, token: str, fn: Any) -> dict[str, Any]:
|
||||
@@ -1918,9 +1990,12 @@ def _once(user: dict[str, Any], task_id: int, token: str, fn: Any) -> dict[str,
|
||||
with _once_lock:
|
||||
for k in [k for k, (t, _) in _once_results.items() if now - t > _ONCE_TTL_SEC]:
|
||||
_once_results.pop(k, None)
|
||||
_once_key_locks.pop(k, None)
|
||||
klock = _once_key_locks.setdefault(key, threading.Lock())
|
||||
with klock: # 같은 토큰의 동시 요청은 첫 요청이 끝날 때까지 기다렸다가 그 결과를 받는다
|
||||
entry = _once_key_locks.get(key)
|
||||
if entry is None:
|
||||
entry = _once_key_locks[key] = [threading.Lock(), 0]
|
||||
entry[1] += 1
|
||||
try:
|
||||
with entry[0]: # 같은 토큰의 동시 요청은 첫 요청이 끝날 때까지 기다렸다가 그 결과를 받는다
|
||||
with _once_lock:
|
||||
hit = _once_results.get(key)
|
||||
if hit is not None:
|
||||
@@ -1929,6 +2004,11 @@ def _once(user: dict[str, Any], task_id: int, token: str, fn: Any) -> dict[str,
|
||||
with _once_lock:
|
||||
_once_results[key] = (time.monotonic(), out)
|
||||
return out
|
||||
finally:
|
||||
with _once_lock:
|
||||
entry[1] -= 1
|
||||
if entry[1] <= 0 and _once_key_locks.get(key) is entry:
|
||||
_once_key_locks.pop(key, None)
|
||||
|
||||
|
||||
_MAX_COMMENT_FILES = 20
|
||||
@@ -2142,14 +2222,21 @@ def api_upload_attachment(
|
||||
orig = (file.filename or "file").replace("\\", "_").replace("/", "_").strip()
|
||||
suffix = Path(orig).suffix[:16]
|
||||
stored = f"{uuid.uuid4().hex}{suffix}"
|
||||
dest = _attach_dir(request, task_id) / stored
|
||||
dest = _attach_dir(request, task_id) / stored # 요청마다 새 uuid 이름 — 기존 파일을 덮지 않는다
|
||||
dest.write_bytes(data)
|
||||
|
||||
try:
|
||||
att = st.add_attachment(
|
||||
task_id=task_id, filename=orig, stored_name=stored,
|
||||
content_type=file.content_type or "application/octet-stream",
|
||||
size_bytes=len(data), uploaded_by=user["email"], comment_id=comment_id,
|
||||
)
|
||||
except Exception:
|
||||
# DB 에 안 들어간 파일은 디스크에도 남기지 않는다(댓글+첨부 일괄 등록과 같은 원칙) — 이 요청이 쓴 파일만.
|
||||
try:
|
||||
dest.unlink(missing_ok=True)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("첨부 정리 실패: %s", dest.name)
|
||||
raise
|
||||
return JSONResponse({"attachment": att}, status_code=201)
|
||||
|
||||
|
||||
@@ -2317,14 +2404,44 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]
|
||||
out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
|
||||
if after < 0:
|
||||
return out
|
||||
rows = [n for n in st.list_notifications(recipient_email=user["email"], unread_only=True, limit=50)
|
||||
if n.get("type") in ("mention", "assigned") and int(n["id"]) > after]
|
||||
rows = sorted(_visible_notifications(st, user, rows), key=lambda n: int(n["id"]))[:10]
|
||||
# 수신자·읽지 않음·종류·after 는 DB 에서 먼저(오래된 것부터), 지금 권한은 여기서 — 페이지를 넘기며
|
||||
# 볼 수 있는 것 10건을 모은다. 예전엔 최신 50건을 먼저 자른 뒤 걸러서, 그 뒤에 댓글 알림이 50건
|
||||
# 쌓이거나 배정이 60건을 넘거나 볼 수 없는 작업 알림이 앞을 채우면 팝업이 빠졌다.
|
||||
rows: list[dict[str, Any]] = []
|
||||
cursor = int(after)
|
||||
for _ in range(_ALERT_SCAN_PAGES):
|
||||
page = st.list_unread_after(recipient_email=user["email"], after_id=cursor,
|
||||
types=_ALERT_TYPES, limit=_ALERT_PAGE)
|
||||
if not page:
|
||||
break
|
||||
rows.extend(_visible_notifications(st, user, page))
|
||||
cursor = max(int(n["id"]) for n in page)
|
||||
if len(rows) >= _ALERT_MAX or len(page) < _ALERT_PAGE:
|
||||
break
|
||||
rows = sorted(rows, key=lambda n: int(n["id"]))[:_ALERT_MAX]
|
||||
out["alerts"] = [{k: n.get(k) for k in ("id", "type", "title", "body", "task_id", "project_id", "actor_email", "created_at")}
|
||||
for n in rows]
|
||||
for a in out["alerts"]:
|
||||
a["href"] = _alert_href(a)
|
||||
return out
|
||||
|
||||
|
||||
_ALERT_TYPES = ("mention", "assigned")
|
||||
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
|
||||
_ALERT_PAGE = 200
|
||||
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
|
||||
|
||||
|
||||
def _alert_href(n: dict[str, Any]) -> str:
|
||||
"""알림을 열 주소 — 작업 알림은 /project/t/{id}(지금 권한으로 열 수 있는 프로젝트를 서버가 고른다 —
|
||||
연결된 프로젝트에서만 읽을 수 있는 작업도 403 이 나지 않게), 작업 없는 프로젝트 알림은 그 프로젝트."""
|
||||
if n.get("task_id"):
|
||||
return f"/project/t/{int(n['task_id'])}"
|
||||
if n.get("project_id"):
|
||||
return f"/project/p/{int(n['project_id'])}"
|
||||
return "/project/inbox"
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# PC 알림 프로그램(desktop/notifier, 023) — 브라우저 쿠키 대신 PC별 연결 토큰(Authorization: Bearer).
|
||||
# 연결: 프로그램 POST link/start → 사용자가 브라우저 /project/notifier?code= 에서 [연결] → 프로그램 POST link/poll 로 토큰 1회.
|
||||
@@ -2520,8 +2637,13 @@ def _safe_mentions(st: Any, user: dict[str, Any], *, limit: int = 100) -> list[d
|
||||
|
||||
|
||||
def _safe_mention_unread(st: Any, user: dict[str, Any]) -> int:
|
||||
"""수신함 배지 — 지금 볼 수 있는 작업의 미확인 태그 수(_safe_mentions 와 같은 기준)."""
|
||||
return sum(int(t.get("unread_mentions") or 0) for t in _safe_mentions(st, user, limit=1000))
|
||||
"""수신함 배지 — 지금 볼 수 있는 작업의 미확인 태그 수(_safe_mentions 와 같은 기준). 미확인 태그가 있는
|
||||
작업만 가볍게 읽어 개수 제한 없이 센다(예전엔 태그된 작업 최근 1000개 안에서만)."""
|
||||
try:
|
||||
rows = st.list_unread_mention_refs(mentioned_email=user["email"])
|
||||
except Exception: # noqa: BLE001 - 006 미적용
|
||||
return 0
|
||||
return sum(int(t.get("unread_mentions") or 0) for t in access.filter_visible_tasks(st, user, rows))
|
||||
|
||||
|
||||
def _visible_notifications(st: Any, user: dict[str, Any], items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
@@ -2544,8 +2666,8 @@ def _visible_notifications(st: Any, user: dict[str, Any], items: list[dict[str,
|
||||
|
||||
|
||||
def _notification_unread(st: Any, user: dict[str, Any]) -> int:
|
||||
rows = st.list_notifications(recipient_email=user["email"], unread_only=True, limit=500)
|
||||
return len(_visible_notifications(st, user, rows))
|
||||
"""읽지 않은 알림 수 — 지금 볼 수 있는 것만, 개수 제한 없이(예전엔 최근 500건만 세었다)."""
|
||||
return len(_visible_notifications(st, user, st.list_unread_refs(recipient_email=user["email"])))
|
||||
|
||||
|
||||
@router.get("/api/mentions")
|
||||
@@ -2576,12 +2698,14 @@ def api_mentions_read(
|
||||
st = _db_or_503(request)
|
||||
task_id = payload.get("task_id")
|
||||
try:
|
||||
n = st.mark_mentions_read(
|
||||
mentioned_email=user["email"],
|
||||
task_id=int(task_id) if task_id else None,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
tid = int(task_id) if task_id else None
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="task_id 가 올바르지 않습니다.")
|
||||
try:
|
||||
n = st.mark_mentions_read(mentioned_email=user["email"], task_id=tid)
|
||||
except UndefinedTable: # 006 미적용 — 태그 기록이 없다
|
||||
n = 0
|
||||
# 그 밖의 DB 오류는 실패로 돌려준다 — 예전엔 성공처럼 답해 화면이 확인한 것으로 지웠다.
|
||||
return JSONResponse({"ok": True, "marked": n})
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
<div class="pj-field-label">멤버
|
||||
<div class="pj-member-picker" id="pj-f-members">불러오는 중…</div>
|
||||
</div>
|
||||
<p class="pj-modal-msg" id="pj-f-project-msg" role="status" hidden></p>
|
||||
<div class="pj-modal-actions">
|
||||
<button type="button" class="pj-btn" data-close>취소</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-project">만들기</button>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -291,5 +291,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261007a" defer></script>
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -181,6 +181,10 @@
|
||||
<li><b>색상</b>(32가지)과 <b>아이콘</b>을 고릅니다. 아이콘 첫 칸 <span class="pjh-ui">Aa</span>를 고르면 아이콘 대신 이름 첫 글자가 나옵니다.</li>
|
||||
<li>함께할 <b>멤버</b>에 체크하고 <span class="pjh-ui">만들기</span>를 누릅니다. 만든 사람은 자동으로 프로젝트 주인이 됩니다.</li>
|
||||
</ol>
|
||||
<p>프로젝트는 만들어졌는데 일부 멤버를 배정하지 못하면 창이 닫히지 않고 <b>배정하지 못한 멤버</b>가 빨갛게 표시됩니다.
|
||||
<span class="pjh-ui">실패한 멤버 다시 배정</span>을 누르면 그 멤버만 다시 배정합니다(프로젝트를 또 만들지 않습니다).
|
||||
창을 닫으면 만든 프로젝트로 넘어가며, 남은 멤버는 프로젝트 화면에서 배정하면 됩니다.
|
||||
다른 사람을 소유자로 정해 만들면 만든 사람은 일반 멤버로 함께 들어갑니다(나중에 멤버에서 뺄 수 있습니다).</p>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
||||
<div>새 프로젝트는 섹션 없이 빈 보드로 시작합니다. 보드의 <span class="pjh-ui">+ 섹션 추가</span>로 “할 일 · 진행 중 · 완료”처럼 단계를 먼저 만들어 두면 편합니다. (<a href="#board">6장</a>)</div></div>
|
||||
<h3>프로젝트 수정 (Pro user 이상)</h3>
|
||||
@@ -192,7 +196,8 @@
|
||||
<li>색이 밝으면(연노랑·하늘색 등) 글자와 아이콘이 자동으로 어둡게 바뀌어 잘 보입니다.</li>
|
||||
</ul>
|
||||
<h3>순서 바꾸기 (Pro user 이상)</h3>
|
||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.</p>
|
||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
|
||||
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
|
||||
<h3>프로젝트 삭제</h3>
|
||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
|
||||
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
||||
@@ -222,7 +227,8 @@
|
||||
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
|
||||
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 작업을 함께 봅니다
|
||||
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.</p>
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.
|
||||
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 작업</b>도 한 번씩 함께 보입니다.</p>
|
||||
<h3>필터 바</h3>
|
||||
<p>탭 아래 한 줄로 작업을 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
||||
<ul>
|
||||
@@ -484,7 +490,10 @@
|
||||
<h3>수신함 화면</h3>
|
||||
<ul>
|
||||
<li><b>나를 태그한 작업</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열리고(나를 태그한 작업도 같음), 작업 창이 열린 채 다른 줄을 누르면 작업 창이 그 작업으로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 작업의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.</li>
|
||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열리고(나를 태그한 작업도 같음), 작업 창이 열린 채 다른 줄을 누르면 작업 창이 그 작업으로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 작업의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
||||
작업 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(작업 창을 직접 닫을 때와 같음).
|
||||
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
|
||||
다른 프로젝트에서 연결돼 와 읽기만 되는 작업의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
||||
</ul>
|
||||
<h3>어떤 알림이 누구에게 가나요?</h3>
|
||||
@@ -595,7 +604,7 @@
|
||||
<section class="pjh-sec" id="meetings">
|
||||
<h2><span class="pjh-num">21</span>주간 회의록</h2>
|
||||
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 주요 업무와 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 프로젝트 관리 권한이 있는 직원은 <b>누구나 회의록을 만들고 고칠 수 있습니다</b>. Pro user 이상이 <span class="pjh-ui">회의 완료</span>를 누르면 그 회의록은 아무도 고칠 수 없게 잠기고(🔒 회의 완료 표시), Pro user 이상은 <span class="pjh-ui">완료 해제</span>로 다시 열 수 있습니다. 회의록 삭제도 Pro user 이상만 합니다.</p>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>지난주 리뷰의 <b>결과</b>(글·금액)는 다음 주 회의에서 적는 값이라, 지난주 회의록이 완료돼 있어도 이번 주 회의록이 열려 있으면 적을 수 있습니다. 이번 주 회의록까지 완료하면 함께 잠깁니다.</div></div>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>지난주 리뷰의 <b>결과</b>(글·금액)는 다음 주 회의에서 적는 값이라, 지난주 회의록이 완료돼 있어도 이번 주 회의록이 열려 있으면 적을 수 있습니다. 이번 주 회의록까지 완료하면 함께 잠깁니다. 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있는 동안만 결과를 고칠 수 있습니다.</div></div>
|
||||
|
||||
<h3 id="meetings-week">회의록 열기와 주차 기준</h3>
|
||||
<p>왼쪽 연도 앞 화살표를 누르면 해당 연도의 하위 월 전체를 접거나 펼칠 수 있습니다. 연도 글자를 누르면 연간 목표를 엽니다. 연도와 월의 접기·펼치기 선택은 이 브라우저에 기억됩니다.</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
{% for t in mentioned_tasks %}
|
||||
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
|
||||
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
|
||||
data-href="/project/p/{{ t.project_id }}?task={{ t.id }}" title="누르면 오른쪽에 작업 창">
|
||||
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 작업 창">
|
||||
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
||||
<div class="pj-inbox-body">
|
||||
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
||||
@@ -70,7 +70,7 @@
|
||||
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}" tabindex="0" role="button"
|
||||
data-id="{{ n.id }}"
|
||||
{% if n.task_id %}data-project="{{ n.project_id }}" data-task-id="{{ n.task_id }}"{% endif %}
|
||||
{% if n.project_id %}data-href="/project/p/{{ n.project_id }}{% if n.task_id %}?task={{ n.task_id }}{% endif %}"{% endif %}>
|
||||
{% if n.task_id %}data-href="/project/t/{{ n.task_id }}"{% elif n.project_id %}data-href="/project/p/{{ n.project_id }}"{% endif %}>
|
||||
<span class="material-symbols-outlined pj-inbox-icon">
|
||||
{% if n.type == 'assigned' %}assignment_ind
|
||||
{% elif n.type == 'completed' %}task_alt
|
||||
@@ -101,5 +101,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -488,5 +488,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261008d" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1028,6 +1028,12 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
.pj-member-pick-avatar .pj-member-pick-icon.material-symbols-outlined { font-size: 40px; }
|
||||
.pj-member-pick-avatar img.pj-member-pick-icon { width: 36px; height: 36px; }
|
||||
.pj-member-pick-stacked .pj-member-pick-name { font-size: 12.5px; }
|
||||
/* 새 프로젝트 — 만든 뒤 배정에 실패한 멤버(다시 배정 대상)와 안내줄 */
|
||||
.pj-member-pick-stacked.is-failed { background: #fdecec; box-shadow: inset 0 0 0 1px #f1a8a8; }
|
||||
.pj-member-pick-stacked.is-failed .pj-member-pick-name { color: #b42318; }
|
||||
.pj-modal-msg { margin: 8px 0 0; padding: 8px 10px; border-radius: 6px; font-size: 12.5px; line-height: 1.5;
|
||||
background: #f5f6f8; color: #333; }
|
||||
.pj-modal-msg.is-error { background: #fdecec; color: #b42318; }
|
||||
|
||||
/* ── 좌측 사이드바 "전체 멤버" — 메뉴의 실제 내부 폭에 따라 4열↔3열, 아이콘 아래 이름(새 프로젝트
|
||||
모달의 pj-member-pick-stacked 와 같은 아이콘 크기 재사용). ── */
|
||||
|
||||
+227
-60
@@ -1294,12 +1294,53 @@
|
||||
membersBox.innerHTML = "<span class='pj-empty-sm'>불러오기 실패</span>";
|
||||
}
|
||||
});
|
||||
el("pj-save-project").addEventListener("click", async function () {
|
||||
// 만들기는 두 단계 — ① 프로젝트 생성(한 번만) ② 고른 멤버 배정(사람마다). 생성이 끝난 뒤 배정이 실패하면
|
||||
// 창을 닫지 않고 실패한 사람을 표시한다 — [다시 배정]은 실패한 사람만 다시 보내고 프로젝트를 또 만들지 않는다.
|
||||
// 진행 중 연타는 무시하고, 진행 중 [취소]·바깥 클릭으로 닫아도 요청은 끝까지 가며 결과는 알림으로 알린다.
|
||||
const saveBtn = el("pj-save-project");
|
||||
const msgBox = el("pj-f-project-msg");
|
||||
let created = null; // 이번 창에서 이미 만든 프로젝트(다시 배정 때 재사용)
|
||||
let assigned = new Set(); // 이미 배정에 성공한 이메일
|
||||
let saving = false;
|
||||
function setMsg(html, isError) {
|
||||
if (!msgBox) return;
|
||||
msgBox.hidden = !html;
|
||||
msgBox.innerHTML = html || "";
|
||||
msgBox.classList.toggle("is-error", !!isError);
|
||||
}
|
||||
function resetForm() {
|
||||
created = null;
|
||||
assigned = new Set();
|
||||
setMsg("");
|
||||
saveBtn.textContent = "만들기";
|
||||
["pj-f-name", "pj-f-desc", "pj-f-due"].forEach(function (id) { el(id).value = ""; el(id).disabled = false; });
|
||||
if (membersBox) membersBox.querySelectorAll(".pj-member-pick").forEach(function (l) { l.classList.remove("is-failed"); });
|
||||
getColor = renderColorPalette(el("pj-f-colors"), null, "#4573d2");
|
||||
getIcon = renderIconPalette(el("pj-f-icons"), "");
|
||||
}
|
||||
function finish() {
|
||||
const p = created;
|
||||
closeModal(modal);
|
||||
resetForm();
|
||||
if (p && onCreated) onCreated(p);
|
||||
}
|
||||
// 만든 뒤 배정에 실패한 채로 창을 닫으면 — 만든 프로젝트로 넘어간다(멤버는 프로젝트 화면에서 다시 배정).
|
||||
new MutationObserver(function () {
|
||||
if (!modal.hidden || saving || !created) return;
|
||||
showToast("프로젝트는 만들어졌습니다. 배정하지 못한 멤버는 프로젝트 화면에서 다시 배정하세요.", "error");
|
||||
finish();
|
||||
}).observe(modal, { attributes: true, attributeFilter: ["hidden"] });
|
||||
saveBtn.addEventListener("click", async function () {
|
||||
if (saving) return;
|
||||
const name = el("pj-f-name").value.trim();
|
||||
if (!name) { alert("이름을 입력하세요."); return; }
|
||||
const memberEmails = membersBox
|
||||
? Array.from(membersBox.querySelectorAll("input[type=checkbox]:checked")).map(function (c) { return c.value; })
|
||||
if (!created && !name) { alert("이름을 입력하세요."); return; }
|
||||
const picked = membersBox
|
||||
? Array.from(membersBox.querySelectorAll("input[type=checkbox]:checked"))
|
||||
: [];
|
||||
saving = true;
|
||||
saveBtn.disabled = true;
|
||||
try {
|
||||
if (!created) {
|
||||
try {
|
||||
const res = await api("POST", "/project/api/projects", {
|
||||
name: name,
|
||||
@@ -1308,18 +1349,46 @@
|
||||
color: getColor(),
|
||||
icon: getIcon() || undefined,
|
||||
});
|
||||
const pid = res.project.id;
|
||||
for (const email of memberEmails) {
|
||||
try { await api("POST", "/project/api/projects/" + pid + "/members", { user_email: email }); }
|
||||
catch (_) {}
|
||||
created = res.project;
|
||||
} catch (e) {
|
||||
if (modal.hidden) showToast("프로젝트를 만들지 못했습니다: " + e.message, "error");
|
||||
else setMsg("프로젝트를 만들지 못했습니다: " + escapeHtml(e.message), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const failed = [];
|
||||
for (const box of picked) {
|
||||
const email = box.value;
|
||||
if (assigned.has(email)) continue;
|
||||
const label = box.closest(".pj-member-pick");
|
||||
try {
|
||||
await api("POST", "/project/api/projects/" + created.id + "/members", { user_email: email });
|
||||
assigned.add(email);
|
||||
if (label) label.classList.remove("is-failed");
|
||||
} catch (e) {
|
||||
failed.push({ email: email, reason: e.message });
|
||||
if (label) label.classList.add("is-failed");
|
||||
}
|
||||
}
|
||||
if (!failed.length) {
|
||||
if (modal.hidden) { showToast("프로젝트를 만들었습니다."); }
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
// 생성은 됐다 — 이름 등은 더 바꿀 수 없게 잠그고, 실패한 멤버만 다시 보내게 한다.
|
||||
["pj-f-name", "pj-f-desc", "pj-f-due"].forEach(function (id) { el(id).disabled = true; });
|
||||
saveBtn.textContent = "실패한 멤버 다시 배정";
|
||||
const html = "프로젝트 '" + escapeHtml(created.name || name) + "' 는 만들어졌습니다. 멤버 " + failed.length +
|
||||
"명을 배정하지 못했습니다: " + failed.map(function (f) {
|
||||
return "<b>" + escapeHtml(idOf(f.email)) + "</b>(" + escapeHtml(f.reason) + ")";
|
||||
}).join(", ") + ". [실패한 멤버 다시 배정]을 누르거나, 창을 닫고 프로젝트 화면에서 배정하세요.";
|
||||
if (modal.hidden) showToast("프로젝트는 만들어졌지만 멤버 " + failed.length + "명을 배정하지 못했습니다.", "error");
|
||||
else setMsg(html, true);
|
||||
} finally {
|
||||
saving = false;
|
||||
saveBtn.disabled = false;
|
||||
if (modal.hidden && created) finish(); // 진행 중에 창을 닫았다 — 끝난 뒤 만든 프로젝트로
|
||||
}
|
||||
closeModal(modal);
|
||||
el("pj-f-name").value = ""; el("pj-f-desc").value = "";
|
||||
el("pj-f-due").value = "";
|
||||
getColor = renderColorPalette(el("pj-f-colors"), null, "#4573d2");
|
||||
getIcon = renderIconPalette(el("pj-f-icons"), "");
|
||||
if (onCreated) onCreated(res.project);
|
||||
} catch (e) { showToast("생성 실패: " + e.message, "error"); }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1439,8 +1508,9 @@
|
||||
}
|
||||
function render() {
|
||||
let rootUl = el("pj-tree-root");
|
||||
const active = projects.filter(function (p) { return p.status !== "completed"; });
|
||||
const done = projects.filter(function (p) { return p.status === "completed"; });
|
||||
// view_only = 보관된 프로젝트·서브프로젝트를 직접 연 경우 화면용으로만 받은 것 — 목록엔 안 그린다.
|
||||
const active = projects.filter(function (p) { return p.status !== "completed" && !p.view_only; });
|
||||
const done = projects.filter(function (p) { return p.status === "completed" && !p.view_only; });
|
||||
const block = side.querySelector(".pj-tree-block");
|
||||
// 처음에 프로젝트가 하나도 없었으면 서버가 "프로젝트 없음" 만 그렸다 —
|
||||
// 새로 만들면 그때 목록(ul)을 만든다.
|
||||
@@ -3277,10 +3347,19 @@
|
||||
let taskFilter = Object.assign({}, TASK_FILTER_DEFAULT);
|
||||
try { Object.assign(taskFilter, JSON.parse(localStorage.getItem(FILTER_KEY) || "{}")); } catch (_) {}
|
||||
const todayNowP = kstTodayIso; // 한국시간 오늘(그때그때)
|
||||
// 전체 보기는 작업마다 한 행 — 원 소속 행이 있으면 그 행, 원 소속을 볼 수 없어 연결된 프로젝트의
|
||||
// 행(읽기 전용)만 있으면 그중 첫 행(예전엔 원 소속 행만 남겨 이런 작업이 전체 보기에서 빠졌다).
|
||||
function scopeTasks() {
|
||||
return viewScope === "project"
|
||||
? tasks.filter(function (t) { return t.context_project_id === projectId; })
|
||||
: tasks.filter(function (t) { return t.context_project_id === t.project_id; });
|
||||
if (viewScope === "project") return tasks.filter(function (t) { return t.context_project_id === projectId; });
|
||||
const home = new Set();
|
||||
tasks.forEach(function (t) { if (t.context_project_id === t.project_id) home.add(t.id); });
|
||||
const seen = new Set();
|
||||
return tasks.filter(function (t) {
|
||||
if (t.context_project_id === t.project_id) return true;
|
||||
if (home.has(t.id) || seen.has(t.id)) return false;
|
||||
seen.add(t.id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
// 모든 뷰가 이 함수로 업무를 받는다 — 스코프 → 필터 → 정렬 순.
|
||||
function visibleTasks() {
|
||||
@@ -6451,6 +6530,22 @@
|
||||
closeSlidePanel(taskModal);
|
||||
} finally { taskClosing = false; }
|
||||
}
|
||||
// 수신함 오른쪽 작업 창(iframe, html.pj-embed) — 바깥(수신함)이 다른 줄로 바꾸거나 창을 닫기 전에 부른다.
|
||||
// 작업 창 닫기와 같은 절차(이미지 업로드·만들기·저장 대기 → 실패 칸 재시도 → "버리고 넘어가기 / 계속 편집").
|
||||
// true = 넘어가도 됨(이 창의 늦은 응답은 버린다), false = 계속 편집(창·입력 그대로).
|
||||
if (document.documentElement.classList.contains("pj-embed")) {
|
||||
let embedSettling = null;
|
||||
window.__pjEmbedSettle = function () {
|
||||
if (embedSettling) return embedSettling; // 저장 중 Esc·다른 줄 연타 — 같은 확인 하나를 기다린다
|
||||
embedSettling = (async function () {
|
||||
if (taskModal.hidden) return true;
|
||||
if (!(await settleBeforeLeave())) return false;
|
||||
taskGen++;
|
||||
return true;
|
||||
})();
|
||||
return embedSettling.finally(function () { embedSettling = null; });
|
||||
};
|
||||
}
|
||||
taskModal.addEventListener("click", function (e) {
|
||||
if (e.target === taskModal || e.target.closest("[data-close]")) attemptCloseTaskModal();
|
||||
});
|
||||
@@ -8567,20 +8662,38 @@
|
||||
const counter = document.getElementById("pj-mention-unread");
|
||||
let panel = null;
|
||||
let selected = []; // 지금 작업 창에 열린 줄들(같은 작업의 태그·알림)
|
||||
let shownLi = null; // 지금 작업 창에 열린 줄(대표) — 창이 닫혀 있으면 null
|
||||
// 창 바꾸기(다른 줄 열기·닫기)는 한 번에 하나만, 마지막 요청만 따른다 — 저장을 기다리는 사이
|
||||
// A→B→A 를 빨리 눌러도 확인이 끝난 뒤 그때 원하는 쪽으로 한 번만 바꾼다. undefined = 요청 없음, null = 닫기.
|
||||
let wanted;
|
||||
let switching = null;
|
||||
const readReq = new WeakMap(); // 줄 → 읽음/확인 요청(Promise<boolean>)
|
||||
|
||||
function itemsOfTask(li) {
|
||||
const tid = li.dataset.taskId;
|
||||
if (!tid) return [li];
|
||||
return Array.prototype.slice.call(document.querySelectorAll('.pj-inbox-item[data-task-id="' + tid + '"]'));
|
||||
}
|
||||
// 읽음/확인 — 서버가 받았을 때만 확인한 것으로 둔다. 실패하면 굵게(읽지 않음) 되돌리고 목록에 남긴다.
|
||||
function markSeen(li) {
|
||||
if (li.dataset.seen) return;
|
||||
li.dataset.seen = "1";
|
||||
if (readReq.has(li)) return readReq.get(li);
|
||||
if (li.dataset.seen === "1") return Promise.resolve(true);
|
||||
li.classList.remove("is-unread");
|
||||
const req = li.classList.contains("pj-mention-item")
|
||||
? api("POST", "/project/api/mentions/read", { task_id: Number(li.dataset.taskId) })
|
||||
: fetch("/project/api/notifications/" + li.dataset.id + "/read", { method: "POST" });
|
||||
Promise.resolve(req).catch(function () {});
|
||||
: fetch("/project/api/notifications/" + li.dataset.id + "/read", { method: "POST" })
|
||||
.then(function (res) { if (!res.ok) throw new Error("HTTP " + res.status); });
|
||||
const p = Promise.resolve(req).then(function () {
|
||||
li.dataset.seen = "1";
|
||||
return true;
|
||||
}, function (e) {
|
||||
readReq.delete(li); // 다음에 누르면 다시 보낸다
|
||||
li.classList.add("is-unread");
|
||||
showToast("확인 처리에 실패해 목록에 그대로 둡니다: " + ((e && e.message) || ""), "error");
|
||||
return false;
|
||||
});
|
||||
readReq.set(li, p);
|
||||
return p;
|
||||
}
|
||||
function refreshEmpty() {
|
||||
[[mentionList, "태그된 작업이 없습니다."], [notiList, "알림이 없습니다."]].forEach(function (x) {
|
||||
@@ -8598,29 +8711,52 @@
|
||||
counter.hidden = n <= 0;
|
||||
}
|
||||
}
|
||||
// 확인한 줄을 목록에서 뺀다(살짝 접히며).
|
||||
// 확인이 끝난(서버가 받은) 줄만 목록에서 뺀다(살짝 접히며). 실패한 줄·지금 열린 줄은 남긴다.
|
||||
function removeItems(list) {
|
||||
list.forEach(function (li) {
|
||||
if (!li.isConnected) return;
|
||||
Promise.resolve(readReq.get(li) || li.dataset.seen === "1").then(function (ok) {
|
||||
if (!ok || !li.isConnected || selected.indexOf(li) >= 0) return;
|
||||
li.classList.add("is-leaving");
|
||||
setTimeout(function () { li.remove(); refreshEmpty(); }, 220);
|
||||
});
|
||||
});
|
||||
}
|
||||
function setSelected(list) {
|
||||
const prev = selected;
|
||||
selected = list;
|
||||
prev.forEach(function (li) { li.classList.remove("is-selected"); });
|
||||
removeItems(prev.filter(function (li) { return list.indexOf(li) < 0; }));
|
||||
list.forEach(function (li) { li.classList.add("is-selected"); });
|
||||
removeItems(prev.filter(function (li) { return list.indexOf(li) < 0; }));
|
||||
}
|
||||
function close() {
|
||||
if (!panel || !panel.classList.contains("is-open")) return;
|
||||
function isOpen() { return !!panel && panel.classList.contains("is-open"); }
|
||||
function isShown(target) {
|
||||
if (target === null) return !isOpen();
|
||||
return isOpen() && !!shownLi && itemsOfTask(shownLi).indexOf(target.li) >= 0;
|
||||
}
|
||||
// 지금 창의 작업 창 저장이 끝나길 기다린다 — 작업 창 닫기와 같은 절차(업로드·만들기·저장 대기 → 실패 칸
|
||||
// 재시도 → "버리고 넘어가기 / 계속 편집", project.js 의 __pjEmbedSettle). 창이 아직 안 열렸거나 권한 없음
|
||||
// 화면이면 저장할 입력이 없다. beforeunload 경고에 기대지 않는다(iframe 주소를 바꾸면 경고 없이 사라진다).
|
||||
async function settleFrame() {
|
||||
if (!isOpen()) return true;
|
||||
let fn = null;
|
||||
try { fn = panel.querySelector("iframe").contentWindow.__pjEmbedSettle; } catch (_) { fn = null; }
|
||||
if (typeof fn !== "function") return true;
|
||||
try { return !!(await fn()); } catch (e) {
|
||||
showToast("작업 창 저장 상태를 확인하지 못했습니다. 작업 창에서 닫아 주세요.", "error");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function applyTarget(target) {
|
||||
if (target === null) {
|
||||
if (!isOpen()) return;
|
||||
panel.classList.remove("is-open");
|
||||
shownLi = null;
|
||||
setSelected([]);
|
||||
const p = panel;
|
||||
setTimeout(function () { if (!p.classList.contains("is-open")) p.querySelector("iframe").src = "about:blank"; }, 250);
|
||||
return;
|
||||
}
|
||||
function open(url) {
|
||||
if (!panel) {
|
||||
panel = document.createElement("div");
|
||||
panel.className = "pj-inbox-panel";
|
||||
@@ -8631,31 +8767,53 @@
|
||||
if (w) panel.style.width = "min(" + Math.round(w * uiZoom()) + "px, 92vw)";
|
||||
} catch (_) {}
|
||||
}
|
||||
panel.querySelector("iframe").src = url + (url.indexOf("?") >= 0 ? "&" : "?") + "embed=1";
|
||||
const group = itemsOfTask(target.li);
|
||||
group.forEach(markSeen); // 실제로 여는 줄만 확인한다(계속 편집을 고르면 새 줄은 그대로)
|
||||
shownLi = target.li;
|
||||
setSelected(group);
|
||||
// /project/t/{id} — 서버가 지금 권한으로 열 수 있는 프로젝트(연결된 프로젝트 포함)로 보내며 embed=1 을 이어 준다.
|
||||
panel.querySelector("iframe").src = target.href + (target.href.indexOf("?") >= 0 ? "&" : "?") + "embed=1";
|
||||
void panel.offsetWidth;
|
||||
panel.classList.add("is-open");
|
||||
}
|
||||
function requestPanel(target) {
|
||||
wanted = target;
|
||||
if (switching) return switching;
|
||||
switching = (async function () {
|
||||
while (wanted !== undefined) {
|
||||
const t = wanted;
|
||||
if (isShown(t)) { wanted = undefined; break; }
|
||||
const ok = await settleFrame();
|
||||
if (!ok) { wanted = undefined; break; } // 계속 편집 — 창·입력·선택 그대로
|
||||
if (wanted !== t) continue; // 기다리는 사이 다른 줄·닫기를 눌렀다 — 그쪽으로 다시
|
||||
wanted = undefined;
|
||||
applyTarget(t);
|
||||
}
|
||||
})().finally(function () { switching = null; });
|
||||
return switching;
|
||||
}
|
||||
function activate(li, newTab) {
|
||||
const href = li.dataset.href || "";
|
||||
const group = itemsOfTask(li);
|
||||
group.forEach(markSeen);
|
||||
if (newTab && href) { window.open(href, "_blank"); removeItems(group); return; }
|
||||
if (li.dataset.taskId && href) {
|
||||
if (selected.indexOf(li) >= 0 && panel && panel.classList.contains("is-open")) return;
|
||||
setSelected(group);
|
||||
open(href);
|
||||
} else if (href) {
|
||||
location.href = href; // 작업이 없는 프로젝트 알림 — 그 프로젝트로
|
||||
} else {
|
||||
removeItems(group); // 갈 곳이 없는 알림 — 읽음 처리하고 빼기만
|
||||
if (newTab && href) { group.forEach(markSeen); window.open(href, "_blank"); removeItems(group); return; }
|
||||
if (li.dataset.taskId && href) { requestPanel({ li: li, href: href }); return; }
|
||||
if (href) {
|
||||
// 작업이 없는 프로젝트 알림 — 열린 작업 창의 저장을 마친 뒤 그 프로젝트로
|
||||
requestPanel(null).then(function () {
|
||||
if (!isShown(null)) return; // 계속 편집
|
||||
Promise.all(group.map(markSeen)).then(function () { location.href = href; });
|
||||
});
|
||||
return;
|
||||
}
|
||||
group.forEach(markSeen);
|
||||
removeItems(group); // 갈 곳이 없는 알림 — 읽음 처리하고 빼기만
|
||||
}
|
||||
|
||||
window.addEventListener("message", function (e) {
|
||||
if (e.origin === location.origin && e.data && e.data.type === "pj-embed-close") close();
|
||||
if (e.origin === location.origin && e.data && e.data.type === "pj-embed-close") requestPanel(null);
|
||||
});
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (e.key === "Escape") { close(); return; }
|
||||
if (e.key === "Escape") { if (isOpen() || switching) requestPanel(null); return; }
|
||||
const li = (e.key === "Enter" || e.key === " ") && e.target.closest && e.target.closest(".pj-inbox-item");
|
||||
if (li && !isImeEnter(e)) { e.preventDefault(); activate(li, false); }
|
||||
});
|
||||
@@ -8667,8 +8825,8 @@
|
||||
return;
|
||||
}
|
||||
// 작업 창이 열린 채 왼쪽 수신함 영역(줄 밖)을 누르면 작업 창을 닫는다. 메뉴·모달·알림 팝업 안은 제외.
|
||||
if (panel && panel.classList.contains("is-open") && e.target.closest &&
|
||||
e.target.closest(".pj-inbox-view") && !e.target.closest(".pj-inbox-panel, .pj-modal, .pj-ctxmenu, .pj-alert-pop, button")) close();
|
||||
if (isOpen() && e.target.closest &&
|
||||
e.target.closest(".pj-inbox-view") && !e.target.closest(".pj-inbox-panel, .pj-modal, .pj-ctxmenu, .pj-alert-pop, button")) requestPanel(null);
|
||||
});
|
||||
// 오른쪽 클릭 — 열지 않고 확인(읽음)만
|
||||
document.addEventListener("contextmenu", function (e) {
|
||||
@@ -8679,24 +8837,31 @@
|
||||
{ label: "확인(목록에서 빼기)", onClick: function () { const g = itemsOfTask(li); g.forEach(markSeen); if (selected.indexOf(li) < 0) removeItems(g); } },
|
||||
]);
|
||||
});
|
||||
// 모두 확인 — 그 목록 줄을 모두 빼고, 열린 작업 창도 닫는다
|
||||
const mentionsAll = document.getElementById("pj-mentions-readall");
|
||||
if (mentionsAll) mentionsAll.addEventListener("click", async function () {
|
||||
// 모두 확인 — 열린 작업 창의 저장을 마친 뒤 그 목록 줄을 모두 뺀다
|
||||
function readAll(list, send) {
|
||||
return async function () {
|
||||
await requestPanel(null);
|
||||
if (!isShown(null)) return; // 계속 편집 — 아무것도 바꾸지 않는다
|
||||
try {
|
||||
await api("POST", "/project/api/mentions/read", {});
|
||||
close();
|
||||
if (mentionList) removeItems(Array.prototype.slice.call(mentionList.querySelectorAll(".pj-inbox-item")));
|
||||
await send();
|
||||
if (!list) return;
|
||||
const items = Array.prototype.slice.call(list.querySelectorAll(".pj-inbox-item"));
|
||||
items.forEach(function (li) { li.dataset.seen = "1"; li.classList.remove("is-unread"); });
|
||||
removeItems(items);
|
||||
} catch (e) { showToast("처리 실패: " + e.message, "error"); }
|
||||
});
|
||||
};
|
||||
}
|
||||
const mentionsAll = document.getElementById("pj-mentions-readall");
|
||||
if (mentionsAll) mentionsAll.addEventListener("click", readAll(mentionList, function () {
|
||||
return api("POST", "/project/api/mentions/read", {});
|
||||
}));
|
||||
const notiAll = document.getElementById("pj-readall");
|
||||
if (notiAll) notiAll.addEventListener("click", async function () {
|
||||
try {
|
||||
const res = await fetch("/project/api/notifications/read-all", { method: "POST" });
|
||||
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||
close();
|
||||
if (notiList) removeItems(Array.prototype.slice.call(notiList.querySelectorAll(".pj-inbox-item")));
|
||||
} catch (e) { showToast("실패: " + e.message, "error"); }
|
||||
});
|
||||
if (notiAll) notiAll.addEventListener("click", readAll(notiList, function () {
|
||||
return fetch("/project/api/notifications/read-all", { method: "POST" })
|
||||
.then(function (res) { if (!res.ok) throw new Error("HTTP " + res.status); });
|
||||
}));
|
||||
// 자동 테스트(tests/js)에서만 — 창 바꾸기 진행 상태를 기다릴 수 있게.
|
||||
if (window.__PJ_TEST__) window.__pjInbox = { settling: function () { return switching || Promise.resolve(); } };
|
||||
}
|
||||
|
||||
// ── 실시간 새로고침 ──
|
||||
@@ -11160,7 +11325,9 @@
|
||||
'<button type="button" class="pj-btn pj-btn-sm" data-alert-close>닫기</button></div>' +
|
||||
'<div class="pj-alert-list">' + items.map(function (n) {
|
||||
const isMention = n.type === "mention";
|
||||
const href = n.project_id ? "/project/p/" + n.project_id + (n.task_id ? "?task=" + n.task_id : "") : "/project/inbox";
|
||||
// 서버가 준 주소(작업 = /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 작업도 열린다)
|
||||
const href = n.href || (n.task_id ? "/project/t/" + n.task_id
|
||||
: n.project_id ? "/project/p/" + n.project_id : "/project/inbox");
|
||||
return '<a class="pj-alert-item" href="' + escapeHtml(href) + '" data-alert-open="' + escapeHtml(n.id) + '">' +
|
||||
'<span class="pj-alert-kind ' + (isMention ? "is-mention" : "is-assigned") + '">' +
|
||||
(isMention ? "나를 태그" : "작업 배정") + "</span>" +
|
||||
|
||||
@@ -46,9 +46,11 @@ namespace DbxNotifier
|
||||
}
|
||||
}
|
||||
|
||||
public string Path => ProjectId > 0
|
||||
? "/project/p/" + ProjectId + (TaskId > 0 ? "?task=" + TaskId : "")
|
||||
: "/project/inbox";
|
||||
// 작업 알림은 공유 링크(/project/t/{id}) — 서버가 지금 권한으로 열 수 있는 프로젝트(연결된 프로젝트 포함)로
|
||||
// 보낸다. 원 소속 주소로 열면 연결된 프로젝트에서만 읽을 수 있는 사람에게 403 이 났다.
|
||||
public string Path => TaskId > 0
|
||||
? "/project/t/" + TaskId
|
||||
: ProjectId > 0 ? "/project/p/" + ProjectId : "/project/inbox";
|
||||
}
|
||||
|
||||
internal sealed class AlertResult
|
||||
|
||||
+59
-3
@@ -1011,7 +1011,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
`client_token`) 한 요청으로, 댓글+첨부를 한 트랜잭션(`add_comment_with_attachments`)에 만든다. 빈 파일·20MB 초과가 하나라도
|
||||
있으면 아무것도 만들지 않고 400 `detail.failed=[{index,name,reason}]` → 화면은 그 파일만 빨갛게 표시하고 입력·파일을 유지.
|
||||
DB 실패면 방금 쓴 파일도 지운다. 글 댓글(`POST /comments`)은 본문 필수 — 예전 `has_attachment` 플래그는 받지 않는다.
|
||||
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리, 단일 워커 기준).
|
||||
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리 — 보장 범위는 6-15).
|
||||
작업 창 댓글 목록도 댓글별 첨부(이미지 미리보기·파일명 다운로드, 이스케이프)를 보여 주고, 첨부 파일 목록엔 "댓글" 표시.
|
||||
|
||||
**마감 알림** — `add_reminder_notification`: 발송 기록(`task_reminders`)과 수신함 알림을 한 트랜잭션에. 알림 생성이 실패하면
|
||||
@@ -1138,7 +1138,63 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame
|
||||
- 회의록 표 첫 열 머리 글자 "구역" → **"구분"**(화면 글자만, 데이터·코드의 section 이름은 그대로).
|
||||
- 테스트: `tests/test_project_roles.py`(DB 없이 등급별 API), `tests/test_project_module.py` 의 소유자·삭제 테스트를 새 규칙으로.
|
||||
|
||||
## 6-15. 검토 반영 — 권한·열기 경로·저장·동시성 (2026-10-12, 마이그레이션 없음)
|
||||
|
||||
권한 정책(6-14 표)은 그대로 두고, 그 정책이 새던 곳을 막았다. 테스트 `tests/test_project_review_fixes.py`(DB 없이),
|
||||
`tests/test_project_meeting_lock.py`·`test_project_alerts_api.py`, `tests/js/project_ui.test.js` 의 [검토 *] 항목.
|
||||
|
||||
- **서브프로젝트 작업**: `GET /api/projects/{id}/tasks`(하위 프로젝트까지 재귀)는 작업마다 지금 권한으로 다시 거른다
|
||||
(`access.filter_visible_tasks`) — 부모 멤버라고 멤버가 아닌 자식 프로젝트 작업이 보이지 않는다. 연결된 작업의 READ 는 그대로.
|
||||
(이 API·`POST /subprojects` 는 지금 화면에서 부르지 않는다 — 외부 호출 호환 때문에 남겨 둠.)
|
||||
- **사이드바 순서** `PUT /api/projects/order`: Pro user 이상 + 보낸 id **전부** 지금 관리할 수 있는 프로젝트여야(없는 id 도 같은 403,
|
||||
하나라도 아니면 아무것도 안 바뀜). 빈 목록·정수 아님(참/거짓·소수·글자)·0 이하·중복 = 400. 순서는 예전처럼 모두가 같이 보는 순서.
|
||||
- **작업 열기 경로 하나로**: 수신함 줄·웹 큰 팝업·PC 알림 [열기] = `/project/t/{task_id}`(공유 링크). 서버(`_task_open_project`)가
|
||||
지금 권한으로 열 프로젝트를 고른다 — FULL 이면 원 소속, READ 면 내가 볼 수 있는 연결된 프로젝트. `?embed=1` 은 옮긴 주소에도
|
||||
붙는다(수신함 iframe). 알림 응답에 `href` 가 붙는다. 예전 주소 `/p/{원 소속}?task=` 로 READ 사용자가 오면 403 대신 연결된
|
||||
프로젝트로 보낸다(옛 PC 알림 프로그램·북마크). 작업 없는 프로젝트 알림은 예전처럼 `/p/{id}`.
|
||||
- **보관·서브프로젝트 화면**: `project_page`·스냅샷(scope=all)·담당자별 합계(scope=all)는 같은 범위(`_view_scope`) — 활성 최상위
|
||||
멤버 프로젝트 + **지금 연 프로젝트 하나**(보관됐거나 서브프로젝트여서 목록에 없을 때만). 다른 보관 프로젝트는 읽지 않는다. 그
|
||||
프로젝트 메타는 `view_only: true` 로 와서 사이드바 목록엔 그리지 않는다(작업 권한 판단·타임라인 그룹용).
|
||||
- **전체 보기**: 작업마다 한 행 — 원 소속 행이 있으면 그것, 원 소속을 볼 수 없어 연결된 프로젝트 행(READ)만 있으면 그중 첫 행
|
||||
(`scopeTasks`). 예전엔 원 소속 행만 남겨 이런 작업이 빠졌다. 사용자별 작업 팝업(`/api/users/tasks`, 전체 대상)도 같은 기준(READ 포함).
|
||||
- **큰 팝업 알림**(`_alerts_payload`, 웹·PC 공용): 수신자·읽지 않음·종류(태그·배정)·`id > after` 를 DB 에서 먼저 걸고
|
||||
(`list_unread_after`) **오래된 것부터** 200건씩 넘기며 지금 볼 수 있는 것 10건을 모은다(한 번에 최대 25쪽 = 5,000행).
|
||||
예전엔 최신 50건을 자른 뒤 걸러 — 배정 뒤 댓글 알림 50건, 배정 60건 이상, 볼 수 없는 알림이 앞을 채우면 팝업이 빠졌다.
|
||||
기준점(`latest_id`)·처음 연결 때 옛 알림 안 띄움·PC 프로그램이 돌면 웹 팝업 쉼은 그대로.
|
||||
- **수신함 오른쪽 작업 창**: 다른 줄로 바꾸거나 닫기(Esc·바깥 클릭·모두 확인·프로젝트 알림 이동) 전에 iframe 안 작업 창의
|
||||
`window.__pjEmbedSettle()` 을 기다린다 — 작업 창 닫기와 같은 절차(업로드·만들기·저장 대기 → 실패 칸 재시도 → "버리고 넘어가기 /
|
||||
계속 편집"). 계속 편집이면 창·입력·선택 그대로, 새 줄은 확인하지 않는다. 바꾸기는 한 번에 하나, 마지막 요청만(A→B→A·저장 중
|
||||
Esc 연타). beforeunload 경고에 기대지 않는다. 읽음/확인은 **서버가 받았을 때만** 확인으로 두고(실패면 굵게 남기고 알림), 확인된
|
||||
줄만 목록에서 뺀다. `POST /api/mentions/read` 는 006 미적용(표 없음)만 0건 성공, 그 밖의 DB 오류는 실패로 돌려준다.
|
||||
- **일반 첨부**(`POST /api/tasks/{id}/attachments`): DB 저장이 실패하면 이 요청이 쓴 파일(새 uuid 이름)만 지운다. 크기·빈 파일·
|
||||
권한·inline 정책은 그대로.
|
||||
- **새 프로젝트 창**: ① 생성(한 번만) ② 멤버 배정(사람마다)을 나눠 안내 — 배정 실패면 창을 닫지 않고 실패한 멤버를 빨갛게,
|
||||
[실패한 멤버 다시 배정]은 그 멤버만(프로젝트를 또 만들지 않음). 진행 중 연타 무시, 진행 중 닫아도 요청은 끝까지 가고 결과는 알림.
|
||||
만든 프로젝트를 되돌리려고 지우지 않는다.
|
||||
- **배지 개수**: 내 작업(`list_my_open_refs`)·수신함 태그(`list_unread_mention_refs`)·읽지 않은 알림(`list_unread_refs`)은 가벼운 열만
|
||||
제한 없이 읽어 지금 권한으로 센다(예전 1000·1000·500건 상한). 내 작업 목록은 **미완료 전부** + 최근 완료 1000건
|
||||
(`list_my_tasks(completed_limit=)`) — 오래된 완료가 새 미완료를 밀어내지 않는다.
|
||||
- **동시성**: `update_task` 는 기존 값 읽기·섹션 확인·기본 담당자·완료 섹션 여부·최종 날짜 검사·변경·이력을 한 트랜잭션에서 그
|
||||
작업 행을 잠그고(`FOR UPDATE`) 같은 연결로 한다 — 시작일·마감일을 동시에 바꿔도 역전되지 않고, 동시 완료의 완료 이력·알림은 실제로
|
||||
바뀐 한 요청에서만. `update_project` 날짜 검사도 행 잠금 뒤. (한 창 저장 직렬화와 별개 — 여러 사람 사이의 충돌 방지.)
|
||||
- **회의록**: 머리(메모·참석자·금주 목표) 수정은 그 회의록 행을 잠그고 완료 여부를 본다([회의 완료]도 같은 행을 잠근다). 결과 칸만
|
||||
고칠 때(`_check_result_open`): 다음 주차 회의록이 **있으면** 그 회의록이 열려 있을 때만, **없으면** 그 주 회의록이 열려 있을 때만
|
||||
(예전엔 다음 회의록이 없으면 완료된 주의 결과도 고칠 수 있었다). 다음 주차 = `week_period` 끝 + 1일(달이 바뀌어도, 월요일이 아닌
|
||||
시작일도). 다음 회의록 행은 `FOR SHARE` — 잠금 순서는 늘 주차 오름차순(교착 없음).
|
||||
- **소유자를 남으로 정해 만들기**: 만든 사람을 같은 트랜잭션에서 **일반 멤버 행**으로 넣는다(`create_project(member_emails=)`) —
|
||||
`created_by` 로 권한을 주지 않으니 나중에 멤버에서 빼면 권한도 없어진다. 소유자 변경 뒤 옛 소유자 권한 회수도 그대로.
|
||||
- **중복 방지 키**(`_once`, 댓글 `client_token`): 키별 잠금을 쓰는 요청 수로 관리해 0 이 되면 바로 뺀다(실패한 키도) — 결과를 먼저
|
||||
저장한 뒤 잠금을 풀어 기다리던 요청은 결과로 답한다. 실패하면 다음 요청이 새로 만든다(재시도). **보장 범위: 웹 프로세스 하나**
|
||||
— 지금 운영은 web 컨테이너 1개·uvicorn 워커 1개(Dockerfile). 워커·컨테이너를 늘리면 다른 워커로 간 재전송은 막지 못하고 재시작하면
|
||||
기록도 사라진다(그때는 DB UNIQUE 키가 필요).
|
||||
- **섹션 기본 담당자**: 자동 배정 전에 그 사람이 지금 등록된 project 권한 사용자인지도 본다(`_registered_project_user`, 사용자 목록만 —
|
||||
잠근 트랜잭션 안에서 DB 연결을 더 빌리지 않음). 기본 담당자 지정도 같은 기준. 협업자 추가는 담당자 후보와 같은 `access.can_assign`
|
||||
(예전엔 관리자는 멤버가 아니어도 넣을 수 있었다).
|
||||
|
||||
정책 결정이 필요한 것(바꾸지 않음): 배정·완료 **메일**은 `PROJECT_NOTIFY_EMAIL`(없으면 Admin 전원)에게 프로젝트·작업 제목·담당자가
|
||||
간다 — 화면에선 비멤버 Admin 이 그 프로젝트를 못 보지만 메일로는 제목을 받는다(4장 관리자 보고 정책).
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩,
|
||||
아사나도 UI상 1단계만 허용해 현재 의도적으로 안 함).
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성.
|
||||
(세부 작업의 세부 작업은 2026-10-08 부터 지원 — 6-13 담당자별 합계 참고.)
|
||||
|
||||
@@ -60,3 +60,16 @@ python -m unittest discover -s tests -p test_project_meeting_cells.py
|
||||
`PROJECT_TEST_DB_URL`에 기존 로컬 테스트 DB를 지정해야 하며, 미설정 또는 로컬 주소가 아니면 건너뛴다.
|
||||
회의록 셀 테스트는 DB 연결을 대신하는 트랜잭션 모형으로 실제 저장소 메서드·API 권한/충돌·이동/병합 롤백·
|
||||
019 미적용·병합 행 작업 보호·서식 보존·안전한 템플릿 출력을 검증한다. 실제 PostgreSQL 잠금 동작 검증은 별도다.
|
||||
|
||||
# 프로젝트 화면·수신함 UI 테스트 (jsdom + 실제 Chrome)
|
||||
|
||||
`project.html`·`inbox.html` + `static/project.js` — 작업 창 저장/실패/동기화, 전체 보기의 연결된(읽기 전용) 작업,
|
||||
수신함 오른쪽 작업 창(저장 대기 뒤 바꾸기·계속 편집·A→B→A·저장 중 Esc·읽음 실패), 새 프로젝트 창(생성/멤버 배정 결과 분리·
|
||||
실패한 멤버만 다시 배정·연타)을 가짜 서버로 검증한다.
|
||||
|
||||
```powershell
|
||||
python tests/js/render_project.py # → tests/js/.out/project_*.html · inbox_render.html
|
||||
node tests/js/project_ui.test.js # jsdom
|
||||
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉트 뒤 embed·저장 실패 확인창·A→B→A·iframe 안 Esc·읽음 실패
|
||||
```
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// 실제 브라우저 — 수신함 오른쪽 작업 창(iframe)이 다른 줄로 바뀌거나 닫히기 전에 작업 창의 저장을 기다리는지,
|
||||
// 저장 실패면 작업 창과 같은 "버리고 넘어가기 / 계속 편집"을 묻는지, 공유 링크 리다이렉트 뒤에도 embed 인지,
|
||||
// iframe 안 Esc·빠른 A→B→A·읽음 실패를 확인한다. 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/inbox_panel.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
|
||||
const detail = (id, title) => ({ id, title, project_id: 1, stage_id: 11, description: "", priority: "normal",
|
||||
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null });
|
||||
let putStatus = 200, holdPut = false, releasePut = null, failNotiRead = false;
|
||||
const puts = [], reads = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/inbox") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "inbox_render.html"))); return; }
|
||||
const tm = /^\/project\/t\/(\d+)$/.exec(url.pathname);
|
||||
if (tm) { // 공유 링크 — 서버(router.task_permalink)처럼 embed 를 이어서 보낸다
|
||||
res.statusCode = 303;
|
||||
res.setHeader("Location", `/project/p/1?task=${tm[1]}${url.searchParams.get("embed") === "1" ? "&embed=1" : ""}`);
|
||||
res.end(); return;
|
||||
}
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "project_render.html"))); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
let raw = ""; for await (const c of req) raw += c;
|
||||
const body = raw ? JSON.parse(raw) : null;
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") return json(200, { task: detail(+task[1], "작업 " + task[1]) });
|
||||
if (task && req.method === "PUT") {
|
||||
puts.push({ id: +task[1], body });
|
||||
if (holdPut) await new Promise(r => { releasePut = r; });
|
||||
return putStatus >= 400 ? json(putStatus, { detail: "서버 오류" }) : json(200, { task: Object.assign(detail(+task[1], "작업"), body) });
|
||||
}
|
||||
if (url.pathname === "/project/api/mentions/read") { reads.push("m" + (body && body.task_id)); return json(200, { ok: true, marked: 1 }); }
|
||||
const nr = /^\/project\/api\/notifications\/(\d+)\/read$/.exec(url.pathname);
|
||||
if (nr) { reads.push("n" + nr[1]); return failNotiRead ? json(500, { detail: "db" }) : json(200, { ok: true }); }
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } }); // 작업 창이 왼쪽 목록을 가리지 않는 보통 PC 화면
|
||||
const dialogs = [];
|
||||
let dialogAnswer = false;
|
||||
page.on("dialog", async d => { dialogs.push(d.type() + ":" + d.message().slice(0, 20)); if (dialogAnswer) await d.accept(); else await d.dismiss(); });
|
||||
const pass = [];
|
||||
const ok = (name, cond, extra) => { assert.ok(cond, name + (extra === undefined ? "" : " → " + JSON.stringify(extra))); pass.push(name); console.log("PASS " + name); };
|
||||
try {
|
||||
await page.goto(base + "/project/inbox");
|
||||
const frameOf = () => page.frames().find(f => f !== page.mainFrame());
|
||||
const frameUrl = () => (frameOf() ? frameOf().url() : "");
|
||||
const waitModal = async () => {
|
||||
await page.waitForFunction(() => { const f = document.querySelector(".pj-inbox-panel iframe"); const d = f && f.contentDocument;
|
||||
const m = d && d.getElementById("pj-modal-task"); return !!(m && !m.hidden && d.getElementById("pj-t-id").value); });
|
||||
};
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
await waitModal();
|
||||
ok("공유 링크 리다이렉트 뒤에도 embed 화면(작업 창만)", /\/project\/p\/1\?/.test(frameUrl()) && /embed=1/.test(frameUrl()) &&
|
||||
await frameOf().evaluate(() => document.documentElement.classList.contains("pj-embed")), frameUrl());
|
||||
ok("같은 작업의 태그·알림을 함께 확인", reads.includes("m101") && reads.includes("n901"), reads);
|
||||
|
||||
// ① 저장 실패 → 다른 줄 → 묻기 → 계속 편집: 창·입력 그대로
|
||||
putStatus = 500;
|
||||
const fr = frameOf();
|
||||
await fr.fill("#pj-t-title", "작업 101 고침");
|
||||
await fr.evaluate(() => document.getElementById("pj-t-title").blur());
|
||||
await page.waitForTimeout(150);
|
||||
dialogAnswer = false;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await page.waitForTimeout(400);
|
||||
ok("저장 실패면 바꾸기 전에 묻고(작업 창과 같은 확인), 계속 편집이면 그대로", dialogs.length === 1 && /\?task=|\/p\/1/.test(frameUrl()) &&
|
||||
await fr.evaluate(() => document.getElementById("pj-t-title").value) === "작업 101 고침" &&
|
||||
!reads.includes("m102"), { dialogs, url: frameUrl(), reads });
|
||||
|
||||
// ② 저장 대기 중 A→B→A — 확인 뒤 A 그대로, 새 줄 안 열림
|
||||
putStatus = 200; holdPut = true;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await page.waitForTimeout(150);
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
await page.waitForTimeout(100);
|
||||
ok("저장이 끝나기 전엔 창을 바꾸지 않는다", frameOf() === fr && releasePut !== null);
|
||||
holdPut = false; releasePut(); releasePut = null;
|
||||
await page.waitForTimeout(500);
|
||||
ok("A→B→A 빨리 — 저장 성공 뒤 A 작업 창 그대로(다시 읽지 않음)", frameOf() === fr &&
|
||||
await fr.evaluate(() => document.getElementById("pj-t-id").value) === "101" && puts[puts.length - 1].body.title === "작업 101 고침" &&
|
||||
!reads.includes("m102"), { puts: puts.length, reads });
|
||||
|
||||
// ③ 저장 성공 상태에서 B → 바로 바뀌고 이탈 경고 없음
|
||||
const before = dialogs.length;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await waitModal();
|
||||
await page.waitForFunction(() => document.querySelector(".pj-inbox-panel iframe").contentDocument.getElementById("pj-t-id").value === "102");
|
||||
ok("저장된 상태면 묻지 않고 B 로(beforeunload 경고도 없음)", dialogs.length === before && reads.includes("m102"), dialogs);
|
||||
|
||||
// ④ iframe 안 포커스에서 Esc — 작업 창이 닫히며 패널도 닫힘, 확인한 줄은 목록에서 빠짐
|
||||
const fr2 = frameOf();
|
||||
await fr2.focus("#pj-t-title");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForFunction(() => !document.querySelector(".pj-inbox-panel").classList.contains("is-open"));
|
||||
await page.waitForTimeout(400);
|
||||
ok("iframe 안에서 Esc → 패널 닫힘, 확인한 태그 줄은 빠짐", await page.evaluate(() =>
|
||||
!document.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]')));
|
||||
|
||||
// ⑤ 읽음 실패한 알림 줄은 남는다
|
||||
failNotiRead = true;
|
||||
await page.click('#pj-inbox .pj-inbox-item[data-id="903"]', { button: "right" });
|
||||
await page.click(".pj-ctxmenu button, .pj-ctxmenu [role=menuitem], .pj-ctxmenu li");
|
||||
await page.waitForTimeout(400);
|
||||
ok("읽음 처리 실패 — 줄이 남고 굵게(읽지 않음)", await page.evaluate(() => {
|
||||
const li = document.querySelector('#pj-inbox .pj-inbox-item[data-id="903"]'); return !!li && li.classList.contains("is-unread"); }));
|
||||
console.log("\nALL PASS (" + pass.length + ")");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -16,6 +16,7 @@ const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
|
||||
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
|
||||
const fails = [];
|
||||
@@ -779,6 +780,124 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
const shown = Array.from(d.querySelectorAll(".pj-tmember")).map(function (n) { return n.dataset.email; });
|
||||
check("[멤버 배정·제외] 머리 멤버 아이콘 갱신", shown.indexOf("bob@test.local") < 0 && shown.indexOf("carol@test.local") >= 0, shown);
|
||||
}
|
||||
// ── [검토 A] 전체 보기 — 원 소속을 볼 수 없는 연결된 작업(301, 읽기 전용)도 한 번 나온다 ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-side-allview").click(); await settle();
|
||||
const cards = function (id) { return d.querySelectorAll('.pj-card[data-task-id="' + id + '"]').length; };
|
||||
check("[전체 보기] 연결된 작업(원 소속 못 봄)도 한 장, 원 소속 작업은 그대로 한 장", cards(301) === 1 && cards(101) === 1 && cards(103) === 1,
|
||||
[cards(301), cards(101), cards(103)]);
|
||||
}
|
||||
// ── [검토 7] 수신함 iframe 안쪽 — __pjEmbedSettle 이 작업 창 닫기와 같은 저장 절차를 탄다 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.d.documentElement.classList.add("pj-embed");
|
||||
let putStatus = 500; const puts = [];
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) {
|
||||
puts.push(b);
|
||||
return putStatus >= 400 ? { status: putStatus, body: { detail: "서버 오류" } } : { body: { task: Object.assign(detail(101, "작업 A"), b) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const ta = d.getElementById("pj-t-title");
|
||||
ta.value = "작업 A3"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
env.setConfirm(false); // 계속 편집
|
||||
const ok1 = await env.w.__pjEmbedSettle(); await settle();
|
||||
check("[수신함 iframe] 저장 실패 → 다시 시도 후 묻고, 계속 편집이면 false·입력 유지",
|
||||
ok1 === false && !modal.hidden && titleVal(d) === "작업 A3" && env.confirms === 1 && puts.length >= 2, [ok1, env.confirms, puts.length]);
|
||||
putStatus = 200;
|
||||
const ok2 = await env.w.__pjEmbedSettle(); await settle();
|
||||
check("[수신함 iframe] 다시 — 재시도 성공이면 true(묻지 않음)", ok2 === true && env.confirms === 1 && puts[puts.length - 1].title === "작업 A3",
|
||||
[ok2, env.confirms]);
|
||||
}
|
||||
// ── [검토 7] 수신함 작업 창 — 바꾸기·닫기 전 저장 대기, 계속 편집이면 그대로, A→B→A, 저장 중 Esc, 읽음 실패 ──
|
||||
{
|
||||
const env = makeEnv(inboxHtml); baseRoutes(env);
|
||||
const reads = [];
|
||||
env.route("POST", /\/project\/api\/mentions\/read$/, function (u, b) { reads.push("m" + (b && b.task_id)); return { body: { ok: true, marked: 1 } }; });
|
||||
let failNoti = true;
|
||||
env.route("POST", /\/project\/api\/notifications\/\d+\/read$/, function (u) {
|
||||
reads.push("n" + u.split("/")[4]);
|
||||
return failNoti ? { status: 500, body: { detail: "db" } } : { body: { ok: true } };
|
||||
});
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
const A = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
const B = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
const N901 = d.querySelector('#pj-inbox .pj-inbox-item[data-id="901"]');
|
||||
const frame = function () { const p = d.body.querySelector(".pj-inbox-panel"); return p && p.querySelector("iframe"); };
|
||||
const src = function () { return frame() ? frame().getAttribute("src") : ""; };
|
||||
A.click(); await settle();
|
||||
check("[수신함] 줄 → 오른쪽 작업 창 = 공유 링크 + embed", src() === "/project/t/101?embed=1", src());
|
||||
check("[수신함] 같은 작업의 태그·알림을 함께 확인", reads.indexOf("m101") >= 0 && reads.indexOf("n901") >= 0, reads);
|
||||
await settle();
|
||||
check("[수신함] 알림 읽음 실패 — 굵게(읽지 않음) 그대로", N901.classList.contains("is-unread"));
|
||||
let gate = deferred(), settles = 0;
|
||||
frame().contentWindow.__pjEmbedSettle = function () { settles++; return gate.promise; };
|
||||
B.click(); await settle();
|
||||
check("[수신함] 작업 창 저장 확인 중엔 바꾸지 않음", src() === "/project/t/101?embed=1" && settles === 1, [src(), settles]);
|
||||
A.click(); await settle(); // A→B→A 빨리
|
||||
gate.resolve(true); await settle();
|
||||
check("[수신함] A→B→A — 확인 뒤 A 그대로, B 는 열거나 확인하지 않음",
|
||||
src() === "/project/t/101?embed=1" && reads.indexOf("m102") < 0 && B.classList.contains("is-unread") && settles === 1, [src(), reads, settles]);
|
||||
gate = deferred();
|
||||
B.click(); await settle(); gate.resolve(false); await settle();
|
||||
check("[수신함] 계속 편집 — 창·선택 그대로, 새 줄 확인 안 함",
|
||||
src() === "/project/t/101?embed=1" && A.classList.contains("is-selected") && !B.classList.contains("is-selected") && reads.indexOf("m102") < 0);
|
||||
gate = deferred(); settles = 0;
|
||||
const esc = function () { d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); };
|
||||
esc(); await settle(); esc(); await settle();
|
||||
const panelEl = d.body.querySelector(".pj-inbox-panel");
|
||||
check("[수신함] 저장 중 Esc(두 번) — 확인 하나만, 끝나기 전엔 열린 채", panelEl.classList.contains("is-open") && settles === 1, settles);
|
||||
gate.resolve(true); await settle();
|
||||
check("[수신함] 저장이 끝나면 닫힘", !panelEl.classList.contains("is-open"));
|
||||
await wait(260); await settle();
|
||||
check("[수신함] 확인된 태그 줄은 빠지고, 읽음 실패한 알림 줄은 남는다", !A.isConnected && N901.isConnected, [A.isConnected, N901.isConnected]);
|
||||
failNoti = false;
|
||||
B.click(); await settle(); await settle();
|
||||
check("[수신함] 닫힌 뒤 다른 줄 — 바로 열림", src() === "/project/t/102?embed=1", src());
|
||||
}
|
||||
// ── [검토 9] 새 프로젝트 — 생성과 멤버 배정 결과를 따로, 실패한 멤버만 다시, 연타해도 한 번 생성 ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/assignable-users$/, function () { return { body: { users: [
|
||||
{ email: "bob@test.local", id: "bob", name: "Bob", avatar: "" },
|
||||
{ email: "carol@test.local", id: "carol", name: "Carol", avatar: "" }] } }; });
|
||||
let creates = 0, failCarol = true;
|
||||
const memberCalls = [];
|
||||
const createGate = deferred();
|
||||
env.route("POST", /\/project\/api\/projects$/, async function () {
|
||||
creates++;
|
||||
await createGate.promise;
|
||||
return { status: 201, body: { project: { id: 9, name: "새 프로젝트" } } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/projects\/9\/members$/, function (u, b) {
|
||||
memberCalls.push(b.user_email);
|
||||
return failCarol && b.user_email === "carol@test.local" ? { status: 400, body: { detail: "배정 불가" } } : { status: 201, body: { member: {} } };
|
||||
});
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-new-project-side").click(); await settle();
|
||||
d.getElementById("pj-f-name").value = "새 프로젝트";
|
||||
d.querySelectorAll("#pj-f-members input[type=checkbox]").forEach(function (c) { c.checked = true; });
|
||||
const save = d.getElementById("pj-save-project");
|
||||
save.click(); save.click(); await settle(); // 연타
|
||||
createGate.resolve(); await settle(); await settle();
|
||||
const modal = d.getElementById("pj-modal-project");
|
||||
const msg = d.getElementById("pj-f-project-msg");
|
||||
const carol = d.querySelector('#pj-f-members input[value="carol@test.local"]').closest(".pj-member-pick");
|
||||
check("[새 프로젝트] 연타해도 한 번만 생성", creates === 1, creates);
|
||||
check("[새 프로젝트] 배정 실패 — 창 유지, 생성됨·실패 멤버 안내, 실패 표시",
|
||||
!modal.hidden && !msg.hidden && /만들어졌습니다/.test(msg.textContent) && /배정 불가/.test(msg.textContent) &&
|
||||
carol.classList.contains("is-failed") && /다시 배정/.test(save.textContent), [modal.hidden, msg.textContent, save.textContent]);
|
||||
failCarol = false;
|
||||
save.click(); await settle(); await settle();
|
||||
check("[새 프로젝트] 다시 배정 — 실패한 멤버만, 프로젝트는 다시 만들지 않음, 끝나면 닫힘",
|
||||
creates === 1 && JSON.stringify(memberCalls) === JSON.stringify(["bob@test.local", "carol@test.local", "carol@test.local"]) && modal.hidden,
|
||||
[creates, memberCalls, modal.hidden]);
|
||||
}
|
||||
clearTimeout(WATCHDOG);
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
|
||||
@@ -52,6 +52,31 @@ def main() -> None:
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)):
|
||||
render_one(env, name, admin)
|
||||
render_inbox(env)
|
||||
|
||||
|
||||
def render_inbox(env) -> None:
|
||||
"""수신함(project/inbox.html) — 태그한 작업 101·102, 알림(작업 101·102·프로젝트만)."""
|
||||
def mt(tid: int, title: str) -> dict:
|
||||
return {"id": tid, "title": title, "project_id": 1, "project_name": "P1", "project_color": "#4573d2",
|
||||
"unread_mentions": 1, "stage_name": "할 일", "due_label": "", "mention_actor": "bob@test.local",
|
||||
"completed_at": None}
|
||||
|
||||
def nt(nid: int, ntype: str, title: str, task_id: int | None) -> dict:
|
||||
return {"id": nid, "type": ntype, "title": title, "body": "P1", "task_id": task_id, "project_id": 1,
|
||||
"is_read": False, "actor_email": "bob@test.local", "created_at": "2026-10-12T09:00:00+09:00"}
|
||||
|
||||
html = env.get_template("project/inbox.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, pj_pro=False, pj_admin=False,
|
||||
nav_projects=PROJECTS, goal_years=[2026], my_open_total=0, mention_unread=2,
|
||||
color_palette=["#4573d2"], project_icons=["folder"], project_asana_icons=[],
|
||||
mentioned_tasks=[mt(101, "작업 A"), mt(102, "작업 B")],
|
||||
notifications=[nt(901, "assigned", "작업 배정: 작업 A", 101), nt(902, "comment", "새 댓글: 작업 B", 102),
|
||||
nt(903, "completed", "프로젝트 알림", None)],
|
||||
)
|
||||
path = os.path.join(OUT_DIR, "inbox_render.html")
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
def render_one(env, name: str, admin: bool) -> None:
|
||||
|
||||
@@ -18,13 +18,24 @@ ROWS = [ # 최신순(list_notifications 와 같게)
|
||||
|
||||
|
||||
class FakeStore:
|
||||
"""list_notifications(최신순) + list_unread_after(DB 쪽 조건·오래된 것부터) — db.py 와 같은 의미."""
|
||||
desktop = False
|
||||
|
||||
def __init__(self, rows=None):
|
||||
self.rows = list(ROWS if rows is None else rows)
|
||||
self.pages = 0
|
||||
|
||||
def notifier_active(self, email):
|
||||
return self.desktop
|
||||
|
||||
def list_notifications(self, recipient_email, unread_only=False, limit=100):
|
||||
rows = [r for r in ROWS if not unread_only or not r["is_read"]]
|
||||
rows = sorted((r for r in self.rows if not unread_only or not r["is_read"]), key=lambda r: -r["id"])
|
||||
return rows[:limit]
|
||||
|
||||
def list_unread_after(self, recipient_email, after_id, types, limit=200):
|
||||
self.pages += 1
|
||||
rows = sorted((r for r in self.rows if not r["is_read"] and r["id"] > after_id and r["type"] in types),
|
||||
key=lambda r: r["id"])
|
||||
return rows[:limit]
|
||||
|
||||
|
||||
@@ -34,12 +45,13 @@ class AlertsApiTests(unittest.TestCase):
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
|
||||
def get(self, qs="", desktop=False):
|
||||
st = FakeStore()
|
||||
def get(self, qs="", desktop=False, st=None, visible=None):
|
||||
st = st or FakeStore()
|
||||
st.desktop = desktop
|
||||
vis = visible or (lambda st, user, items: items)
|
||||
with patch.object(api, "_require_user", return_value={"email": "Me@Test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=st), \
|
||||
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
|
||||
patch.object(api, "_visible_notifications", side_effect=vis):
|
||||
return self.client.get("/project/api/notifications/alerts" + qs).json()
|
||||
|
||||
def test_without_after_returns_only_baseline(self):
|
||||
@@ -52,6 +64,13 @@ class AlertsApiTests(unittest.TestCase):
|
||||
self.assertEqual(out["alerts"][1]["type"], "mention")
|
||||
self.assertNotIn("desktop", out)
|
||||
|
||||
def test_alert_links_use_task_permalink(self):
|
||||
# 작업 알림은 /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 사람도 403 없이 열린다
|
||||
out = self.get("?after=5")
|
||||
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
|
||||
st = FakeStore([{"id": 3, "type": "mention", "is_read": False, "task_id": None, "project_id": 4}])
|
||||
self.assertEqual(self.get("?after=0", st=st)["alerts"][0]["href"], "/project/p/4")
|
||||
|
||||
def test_pc_notifier_running_silences_web_popup(self):
|
||||
out = self.get("?after=5", desktop=True)
|
||||
self.assertEqual((out["alerts"], out["latest_id"], out["desktop"]), ([], 9, True))
|
||||
@@ -60,12 +79,39 @@ class AlertsApiTests(unittest.TestCase):
|
||||
class Broken(FakeStore):
|
||||
def notifier_active(self, email):
|
||||
raise RuntimeError("db down")
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=Broken()), \
|
||||
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
|
||||
out = self.client.get("/project/api/notifications/alerts?after=5").json()
|
||||
out = self.get("?after=5", st=Broken())
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
|
||||
|
||||
# ── 예전엔 최신 50건을 자른 뒤 걸러서 빠지던 경우들 ──
|
||||
def test_assignment_behind_fifty_comment_alerts_is_not_lost(self):
|
||||
rows = [{"id": 1, "type": "assigned", "title": "배정", "is_read": False, "task_id": 1, "project_id": 1}]
|
||||
rows += [{"id": 100 + i, "type": "comment", "title": "댓글", "is_read": False, "task_id": 1, "project_id": 1}
|
||||
for i in range(50)]
|
||||
out = self.get("?after=0", st=FakeStore(rows))
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [1])
|
||||
|
||||
def test_more_than_sixty_assignments_page_oldest_first(self):
|
||||
rows = [{"id": i, "type": "assigned", "title": f"배정{i}", "is_read": False, "task_id": i, "project_id": 1}
|
||||
for i in range(1, 66)]
|
||||
st = FakeStore(rows)
|
||||
out = self.get("?after=0", st=st)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], list(range(1, 11))) # 오래된 것부터 10건
|
||||
out = self.get("?after=10", st=st) # 닫으면 그 뒤 것(화면이 본 것=10 으로 다시 묻는다)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], list(range(11, 21)))
|
||||
out = self.get("?after=60", st=st)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [61, 62, 63, 64, 65])
|
||||
|
||||
def test_invisible_alerts_ahead_do_not_hide_visible_ones(self):
|
||||
# 앞쪽 450건은 지금 볼 수 없는 작업(권한 회수) — 페이지를 넘겨 그 뒤의 볼 수 있는 알림을 찾는다
|
||||
rows = [{"id": i, "type": "mention", "title": "x", "is_read": False, "task_id": 9, "project_id": 9}
|
||||
for i in range(1, 451)]
|
||||
rows.append({"id": 500, "type": "mention", "title": "보임", "is_read": False, "task_id": 1, "project_id": 1})
|
||||
st = FakeStore(rows)
|
||||
out = self.get("?after=0", st=st,
|
||||
visible=lambda st, user, items: [n for n in items if n["project_id"] == 1])
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [500])
|
||||
self.assertEqual(st.pages, 3) # 200·200·51 — 끝까지 읽고 멈춘다
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -17,6 +17,11 @@ class FakeStore:
|
||||
def list_projects(self, include_archived, member_email):
|
||||
return [{"id": 1, "parent_id": None}, {"id": 2, "parent_id": None}, {"id": 5, "parent_id": 1}]
|
||||
|
||||
def get_project(self, project_id):
|
||||
# 7 = 보관된 프로젝트(활성 목록에 없음), 5 = 서브프로젝트
|
||||
return {"id": project_id, "parent_id": 1 if project_id == 5 else None,
|
||||
"status": "archived" if project_id == 7 else "active"}
|
||||
|
||||
def list_tasks_for_projects(self, project_ids):
|
||||
self.asked_projects = project_ids
|
||||
return [{"id": 10 * pid} for pid in project_ids]
|
||||
@@ -33,12 +38,12 @@ class SubtaskSummaryTests(unittest.TestCase):
|
||||
self.client = TestClient(app)
|
||||
self.st = FakeStore()
|
||||
|
||||
def call(self, scope):
|
||||
def call(self, scope, pid=1):
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
|
||||
patch.object(api, "_db_or_503", return_value=self.st), \
|
||||
patch.object(api, "_require_manage", return_value=None), \
|
||||
patch.object(api, "_accessible_project_ids", return_value=None):
|
||||
return self.client.get(f"/project/api/projects/1/subtasks-summary?scope={scope}")
|
||||
return self.client.get(f"/project/api/projects/{pid}/subtasks-summary?scope={scope}")
|
||||
|
||||
def test_project_scope_uses_only_this_project(self):
|
||||
r = self.call("project")
|
||||
@@ -51,6 +56,13 @@ class SubtaskSummaryTests(unittest.TestCase):
|
||||
self.call("all")
|
||||
self.assertEqual(self.st.asked_projects, [1, 2]) # 서브프로젝트(5) 제외 — 스냅샷과 같은 범위
|
||||
|
||||
def test_all_scope_adds_open_archived_or_subproject_only(self):
|
||||
# 지금 연 프로젝트가 보관(7)·서브프로젝트(5)면 그 하나만 더한다(다른 보관 프로젝트는 읽지 않는다)
|
||||
self.call("all", pid=7)
|
||||
self.assertEqual(self.st.asked_projects, [1, 2, 7])
|
||||
self.call("all", pid=5)
|
||||
self.assertEqual(self.st.asked_projects, [1, 2, 5])
|
||||
|
||||
def test_no_access_is_rejected(self):
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
|
||||
patch.object(api, "_db_or_503", return_value=self.st), \
|
||||
|
||||
@@ -11,7 +11,7 @@ from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import store
|
||||
from app.modules.project.db import ProjectStore
|
||||
from tests.test_project_meeting_cells import Connection
|
||||
from tests.test_project_meeting_cells import Connection, Result
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
@@ -20,11 +20,22 @@ class LockConnection(Connection):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.completed = set() # 완료된 주차 시작일
|
||||
# 있는 회의록 — 9/28 주차(9/28~9/30)와 바로 다음 주차(10/1, 목요일 시작 — 달이 바뀐다)
|
||||
self.meetings = {date(2026, 9, 28), date(2026, 10, 1)}
|
||||
self.shared = [] # FOR SHARE 로 잠근 주차(다음 회의록)
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
if sql.startswith("SELECT completed_at FROM goal_meetings WHERE week_start = %s"):
|
||||
from tests.test_project_meeting_cells import Result
|
||||
if sql.endswith("FOR SHARE"):
|
||||
assert self.depth > 0, "다음 회의록 잠금은 트랜잭션 안에서"
|
||||
self.shared.append(params[0])
|
||||
if params[0] not in self.meetings:
|
||||
return Result([])
|
||||
return Result([{"completed_at": "done" if params[0] in self.completed else None}])
|
||||
if sql.startswith("UPDATE goal_meetings SET"):
|
||||
assert self.locked and self.depth > 0, "머리 변경은 회의록 행을 잠근 트랜잭션 안에서"
|
||||
self.calls.append((sql, params))
|
||||
return Result([{"week_start": params[-1]}])
|
||||
return super().execute(sql, params)
|
||||
|
||||
|
||||
@@ -55,10 +66,35 @@ class MeetingLockTests(unittest.TestCase):
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "잘 됨", "result_amount": "100"})
|
||||
self.assertEqual((out["result_note"], out["result_amount"]), ("잘 됨", 100))
|
||||
self.assertEqual(self.conn.shared, [date(2026, 10, 1)]) # 달이 바뀐 다음 주차(목요일 시작)를 잠그고 확인
|
||||
self.conn.completed.add(date(2026, 10, 1))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"result_note": "늦게"})
|
||||
|
||||
def test_completed_week_without_next_meeting_is_locked(self):
|
||||
# 예전엔 다음 주차 회의록이 없으면 완료된 회의록의 결과도 고칠 수 있었다
|
||||
self.conn.meetings.discard(date(2026, 10, 1))
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"result_note": "다음 회의 전"})
|
||||
self.assertEqual(self.conn.rows[1]["result_note"], "")
|
||||
|
||||
def test_open_week_without_next_meeting_accepts_result(self):
|
||||
self.conn.meetings.discard(date(2026, 10, 1))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "이번 주 결과"})
|
||||
self.assertEqual(out["result_note"], "이번 주 결과")
|
||||
|
||||
def test_header_update_checks_lock_inside_row_lock(self):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "메모"})
|
||||
sqls = [s for s, _ in self.conn.calls]
|
||||
lock = next(i for i, s in enumerate(sqls) if s.startswith("SELECT week_start FROM goal_meetings") and "FOR UPDATE" in s)
|
||||
upd = next(i for i, s in enumerate(sqls) if s.startswith("UPDATE goal_meetings SET"))
|
||||
self.assertLess(lock, upd)
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "잠김"})
|
||||
self.assertEqual(sum(1 for s, _ in self.conn.calls if s.startswith("UPDATE goal_meetings SET")), 1)
|
||||
|
||||
def test_anyone_edits_but_only_admin_completes(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
|
||||
@@ -346,7 +346,7 @@ def test_file_comment_atomic_and_idempotent():
|
||||
# [04] 날짜 범위
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_date_range_validation():
|
||||
p = _project("P-date", ADMIN, (BOB,))
|
||||
p = _project("P-date", ADMIN, (BOB, PRO))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
base = f"/project/api/projects/{p['id']}/tasks"
|
||||
assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400
|
||||
@@ -359,11 +359,11 @@ def test_date_range_validation():
|
||||
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400
|
||||
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200
|
||||
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200
|
||||
# 프로젝트도 같은 규칙(부분 수정 포함)
|
||||
# 프로젝트도 같은 규칙(부분 수정 포함) — 프로젝트 수정은 Pro user 이상 멤버(2026-10-12)
|
||||
pu = f"/project/api/projects/{p['id']}"
|
||||
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
|
||||
assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200
|
||||
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400
|
||||
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
|
||||
assert req("PUT", pu, PRO, json={"due_date": "2026-10-01"}).status_code == 200
|
||||
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01"}).status_code == 400
|
||||
assert req("POST", "/project/api/projects", PRO, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
|
||||
|
||||
|
||||
@@ -1031,6 +1031,141 @@ def test_meeting_perf_unknown_vs_zero():
|
||||
_drop_meetings([w, w - timedelta(days=7)])
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [검토 2026-10-12] 실제 DB — 동시성·조회 범위·알림 페이지·배지·회의록 결과 잠금
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _race(fns):
|
||||
"""함수들을 최대한 같은 순간에 돌리고 (결과 또는 예외) 목록."""
|
||||
gate = threading.Barrier(len(fns))
|
||||
out: list = [None] * len(fns)
|
||||
|
||||
def run(i, fn):
|
||||
gate.wait()
|
||||
try:
|
||||
out[i] = fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
out[i] = exc
|
||||
ths = [threading.Thread(target=run, args=(i, f)) for i, f in enumerate(fns)]
|
||||
[t.start() for t in ths]
|
||||
[t.join() for t in ths]
|
||||
return out
|
||||
|
||||
|
||||
def test_review_task_dates_never_invert_under_race():
|
||||
p = _project("P-race", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
for _ in range(10):
|
||||
t = ST.create_task(project_id=p["id"], title="race", stage_id=s["id"],
|
||||
start_date="2026-10-10", due_date="2026-10-20", created_by=BOB)
|
||||
_race([lambda: ST.update_task(task_id=t["id"], fields={"start_date": "2026-10-18"}),
|
||||
lambda: ST.update_task(task_id=t["id"], fields={"due_date": "2026-10-12"})])
|
||||
got = ST.get_task(task_id=t["id"])
|
||||
assert got["start_date"] <= got["due_date"], got # 한쪽은 지금 값으로 검사돼 거절된다
|
||||
# 프로젝트도 같은 규칙
|
||||
for _ in range(5):
|
||||
q = ST.create_project(name=f"race-{uuid.uuid4().hex[:4]}", owner_email=ADMIN, created_by=ADMIN,
|
||||
start_date="2026-10-10", due_date="2026-10-20")
|
||||
_race([lambda: ST.update_project(project_id=q["id"], fields={"start_date": "2026-10-18"}),
|
||||
lambda: ST.update_project(project_id=q["id"], fields={"due_date": "2026-10-12"})])
|
||||
got = ST.get_project(project_id=q["id"])
|
||||
assert got["start_date"] <= got["due_date"], got
|
||||
|
||||
|
||||
def test_review_concurrent_completion_logs_once():
|
||||
p = _project("P-done-race", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
t = ST.create_task(project_id=p["id"], title="once", stage_id=s["id"], created_by=BOB)
|
||||
outs = _race([lambda: ST.update_task(task_id=t["id"], fields={"completed": True}, actor=BOB) for _ in range(4)])
|
||||
assert sum(1 for o in outs if isinstance(o, dict) and o["_newly_completed"]) == 1, outs
|
||||
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id = %s AND action = 'completed'", t["id"]) == 1
|
||||
|
||||
|
||||
def test_review_subproject_tasks_and_archived_scope():
|
||||
parent = _project("P-parent", ADMIN, (BOB, CAROL))
|
||||
child = ST.create_project(name=f"child-{uuid.uuid4().hex[:4]}", parent_id=parent["id"], owner_email=ADMIN, created_by=ADMIN)
|
||||
ST.add_member(project_id=child["id"], user_email=CAROL)
|
||||
tp = ST.create_task(project_id=parent["id"], title="부모", created_by=ADMIN)
|
||||
tc = ST.create_task(project_id=child["id"], title="자식", created_by=ADMIN)
|
||||
ids = lambda who: sorted(t["id"] for t in req("GET", f"/project/api/projects/{parent['id']}/tasks", who).json()["tasks"])
|
||||
assert ids(BOB) == [tp["id"]] # 부모 멤버·자식 비멤버 — 자식 작업 안 보임
|
||||
assert ids(CAROL) == sorted([tp["id"], tc["id"]])
|
||||
assert req("GET", f"/project/api/projects/{parent['id']}/tasks", ADMIN).status_code == 200 # ADMIN = owner
|
||||
# 보관된 프로젝트를 열어도 자기 작업은 받는다(스냅샷)
|
||||
arch = _project("P-arch", BOB)
|
||||
ta = ST.create_task(project_id=arch["id"], title="보관 작업", created_by=BOB)
|
||||
ST.update_project(project_id=arch["id"], fields={"status": "archived"})
|
||||
snap = req("GET", f"/project/api/projects/{arch['id']}/snapshot?scope=all", BOB).json()
|
||||
assert ta["id"] in [t["id"] for t in snap["tasks"]]
|
||||
assert [x["id"] for x in snap["projects"] if x.get("view_only")] == [arch["id"]]
|
||||
|
||||
|
||||
def test_review_alert_paging_and_badges():
|
||||
me = USERS.add(f"alert-{uuid.uuid4().hex[:6]}@test.local")
|
||||
p = _project("P-alert", ADMIN, (me,))
|
||||
t = ST.create_task(project_id=p["id"], title="x", created_by=ADMIN)
|
||||
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="assigned", title="배정")
|
||||
for _ in range(55):
|
||||
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="comment", title="댓글")
|
||||
out = req("GET", "/project/api/notifications/alerts?after=0", me).json()
|
||||
assert [a["type"] for a in out["alerts"]] == ["assigned"] and out["alerts"][0]["href"] == f"/project/t/{t['id']}"
|
||||
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 56
|
||||
# 권한을 잃은 프로젝트의 알림은 배지에서 빠진다(기록은 그대로)
|
||||
ST.remove_member(project_id=p["id"], user_email=me)
|
||||
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 0
|
||||
# 내 작업 배지·목록 — 미완료는 전부, 완료는 최근 것만
|
||||
q = _project("P-my", ADMIN, (me,))
|
||||
open_ids = [ST.create_task(project_id=q["id"], title=f"o{i}", assignee_email=me, created_by=ADMIN)["id"] for i in range(3)]
|
||||
done_ids = []
|
||||
for i in range(3):
|
||||
d = ST.create_task(project_id=q["id"], title=f"d{i}", assignee_email=me, created_by=ADMIN)
|
||||
ST.update_task(task_id=d["id"], fields={"completed": True})
|
||||
done_ids.append(d["id"])
|
||||
rows = ST.list_my_tasks(assignee_email=me, completed_limit=1)
|
||||
assert sorted(r["id"] for r in rows if not r["completed_at"]) == sorted(open_ids)
|
||||
assert [r["id"] for r in rows if r["completed_at"]] == [done_ids[-1]]
|
||||
assert req("GET", "/project/api/my-tasks/open-count", me).json()["open"] == 3
|
||||
ST.add_mentions(task_id=open_ids[0], emails=[me], actor_email=ADMIN)
|
||||
assert req("GET", "/project/api/mentions/unread-count", me).json()["unread"] == 1
|
||||
|
||||
|
||||
def test_review_reorder_and_creator_membership():
|
||||
mine = _project("P-ord", PRO)
|
||||
other = _project("P-ord-other", ADMIN)
|
||||
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], other["id"]]}).status_code == 403
|
||||
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], mine["id"]]}).status_code == 400
|
||||
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"]]}).status_code == 200
|
||||
r = req("POST", "/project/api/projects", PRO, json={"name": f"own-{RUN}", "owner_email": ALICE})
|
||||
assert r.status_code == 201, r.text
|
||||
pid = r.json()["project"]["id"]
|
||||
assert ST.get_project(project_id=pid)["owner_email"] == ALICE
|
||||
assert req("GET", f"/project/p/{pid}", PRO).status_code == 200 # 만든 직후 자기 프로젝트를 연다(멤버 행)
|
||||
ST.remove_member(project_id=pid, user_email=PRO)
|
||||
assert req("GET", f"/project/p/{pid}", PRO).status_code == 403 # created_by 로는 권한이 남지 않는다
|
||||
|
||||
|
||||
def test_review_meeting_result_lock_rules():
|
||||
from app.modules.project import store
|
||||
|
||||
w2 = date(2031, 10, 1) # 수요일 시작 1주차(달 경계)
|
||||
w1 = store.prev_week_period(w2)[0] # 9월 마지막 주차
|
||||
_drop_meetings([w1, w2])
|
||||
try:
|
||||
_create_meeting(w1)
|
||||
item = ST.get_meeting(week_start=w1)["items"][0]["id"]
|
||||
put = lambda body: req("PUT", f"/project/api/goals/meeting-items/{item}", BOB, json=body).status_code
|
||||
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
|
||||
assert put({"result_note": "다음 회의 전"}) == 409 # 다음 주차 회의록이 없으면 그 주가 완료되면 잠김
|
||||
_create_meeting(w2)
|
||||
assert put({"result_note": "다음 회의에서"}) == 200 # 다음 주차 회의록이 열려 있으면 결과는 적을 수 있다
|
||||
assert put({"content": "내용"}) == 409 # 주요 업무는 그 주 완료로 잠김(잠금 차이 보존)
|
||||
ST.set_meeting_completed(week_start=w2, done=True, by=ADMIN)
|
||||
assert put({"result_note": "늦게"}) == 409
|
||||
r = req("PUT", f"/project/api/goals/meetings/{w2}", BOB, json={"notes": "잠김"})
|
||||
assert r.status_code == 409, r.text # 완료된 회의록 머리도
|
||||
finally:
|
||||
_drop_meetings([w1, w2])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
|
||||
@@ -24,6 +24,10 @@ class FakeStore:
|
||||
def list_notifications(self, recipient_email, unread_only=False, limit=100):
|
||||
return ROWS[:limit]
|
||||
|
||||
def list_unread_after(self, recipient_email, after_id, types, limit=200):
|
||||
return sorted((r for r in ROWS if not r["is_read"] and r["id"] > after_id and r["type"] in types),
|
||||
key=lambda r: r["id"])[:limit]
|
||||
|
||||
def mark_read(self, notification_id, recipient_email):
|
||||
self.read.append((notification_id, recipient_email))
|
||||
|
||||
@@ -86,6 +90,8 @@ class NotifierApiTests(unittest.TestCase):
|
||||
out = res.json()
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
|
||||
self.assertEqual((out["me"], out["latest_id"], out["name"]), ("me@test.local", 8, "나"))
|
||||
# PC 알림 [열기] 도 웹과 같은 주소(작업 공유 링크) — 서버가 지금 권한으로 열 프로젝트를 고른다
|
||||
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
|
||||
|
||||
def test_alerts_rejects_missing_or_unknown_token(self):
|
||||
self.assertEqual(self.client.get("/project/api/notifier/alerts").status_code, 401)
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
"""2026-10-12 검토 반영 회귀 테스트 — 권한·링크·조회 범위·저장 실패·동시성·중복 방지. DB 없이 가짜 저장소로.
|
||||
|
||||
실제 PostgreSQL 이 있어야 확인되는 동시성(두 요청이 정말 동시에 행을 잠그는 경우)은
|
||||
tests/test_project_module.py 의 test_review_* 가 맡는다(로컬 테스트 DB 전용).
|
||||
"""
|
||||
import importlib
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import access, store
|
||||
from app.modules.project.db import ProjectStore
|
||||
from app.store import SUPER_ADMIN_EMAIL
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
PM = {"email": "pm@test.local", "role": "pro"} # 부모(1)·보관(4) 멤버, 자식(2) 비멤버
|
||||
BOTH = {"email": "both@test.local", "role": "user"} # 부모·자식 멤버
|
||||
CHILD = {"email": "child@test.local", "role": "user"} # 자식만
|
||||
ADMIN = {"email": "admin@test.local", "role": "admin"} # 어디에도 멤버 아님
|
||||
SUPER = {"email": SUPER_ADMIN_EMAIL, "role": "admin"}
|
||||
READER = {"email": "reader@test.local", "role": "pro"} # 부모(1)·연결 대상(3) 멤버 — 자식 작업 20 은 3 에 연결돼 READ
|
||||
|
||||
|
||||
class Store(MagicMock):
|
||||
"""프로젝트 1(부모) ─ 2(서브), 3(다른 프로젝트), 4(보관). 작업 10∈1, 20∈2(3 에 연결), 21∈2."""
|
||||
|
||||
PROJECTS = {
|
||||
1: {"id": 1, "parent_id": None, "name": "부모", "owner_email": "", "status": "active", "created_by": ""},
|
||||
2: {"id": 2, "parent_id": 1, "name": "자식", "owner_email": "", "status": "active", "created_by": ""},
|
||||
3: {"id": 3, "parent_id": None, "name": "연결", "owner_email": "", "status": "active", "created_by": ""},
|
||||
4: {"id": 4, "parent_id": None, "name": "보관", "owner_email": "", "status": "archived", "created_by": ""},
|
||||
}
|
||||
MEMBERS = {1: {"pm@test.local", "both@test.local", "reader@test.local"},
|
||||
2: {"both@test.local", "child@test.local"},
|
||||
3: {"reader@test.local"},
|
||||
4: {"pm@test.local"}}
|
||||
TASKS = {10: {"id": 10, "project_id": 1, "title": "부모 작업", "parent_task_id": None},
|
||||
20: {"id": 20, "project_id": 2, "title": "자식 작업(연결)", "parent_task_id": None},
|
||||
21: {"id": 21, "project_id": 2, "title": "자식 작업", "parent_task_id": None},
|
||||
40: {"id": 40, "project_id": 4, "title": "보관 작업", "parent_task_id": None}}
|
||||
LINKS = {20: {3}}
|
||||
|
||||
def is_member(self, project_id, user_email):
|
||||
return user_email in self.MEMBERS.get(int(project_id), set())
|
||||
|
||||
def list_projects(self, include_archived=False, member_email=None):
|
||||
return [dict(p) for pid, p in self.PROJECTS.items()
|
||||
if (include_archived or p["status"] != "archived")
|
||||
and (member_email is None or member_email in self.MEMBERS.get(pid, set()))]
|
||||
|
||||
def get_project(self, project_id):
|
||||
p = self.PROJECTS.get(int(project_id))
|
||||
return dict(p) if p else None
|
||||
|
||||
def get_task(self, task_id):
|
||||
t = self.TASKS.get(int(task_id))
|
||||
return dict(t) if t else None
|
||||
|
||||
def task_link_scope(self, task_ids):
|
||||
return {int(t): set(self.LINKS[int(t)]) for t in task_ids if int(t) in self.LINKS}
|
||||
|
||||
def list_tasks(self, project_id=None, include_subprojects=False, limit=1000, **kw):
|
||||
tree = {int(project_id)}
|
||||
if include_subprojects:
|
||||
tree |= {pid for pid, p in self.PROJECTS.items() if p["parent_id"] in tree}
|
||||
return [dict(t) for t in self.TASKS.values() if t["project_id"] in tree]
|
||||
|
||||
def list_tasks_for_projects(self, project_ids, **kw):
|
||||
self.asked_task_projects = list(project_ids)
|
||||
out = []
|
||||
for pid in project_ids:
|
||||
out += [{**t, "context_project_id": pid} for t in self.TASKS.values() if t["project_id"] == pid]
|
||||
out += [{**self.TASKS[tid], "context_project_id": pid} for tid, ps in self.LINKS.items() if pid in ps]
|
||||
return out
|
||||
|
||||
def list_stages_for_projects(self, project_ids):
|
||||
return {int(i): [] for i in project_ids}
|
||||
|
||||
def list_stages(self, project_id):
|
||||
return []
|
||||
|
||||
def list_members(self, project_id):
|
||||
return [{"user_email": e} for e in sorted(self.MEMBERS.get(int(project_id), set()))]
|
||||
|
||||
|
||||
def client_for(st, data_dir=None):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = st
|
||||
app.state.data_dir = data_dir or tempfile.mkdtemp(prefix="pj-review-")
|
||||
return TestClient(app, raise_server_exceptions=False)
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.st = Store()
|
||||
for p in (patch.object(access, "can_use_module", side_effect=lambda u: bool(u)),):
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
self.client = client_for(self.st)
|
||||
|
||||
def call(self, who, method, url, **kw):
|
||||
with patch.object(api, "_require_user", return_value=who), patch.object(api, "_db_or_503", return_value=self.st):
|
||||
return self.client.request(method, url, **kw)
|
||||
|
||||
|
||||
# ── [1] 부모 프로젝트 조회로 서브프로젝트 작업이 새지 않는다 ─────────────
|
||||
class SubprojectTasksTests(Base):
|
||||
def ids(self, who, pid=1):
|
||||
r = self.call(who, "GET", f"/project/api/projects/{pid}/tasks")
|
||||
return r.status_code, sorted(t["id"] for t in r.json().get("tasks", [])) if r.status_code == 200 else None
|
||||
|
||||
def test_parent_member_without_child_membership(self):
|
||||
self.assertEqual(self.ids(PM), (200, [10]))
|
||||
|
||||
def test_member_of_both_and_child_member(self):
|
||||
self.assertEqual(self.ids(BOTH), (200, [10, 20, 21]))
|
||||
self.assertEqual(self.ids(CHILD)[0], 403) # 부모 화면은 못 연다
|
||||
self.assertEqual(self.ids(CHILD, pid=2), (200, [20, 21]))
|
||||
|
||||
def test_non_member_admin_and_super(self):
|
||||
self.assertEqual(self.ids(ADMIN)[0], 403)
|
||||
self.assertEqual(self.ids(SUPER), (200, [10, 20, 21]))
|
||||
|
||||
def test_linked_read_task_stays_visible(self):
|
||||
# READER 는 자식(2) 멤버가 아니지만 작업 20 이 자기 프로젝트(3)에 연결돼 읽기 권한(READ)
|
||||
self.assertEqual(self.ids(READER), (200, [10, 20]))
|
||||
self.assertEqual(access.task_access(self.st, READER, self.st.get_task(20)), access.READ)
|
||||
|
||||
|
||||
# ── [2] 사이드바 순서 API — 보낸 id 전부 관리 권한, 이상한 값은 400 ──────────
|
||||
class ReorderTests(Base):
|
||||
def put(self, who, body):
|
||||
self.st.reorder_projects.reset_mock()
|
||||
return self.call(who, "PUT", "/project/api/projects/order", json=body).status_code
|
||||
|
||||
def test_only_manageable_projects(self):
|
||||
self.assertEqual(self.put(PM, {"ordered_ids": [4, 1]}), 200)
|
||||
self.st.reorder_projects.assert_called_once_with(ordered_ids=[4, 1])
|
||||
self.assertEqual(self.put(PM, {"ordered_ids": [1, 3]}), 403) # 3 은 멤버 아님
|
||||
self.st.reorder_projects.assert_not_called() # 일부만 바뀌지 않는다
|
||||
self.assertEqual(self.put(PM, {"ordered_ids": [999]}), 403) # 없는 id 도 같은 403
|
||||
self.assertEqual(self.put(ADMIN, {"ordered_ids": [1]}), 403) # 비멤버 Admin
|
||||
self.assertEqual(self.put(SUPER, {"ordered_ids": [3, 1]}), 200)
|
||||
self.assertEqual(self.put(SUPER, {"ordered_ids": [999]}), 403)
|
||||
self.assertEqual(self.put(BOTH, {"ordered_ids": [1]}), 403) # User 는 등급에서 막힘
|
||||
|
||||
def test_bad_payloads_are_400(self):
|
||||
for body in ({}, {"ordered_ids": []}, {"ordered_ids": "1,2"}, {"ordered_ids": [1, 1]},
|
||||
{"ordered_ids": [True]}, {"ordered_ids": ["a"]}, {"ordered_ids": [1.5]},
|
||||
{"ordered_ids": [0]}, {"ordered_ids": [None]}):
|
||||
with self.subTest(body=body):
|
||||
self.assertEqual(self.put(PM, body), 400)
|
||||
self.st.reorder_projects.assert_not_called()
|
||||
|
||||
|
||||
# ── [3][4] 작업 열기 경로·보관/서브프로젝트 화면 ─────────────────────────
|
||||
class FakeMain(types.ModuleType):
|
||||
def __init__(self, who):
|
||||
super().__init__("app.main")
|
||||
self.who = who
|
||||
self.ctx = None
|
||||
self.user_store = SimpleNamespace(list_all=lambda: [], get=lambda e: None)
|
||||
|
||||
def get_current_user_record(self, request):
|
||||
return self.who
|
||||
|
||||
def build_erp_nav(self, user, active=""):
|
||||
return []
|
||||
|
||||
def render_template(self, request, name, ctx, status_code=200):
|
||||
self.ctx = ctx
|
||||
return HTMLResponse(f"{name}|{ctx.get('reason', '')}", status_code=status_code)
|
||||
|
||||
|
||||
class OpenPathTests(Base):
|
||||
def get(self, who, url):
|
||||
fake = FakeMain(who)
|
||||
with patch.dict(sys.modules, {"app.main": fake}), patch("app.store.has_module", return_value=True):
|
||||
r = self.call(who, "GET", url, follow_redirects=False)
|
||||
return r, fake
|
||||
|
||||
def test_permalink_opens_linked_project_for_read_user_and_keeps_embed(self):
|
||||
r, _ = self.get(READER, "/project/t/20?embed=1")
|
||||
self.assertEqual((r.status_code, r.headers["location"]), (303, "/project/p/3?task=20&embed=1"))
|
||||
r, _ = self.get(PM, "/project/t/10")
|
||||
self.assertEqual(r.headers["location"], "/project/p/1?task=10")
|
||||
r, _ = self.get(ADMIN, "/project/t/20")
|
||||
self.assertEqual(r.status_code, 403)
|
||||
|
||||
def test_old_home_project_url_redirects_read_user(self):
|
||||
# 옛 PC 알림 프로그램·북마크(/p/{원 소속}?task=) — 403 대신 읽을 수 있는 연결된 프로젝트로
|
||||
r, _ = self.get(READER, "/project/p/2?task=20&embed=1")
|
||||
self.assertEqual((r.status_code, r.headers["location"]), (303, "/project/p/3?task=20&embed=1"))
|
||||
r, _ = self.get(ADMIN, "/project/p/2?task=20")
|
||||
self.assertEqual(r.status_code, 403)
|
||||
r, _ = self.get(READER, "/project/p/2")
|
||||
self.assertEqual(r.status_code, 403)
|
||||
|
||||
def test_archived_project_page_reads_its_own_tasks_only(self):
|
||||
r, fake = self.get(PM, "/project/p/4")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(self.st.asked_task_projects, [1, 4]) # 활성 최상위(1) + 지금 연 보관 프로젝트(4)만
|
||||
self.assertIn(40, [t["id"] for t in fake.ctx["tasks"]])
|
||||
metas = {p["id"]: p for p in fake.ctx["projects_meta"]}
|
||||
self.assertTrue(metas[4]["view_only"]) # 화면용 — 사이드바 목록에는 없다
|
||||
self.assertNotIn(4, [p["id"] for p in fake.ctx["nav_projects"]])
|
||||
|
||||
def test_snapshot_matches_first_page_scope(self):
|
||||
r = self.call(PM, "GET", "/project/api/projects/4/snapshot?scope=all")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
out = r.json()
|
||||
self.assertEqual(self.st.asked_task_projects, [1, 4])
|
||||
self.assertIn(40, [t["id"] for t in out["tasks"]])
|
||||
self.assertEqual([p["id"] for p in out["projects"] if p.get("view_only")], [4])
|
||||
|
||||
def test_subproject_page_includes_its_tasks(self):
|
||||
r, fake = self.get(BOTH, "/project/p/2")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(self.st.asked_task_projects, [1, 2]) # 최상위 멤버 프로젝트(1) + 지금 연 서브프로젝트(2)
|
||||
self.assertEqual(sorted(t["id"] for t in fake.ctx["tasks"] if t["context_project_id"] == 2), [20, 21])
|
||||
|
||||
|
||||
# ── [8] 일반 첨부 — DB 저장 실패면 이 요청이 쓴 파일만 지운다 ─────────────
|
||||
class AttachmentCleanupTests(Base):
|
||||
def test_db_failure_removes_only_new_file(self):
|
||||
data_dir = tempfile.mkdtemp(prefix="pj-att-")
|
||||
self.client = client_for(self.st, data_dir)
|
||||
old = Path(data_dir) / "project" / "10"
|
||||
old.mkdir(parents=True)
|
||||
(old / "existing.bin").write_bytes(b"keep")
|
||||
self.st.add_attachment.side_effect = RuntimeError("db down")
|
||||
r = self.call(PM, "POST", "/project/api/tasks/10/attachments", files={"file": ("a.txt", b"hello", "text/plain")})
|
||||
self.assertEqual(r.status_code, 500)
|
||||
self.assertEqual(sorted(p.name for p in old.iterdir()), ["existing.bin"])
|
||||
self.st.add_attachment.side_effect = None
|
||||
self.st.add_attachment.return_value = {"id": 1}
|
||||
r = self.call(PM, "POST", "/project/api/tasks/10/attachments", files={"file": ("a.txt", b"hello", "text/plain")})
|
||||
self.assertEqual(r.status_code, 201)
|
||||
self.assertEqual(len(list(old.iterdir())), 2)
|
||||
# 빈 파일·권한은 그대로
|
||||
self.assertEqual(self.call(PM, "POST", "/project/api/tasks/10/attachments",
|
||||
files={"file": ("e.txt", b"", "text/plain")}).status_code, 400)
|
||||
self.assertEqual(self.call(CHILD, "POST", "/project/api/tasks/10/attachments",
|
||||
files={"file": ("a.txt", b"x", "text/plain")}).status_code, 403)
|
||||
|
||||
|
||||
# ── [10] 배지 개수 — 제한 없이, 지금 권한으로 ─────────────────────────────
|
||||
class BadgeCountTests(Base):
|
||||
def test_my_open_count_is_exact_past_old_limit(self):
|
||||
self.st.list_my_open_refs.return_value = (
|
||||
[{"id": i, "project_id": 1} for i in range(1, 1501)] + [{"id": 5000 + i, "project_id": 2} for i in range(10)])
|
||||
self.assertEqual(api._my_open_count(self.st, PM), 1500) # 2(비멤버)의 10건은 빼고
|
||||
self.assertEqual(api._my_open_count(self.st, BOTH), 1510)
|
||||
|
||||
def test_unread_notification_count_is_exact(self):
|
||||
self.st.list_unread_refs.return_value = (
|
||||
[{"id": i, "project_id": 1, "task_id": 10} for i in range(700)] + [{"id": 900, "project_id": 2, "task_id": 21}])
|
||||
self.assertEqual(api._notification_unread(self.st, PM), 700)
|
||||
self.assertEqual(api._notification_unread(self.st, BOTH), 701)
|
||||
|
||||
def test_unread_mentions_count_filters_by_current_access(self):
|
||||
self.st.list_unread_mention_refs.return_value = [
|
||||
{"id": 10, "project_id": 1, "unread_mentions": 3}, {"id": 21, "project_id": 2, "unread_mentions": 4}]
|
||||
self.assertEqual(api._safe_mention_unread(self.st, PM), 3)
|
||||
self.assertEqual(api._safe_mention_unread(self.st, BOTH), 7)
|
||||
|
||||
|
||||
# ── [13] 남을 소유자로 지정해 만들면 만든 사람은 명시적 멤버로 ───────────────
|
||||
class CreatorMemberTests(Base):
|
||||
def test_creator_added_as_member_only_when_owner_is_someone_else(self):
|
||||
self.st.create_project.return_value = {"id": 9, "name": "n"}
|
||||
with patch.object(api, "_check_owner_candidate"):
|
||||
self.call(PM, "POST", "/project/api/projects", json={"name": "n", "owner_email": "other@test.local"})
|
||||
kw = self.st.create_project.call_args.kwargs
|
||||
self.assertEqual((kw["owner_email"], kw["member_emails"]), ("other@test.local", ["pm@test.local"]))
|
||||
self.call(PM, "POST", "/project/api/projects", json={"name": "n"})
|
||||
kw = self.st.create_project.call_args.kwargs
|
||||
self.assertEqual((kw["owner_email"], kw["member_emails"]), ("pm@test.local", []))
|
||||
|
||||
|
||||
# ── [14] 중복 방지 키 — 실패·성공·동시 요청에서 잠금이 남지 않는다 ───────────
|
||||
class OnceTests(unittest.TestCase):
|
||||
USER = {"email": "me@test.local"}
|
||||
|
||||
def setUp(self):
|
||||
api._once_results.clear()
|
||||
api._once_key_locks.clear()
|
||||
|
||||
def test_failure_releases_lock_and_retry_runs_again(self):
|
||||
calls = []
|
||||
|
||||
def boom():
|
||||
calls.append(1)
|
||||
raise RuntimeError("x")
|
||||
with self.assertRaises(RuntimeError):
|
||||
api._once(self.USER, 1, "tok", boom)
|
||||
self.assertEqual(api._once_key_locks, {}) # 실패한 키의 잠금이 남지 않는다
|
||||
out = api._once(self.USER, 1, "tok", lambda: {"ok": 1})
|
||||
self.assertEqual((out, len(calls)), ({"ok": 1}, 1))
|
||||
self.assertEqual(api._once(self.USER, 1, "tok", lambda: {"ok": 2}), {"ok": 1, "duplicate": True}) # 응답 유실 후 재전송
|
||||
self.assertEqual(api._once_key_locks, {})
|
||||
|
||||
def test_concurrent_same_token_runs_once(self):
|
||||
started, release, runs, outs = threading.Event(), threading.Event(), [], []
|
||||
|
||||
def slow():
|
||||
runs.append(1)
|
||||
started.set()
|
||||
release.wait(2)
|
||||
return {"id": 7}
|
||||
th = [threading.Thread(target=lambda: outs.append(api._once(self.USER, 1, "same", slow))) for _ in range(5)]
|
||||
th[0].start()
|
||||
started.wait(2)
|
||||
for t in th[1:]:
|
||||
t.start()
|
||||
time.sleep(0.05)
|
||||
self.assertEqual(api._once_key_locks[("me@test.local", 1, "same")][1], 5) # 기다리는 요청이 있는 동안 유지
|
||||
release.set()
|
||||
for t in th:
|
||||
t.join(2)
|
||||
self.assertEqual(len(runs), 1)
|
||||
self.assertEqual(sorted(bool(o.get("duplicate")) for o in outs), [False, True, True, True, True])
|
||||
self.assertEqual(api._once_key_locks, {})
|
||||
|
||||
def test_expired_results_are_purged(self):
|
||||
api._once(self.USER, 1, "old", lambda: {"ok": 1})
|
||||
with patch.object(api.time, "monotonic", return_value=time.monotonic() + api._ONCE_TTL_SEC + 1):
|
||||
api._once(self.USER, 1, "new", lambda: {"ok": 2})
|
||||
self.assertNotIn(("me@test.local", 1, "old"), api._once_results)
|
||||
|
||||
|
||||
# ── [B] 섹션 기본 담당자 — 지금 권한(등록·project 권한)도 통과해야 자동 배정 ──────
|
||||
class _Res:
|
||||
def __init__(self, rows):
|
||||
self.rows = list(rows)
|
||||
|
||||
def fetchone(self):
|
||||
return self.rows[0] if self.rows else None
|
||||
|
||||
def fetchall(self):
|
||||
return self.rows
|
||||
|
||||
|
||||
class StageDefaultAssigneeTests(unittest.TestCase):
|
||||
def conn(self):
|
||||
def execute(sql, params=()):
|
||||
if "to_jsonb(s)" in sql:
|
||||
return _Res([{"e": "Gone@Test.local"}])
|
||||
if "FROM project_members" in sql:
|
||||
return _Res([{"user_name": "Gone"}])
|
||||
raise AssertionError(sql)
|
||||
return SimpleNamespace(execute=execute)
|
||||
|
||||
def test_revoked_or_deleted_user_is_not_auto_assigned(self):
|
||||
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1), ("gone@test.local", "Gone"))
|
||||
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1, allowed=lambda e: False), ("", ""))
|
||||
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1, allowed=lambda e: True),
|
||||
("gone@test.local", "Gone"))
|
||||
|
||||
def test_router_check_uses_user_registry_and_module(self):
|
||||
with patch.object(access, "default_user_lookup", return_value=None):
|
||||
self.assertFalse(api._registered_project_user("x@test.local"))
|
||||
with patch.object(access, "default_user_lookup", return_value={"email": "x@test.local"}), \
|
||||
patch.object(access, "can_use_module", return_value=False):
|
||||
self.assertFalse(api._registered_project_user("x@test.local"))
|
||||
with patch.object(access, "default_user_lookup", return_value={"email": "x@test.local"}), \
|
||||
patch.object(access, "can_use_module", return_value=True):
|
||||
self.assertTrue(api._registered_project_user("x@test.local"))
|
||||
|
||||
|
||||
# ── [11] 작업 수정 — 잠근 행으로 검사, 같은 연결, 실제 전환 기준 알림 힌트 ────────
|
||||
class TaskConn:
|
||||
"""tasks 한 행 + 섹션. FOR UPDATE 로 읽힌 '지금 값'이 검사·알림 기준이어야 한다."""
|
||||
|
||||
def __init__(self, row):
|
||||
self.row = dict(row)
|
||||
self.depth, self.locked, self.updates, self.logs = 0, False, [], []
|
||||
self.stages = {11: {"project_id": 1, "is_done_stage": False, "dae": "dae@test.local"},
|
||||
12: {"project_id": 1, "is_done_stage": True, "dae": ""}}
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
self.depth += 1
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.depth -= 1
|
||||
self.locked = False
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
if sql.startswith("SELECT * FROM tasks WHERE id = %s FOR UPDATE"):
|
||||
assert self.depth > 0
|
||||
self.locked = True
|
||||
return _Res([dict(self.row)])
|
||||
if sql.startswith("SELECT 1 FROM project_stages WHERE id = %s AND project_id = %s"):
|
||||
s = self.stages.get(params[0])
|
||||
return _Res([{"?": 1}] if s and s["project_id"] == params[1] else [])
|
||||
if "to_jsonb(s)" in sql:
|
||||
return _Res([{"e": self.stages[params[0]]["dae"]}])
|
||||
if "FROM project_members" in sql:
|
||||
return _Res([{"user_name": "Dae"}])
|
||||
if sql.startswith("SELECT is_done_stage FROM project_stages"):
|
||||
return _Res([{"is_done_stage": self.stages[params[0]]["is_done_stage"]}])
|
||||
if sql.startswith("UPDATE tasks SET"):
|
||||
assert self.locked, "변경은 잠근 행에"
|
||||
self.updates.append((sql, params))
|
||||
return _Res([])
|
||||
if sql.startswith("INSERT INTO project_activity"):
|
||||
self.logs.append(params)
|
||||
return _Res([])
|
||||
raise AssertionError(sql)
|
||||
|
||||
|
||||
class UpdateTaskConcurrencyTests(unittest.TestCase):
|
||||
def make(self, row, stale=None):
|
||||
self.conn = TaskConn(row)
|
||||
self.borrows = 0
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
self.borrows += 1
|
||||
yield self.conn
|
||||
|
||||
st = ProjectStore.__new__(ProjectStore)
|
||||
st._pool = SimpleNamespace(connection=connection)
|
||||
# 잠그기 전 다른 연결로 읽은 옛 값(예전 코드가 검사에 쓰던 값) — 이제는 결과 표시에만 쓰인다
|
||||
st.get_task = lambda task_id: {**(stale or self.conn.row), "id": task_id}
|
||||
return st
|
||||
|
||||
BASE = {"id": 7, "project_id": 1, "stage_id": 11, "title": "t", "assignee_email": "", "completed_at": None,
|
||||
"start_date": "2026-10-10", "due_date": "2026-10-20", "start_time": None, "due_time": None}
|
||||
|
||||
def test_date_check_uses_locked_current_row(self):
|
||||
# A 가 시작일을 10/18 로 이미 바꿨다(잠근 행) — B 의 마감일 10/12 는 옛 값(10/10)으론 통과했지만 이제 거절
|
||||
st = self.make({**self.BASE, "start_date": "2026-10-18"}, stale=self.BASE)
|
||||
with self.assertRaises(ValueError):
|
||||
st.update_task(task_id=7, fields={"due_date": "2026-10-12"})
|
||||
self.assertEqual(self.conn.updates, [])
|
||||
st.update_task(task_id=7, fields={"due_date": "2026-10-25"})
|
||||
self.assertEqual(len(self.conn.updates), 1)
|
||||
self.assertEqual(self.borrows, 2) # 요청마다 연결 하나(get_task 대역 제외) — 트랜잭션 안에서 다시 빌리지 않는다
|
||||
|
||||
def test_second_completion_is_not_a_new_transition(self):
|
||||
st = self.make({**self.BASE, "completed_at": "2026-10-11T10:00:00+09:00"})
|
||||
out = st.update_task(task_id=7, fields={"completed": True}, actor="b@test.local")
|
||||
self.assertFalse(out["_newly_completed"])
|
||||
self.assertEqual((self.conn.updates, self.conn.logs), ([], []))
|
||||
|
||||
def test_stage_move_default_assignee_and_done_in_same_connection(self):
|
||||
st = self.make({**self.BASE, "stage_id": 12})
|
||||
asked = []
|
||||
out = st.update_task(task_id=7, fields={"stage_id": 11}, actor="a@test.local",
|
||||
assignee_allowed=lambda e: asked.append(e) or True)
|
||||
self.assertEqual((asked, out["_newly_assigned"], self.borrows), (["dae@test.local"], "dae@test.local", 1))
|
||||
st = self.make({**self.BASE, "stage_id": 12})
|
||||
out = st.update_task(task_id=7, fields={"stage_id": 11}, assignee_allowed=lambda e: False)
|
||||
self.assertIsNone(out["_newly_assigned"]) # 권한을 잃은 기본 담당자는 자동 배정·배정 알림 없음
|
||||
st = self.make(self.BASE)
|
||||
out = st.update_task(task_id=7, fields={"stage_id": 12})
|
||||
self.assertTrue(out["_newly_completed"])
|
||||
self.assertEqual(len(self.conn.logs), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -27,6 +27,10 @@ class FakeStore(MagicMock):
|
||||
def is_member(self, project_id, user_email):
|
||||
return user_email in self.MEMBERS.get(int(project_id), set())
|
||||
|
||||
def list_projects(self, include_archived=False, member_email=None):
|
||||
return [{"id": pid, "parent_id": None} for pid, ms in self.MEMBERS.items()
|
||||
if member_email is None or member_email in ms]
|
||||
|
||||
def get_project(self, project_id):
|
||||
return {"id": project_id, "name": "P1", "owner_email": "admin@test.local", "created_by": "admin@test.local"}
|
||||
|
||||
@@ -145,6 +149,8 @@ class RoleApiTests(unittest.TestCase):
|
||||
body = {"ordered_ids": [1]}
|
||||
self.assertEqual(self.call(USER, "PUT", "/project/api/projects/order", json=body).status_code, 403)
|
||||
self.assertEqual(self.call(PRO, "PUT", "/project/api/projects/order", json=body).status_code, 200)
|
||||
# Pro user 라도 멤버가 아닌 프로젝트는 순서를 못 바꾼다(검토 2026-10-12)
|
||||
self.assertEqual(self.call(OUTSIDER_PRO, "PUT", "/project/api/projects/order", json=body).status_code, 403)
|
||||
|
||||
def test_section_delete_admin_any_others_creator(self):
|
||||
self.assertEqual(self.call(PRO, "DELETE", "/project/api/projects/1/stages/5").status_code, 403)
|
||||
@@ -173,8 +179,7 @@ class RoleApiTests(unittest.TestCase):
|
||||
self.assertEqual(self.call(PRO, "GET", "/project/api/projects/1/subtasks-summary").status_code, 200)
|
||||
|
||||
def test_trash_restore_pro(self):
|
||||
self.st.list_trash.return_value = [{"id": 4, "project_id": 1}]
|
||||
self.st.list_projects.return_value = [{"id": 1}]
|
||||
self.st.list_trash.return_value = [{"id": 4, "project_id": 1}] # 프로젝트 1 = PRO 가 멤버(list_projects)
|
||||
self.st.restore_trash.return_value = {"restored": 1}
|
||||
self.assertEqual(self.call(USER, "POST", "/project/api/trash/4/restore").status_code, 403)
|
||||
self.assertEqual(self.call(PRO, "POST", "/project/api/trash/4/restore").status_code, 200)
|
||||
|
||||
Reference in New Issue
Block a user