diff --git a/CLAUDE.md b/CLAUDE.md index 410e997..48733d6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 말레이시아 창고 재고관리 (`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) 조회·편집·즉시적용·예약적용·버전 이력. 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지(`POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A` — NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다. 그래서 "마지막 쓰기가 권위": 상세설명은 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 쓰고(`store.resolve_description`), 스칼라(상품명·가격·이미지·진열/판매)는 PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌운다(`store.overlay_recent_write`). 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분). 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다. 예약은 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)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md` +- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md` - 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면·API 는 `is_admin`. 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md` diff --git a/app/modules/project/access.py b/app/modules/project/access.py new file mode 100644 index 0000000..1ac297b --- /dev/null +++ b/app/modules/project/access.py @@ -0,0 +1,151 @@ +"""프로젝트 관리 — 현재 접근 권한의 공통 기준(서버). + +라우터·마감 알림이 같은 규칙을 쓰도록 한 곳에 모은다. 모든 판단은 "지금" 기준이다 — +예전에 멤버였거나 담당자·멘션·협업자로 기록돼 있어도, 지금 권한이 없으면 보이지도 +바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다). + +프로젝트 + 관리(=보기·작업 CRUD) : 관리자(is_admin) · 프로젝트 owner · 배정 멤버. 모두 `project` 모듈 권한이 있어야 한다. + +작업 + FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙) + READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음 + → 그 작업의 상세·하위 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다. + 연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용. + None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외 +""" + +from __future__ import annotations + +from typing import Any, Callable, Iterable + +from . import store + +FULL = "full" +READ = "read" + +UserLookup = Callable[[str], "dict[str, Any] | None"] + + +def default_user_lookup(email: str) -> dict[str, Any] | None: + """등록 사용자 레코드(app.main.user_store). 지연 import — 테스트는 lookup 을 직접 넘긴다.""" + from app.main import user_store # noqa: WPS433 + + return user_store.get(store.norm_str(email, lower=True)) + + +def _is_admin(user: dict[str, Any] | None) -> bool: + from app.store import is_admin # noqa: WPS433 + + return is_admin(user) + + +def can_use_module(user: dict[str, Any] | None) -> bool: + from app.store import has_module # noqa: WPS433 + + return bool(user) and has_module(user, "project") + + +def email_of(user: dict[str, Any] | None) -> str: + return store.norm_str((user or {}).get("email", ""), lower=True) + + +def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool: + """프로젝트 관리(=보기·작업 CRUD) — 관리자 또는 owner/멤버. 모듈 권한이 없으면 False.""" + if not can_use_module(user): + return False + if _is_admin(user): + return True + try: + pid = int(project_id) + except (TypeError, ValueError): + return False + return bool(st.is_member(project_id=pid, user_email=email_of(user))) + + +def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None: + """관리할 수 있는 프로젝트 id 집합. 관리자는 None(=전체).""" + if _is_admin(user): + return None + if not can_use_module(user): + return set() + return { + int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user)) + } + + +def task_access(st: Any, user: dict[str, Any] | None, task: dict[str, Any] | None) -> str | None: + """작업 하나에 대한 지금 권한: FULL / READ / None.""" + if not task or not can_use_module(user): + return None + if can_manage_project(st, user, task.get("project_id")): + return FULL + for pid in link_scope(st, [int(task["id"])]).get(int(task["id"]), set()): + if can_manage_project(st, user, pid): + return READ + return None + + +def link_scope(st: Any, task_ids: Iterable[int]) -> dict[int, set[int]]: + """작업 id → 이 작업 또는 상위 작업이 연결된 프로젝트 id 들. 연결 표가 없으면 빈 값.""" + ids = [int(i) for i in task_ids] + if not ids: + return {} + try: + return st.task_link_scope(task_ids=ids) + except Exception: # noqa: BLE001 - 003 미적용(연결 기능 없음) → 연결로 보이는 작업 없음 + return {} + + +def filter_visible_tasks(st: Any, user: dict[str, Any], tasks: list[dict[str, Any]], + *, key: str = "id") -> list[dict[str, Any]]: + """목록에서 지금 볼 수 있는(FULL 또는 READ) 작업만 남긴다 — 내 작업·수신함·알림 공용.""" + allowed = visible_project_ids(st, user) + if allowed is None: + return list(tasks) + ids = [int(t[key]) for t in tasks if t.get(key) is not None] + scope = link_scope(st, ids) + out = [] + for t in tasks: + tid = t.get(key) + pid = t.get("project_id") + if pid is not None and int(pid) in allowed: + out.append(t) + elif tid is not None and scope.get(int(tid), set()) & allowed: + out.append(t) + return out + + +def email_task_access(st: Any, email: str, task: dict[str, Any], + lookup: UserLookup | None = None) -> str | None: + """이메일(알림·멘션 대상)이 지금 이 작업을 볼 수 있는지. 등록 안 된 사람·모듈 권한 없는 사람은 None.""" + rec = (lookup or default_user_lookup)(email) + if not rec: + return None + rec = {**rec, "email": rec.get("email") or email} + return task_access(st, rec, task) + + +def filter_recipients(st: Any, task: dict[str, Any], emails: Iterable[str], + lookup: UserLookup | None = None) -> list[str]: + """알림·메일·멘션 대상 중 지금 이 작업을 볼 수 있는 사람만(순서 유지, 중복 제거).""" + out: list[str] = [] + seen: set[str] = set() + for e in emails: + em = store.norm_str(e, lower=True) + if not em or em in seen: + continue + seen.add(em) + if email_task_access(st, em, task, lookup) is not None: + out.append(em) + return out + + +def can_assign(st: Any, email: str, project_id: Any, lookup: UserLookup | None = None) -> bool: + """담당자·소유자 후보 — 등록된 사용자이고 project 모듈 권한이 있으며, 그 프로젝트를 + 관리할 수 있어야 한다(관리자 포함). 권한 없는 사람에게 작업 정보가 담긴 알림이 가지 않게.""" + rec = (lookup or default_user_lookup)(email) + if not rec: + return False + rec = {**rec, "email": rec.get("email") or email} + return can_manage_project(st, rec, project_id) diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 179712f..cb652f1 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -100,6 +100,7 @@ class ProjectStore: ic = store.validate_project_icon(icon) sd = store.validate_date(start_date) dd = store.validate_date(due_date) + store.validate_date_range(sd, dd) with self._pool.connection() as conn: with conn.transaction(): if parent_id is not None: @@ -158,15 +159,26 @@ class ProjectStore: } sets: list[str] = [] params: list[Any] = [] + clean: dict[str, Any] = {} for key, fn in allowed.items(): if key in fields: + clean[key] = fn(fields[key]) sets.append(f"{key} = %s") - params.append(fn(fields[key])) + params.append(clean[key]) if not sets: existing = self.get_project(project_id=project_id) if existing is None: raise KeyError(project_id) return existing + if "start_date" in clean or "due_date" in clean: + # 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다. + existing = self.get_project(project_id=project_id) + if existing is None: + raise KeyError(project_id) + 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( @@ -605,7 +617,9 @@ class ProjectStore: dd = store.validate_date(due_date) sti = store.validate_time(start_time) dti = store.validate_time(due_time) + store.validate_date_range(sd, dd, sti, dti) assignee = store.norm_str(assignee_email, lower=True) + done_at = None with self._pool.connection() as conn: with conn.transaction(): if parent_task_id is not None: @@ -636,6 +650,13 @@ class ProjectStore: # 세션이 없어 해당 없음). if not assignee and stage_id is not None: assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id) + # 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력). + if stage_id is not None: + done_row = conn.execute( + "SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,) + ).fetchone() + if done_row and done_row["is_done_stage"]: + done_at = now_kst() nxt = conn.execute( "SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks " "WHERE project_id = %s", @@ -646,21 +667,26 @@ class ProjectStore: INSERT INTO tasks (project_id, stage_id, parent_task_id, title, description, assignee_email, assignee_name, priority, start_date, due_date, - start_time, due_time, sort_order, created_by) - VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) + start_time, due_time, sort_order, created_by, completed_at) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING * """, ( project_id, stage_id, parent_task_id, ttl, store.norm_str(description), assignee, store.norm_str(assignee_name), pr, sd, dd, - sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), + sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at, ), ).fetchone() if assignee: self._log(conn, project_id=project_id, task_id=row["id"], actor=created_by, action=store.ACTION_ASSIGNED, detail=f"{ttl} → {assignee}") - return self.get_task(task_id=row["id"]) + if done_at is not None: + self._log(conn, project_id=project_id, task_id=row["id"], + actor=created_by, action=store.ACTION_COMPLETED, detail=ttl) + out = self.get_task(task_id=row["id"]) + out["_newly_completed"] = done_at is not None + return out def move_subtask( self, *, task_id: int, parent_task_id: int, actor: str = "" @@ -806,6 +832,15 @@ class ProjectStore: 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(): @@ -1217,6 +1252,51 @@ class ProjectStore: ).fetchone() return self._serialize(row) + def add_comment_with_attachments( + self, *, task_id: int, author_email: str, author_name: str, body: str, + files: list[dict[str, Any]], parent_id: int | None = None, + ) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """댓글과 첨부를 한 트랜잭션에 — 둘 중 하나라도 실패하면 아무것도 남지 않는다 + (첨부 없이 빈 댓글만 남던 문제). files = [{filename, stored_name, content_type, size_bytes}]. + 본문이 비어도 되지만 첨부가 한 개 이상 있어야 한다.""" + text = store.norm_str(body) + if not files and not text: + raise ValueError("댓글 내용이 비었습니다.") + author = store.norm_str(author_email, lower=True) + with self._pool.connection() as conn: + with conn.transaction(): + root = None + if parent_id: + p = conn.execute( + "SELECT id, task_id, parent_id FROM task_comments WHERE id = %s", (parent_id,) + ).fetchone() + if not p or int(p["task_id"]) != int(task_id): + raise ValueError("답글을 달 댓글을 찾을 수 없습니다.") + root = int(p["parent_id"] or p["id"]) + if root is not None: + row = conn.execute( + "INSERT INTO task_comments (task_id, author_email, author_name, body, parent_id) " + "VALUES (%s,%s,%s,%s,%s) RETURNING *", + (task_id, author, store.norm_str(author_name), text, root), + ).fetchone() + else: + row = conn.execute( + "INSERT INTO task_comments (task_id, author_email, author_name, body) " + "VALUES (%s,%s,%s,%s) RETURNING *", + (task_id, author, store.norm_str(author_name), text), + ).fetchone() + atts = [] + for f in files: + atts.append(conn.execute( + "INSERT INTO task_attachments " + "(task_id, filename, stored_name, content_type, size_bytes, uploaded_by, comment_id) " + "VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING *", + (task_id, store.norm_str(f["filename"]), f["stored_name"], + store.norm_str(f.get("content_type") or "application/octet-stream"), + int(f["size_bytes"]), author, row["id"]), + ).fetchone()) + return self._serialize(row), [self._serialize(a) for a in atts] + def update_comment( self, *, comment_id: int, requester: str, is_admin: bool, body: str ) -> dict[str, Any]: @@ -1655,6 +1735,58 @@ class ProjectStore: ).fetchall() return [self._serialize(r) for r in rows] + def add_reminder_notification( + self, *, task_id: int, kind: str, due_date: str, recipient_email: str, + project_id: int | None, title: str, body: str, + ) -> bool: + """마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True, + 이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서 + 다시 시도된다(예전엔 기록만 남아 영영 안 갔다). 동시에 두 번 돌아도 UNIQUE 로 한 번만.""" + rcpt = store.norm_str(recipient_email, lower=True) + with self._pool.connection() as conn: + with conn.transaction(): + row = conn.execute( + "INSERT INTO task_reminders (task_id, kind, due_date, recipient_email) " + "VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING RETURNING id", + (task_id, kind, due_date, rcpt), + ).fetchone() + if row is None: + return False + conn.execute( + "INSERT INTO project_notifications " + "(recipient_email, actor_email, project_id, task_id, type, title, body) " + "VALUES (%s,'',%s,%s,%s,%s,%s)", + (rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)), + ) + return True + + def task_link_scope(self, *, task_ids: list[int]) -> dict[int, set[int]]: + """작업 id → 이 작업 또는 그 상위 작업들이 연결(멀티호밍)된 프로젝트 id 집합. + 연결된 프로젝트 멤버가 그 작업(과 하위 작업)을 읽기 전용으로 볼 수 있는지 판단한다.""" + ids = sorted({int(i) for i in task_ids}) + if not ids: + return {} + with self._pool.connection() as conn: + rows = conn.execute( + """ + WITH RECURSIVE chain AS ( + SELECT id AS task_id, id AS anc_id, parent_task_id, 0 AS depth + FROM tasks WHERE id = ANY(%s) + UNION ALL + SELECT c.task_id, t.id, t.parent_task_id, c.depth + 1 + FROM chain c JOIN tasks t ON t.id = c.parent_task_id + WHERE c.depth < 20 + ) + SELECT c.task_id, l.project_id + FROM chain c JOIN task_project_links l ON l.task_id = c.anc_id + """, + (ids,), + ).fetchall() + out: dict[int, set[int]] = {} + for r in rows: + out.setdefault(int(r["task_id"]), set()).add(int(r["project_id"])) + return out + def record_reminder( self, *, task_id: int, kind: str, due_date: str, recipient_email: str, ) -> bool: diff --git a/app/modules/project/reminders.py b/app/modules/project/reminders.py index 67bc814..ea22564 100644 --- a/app/modules/project/reminders.py +++ b/app/modules/project/reminders.py @@ -5,10 +5,11 @@ · due_today — 오늘 마감 · overdue — 마감이 지남(최근 7일 이내 마감분만 — 첫 적용 때 오래된 업무가 한꺼번에 쏟아지지 않게, 연휴로 며칠 건너뛰어도 놓치지 않게) -수신자는 담당자. 담당자가 없으면 팔로워 전원. +수신자는 담당자. 담당자가 없으면 팔로워 전원. 단, 지금 그 작업을 볼 수 있는 사람만. 중복 방지: task_reminders(업무, 종류, 마감일, 수신자) UNIQUE — 같은 알림은 한 번만 간다(재기동·여러 번 실행해도 안전). 마감일을 바꾸면 새 마감일 기준으로 다시 알린다. +발송 기록과 수신함 알림은 한 트랜잭션이라, 알림 생성이 실패하면 다음 실행에 다시 시도된다. 실행 방식: 웹 프로세스 안의 데몬 스레드(start_reminder_thread). 5분마다 깨어나 "오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가 @@ -33,7 +34,7 @@ from typing import Any from app.timezone import now_kst -from . import store +from . import access, store logger = logging.getLogger("project.reminders") @@ -87,8 +88,18 @@ def _title_for(kind: str, task: dict[str, Any], today: date) -> str: return f"마감 지남({(today - due).days}일): {task['title']}" -def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]: - """한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다.""" +def run_due_reminders( + st: Any, *, today: date | None = None, lookup: access.UserLookup | None = None, +) -> dict[str, int]: + """한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다. + + - 수신자는 지금 그 작업을 볼 수 있는 사람만(access.filter_recipients) — 멤버에서 빠진 담당자· + 협업자, 모듈 권한이 없어진 직원에게는 수신함 알림도 메일도 가지 않는다. + - 발송 기록(task_reminders)과 수신함 알림은 한 트랜잭션(add_reminder_notification) — 알림 생성이 + 실패하면 기록도 되돌려져 다음 실행에서 다시 시도된다. 같은 알림은 UNIQUE 로 한 번만(동시 실행 포함). + - 보장 범위: 수신함 알림까지. 메일(PROJECT_REMINDER_EMAIL)은 알림이 새로 만들어진 것만 요약해 한 번 + 보내며, 메일 발송 실패는 재시도하지 않는다(수신함 알림은 이미 남아 있다). + """ today = today or now_kst().date() start = today - timedelta(days=OVERDUE_WINDOW_DAYS) end = next_workday(today) @@ -101,22 +112,25 @@ def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]: if kind is None: continue assignee = store.norm_str(t.get("assignee_email"), lower=True) - recipients = [assignee] if assignee else store.normalize_emails(t.get("followers") or []) + wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or []) + try: + recipients = access.filter_recipients(st, t, wanted, lookup) + except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다(다음 실행에 재시도) + logger.warning("마감 알림 수신자 확인 실패: task=%s", t["id"]) + continue for rcpt in recipients: - if not st.record_reminder( - task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt, - ): - continue # 이미 보냄 title = _title_for(kind, t, today) try: - st.add_notification( - recipient_email=rcpt, actor_email="", project_id=t["project_id"], - task_id=t["id"], type=kind, title=title, + created = st.add_reminder_notification( + task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt, + project_id=t["project_id"], title=title, body=f"{t.get('project_name') or ''} · 마감 {t['due_date'][:10]}", ) - except Exception: # noqa: BLE001 - logger.warning("마감 알림 생성 실패: task=%s", t["id"]) + except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도 + logger.warning("마감 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"]) continue + if not created: + continue # 이미 보냄 counts[kind] += 1 digest.setdefault(rcpt, []).append((title, t)) diff --git a/app/modules/project/router.py b/app/modules/project/router.py index 6b3c735..d21331a 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -19,7 +19,10 @@ from __future__ import annotations import calendar as _calendar +import json import logging +import threading +import time import uuid from datetime import date from pathlib import Path @@ -46,7 +49,7 @@ from psycopg.errors import UndefinedColumn, UndefinedTable from app.timezone import KST, now_kst, today_kst -from . import store +from . import access, store # 첨부 업로드 제한 _MAX_ATTACH_BYTES = 20 * 1024 * 1024 # 20MB @@ -91,12 +94,8 @@ def _require_admin(request: Request) -> dict[str, Any]: def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool: - """프로젝트 단위 관리 권한: 관리자이거나 멤버/owner.""" - from app.store import is_admin # noqa: WPS433 - - if is_admin(user): - return True - return bool(st.is_member(project_id=project_id, user_email=user["email"])) + """프로젝트 단위 관리 권한: 관리자이거나 멤버/owner (access.can_manage_project — 지금 기준).""" + return access.can_manage_project(st, user, project_id) def _require_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> None: @@ -123,13 +122,44 @@ _DELETE_DENIED = "삭제는 만든 사람만 할 수 있습니다." def _accessible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None: """사용자가 볼 수 있는 프로젝트 id 집합. 관리자는 None(=전체).""" - from app.store import is_admin # noqa: WPS433 + return access.visible_project_ids(st, user) - if is_admin(user): - return None - return { - p["id"] for p in st.list_projects(include_archived=True, member_email=user["email"]) - } + +_TASK_DENIED = "이 작업을 볼 권한이 없습니다. 프로젝트 관리자에게 멤버 배정을 요청하세요." +_TASK_READ_ONLY = ("다른 프로젝트에서 연결된 작업이라 읽기만 할 수 있습니다. " + "변경은 원 소속 프로젝트 멤버만 할 수 있습니다.") + + +def _task_or_404(st: Any, task_id: int) -> dict[str, Any]: + task = st.get_task(task_id=task_id) + if task is None: + raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") + return task + + +def _require_task( + st: Any, user: dict[str, Any], task: dict[str, Any], *, write: bool = True +) -> str: + """작업 권한 공통 검사 — write=True 면 원 소속 권한(FULL)만, False 면 연결된 프로젝트의 + 읽기(READ)도 허용. 권한 레벨을 돌려준다.""" + level = access.task_access(st, user, task) + if level is None: + raise HTTPException(status_code=403, detail=_TASK_DENIED) + if write and level != access.FULL: + raise HTTPException(status_code=403, detail=_TASK_READ_ONLY) + return level + + +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) + ) + + +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")) def _remove_task_dirs(request: Request, task_ids: list[int]) -> None: @@ -260,12 +290,18 @@ def _follow(st: Any, task_id: int, emails: list[str]) -> None: def _task_recipients( st: Any, project: dict[str, Any], task: dict[str, Any], *, exclude: str = "" ) -> list[str]: - """업무 관련 인앱 알림 수신자 (행위자 제외). + """업무 관련 인앱 알림 수신자 (행위자 제외, 지금 이 작업을 볼 수 있는 사람만). = 담당자 + 팔로워(아사나의 협업자). 예전엔 프로젝트 멤버 전원에게 갔는데 알림이 너무 많아 정작 중요한 게 묻혔다. 팔로워 표(008)가 없으면 예전처럼 - 담당자 + owner + 멤버 전원. + 담당자 + owner + 멤버 전원. 멤버에서 빠진 담당자·협업자는 기록은 남아도 받지 않는다. """ + return access.filter_recipients(st, task, _task_recipients_raw(st, project, task, exclude=exclude)) + + +def _task_recipients_raw( + st: Any, project: dict[str, Any], task: dict[str, Any], *, exclude: str = "" +) -> list[str]: emails: set[str] = set() if task.get("assignee_email"): emails.add(store.norm_str(task["assignee_email"], lower=True)) @@ -305,24 +341,31 @@ def _record_mentions( st: Any, *, task: dict[str, Any], emails: list[str], actor: str, comment_id: int | None = None, source: str = "description", project_name: str = "", -) -> None: - """@태그를 기록하고 새로 태그된 사람에게만 알림을 만든다. +) -> list[str]: + """@태그를 기록하고 새로 태그된 사람에게만 알림을 만든다. 태그할 수 없는 사람(이 작업을 + 지금 볼 수 없는 직원·등록 안 된 이메일)은 기록·알림·협업자 등록 없이 건너뛰고 그 목록을 + 돌려준다 — 태그로 작업 정보가 새거나 접근 권한이 생기지 않게(payload 에 이메일을 직접 넣어도). 태그는 부가 기능이라 여기서 실패해도(예: 006 마이그레이션 미적용) 본 저장/등록은 막지 않는다 — 로그만 남긴다. """ - if not emails: - return + wanted = store.normalize_emails(emails) + if not wanted: + return [] + allowed = access.filter_recipients(st, task, wanted) + skipped = [e for e in wanted if e not in allowed and e != store.norm_str(actor, lower=True)] + if not allowed: + return skipped try: added = st.add_mentions( - task_id=task["id"], emails=emails, actor_email=actor, + task_id=task["id"], emails=allowed, actor_email=actor, comment_id=comment_id, source=source, ) except Exception: # noqa: BLE001 logger.warning("멘션 기록 실패: task=%s", task.get("id")) - return + return skipped if not added: - return + return skipped _follow(st, task["id"], added) # 태그된 사람은 이후 소식도 받도록 팔로워로 where = "댓글" if source == "comment" else "설명" _inbox( @@ -331,6 +374,31 @@ def _record_mentions( title=f"나를 태그함: {task['title']}", body=f"{project_name or task.get('project_name') or ''} · {where}", ) + return skipped + + +def _notify_completed( + bg: BackgroundTasks, request: Request, st: Any, *, project: dict[str, Any], + task: dict[str, Any], actor: str, +) -> None: + """작업 완료 알림 — 관리자 메일 + 담당자·협업자 수신함(행위자 제외, 지금 볼 수 있는 사람만). + 완료 섹션으로 옮김·완료로 표시·완료 섹션에 바로 만듦 모두 이 한 곳.""" + project_name = project.get("name") or task.get("project_name") or "" + _notify( + bg, request, + subject=store.build_subject_completed(project_name=project_name, task_title=task["title"]), + body=( + f"프로젝트: {project_name}\n" + f"완료된 작업: {task['title']}\n" + f"담당자: {task.get('assignee_name') or task.get('assignee_email') or '-'}\n" + f"완료 처리: {actor}\n" + ), + ) + _inbox( + st, recipients=_task_recipients(st, project, task, exclude=actor), + actor=actor, project_id=task["project_id"], task_id=task["id"], + ntype="completed", title=f"작업 완료: {task['title']}", body=project_name, + ) def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse: @@ -572,7 +640,7 @@ def my_tasks_page(request: Request) -> HTMLResponse: nav_projects = _nav_projects(st, user, admin) today_iso = today_kst().isoformat() - my_tasks = st.list_my_tasks(assignee_email=user["email"], limit=1000) + my_tasks = _my_visible_tasks(st, user) for t in my_tasks: t["start_label"] = _fmt_date_kr(t.get("start_date")) t["due_label"] = _fmt_date_kr(t.get("due_date")) @@ -601,7 +669,7 @@ def my_tasks_page(request: Request) -> HTMLResponse: "goal_years": _goal_years_nav(st), "my_tasks": my_tasks, "my_open_total": my_open_total, - "mention_unread": _safe_mention_unread(st, user["email"]), + "mention_unread": _safe_mention_unread(st, user), "avatars": avatars, "priority_labels": store.PRIORITY_LABELS, "color_palette": list(store.COLOR_PALETTE), @@ -655,17 +723,23 @@ def task_permalink(request: Request, task_id: int): task = st.get_task(task_id=task_id) if task is None: return _denied("작업을 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404) - if not _can_manage(request, st, user, task["project_id"]): + level = access.task_access(st, user, task) + if level 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/{task['project_id']}?task={task_id}", status_code=303 - ) + return RedirectResponse(url=f"/project/p/{target}?task={task_id}", status_code=303) @router.get("/p/{project_id}", response_class=HTMLResponse) @@ -776,8 +850,8 @@ def project_page(request: Request, project_id: int) -> HTMLResponse: } # 좌측 사이드바 "내 업무" 배지(진행 중 개수)와 수신함 배지. - my_open_total = st.count_my_open(assignee_email=user["email"]) - mention_unread = _safe_mention_unread(st, user["email"]) + my_open_total = _my_open_count(st, user) + mention_unread = _safe_mention_unread(st, user) # 달력(휴가식 월간 그리드) — ?y=&m= 로 월 이동, 기본 이번 달 today = today_kst() @@ -858,6 +932,29 @@ def api_list_projects(request: Request) -> JSONResponse: _PROJECT_ICON_MIGRATION_MSG = "프로젝트 아이콘 기능이 아직 준비되지 않았습니다(DB 마이그레이션 011 필요)." +_OWNER_ADMIN_ONLY = "프로젝트 소유자는 관리자만 지정·변경할 수 있습니다." + + +def _owner_for_create(user: dict[str, Any], payload: dict[str, Any]) -> str: + """새 프로젝트 소유자 — 만든 사람. 다른 사람을 소유자로 지정하는 건 관리자만(그 사람은 + 등록 사용자이고 project 모듈 권한이 있어야 한다). 비관리자가 남을 지정하면 거절.""" + me = store.norm_str(user["email"], lower=True) + want = store.norm_str(payload.get("owner_email") or "", lower=True) + if not want or want == me: + return me + from app.store import is_admin # noqa: WPS433 + + if not is_admin(user): + raise HTTPException(status_code=403, detail=_OWNER_ADMIN_ONLY) + _check_owner_candidate(want) + return want + + +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}): + raise HTTPException(status_code=400, + detail="소유자는 프로젝트 관리 권한이 있는 등록 사용자여야 합니다.") @router.post("/api/projects") @@ -873,7 +970,7 @@ def api_create_project( parent_id=None, description=payload.get("description", ""), color=payload.get("color", ""), - owner_email=payload.get("owner_email", "") or user["email"], + owner_email=_owner_for_create(user, payload), start_date=payload.get("start_date"), due_date=payload.get("due_date"), created_by=user["email"], @@ -900,7 +997,7 @@ def api_create_subproject( parent_id=project_id, description=payload.get("description", ""), color=payload.get("color", ""), - owner_email=payload.get("owner_email", "") or user["email"], + owner_email=_owner_for_create(user, payload), start_date=payload.get("start_date"), due_date=payload.get("due_date"), created_by=user["email"], @@ -937,11 +1034,27 @@ def api_reorder_projects( def api_update_project( request: Request, project_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: + from app.store import is_admin # noqa: WPS433 + user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) + fields = dict(payload) + if "owner_email" in fields: + # 소유자는 멤버 목록과 별개로 계속 관리 권한을 준다 — 스스로를 소유자로 바꿔 권한 회수를 + # 피할 수 없게 관리자만. 값이 그대로면(화면이 같이 보낸 경우) 그냥 무시한다. + current = st.get_project(project_id=project_id) + if current is None: + raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") + want = store.norm_str(fields.get("owner_email") or "", lower=True) + if want == store.norm_str(current.get("owner_email") or "", lower=True): + fields.pop("owner_email") + elif not is_admin(user): + raise HTTPException(status_code=403, detail=_OWNER_ADMIN_ONLY) + elif want: + _check_owner_candidate(want) try: - project = st.update_project(project_id=project_id, fields=payload) + project = st.update_project(project_id=project_id, fields=fields) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except UndefinedColumn: @@ -959,6 +1072,8 @@ def api_delete_project(request: Request, project_id: int) -> JSONResponse: project = st.get_project(project_id=project_id) if project is None: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") + # 만든 사람이어도 지금 그 프로젝트 권한이 없으면(멤버에서 빠짐) 지울 수 없다. + _require_manage(request, st, user, project_id) if not _can_delete(user, project.get("created_by")): raise HTTPException(status_code=403, detail=_DELETE_DENIED) try: @@ -997,14 +1112,23 @@ def api_assignable_users(request: Request) -> JSONResponse: @router.get("/api/all-users") -def api_all_users(request: Request) -> JSONResponse: +def api_all_users(request: Request, task_id: int | None = None) -> JSONResponse: """project 모듈 권한 보유 등록 사용자 전원 — 좌측 "전체 멤버"(관리자 에게만 그린다) + 설명란/댓글 @태그 후보 목록. @태그는 일반 직원도 쓰므로 - 이 API 자체는 로그인 사용자 누구나 호출 가능(이름·아이디·사진만 반환).""" - _require_user(request) + 이 API 자체는 로그인 사용자 누구나 호출 가능(이름·아이디·사진만 반환). + + task_id 를 주면 @태그 후보 — 그 작업을 지금 볼 수 있는 사람만(원 소속 멤버·owner·관리자, + 연결된 프로젝트 멤버). 태그로 작업 정보가 새지 않게 서버도 저장할 때 다시 거른다.""" + user = _require_user(request) from app.main import user_store # noqa: WPS433 from app.store import has_module # noqa: WPS433 + users = [u for u in user_store.list_all() if has_module(u, "project")] + if task_id is not None: + st = _db_or_503(request) + task = _task_or_404(st, task_id) + _require_task(st, user, task, write=False) + users = [u for u in users if access.task_access(st, u, task) is not None] out = [ { "email": u["email"], @@ -1012,8 +1136,7 @@ def api_all_users(request: Request) -> JSONResponse: "id": u["email"].split("@")[0], "avatar": u.get("picture") or "", } - for u in user_store.list_all() - if has_module(u, "project") + for u in users ] out.sort(key=lambda x: x["id"]) return JSONResponse({"users": out}) @@ -1175,28 +1298,63 @@ def api_list_tasks(request: Request, project_id: int) -> JSONResponse: @router.get("/api/projects/{project_id}/snapshot") -def api_project_snapshot(request: Request, project_id: int) -> JSONResponse: +def api_project_snapshot(request: Request, project_id: int, scope: str = "project") -> JSONResponse: """프로젝트 화면 실시간 동기화용 — 업무(이 프로젝트 + 여기 연결된 업무, context_project_id·home_stage_id 포함)·세션·멤버를 요청 한 번에. - 예전엔 API 3개를 따로 불렀고, 업무 API 는 연결 업무를 빼고 돌려줘서 - 화면의 연결 업무 행과 맞지 않았다. + scope=all — 프로젝트 화면이 들고 있는 것과 같은 범위(지금 볼 수 있는 모든 최상위 프로젝트의 + 작업·섹션·프로젝트 목록)를 통째로 준다. 다른 프로젝트의 새 작업·삭제·섹션 변경·권한 회수까지 + 반영된다(예전엔 지금 연 프로젝트 것만 받아 다른 프로젝트 행이 남거나 빠졌다). + 이 프로젝트 권한을 잃었으면 403 — 화면이 편집을 멈추고 안내한다. """ user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) + if scope != "all": + return JSONResponse({ + "tasks": st.list_tasks_for_projects(project_ids=[project_id]), + "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] + stages_by_project = st.list_stages_for_projects(project_ids=ids) return JSONResponse({ - "tasks": st.list_tasks_for_projects(project_ids=[project_id]), - "stages": st.list_stages(project_id=project_id), + "scope": "all", + "project": st.get_project(project_id=project_id), + "projects": [_project_meta(p) for p in top], + "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), "members": st.list_members(project_id=project_id), }) +def _project_meta(p: dict[str, Any]) -> dict[str, Any]: + """프로젝트 화면·스냅샷 공용 프로젝트 요약(사이드바·타임라인 그룹·보드 배지용).""" + return { + "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", + } + + @router.get("/api/my-tasks") def api_my_tasks(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - return JSONResponse({"tasks": st.list_my_tasks(assignee_email=user["email"], limit=1000)}) + return JSONResponse({"tasks": _my_visible_tasks(st, user)}) @router.get("/api/my-tasks/open-count") @@ -1204,7 +1362,7 @@ def api_my_open_count(request: Request) -> JSONResponse: """사이드바 "내 업무" 배지 숫자만 — 목록 전체를 받지 않는다.""" user = _require_user(request) st = _db_or_503(request) - return JSONResponse({"open": st.count_my_open(assignee_email=user["email"])}) + return JSONResponse({"open": _my_open_count(st, user)}) @router.post("/api/projects/{project_id}/tasks") @@ -1220,6 +1378,7 @@ def api_create_task( project = st.get_project(project_id=project_id) if project is None: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") + _check_assignee(st, payload.get("assignee_email"), project_id) try: task = st.create_task( project_id=project_id, @@ -1266,12 +1425,28 @@ def api_create_task( title=f"작업 배정: {task['title']}", body=f"{project['name']} · 마감 {task.get('due_date') or '-'}", ) - _record_mentions( + # 완료 섹션에 바로 만든 작업 — 완료 섹션으로 옮긴 것과 같은 완료 알림. + if task.pop("_newly_completed", False): + _notify_completed(bg, request, st, project=project, task=task, actor=user["email"]) + skipped = _record_mentions( st, task=task, emails=store.extract_mentions_from_html(task.get("description") or ""), actor=user["email"], project_name=project["name"], ) - return JSONResponse({"task": task}, status_code=201) + return JSONResponse({"task": task, "mention_skipped": skipped}, status_code=201) + + +_ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다." + + +def _check_assignee(st: Any, email: Any, project_id: int, *, previous: str = "") -> None: + """새로 지정하는 담당자가 그 프로젝트를 볼 수 있는지 — 권한 없는 사람에게 배정 알림(작업 제목 + 등)이 가지 않게. 비우거나 그대로 두는 건 검사하지 않는다(멤버에서 빠진 예전 담당자 보존).""" + em = store.norm_str(email or "", lower=True) + if not em or em == store.norm_str(previous or "", lower=True): + return + if not access.can_assign(st, em, project_id): + raise HTTPException(status_code=400, detail=_ASSIGNEE_DENIED) @router.put("/api/tasks/{task_id}") @@ -1283,10 +1458,11 @@ def api_update_task( ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - existing = st.get_task(task_id=task_id) - if existing is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, existing["project_id"]) + existing = _task_or_404(st, task_id) + _require_task(st, user, existing, write=True) + if "assignee_email" in payload: + _check_assignee(st, payload.get("assignee_email"), existing["project_id"], + previous=existing.get("assignee_email") or "") if "description" in payload: payload["description"] = store.sanitize_description_html(payload["description"]) try: @@ -1323,39 +1499,24 @@ def api_update_task( body=f"{project_name} · 마감 {task.get('due_date') or '-'}", ) if task.get("_newly_completed"): - _notify( - bg, request, - subject=store.build_subject_completed( - project_name=project_name, task_title=task["title"] - ), - body=( - f"프로젝트: {project_name}\n" - f"완료된 작업: {task['title']}\n" - f"담당자: {task.get('assignee_name') or task.get('assignee_email') or '-'}\n" - f"완료 처리: {user['email']}\n" - ), - ) - _inbox( - st, recipients=_task_recipients(st, project, task, exclude=user["email"]), - actor=user["email"], project_id=existing["project_id"], task_id=task_id, - ntype="completed", title=f"작업 완료: {task['title']}", body=project_name, - ) + _notify_completed(bg, request, st, project=project, task=task, actor=user["email"]) + skipped: list[str] = [] if "description" in payload: - _record_mentions( + skipped = _record_mentions( st, task=task, emails=store.extract_mentions_from_html(payload["description"]), actor=user["email"], project_name=project_name, ) - return JSONResponse({"task": task}) + return JSONResponse({"task": task, "mention_skipped": skipped}) @router.delete("/api/tasks/{task_id}") def api_delete_task(request: Request, task_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - existing = st.get_task(task_id=task_id) - if existing is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") + existing = _task_or_404(st, task_id) + # 만든 사람이어도 지금 원 소속 프로젝트 권한이 없으면(멤버에서 빠짐) 지울 수 없다. + _require_task(st, user, existing, write=True) if not _can_delete(user, existing.get("created_by")): raise HTTPException(status_code=403, detail=_DELETE_DENIED) try: @@ -1376,20 +1537,28 @@ def api_get_task(request: Request, task_id: int) -> JSONResponse: """업무 상세 — 하위 업무·연결된 프로젝트 포함. 업무 편집 팝업을 열 때 쓴다.""" user = _require_user(request) st = _db_or_503(request) - task = st.get_task(task_id=task_id) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + task = _task_or_404(st, task_id) + # 원 소속 권한(FULL) 또는 연결된 프로젝트의 읽기 권한(READ). READ 면 화면이 읽기 전용으로 연다. + level = _require_task(st, user, task, write=False) + task["access"] = level # 하위 업무를 팝업으로 열면 제목 위에 상위 업무 경로를 보여준다(아사나식). if task.get("parent_task_id"): parent = st.get_task(task_id=task["parent_task_id"]) task["parent_title"] = parent["title"] if parent else "" task["subtasks"] = st.list_tasks(parent_task_id=task_id) - task["links"] = st.list_task_links(task_id=task_id) - try: - task["followers"] = st.list_followers(task_id=task_id) - except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다 - task["followers"] = None + # 다른 연결 프로젝트 중 내가 볼 수 없는 곳은 이름·색도 보이지 않게 뺀다. + allowed = _accessible_project_ids(st, user) + task["links"] = [ + ln for ln in st.list_task_links(task_id=task_id) + if allowed is None or int(ln["project_id"]) in allowed + ] + if level != access.FULL: + task["followers"] = None # 읽기 전용 — 협업자 편집 칸을 숨긴다 + else: + try: + task["followers"] = st.list_followers(task_id=task_id) + except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다 + task["followers"] = None return JSONResponse({"task": task}) @@ -1400,10 +1569,8 @@ def api_reorder_subtasks( """작업 팝업의 하위 작업 목록을 드래그로 재정렬. body: {"ordered_ids": [...]}""" user = _require_user(request) st = _db_or_503(request) - parent = st.get_task(task_id=task_id) - if parent is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, parent["project_id"]) + parent = _task_or_404(st, task_id) + _require_task(st, user, parent, write=True) ids = payload.get("ordered_ids") or [] if not isinstance(ids, list) or not ids: raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.") @@ -1427,10 +1594,8 @@ def api_move_subtask( """ user = _require_user(request) st = _db_or_503(request) - existing = st.get_task(task_id=task_id) - if existing is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, existing["project_id"]) + existing = _task_or_404(st, task_id) + _require_task(st, user, existing, write=True) try: parent_id = int(payload.get("parent_task_id")) except (TypeError, ValueError): @@ -1448,10 +1613,8 @@ def api_move_subtask( # JSON API — 팔로워 (아사나의 협업자) # ──────────────────────────────────────────────────────────── def _task_for_followers(request: Request, st: Any, user: dict[str, Any], task_id: int) -> dict[str, Any]: - task = st.get_task(task_id=task_id) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + task = _task_or_404(st, task_id) + _require_task(st, user, task, write=True) return task @@ -1634,10 +1797,8 @@ def api_activity(request: Request, project_id: int) -> JSONResponse: def api_list_comments(request: Request, task_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - task = st.get_task(task_id=task_id) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + task = _task_or_404(st, task_id) + level = _require_task(st, user, task, write=False) # 연결된 프로젝트 멤버도 읽기는 된다 # 완료 이력 줄은 "지금 완료 상태"일 때 마지막 완료 1건만 — 완료를 취소하면 사라지고, # 예전에 완료했다가 취소한 기록도 안 보인다(이력 행 자체는 지우지 않는다). events: list[dict[str, Any]] = [] @@ -1651,6 +1812,8 @@ def api_list_comments(request: Request, task_id: int) -> JSONResponse: # "OO 님이 이 작업을 완료했습니다" — 댓글 사이에 시간순으로 끼워 보인다. "events": [{"type": "completed", **e} for e in events], "features": st.comment_features(), + # 댓글 대화창이 입력칸을 보일지 — read 면 읽기 전용(댓글·반응·답글 불가) + "access": level, }) @@ -1658,49 +1821,172 @@ def api_list_comments(request: Request, task_id: int) -> JSONResponse: def api_add_comment( request: Request, task_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: + """글 댓글(본문 필수). 파일이 있는 댓글은 POST /comments/files(본문+파일 한 번에). + 예전의 has_attachment 플래그(빈 본문 허용 후 파일을 따로 올림)는 더 받지 않는다 — + 업로드가 실패하면 빈 댓글만 남았다.""" user = _require_user(request) st = _db_or_503(request) - task = st.get_task(task_id=task_id) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) - parent_id = payload.get("parent_id") - if parent_id: + task = _task_or_404(st, task_id) + _require_task(st, user, task, write=True) + parent_id = _comment_parent_arg(st, payload.get("parent_id")) + token = str(payload.get("client_token") or "")[:64] + + def create() -> dict[str, Any]: try: - parent_id = int(parent_id) - except (TypeError, ValueError): - raise HTTPException(status_code=400, detail="parent_id 가 올바르지 않습니다.") - if not st.comment_features()["replies"]: - raise HTTPException(status_code=503, detail=_COMMENT_012_MSG) + comment = st.add_comment( + task_id=task_id, + author_email=user["email"], + author_name=user.get("name") or user["email"].split("@")[0], + body=payload.get("body", ""), + parent_id=parent_id, + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + skipped = _after_comment(st, user, task, comment, payload.get("mentions")) + return {"comment": comment, "attachments": [], "mention_skipped": skipped} + + return JSONResponse(_once(user, task_id, token, create), status_code=201) + + +def _comment_parent_arg(st: Any, raw: Any) -> int | None: + if not raw: + return None try: - comment = st.add_comment( - task_id=task_id, - author_email=user["email"], - author_name=user.get("name") or user["email"].split("@")[0], - body=payload.get("body", ""), - allow_empty=bool(payload.get("has_attachment")), - parent_id=parent_id or None, - ) - except ValueError as exc: - raise HTTPException(status_code=400, detail=str(exc)) + parent_id = int(raw) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="parent_id 가 올바르지 않습니다.") + if not st.comment_features()["replies"]: + raise HTTPException(status_code=503, detail=_COMMENT_012_MSG) + return parent_id + + +def _after_comment( + st: Any, user: dict[str, Any], task: dict[str, Any], comment: dict[str, Any], mentions: Any, + *, n_files: int = 0, +) -> list[str]: + """댓글이 만들어진 뒤 — 자동 협업자·알림·@태그. 반환: 태그하지 못한 이메일.""" comment.setdefault("parent_id", None) comment["reactions"] = [] - _follow(st, task_id, [user["email"]]) # 댓글 단 사람은 이후 소식도 받는다 + _follow(st, task["id"], [user["email"]]) # 댓글 단 사람은 이후 소식도 받는다 project = st.get_project(project_id=task["project_id"]) or {"id": task["project_id"], "name": task.get("project_name", "")} + preview = comment["body"][:120] or f"첨부 파일 {n_files}개" _inbox( st, recipients=_task_recipients(st, project, task, exclude=user["email"]), - actor=user["email"], project_id=task["project_id"], task_id=task_id, - ntype="comment", title=f"새 댓글: {task['title']}", - body=comment["body"][:120], + actor=user["email"], project_id=task["project_id"], task_id=task["id"], + ntype="comment", title=f"새 댓글: {task['title']}", body=preview, ) # 댓글은 평문이라 본문에서 이메일을 꺼낼 수 없다 — 화면이 고른 멤버 # 목록을 그대로 받아 기록한다(설명란은 본문 HTML 에서 직접 뽑는다). - _record_mentions( - st, task=task, emails=store.normalize_emails(payload.get("mentions")), + return _record_mentions( + st, task=task, emails=store.normalize_emails(mentions), actor=user["email"], comment_id=comment["id"], source="comment", project_name=project.get("name", ""), ) - return JSONResponse({"comment": comment}, status_code=201) + + +# 같은 댓글이 두 번 등록되지 않게(더블클릭·Enter 연타·응답을 못 받은 재전송) — 화면이 댓글마다 +# 만든 client_token 으로 10분 동안 첫 결과를 돌려준다. 웹 프로세스 하나(uvicorn 단일 워커) 기준. +_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] = {} + + +def _once(user: dict[str, Any], task_id: int, token: str, fn: Any) -> dict[str, Any]: + if not token: + return fn() + key = (store.norm_str(user["email"], lower=True), int(task_id), token) + now = time.monotonic() + 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: # 같은 토큰의 동시 요청은 첫 요청이 끝날 때까지 기다렸다가 그 결과를 받는다 + with _once_lock: + hit = _once_results.get(key) + if hit is not None: + return {**hit[1], "duplicate": True} + out = fn() + with _once_lock: + _once_results[key] = (time.monotonic(), out) + return out + + +_MAX_COMMENT_FILES = 20 + + +@router.post("/api/tasks/{task_id}/comments/files") +def api_add_comment_with_files( + request: Request, + task_id: int, + files: list[UploadFile] = File(...), + body: str = Form(""), + parent_id: str = Form(""), + mentions: str = Form(""), + client_token: str = Form(""), +) -> JSONResponse: + """파일이 있는 댓글 — 본문과 파일을 한 요청으로 받아 한 트랜잭션에 만든다. 파일 하나라도 + 문제가 있으면(빈 파일·20MB 초과) 아무것도 만들지 않고 어느 파일인지 돌려준다(detail.failed). + DB 저장이 실패하면 방금 쓴 파일도 지운다 — 첨부 없는 빈 댓글이 남지 않는다.""" + user = _require_user(request) + st = _db_or_503(request) + task = _task_or_404(st, task_id) + _require_task(st, user, task, write=True) + pid = _comment_parent_arg(st, parent_id) + try: + mention_list = json.loads(mentions) if mentions else [] + except ValueError: + mention_list = [] + if not files: + raise HTTPException(status_code=400, detail="보낼 파일이 없습니다.") + if len(files) > _MAX_COMMENT_FILES: + raise HTTPException(status_code=400, detail=f"파일은 한 번에 {_MAX_COMMENT_FILES}개까지 보낼 수 있습니다.") + + def create() -> dict[str, Any]: + loaded: list[tuple[str, str, bytes]] = [] + failed: list[dict[str, str]] = [] + for i, f in enumerate(files): + name = (f.filename or "file").replace("\\", "_").replace("/", "_").strip() or "file" + data = f.file.read(_MAX_ATTACH_BYTES + 1) + if len(data) > _MAX_ATTACH_BYTES: + failed.append({"index": str(i), "name": name, "reason": "20MB 초과"}) + elif not data: + failed.append({"index": str(i), "name": name, "reason": "빈 파일"}) + else: + loaded.append((name, f.content_type or "application/octet-stream", data)) + if failed: + raise HTTPException(status_code=400, detail={ + "message": "보낼 수 없는 파일이 있어 댓글을 등록하지 않았습니다.", "failed": failed, + }) + written: list[Path] = [] + metas: list[dict[str, Any]] = [] + try: + d = _attach_dir(request, task_id) + for name, ctype, data in loaded: + stored = f"{uuid.uuid4().hex}{Path(name).suffix[:16]}" + (d / stored).write_bytes(data) + written.append(d / stored) + metas.append({"filename": name, "stored_name": stored, "content_type": ctype, + "size_bytes": len(data)}) + comment, atts = st.add_comment_with_attachments( + task_id=task_id, author_email=user["email"], + author_name=user.get("name") or user["email"].split("@")[0], + body=body, files=metas, parent_id=pid, + ) + except Exception as exc: + for w in written: # DB 에 안 들어간 파일은 디스크에도 남기지 않는다 + try: + w.unlink(missing_ok=True) + except Exception: # noqa: BLE001 + logger.warning("댓글 첨부 정리 실패: %s", w.name) + if isinstance(exc, ValueError): + raise HTTPException(status_code=400, detail=str(exc)) + raise + skipped = _after_comment(st, user, task, comment, mention_list, n_files=len(atts)) + return {"comment": comment, "attachments": atts, "mention_skipped": skipped} + + return JSONResponse(_once(user, task_id, client_token[:64], create), status_code=201) _COMMENT_012_MSG = ( @@ -1723,10 +2009,8 @@ def api_toggle_reaction( comment = st.get_comment(comment_id=comment_id) if comment is None: raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.") - task = st.get_task(task_id=comment["task_id"]) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + task = _task_or_404(st, comment["task_id"]) + _require_task(st, user, task, write=True) if not st.comment_features()["reactions"]: raise HTTPException(status_code=503, detail=_COMMENT_012_MSG) try: @@ -1736,6 +2020,16 @@ def api_toggle_reaction( return JSONResponse({"reactions": reactions}) +def _comment_task_access(st: Any, user: dict[str, Any], comment_id: int) -> dict[str, Any]: + """댓글 수정·삭제 전 — 작성자라도 지금 그 작업의 원 소속 권한이 없으면 거절(멤버에서 빠진 뒤 + 자기 댓글을 고치거나 지우던 경로 차단). 작성자 본인/관리자 검사는 DB 쪽이 한다.""" + comment = st.get_comment(comment_id=comment_id) + if comment is None: + raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.") + _require_task(st, user, _task_or_404(st, comment["task_id"]), write=True) + return comment + + @router.put("/api/comments/{comment_id}") def api_update_comment( request: Request, comment_id: int, payload: dict[str, Any] = Body(...) @@ -1744,6 +2038,7 @@ def api_update_comment( user = _require_user(request) st = _db_or_503(request) + _comment_task_access(st, user, comment_id) try: comment = st.update_comment( comment_id=comment_id, requester=user["email"], @@ -1764,6 +2059,7 @@ def api_delete_comment(request: Request, comment_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) + _comment_task_access(st, user, comment_id) try: files = st.delete_comment( comment_id=comment_id, requester=user["email"], is_admin=is_admin(user) @@ -1795,10 +2091,8 @@ def _attach_dir(request: Request, task_id: int) -> Path: def api_list_attachments(request: Request, task_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - task = st.get_task(task_id=task_id) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + task = _task_or_404(st, task_id) + _require_task(st, user, task, write=False) return JSONResponse({"attachments": st.list_attachments(task_id=task_id)}) @@ -1809,16 +2103,20 @@ def api_upload_attachment( ) -> JSONResponse: """comment_id 를 주면 댓글 채팅 팝업의 첨부(이미지/파일)로도 등록 — 같은 표에 저장되므로 업무 "첨부파일" 패널에도 그대로 함께 나온다.""" + from app.store import is_admin # noqa: WPS433 + user = _require_user(request) st = _db_or_503(request) - task = st.get_task(task_id=task_id) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + task = _task_or_404(st, task_id) + _require_task(st, user, task, write=True) if comment_id is not None: comment = st.get_comment(comment_id=comment_id) if comment is None or comment["task_id"] != task_id: raise HTTPException(status_code=400, detail="잘못된 댓글입니다.") + # 남의 댓글에 파일을 붙일 수 없다(작성자 본인·관리자만). + if not is_admin(user) and store.norm_str(comment.get("author_email") or "", lower=True) != \ + store.norm_str(user["email"], lower=True): + raise HTTPException(status_code=403, detail="본인 댓글에만 파일을 붙일 수 있습니다.") # 한도+1 바이트까지만 읽는다 — 20MB 를 넘는 파일을 끝까지 메모리에 올린 뒤에야 # 거절하던 것을 막는다(핸들러가 sync def 라 스레드풀에서 동기 읽기). @@ -1849,10 +2147,7 @@ def api_download_attachment(request: Request, attachment_id: int): att = st.get_attachment(attachment_id=attachment_id) if att is None: raise HTTPException(status_code=404, detail="첨부 파일을 찾을 수 없습니다.") - task = st.get_task(task_id=att["task_id"]) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + _require_task(st, user, _task_or_404(st, att["task_id"]), write=False) path = _attach_dir(request, att["task_id"]) / att["stored_name"] if not path.exists(): raise HTTPException(status_code=404, detail="파일이 디스크에 없습니다.") @@ -1874,10 +2169,7 @@ def api_inline_attachment(request: Request, attachment_id: int): att = st.get_attachment(attachment_id=attachment_id) if att is None: raise HTTPException(status_code=404, detail="첨부 파일을 찾을 수 없습니다.") - task = st.get_task(task_id=att["task_id"]) - if task is None: - raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.") - _require_manage(request, st, user, task["project_id"]) + _require_task(st, user, _task_or_404(st, att["task_id"]), write=False) path = _attach_dir(request, att["task_id"]) / att["stored_name"] if not path.exists(): raise HTTPException(status_code=404, detail="파일이 디스크에 없습니다.") @@ -1900,9 +2192,7 @@ def api_delete_attachment(request: Request, attachment_id: int) -> JSONResponse: att = st.get_attachment(attachment_id=attachment_id) if att is None: raise HTTPException(status_code=404, detail="첨부 파일을 찾을 수 없습니다.") - task = st.get_task(task_id=att["task_id"]) - if task is not None: - _require_manage(request, st, user, task["project_id"]) + _require_task(st, user, _task_or_404(st, att["task_id"]), write=True) removed = st.delete_attachment(attachment_id=attachment_id) try: (_attach_dir(request, removed["task_id"]) / removed["stored_name"]).unlink(missing_ok=True) @@ -1978,17 +2268,17 @@ def api_notifications(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) unread_only = request.query_params.get("unread") in ("1", "true") - items = st.list_notifications( + items = _visible_notifications(st, user, st.list_notifications( recipient_email=user["email"], unread_only=unread_only, limit=100 - ) - return JSONResponse({"notifications": items, "unread": st.count_unread(recipient_email=user["email"])}) + )) + return JSONResponse({"notifications": items, "unread": _notification_unread(st, user)}) @router.get("/api/notifications/unread-count") def api_notif_count(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - return JSONResponse({"unread": st.count_unread(recipient_email=user["email"])}) + return JSONResponse({"unread": _notification_unread(st, user)}) @router.post("/api/notifications/{notification_id}/read") @@ -2010,20 +2300,44 @@ def api_notif_read_all(request: Request) -> JSONResponse: # ──────────────────────────────────────────────────────────── # 수신함 — 나를 @태그한 업무 (아사나 Inbox) # ──────────────────────────────────────────────────────────── -def _safe_mentions(st: Any, email: str, *, limit: int = 100) -> list[dict[str, Any]]: - """task_mentions 조회. 006 마이그레이션 미적용 환경에서도 화면이 죽지 않게.""" +def _safe_mentions(st: Any, user: dict[str, Any], *, limit: int = 100) -> list[dict[str, Any]]: + """나를 태그한 작업 중 지금 볼 수 있는 것만(권한을 잃은 작업의 옛 태그는 숨김). + 006 마이그레이션 미적용 환경에서도 화면이 죽지 않게.""" try: - return st.list_mentioned_tasks(mentioned_email=email, limit=limit) + rows = st.list_mentioned_tasks(mentioned_email=user["email"], limit=1000) except Exception: # noqa: BLE001 logger.warning("멘션 조회 실패 — project_db_006 마이그레이션 확인 필요") return [] + return access.filter_visible_tasks(st, user, rows)[:limit] -def _safe_mention_unread(st: Any, email: str) -> int: - try: - return st.count_unread_mentions(mentioned_email=email) - except Exception: # noqa: BLE001 - return 0 +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)) + + +def _visible_notifications(st: Any, user: dict[str, Any], items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """알림 중 지금 볼 수 있는 프로젝트·작업의 것만. 작업 알림은 작업 기준(연결된 프로젝트의 + 읽기 권한 포함), 프로젝트 알림은 프로젝트 관리 권한, 둘 다 없는 알림은 그대로.""" + allowed = access.visible_project_ids(st, user) + if allowed is None: + return items + scope = access.link_scope(st, [int(n["task_id"]) for n in items if n.get("task_id")]) + out = [] + for n in items: + pid, tid = n.get("project_id"), n.get("task_id") + if pid is None and tid is None: + out.append(n) + elif pid is not None and int(pid) in allowed: + out.append(n) + elif tid is not None and scope.get(int(tid), set()) & allowed: + out.append(n) + return out + + +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)) @router.get("/api/mentions") @@ -2031,10 +2345,10 @@ def api_mentions(request: Request) -> JSONResponse: """나를 태그한 업무 목록 + 미확인 개수.""" user = _require_user(request) st = _db_or_503(request) - tasks = _safe_mentions(st, user["email"]) + tasks = _safe_mentions(st, user) return JSONResponse({ "tasks": tasks, - "unread": _safe_mention_unread(st, user["email"]), + "unread": _safe_mention_unread(st, user), }) @@ -2042,7 +2356,7 @@ def api_mentions(request: Request) -> JSONResponse: def api_mentions_unread(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) - return JSONResponse({"unread": _safe_mention_unread(st, user["email"])}) + return JSONResponse({"unread": _safe_mention_unread(st, user)}) @router.post("/api/mentions/read") @@ -2086,8 +2400,8 @@ def trash_page(request: Request) -> HTMLResponse: "nav_items": build_erp_nav(user, active="project"), "nav_projects": _nav_projects(st, user, True), "goal_years": _goal_years_nav(st), - "my_open_total": st.count_my_open(assignee_email=user["email"]), - "mention_unread": _safe_mention_unread(st, user["email"]), + "my_open_total": _my_open_count(st, user), + "mention_unread": _safe_mention_unread(st, user), "page_title": "휴지통", "page_subtitle": "삭제한 작업 — 3개월 보관, 관리자만 복구", "force_sidebar_collapsed": True, @@ -2166,13 +2480,13 @@ def inbox_page(request: Request) -> HTMLResponse: if st is None: return _render_config_needed(request, user) admin = is_admin(user) - items = st.list_notifications(recipient_email=user["email"], limit=100) - mentioned = _safe_mentions(st, user["email"]) + items = _visible_notifications(st, user, st.list_notifications(recipient_email=user["email"], limit=100)) + mentioned = _safe_mentions(st, user) for t in mentioned: t["due_label"] = _fmt_date_kr(t.get("due_date")) # 좌측 사이드바(project/_side.html)는 세 화면 공용 — 같은 데이터가 필요하다. nav_projects = _nav_projects(st, user, admin) - my_open_total = st.count_my_open(assignee_email=user["email"]) + my_open_total = _my_open_count(st, user) return render_template( request, "project/inbox.html", @@ -2190,7 +2504,7 @@ def inbox_page(request: Request) -> HTMLResponse: "project_icons": list(store.PROJECT_ICONS), "notifications": items, "mentioned_tasks": mentioned, - "mention_unread": _safe_mention_unread(st, user["email"]), + "mention_unread": _safe_mention_unread(st, user), }, ) @@ -2263,8 +2577,8 @@ def goals_page(request: Request, year: int) -> HTMLResponse: "nav_projects": _nav_projects(st, user, admin), "goal_years": _goal_years_nav(st), "goal_year_active": year, - "my_open_total": st.count_my_open(assignee_email=user["email"]), - "mention_unread": _safe_mention_unread(st, user["email"]), + "my_open_total": _my_open_count(st, user), + "mention_unread": _safe_mention_unread(st, user), "page_title": f"{year}년 목표", "page_subtitle": "한 해 전체 목표와 업무 영역별 계획", "force_sidebar_collapsed": True, diff --git a/app/modules/project/store.py b/app/modules/project/store.py index ec6214e..af3e155 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -313,6 +313,30 @@ def validate_date(d: Any) -> str | None: return v[:10] +DATE_RANGE_ERROR = "시작일이 마감일보다 늦을 수 없습니다." +TIME_RANGE_ERROR = "같은 날이면 시작 시각이 마감 시각보다 늦을 수 없습니다." + + +def validate_date_range( + start_date: Any, due_date: Any, start_time: Any = None, due_time: Any = None +) -> None: + """최종 상태(부분 수정이면 기존 값 + 바꾼 값)의 날짜 범위 검사 — 프로젝트·작업 공용. + + 둘 다 있으면 start_date <= due_date. 같은 날이고 두 시각이 모두 있으면 start_time <= due_time. + 한쪽이 비어 있는 입력은 허용. 값 형식 오류는 validate_date/validate_time 이 먼저 낸다. + """ + sd = validate_date(start_date) + dd = validate_date(due_date) + if sd and dd: + if sd > dd: + raise ValueError(DATE_RANGE_ERROR) + if sd == dd: + st = validate_time(start_time) + dt = validate_time(due_time) + if st and dt and st > dt: + raise ValueError(TIME_RANGE_ERROR) + + def validate_time(t: Any) -> str | None: """'HH:MM' 형식만 통과(초는 버림). 빈값/None 은 None(=종일).""" v = norm_str(t) diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index 3c19db4..135c790 100644 --- a/app/modules/project/templates/project/goals.html +++ b/app/modules/project/templates/project/goals.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -169,5 +169,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/help.html b/app/modules/project/templates/project/help.html index dc65b18..ba13cc6 100644 --- a/app/modules/project/templates/project/help.html +++ b/app/modules/project/templates/project/help.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -119,7 +119,9 @@ 작업·섹션·프로젝트 삭제만든 사람만 지울 수 있습니다(최고 관리자는 예외). 댓글 고치기·지우기댓글을 쓴 사람(또는 관리자)만. 새 프로젝트, 프로젝트 수정·순서 바꾸기관리자 (+ · ✎ · ⣿ 버튼이 관리자에게만 보입니다) - 멤버 배정·제외관리자 + 멤버 배정·제외, 프로젝트 소유자 바꾸기관리자 + 다른 프로젝트에서 연결돼 온 작업원래 프로젝트 멤버가 아니면 읽기만 — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다). + 멤버에서 빠졌을 때그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다. 휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트관리자 목표 보기누구나 · 목표 입력·연도 추가·업무 영역 편집은 관리자 @@ -263,7 +265,7 @@ link공유이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다. ✓ 완료로 표시작업을 완료합니다. 다시 누르면 ↩ 완료 취소. 삭제작업을 지웁니다(만든 사람만). 하위 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다. - 저장됨저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 저장 중… → ✓ 저장됨이 잠깐 보입니다. + 저장됨저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 저장 중… → ✓ 저장됨이 잠깐 보입니다. 저장이 안 되면 저장 실패 · 다시 시도(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 버리고 넘어갈지 / 계속 편집할지 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.
info
실시간 저장 — 제목은 칸을 벗어나거나 Enter, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 제목을 쓰는 순간 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 하위 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.
@@ -301,7 +303,8 @@

작업은 하나라서 어느 보드에서 고쳐도 모두 같이 바뀝니다.

댓글

-

작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 Enter(스크롤해도 그 자리에 있습니다). 칸 오른쪽 ☺는 이모티콘, @는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 ↳ 표시와 함께 보입니다. 내가 쓴 댓글은 ✎로 고치고 ×로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다.

+

작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 Enter(스크롤해도 그 자리에 있습니다). 칸 오른쪽 ☺는 이모티콘, @는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 ↳ 표시와 함께 보입니다. 내가 쓴 댓글은 ✎로 고치고 ×로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 댓글 표시가 붙습니다.

+

댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 Enter는 글자 확정만 하고 보내지 않습니다.

diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index f95ec88..ac55de8 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -104,5 +104,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index d170595..123be6c 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index 1d8cb60..9dc742a 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -265,6 +265,11 @@ + +
@@ -491,5 +496,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index 3bd5c30..b9abc13 100644 --- a/app/modules/project/templates/project/trash.html +++ b/app/modules/project/templates/project/trash.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -70,5 +70,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/static/project.css b/app/static/project.css index e14fd36..e5fc976 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2116,3 +2116,44 @@ textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); } width: 16px; height: 16px; border: 1px solid rgba(0, 0, 0, .2); border-radius: 4px; background: linear-gradient(to top right, transparent calc(50% - 1px), #e5484d calc(50% - 1px), #e5484d calc(50% + 1px), transparent calc(50% + 1px)); } + +/* ════════════════════════════════════════════════════════════ + 권한·저장 안전장치(2026-09-30) + ════════════════════════════════════════════════════════════ */ +/* 읽기 전용 안내줄 — 다른 프로젝트에서 연결돼 온 작업(원 소속 권한 없음) */ +.pj-readonly-note { + display: flex; align-items: center; gap: 6px; margin: 4px 0 8px; padding: 7px 10px; + border-radius: 8px; background: #f1f5fb; color: #34507a; font-size: 12.5px; line-height: 1.4; +} +.pj-readonly-note[hidden] { display: none; } +.pj-readonly-note .material-symbols-outlined { font-size: 17px; } +.pj-modal.is-readonly .pj-t-title-input { cursor: default; } +.pj-modal.is-readonly .pj-desc-editor { background: #fafbfc; } +.pj-subtask-row.is-readonly .pj-subtask-check, +.pj-subtask-row.is-readonly .pj-subtask-due, +.pj-subtask-row.is-readonly .pj-subtask-av { cursor: default; opacity: .7; } +/* 이 프로젝트 권한을 잃었을 때 화면 위 안내 */ +.pj-access-lost { + margin: 0 0 10px; padding: 10px 14px; border-radius: 8px; background: #fdecea; color: #a1261b; + font-size: 13px; font-weight: 600; +} +.pj-access-lost a { color: inherit; text-decoration: underline; margin-left: 6px; } +/* 저장 실패 — 눌러서 다시 시도 */ +.pj-autosave-state.is-retry { cursor: pointer; text-decoration: underline dotted; } +/* 작업 창 댓글의 첨부(파일만 있는 댓글도 보이게) */ +.pj-comment-atts { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; } +.pj-comment-att { display: inline-flex; align-items: center; gap: 5px; text-decoration: none; color: var(--pj-ink); } +.pj-comment-att-file { + padding: 4px 8px; border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; font-size: 12.5px; +} +.pj-comment-att-file:hover { background: #f6f7f8; } +.pj-comment-att-img img { + display: block; max-width: 160px; max-height: 120px; border-radius: 6px; border: 1px solid var(--pj-border); + object-fit: cover; +} +/* 첨부 파일 목록에서 댓글에 붙은 파일 표시 */ +.pj-attach-from-comment { + margin-left: 6px; padding: 0 6px; border-radius: 999px; background: #eef0f2; color: #525860; font-size: 11px; +} +/* 댓글 대화창 — 보낼 수 없었던 파일(빈 파일·20MB 초과) */ +.pj-chat-pending-chip.is-failed { border-color: #e5484d; background: #fdecea; color: #a1261b; } diff --git a/app/static/project.js b/app/static/project.js index 3febccb..30bba60 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -13,9 +13,14 @@ if (body !== undefined) opts.body = JSON.stringify(body); const res = await fetch(url, opts); if (!res.ok) { - let msg = res.statusText; - try { msg = (await res.json()).detail || msg; } catch (_) {} - throw new Error(msg); + let msg = res.statusText, detail = null; + try { detail = (await res.json()).detail; } catch (_) {} + if (typeof detail === "string") msg = detail; + else if (detail && detail.message) msg = detail.message; + const err = new Error(msg); + err.status = res.status; // 403(권한 없음)·404 를 일시 오류와 구분하려고 + err.detail = detail; + throw err; } if (res.status === 204) return null; return res.json(); @@ -23,6 +28,17 @@ function el(id) { return document.getElementById(id); } + // 한글 등 입력기 조합 중의 Enter(조합 확정)인지 — 이때는 전송·추가를 하지 않는다. 크롬·엣지는 + // isComposing, 사파리·예전 브라우저는 keyCode 229 로 알려 준다. 조합이 끝난 뒤의 Enter 만 제출. + function isImeEnter(e) { + return !!(e && (e.isComposing || e.keyCode === 229)); + } + // 댓글 한 건을 가리키는 임시 번호 — 같은 댓글을 다시 보내도(응답 유실·연타) 서버가 한 번만 만든다. + function newClientToken() { + try { if (window.crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (_) {} + return Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 12); + } + // ── 확인/알림/입력 창 — 브라우저 기본 창 대신 공용 창(erp-dialog.js). 프로젝트 // 관리 화면의 창 제목은 전부 "KSN 프로그램". 이 파일 안의 alert/confirm/prompt 는 // 아래 함수가 가린다 — confirm/prompt 는 Promise 라서 쓰는 곳은 await 한다. @@ -207,7 +223,14 @@ function isoOf(d) { return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0"); } - function isoToday() { return isoOf(new Date()); } + // 업무 기준 "오늘" = 한국시간(Asia/Seoul, 서머타임 없음 → UTC+9 고정) 날짜. 브라우저가 해외 + // 시간대여도, 한국 오전(UTC 로는 전날)이어도 서버(today_kst)·마감 알림과 같은 날짜를 쓴다. + // 예전 대시보드는 toISOString()(UTC) 날짜라 한국 00~09시에 지연 수가 달랐다. + function kstTodayIso(nowMs) { + const ms = (nowMs == null ? Date.now() : nowMs) + 9 * 3600000; + return new Date(ms).toISOString().slice(0, 10); + } + function isoToday() { return kstTodayIso(); } function dayDiff(iso, baseIso) { const a = new Date(String(iso).slice(0, 10) + "T00:00:00"), b = new Date(baseIso + "T00:00:00"); return Math.round((a - b) / 86400000); @@ -1326,6 +1349,24 @@ }; return map[ext] || "📎"; } + // 작업 창 댓글 목록의 댓글별 첨부(댓글 대화창과 같은 모양) — 이미지는 작은 미리보기(inline, + // 서버가 안전한 이미지 형식만 그대로 보낸다), 그 밖엔 아이콘 + 파일명(다운로드). 파일명은 이스케이프. + // 다운로드·미리보기 주소는 서버가 매번 작업 권한을 다시 검사한다. + function commentAttachmentsHtml(atts) { + if (!atts || !atts.length) return ""; + return '
' + atts.map(function (a) { + const isImg = (a.content_type || "").indexOf("image/") === 0; + const name = escapeHtml(a.filename || "파일"); + if (isImg) { + return '' + + '' + name + ''; + } + return '' + + '' + chatFileIcon(a.filename) + "" + + '' + name + ""; + }).join("") + "
"; + } function initCommentsChat(getTaskTitle) { const modal = el("pj-modal-comments"); if (!modal) return null; @@ -1348,6 +1389,7 @@ // ── 보내기 전 대기 중인 파일(파일 선택/붙여넣기로 담은 것들) ── let pendingFiles = []; + let pendingErrors = new WeakMap(); // 파일 → 보낼 수 없었던 이유(빨간 표시) function renderPending() { const box = el("pj-cm-pending"); if (!box) return; @@ -1355,14 +1397,17 @@ box.hidden = false; box.innerHTML = pendingFiles.map(function (f, i) { const icon = f.type && f.type.indexOf("image/") === 0 ? "🖼️" : chatFileIcon(f.name); - return '' + + const err = pendingErrors.get(f); + return '" + '' + icon + "" + - '' + escapeHtml(f.name) + "" + + '' + escapeHtml(f.name) + (err ? " (" + escapeHtml(err) + ")" : "") + "" + ''; }).join(""); box.querySelectorAll("button[data-idx]").forEach(function (btn) { btn.addEventListener("click", function () { pendingFiles.splice(parseInt(btn.dataset.idx, 10), 1); + chatToken = null; renderPending(); }); }); @@ -1371,6 +1416,7 @@ if (fileInput) fileInput.addEventListener("change", function () { Array.prototype.slice.call(fileInput.files).forEach(function (f) { pendingFiles.push(f); }); fileInput.value = ""; + chatToken = null; renderPending(); }); const cmInput = el("pj-cm-input"); @@ -1390,7 +1436,7 @@ if (file) { pendingFiles.push(file); handled = true; } } } - if (handled) { e.preventDefault(); renderPending(); } + if (handled) { e.preventDefault(); chatToken = null; renderPending(); } }); // ── 댓글에 딸린 첨부(이미지/파일) 렌더 — 이미지는 썸네일, 그 외는 아이콘+파일명 ── @@ -1449,6 +1495,20 @@ ]); const comments = cRes.comments || []; const feats = cRes.features || {}; + // 읽기 전용(연결된 프로젝트에서 본 작업) — 입력칸·답글·반응·삭제를 감춘다(서버도 거절). + const readOnly = cRes.access === "read"; + const form = modal.querySelector(".pj-comment-form"); + if (form) form.hidden = readOnly; + if (readOnly) feats.reactions = false; + let roNote = el("pj-cm-readonly"); + if (!roNote && form) { + roNote = document.createElement("div"); + roNote.id = "pj-cm-readonly"; + roNote.className = "pj-readonly-note"; + roNote.textContent = "다른 프로젝트에서 연결된 작업이라 댓글은 읽기만 할 수 있습니다."; + form.parentNode.insertBefore(roNote, form); + } + if (roNote) roNote.hidden = !readOnly; const byId = {}; comments.forEach(function (c) { byId[c.id] = c; }); // 완료 이력은 가운데 정렬 안내 줄로, 댓글과 시간순으로 섞는다. @@ -1480,7 +1540,7 @@ li.className = "pj-chat-msg" + (mine ? " mine" : " other"); const atts = attByComment[c.id] || []; const attsHtml = atts.length - ? '
' + atts.map(function (a) { return attachmentHtml(a, me); }).join("") + "
" + ? '
' + atts.map(function (a) { return attachmentHtml(a, readOnly ? "" : me); }).join("") + "
" : ""; const parent = c.parent_id ? byId[c.parent_id] : null; const quoteHtml = parent @@ -1492,12 +1552,12 @@ quoteHtml + '
' + (c.body ? '
' : "") + - commentHoverBarHtml(feats, { reply: true }) + + commentHoverBarHtml(feats, { reply: !readOnly }) + "
" + attsHtml + '
' + reactionRowHtml(c, me, feats.reactions) + "
" + '' + - (mine ? '' : "") + + (mine && !readOnly ? '' : "") + '' + (c.created_at || "").slice(0, 16).replace("T", " ") + "" + ""; // 상대방 댓글 — 카톡처럼 왼쪽에 프로필 아이콘, 그 옆에 이름 + 말풍선. @@ -1515,7 +1575,7 @@ }); const replyBtn = li.querySelector("[data-reply]"); if (replyBtn) replyBtn.addEventListener("click", function () { setReplyTo(c); }); - if (mine) { + if (mine && !readOnly) { li.querySelector(".pj-chat-del").addEventListener("click", async function () { if (!(await confirm("이 댓글을 삭제할까요? 첨부된 파일도 함께 삭제됩니다."))) return; try { @@ -1562,6 +1622,8 @@ el("pj-cm-task-id").value = taskId; el("pj-cm-title").textContent = (getTaskTitle && getTaskTitle(taskId)) || "댓글"; pendingFiles = []; + pendingErrors = new WeakMap(); + chatToken = null; renderPending(); setReplyTo(null); openModal(modal); @@ -1591,45 +1653,85 @@ if (e.target.closest && e.target.closest(".pj-cmt-badge[data-task-id]")) { e.preventDefault(); e.stopPropagation(); } }, true); + // 보내기 — 파일이 있으면 본문·파일을 한 요청(/comments/files)으로 보내 서버가 한 트랜잭션에 만든다. + // 한 파일이라도 문제면(빈 파일·20MB 초과) 댓글을 만들지 않고 그 파일만 빨갛게 표시한다 — 빼고 다시 + // 보내면 된다. 네트워크 오류·서버 오류면 입력·파일이 그대로 남아 다시 보낼 수 있고, 같은 client_token + // 이라 응답만 못 받은 경우에도 두 번 만들어지지 않는다. 예전엔 댓글을 먼저 만들고 파일을 따로 올려, + // 업로드가 실패하면 빈 댓글이 남고 고른 파일도 사라졌다. + let chatSending = false; + let chatToken = null; el("pj-cm-send").addEventListener("click", async function () { const taskId = el("pj-cm-task-id").value; const inp = el("pj-cm-input"); const bodyText = inp.value.trim(); - if (!taskId || (!bodyText && !pendingFiles.length)) return; + if (!taskId || (!bodyText && !pendingFiles.length) || chatSending) return; const filesToSend = pendingFiles.slice(); + chatSending = true; + chatToken = chatToken || newClientToken(); + const sendBtn = el("pj-cm-send"); + sendBtn.disabled = true; try { - const res = await api("POST", "/project/api/tasks/" + taskId + "/comments", { - body: bodyText, has_attachment: filesToSend.length > 0, mentions: takeMentions(inp), - parent_id: replyTo ? replyTo.id : undefined, - }); - setReplyTo(null); - const commentId = res.comment.id; - for (let i = 0; i < filesToSend.length; i++) { + let res; + if (filesToSend.length) { const fd = new FormData(); - fd.append("file", filesToSend[i]); - fd.append("comment_id", String(commentId)); - try { - const r = await fetch("/project/api/tasks/" + taskId + "/attachments", { method: "POST", body: fd }); - if (!r.ok) { - let m = r.statusText; - try { m = (await r.json()).detail || m; } catch (_) {} - showToast("파일 업로드 실패(" + filesToSend[i].name + "): " + m, "error"); - } - } catch (_) { showToast("파일 업로드 실패: " + filesToSend[i].name, "error"); } + fd.append("body", bodyText); + fd.append("mentions", JSON.stringify(takeMentions(inp))); + fd.append("client_token", chatToken); + if (replyTo) fd.append("parent_id", String(replyTo.id)); + filesToSend.forEach(function (f) { fd.append("files", f, f.name || "file"); }); + const r = await fetch("/project/api/tasks/" + taskId + "/comments/files", { method: "POST", body: fd }); + let data = null; + try { data = await r.json(); } catch (_) {} + if (!r.ok) { + const d = data && data.detail; + const err = new Error(typeof d === "string" ? d : (d && d.message) || ("요청 실패 (" + r.status + ")")); + err.status = r.status; + err.failed = (d && d.failed) || []; + throw err; + } + res = data; + } else { + res = await api("POST", "/project/api/tasks/" + taskId + "/comments", { + body: bodyText, mentions: takeMentions(inp), client_token: chatToken, + parent_id: replyTo ? replyTo.id : undefined, + }); } + chatToken = null; + setReplyTo(null); pendingFiles = []; + pendingErrors = new WeakMap(); renderPending(); inp.value = ""; clearMentions(inp); + if (res && res.mention_skipped && res.mention_skipped.length) { + showToast("태그하지 못한 사람(이 작업을 볼 수 없음): " + res.mention_skipped.map(idOf).join(", "), "error"); + } const n = await renderChat(taskId); if (n !== null) { markSeen(taskId, n); syncBadge(taskId, n); } - } catch (e) { alert("등록 실패: " + e.message); } + } catch (e) { + if (e.failed && e.failed.length) { + // 문제 파일만 표시 — 나머지는 그대로 두고, 빼거나 바꾼 뒤 다시 보낸다. + e.failed.forEach(function (f) { + const file = filesToSend[parseInt(f.index, 10)]; + if (file) pendingErrors.set(file, f.reason || "실패"); + }); + renderPending(); + } + if (e.status && e.status < 500) chatToken = null; // 거절된 요청은 다음에 새로 보낸다 + showToast("등록 실패: " + e.message + " — 입력과 파일은 그대로 남아 있습니다.", "error"); + } finally { + chatSending = false; + sendBtn.disabled = false; + } }); + el("pj-cm-input").addEventListener("input", function () { chatToken = null; }); el("pj-cm-input").addEventListener("keydown", function (e) { + if (isImeEnter(e)) return; // 한글 조합 확정 Enter 는 전송하지 않는다 if (e.key === "Enter") { e.preventDefault(); el("pj-cm-send").click(); } }); cmtChat = { open: open, wireBadge: wireBadge }; + if (window.__PJ_TEST__) window.__pjChat = cmtChat; // 자동 테스트 전용 return cmtChat; } @@ -1641,14 +1743,34 @@ // · 댓글 : "@아이디 " 평문 + 이메일을 따로 기억(전송 시 함께 보냄) // 으로 들어간다. 태그된 사람은 수신함(/project/inbox)에서 그 업무를 본다. // ════════════════════════════════════════════════════════════ - let mentionUsersCache = null; - async function mentionUsers() { - if (mentionUsersCache) return mentionUsersCache; + // 전체 등록 사용자(댓글 속 "@아이디" 를 칩으로 그릴 때) — 한 번만 받는다. + let allUsersCache = null; + async function allUsers() { + if (allUsersCache) return allUsersCache; try { const res = await api("GET", "/project/api/all-users"); - mentionUsersCache = res.users || []; - } catch (_) { mentionUsersCache = []; } - return mentionUsersCache; + allUsersCache = res.users || []; + } catch (_) { return []; } // 실패는 기억하지 않는다(다음에 다시) + return allUsersCache; + } + // @태그 후보 — 지금 쓰는 작업(댓글 대화창 또는 작업 창)을 볼 수 있는 사람만(서버가 거른다). + // 태그해도 볼 수 없는 사람에게 작업 정보가 가거나 권한이 생기지 않게(서버도 저장 때 다시 거른다). + const mentionUsersCache = {}; + function mentionTaskId() { + const cm = el("pj-modal-comments"); + if (cm && !cm.hidden && el("pj-cm-task-id") && el("pj-cm-task-id").value) return el("pj-cm-task-id").value; + const t = el("pj-t-id"); + return t && t.value ? t.value : ""; + } + async function mentionUsers() { + const tid = mentionTaskId(); + if (!tid) return allUsers(); + if (mentionUsersCache[tid]) return mentionUsersCache[tid]; + try { + const res = await api("GET", "/project/api/all-users?task_id=" + encodeURIComponent(tid)); + mentionUsersCache[tid] = res.users || []; + } catch (_) { return []; } + return mentionUsersCache[tid]; } // 메뉴는 화면에 하나만 띄운다(설명란/댓글/채팅이 번갈아 쓴다). @@ -2055,7 +2177,7 @@ let mentionTokenMap = null; async function ensureMentionTokens() { if (mentionTokenMap) return mentionTokenMap; - const users = await mentionUsers(); + const users = await allUsers(); const map = {}; users.forEach(function (u) { const token = "@" + capName(u.id || String(u.email || "").split("@")[0]); @@ -2322,7 +2444,8 @@ const data = JSON.parse(dataEl.textContent); let tasks = data.tasks || []; const priorityLabels = data.priorityLabels || {}; - const today = data.today || ""; + // 오늘 = 한국시간 날짜를 그때그때(화면을 밤새 열어 두어도 자정이 지나면 바뀐다). + const todayNow = kstTodayIso; const me = (root.dataset.me || "").toLowerCase(); const table = el("pj-mytasks-table"); @@ -2417,7 +2540,7 @@ function passFilter(t) { if (filter === "open" && t.completed_at) return false; if (filter === "done" && !t.completed_at) return false; - return taskMatchesFilter(t, mtFilter, me, today); + return taskMatchesFilter(t, mtFilter, me, todayNow()); } // 최상위 업무만 — 하위 업무(parent_task_id 있음)는 render() 에서 해당 @@ -2584,7 +2707,7 @@ const openN = tasks.filter(function (t) { return !t.completed_at; }).length; const overdueN = tasks.filter(function (t) { - return !t.completed_at && t.due_date && t.due_date.slice(0, 10) < today; + return !t.completed_at && t.due_date && t.due_date.slice(0, 10) < todayNow(); }).length; if (summaryEl) { summaryEl.innerHTML = @@ -2608,12 +2731,17 @@ render(); // 8초 주기 동기화 — 다른 사람이 내 업무를 바꾸면 목록을 다시 받는다. + // 성공하면 true — 실패(false)면 initLiveRefresh 가 같은 버전을 다음 주기에 다시 시도한다. + let syncSeq = 0; softSyncProjectRef = async function () { + const seq = ++syncSeq; try { const res = await api("GET", "/project/api/my-tasks"); + if (seq !== syncSeq) return true; // 더 나중에 시작한 동기화가 있다 — 늦은 응답은 버린다 tasks = res.tasks || []; render(); - } catch (_) {} + return true; + } catch (_) { return false; } }; } @@ -2802,7 +2930,7 @@ const FILTER_KEY = "pj_filter_" + projectId; let taskFilter = Object.assign({}, TASK_FILTER_DEFAULT); try { Object.assign(taskFilter, JSON.parse(localStorage.getItem(FILTER_KEY) || "{}")); } catch (_) {} - const todayIso = data.today || localIso(new Date()); + const todayNowP = kstTodayIso; // 한국시간 오늘(그때그때) function scopeTasks() { return viewScope === "project" ? tasks.filter(function (t) { return t.context_project_id === projectId; }) @@ -2810,6 +2938,7 @@ } // 모든 뷰가 이 함수로 업무를 받는다 — 스코프 → 필터 → 정렬 순. function visibleTasks() { + const todayIso = todayNowP(); const rows = scopeTasks().filter(function (t) { return taskMatchesFilter(t, taskFilter, me, todayIso); }); return sortTasksBy(rows, taskFilter.sort); } @@ -4371,7 +4500,7 @@ const done = !sub.completed_at; try { const res = await api("PUT", "/project/api/tasks/" + sub.id, { completed: done }); - sub.completed_at = (res && res.task && res.task.completed_at) || (done ? todayIso : null); + sub.completed_at = (res && res.task && res.task.completed_at) || (done ? todayNowP() : null); t.subtask_done = Math.max(0, (t.subtask_done || 0) + (done ? 1 : -1)); renderBoard(); } catch (err) { showToast("변경 실패: " + err.message, "error"); } @@ -5029,7 +5158,7 @@ if (!root) return; root.innerHTML = ""; const vis = visibleTasks().filter(function (t) { return !t.parent_task_id; }); // 하위 업무는 보드에도 안 보이므로 제외 - const today = new Date().toISOString().slice(0, 10); + const today = kstTodayIso(); // UTC 날짜(toISOString)면 한국 오전에 하루 어긋났다 const completed = vis.filter(function (t) { return !!t.completed_at; }); const incomplete = vis.filter(function (t) { return !t.completed_at; }); const overdue = incomplete.filter(function (t) { return t.due_date && t.due_date.slice(0, 10) < today; }); @@ -5238,67 +5367,139 @@ // 담당자·섹션·우선순위·마감일: 바꾸는 즉시. 새 작업은 제목이 생기는 순간 만든다. // 요청은 한 줄로 세워(saveChain) 순서가 뒤바뀌지 않게 한다. 보낼 값과 작업 id 는 // 부르는 순간 잡아 두므로, 저장 도중 다른 작업을 열어도 엉뚱한 작업에 쓰지 않는다. + // + // 작업 창 세대(taskGen) — 창을 새로 열 때마다(같은 작업을 다시 열어도, A→B→A) 1 올린다. 비동기 + // 응답(상세·하위 작업·연결·첨부·댓글·담당자 후보·저장 결과)은 요청을 보낼 때의 세대를 잡아 두고, + // 돌아왔을 때 세대가 바뀌었으면 화면·상태에 반영하지 않는다(늦은 A 응답이 B 화면을 덮던 문제). + // 저장 실패(failedFields)는 창을 닫거나 다른 작업으로 넘어갈 때 다시 시도하고, 그래도 실패하면 + // "버리고 닫기 / 계속 편집"을 묻는다 — 실패를 모른 채 닫혀 입력이 사라지던 문제. const autoStateEl = el("pj-autosave-state"); - let saveChain = Promise.resolve(); + let saveChain = Promise.resolve(true); let lastSaved = { title: "", desc: "" }; let descTimer = null; let creatingTask = null; + let taskGen = 0; + let savingCount = 0; + const failedFields = new Set(); + let taskReadOnly = false; + const FIELD_LABEL = { title: "제목", desc: "설명", assignee: "담당자", stage: "섹션", priority: "우선순위", due: "마감일", create: "새 작업" }; function setAutoState(s) { if (!autoStateEl) return; autoStateEl.dataset.state = s || ""; - autoStateEl.textContent = s === "saving" ? "저장 중…" : s === "saved" ? "저장됨" : s === "error" ? "저장 실패" : ""; + autoStateEl.textContent = s === "saving" ? "저장 중…" : s === "saved" ? "저장됨" + : s === "error" ? "저장 실패 · 다시 시도" : ""; + autoStateEl.title = s === "error" ? "눌러서 저장 다시 시도(" + failedLabels() + ")" : ""; + autoStateEl.classList.toggle("is-retry", s === "error"); } + function failedLabels() { + return Array.from(failedFields).map(function (k) { return FIELD_LABEL[k] || k; }).join("·"); + } + if (autoStateEl) autoStateEl.addEventListener("click", function () { + if (autoStateEl.dataset.state === "error") retryFailedSaves(); + }); function resetAutoSave() { clearTimeout(descTimer); descTimer = null; + failedFields.clear(); lastSaved = { title: el("pj-t-title").value.trim(), desc: descEditor ? descEditor.getHtml() : "", }; setAutoState(""); } + // 사용자가 "버리고 닫기"를 고른 경우에만 — 실패한 초안·예약된 저장을 버리고, 아직 돌아오지 않은 + // 저장 결과도 이 창에 반영되지 않게 세대를 넘긴다. + function discardTaskEdits() { + clearTimeout(descTimer); + descTimer = null; + failedFields.clear(); + taskGen++; + lastSaved = { title: el("pj-t-title").value.trim(), desc: descEditor ? descEditor.getHtml() : "" }; + setAutoState(""); + } + function retryFailedSaves() { + if (taskReadOnly) return saveChain; + Array.from(failedFields).forEach(function (k) { + if (k === "create") saveField("title"); + else saveField(k); + }); + return saveChain; + } + // 저장되지 않은 것이 있는지 — 페이지를 떠날 때 경고용(저장된 상태엔 경고하지 않는다). + function hasUnsavedTaskEdits() { + if (taskModal.hidden || taskReadOnly) return false; + if (failedFields.size || descTimer || savingCount > 0 || creatingTask) return true; + if (descEditor && descEditor.isUploading()) return true; + if (!el("pj-t-id").value) return !!el("pj-t-title").value.trim(); + return el("pj-t-title").value.trim() !== lastSaved.title || + (!!descEditor && descEditor.getHtml() !== lastSaved.desc); + } + window.addEventListener("beforeunload", function (e) { + if (!hasUnsavedTaskEdits()) return; + e.preventDefault(); + e.returnValue = ""; + }); function assigneePayload() { const sel = el("pj-t-assignee"); const opt = sel.selectedOptions[0]; return { assignee_email: sel.value, assignee_name: opt ? (opt.dataset.name || "") : "" }; } + // 반환: Promise — 이 칸이 저장됐으면(또는 보낼 게 없으면) true, 실패면 false. function saveField(key) { + if (taskReadOnly) return Promise.resolve(true); const id = el("pj-t-id").value; - if (!id) return key === "title" ? createTaskFromPanel() : Promise.resolve(); + if (!id) return key === "title" ? createTaskFromPanel() : Promise.resolve(true); + const gen = taskGen; let body = null; if (key === "title") { const t = el("pj-t-title").value.trim(); - if (!t) { el("pj-t-title").value = lastSaved.title; fitTitleHeight(); return Promise.resolve(); } - if (t === lastSaved.title) return Promise.resolve(); + if (!t) { el("pj-t-title").value = lastSaved.title || ""; fitTitleHeight(); return Promise.resolve(true); } + if (t === lastSaved.title) return Promise.resolve(true); body = { title: t }; lastSaved.title = t; } else if (key === "desc") { - if (!descEditor) return Promise.resolve(); - if (descEditor.isUploading()) { scheduleDescSave(); return Promise.resolve(); } // 이미지 올라간 뒤 다시 + if (!descEditor) return Promise.resolve(true); + if (descEditor.isUploading()) { scheduleDescSave(); return Promise.resolve(true); } // 이미지 올라간 뒤 다시 const html = descEditor.getHtml(); - if (html === lastSaved.desc) return Promise.resolve(); + if (html === lastSaved.desc) return Promise.resolve(true); body = { description: html }; lastSaved.desc = html; } else if (key === "assignee") { body = assigneePayload(); } else if (key === "stage") { const s = parseInt(el("pj-t-stage").value, 10); - if (!s) return Promise.resolve(); + if (!s) return Promise.resolve(true); body = { stage_id: s }; } else if (key === "priority") { body = { priority: el("pj-t-priority").value }; } else if (key === "due") { body = { due_date: el("pj-t-due").value || null }; } - if (!body) return Promise.resolve(); + if (!body) return Promise.resolve(true); setAutoState("saving"); + savingCount++; saveChain = saveChain.then(async function () { + let res; + try { + res = await api("PUT", "/project/api/tasks/" + id, body); + } catch (e) { + if (gen === taskGen) { + if (key === "title") lastSaved.title = null; // 다음에 다시 시도하도록 + if (key === "desc") lastSaved.desc = null; + failedFields.add(key); + setAutoState("error"); + } + showToast("저장 실패(" + (FIELD_LABEL[key] || key) + "): " + e.message, "error"); + savingCount--; + return false; + } + // 여기부터는 저장 성공 — 화면 반영 중 오류가 나도 "저장 실패"로 표시하지 않는다. try { const wasDone = !!(currentTaskData && currentTaskData.completed_at); - const res = await api("PUT", "/project/api/tasks/" + id, body); mergeTask(res.task); - const stillOpen = !taskModal.hidden && el("pj-t-id").value === String(id); - if (stillOpen) { + // 같은 창(세대)일 때만 화면·상태에 반영한다 — 그 사이 다른 작업을 열었거나 버렸으면 건드리지 않는다. + if (gen === taskGen && !taskModal.hidden) { + failedFields.delete(key); currentTaskData = res.task; // 섹션을 옮기면 서버가 섹션 기본 담당자를 넣거나 완료 처리할 수 있다 — 화면도 맞춘다. if (key === "stage") { @@ -5311,24 +5512,27 @@ // 완료 섹션으로 옮기거나 빼면 완료 이력 줄이 생기거나 사라진다. if (wasDone !== !!res.task.completed_at) loadComments(id); if (res.task._newly_assigned) loadTaskExtras(res.task); // 새 담당자가 협업자로 들어온다 + if (res.mention_skipped && res.mention_skipped.length) warnMentionSkipped(res.mention_skipped); + setAutoState(failedFields.size ? "error" : "saved"); } if (key !== "desc") refreshActiveView(); - setAutoState("saved"); - } catch (e) { - if (key === "title") lastSaved.title = null; // 다음에 다시 시도하도록 - if (key === "desc") lastSaved.desc = null; - setAutoState("error"); - showToast("저장 실패: " + e.message, "error"); - } + } catch (err) { + console.error("저장 후 화면 반영 오류", err); // 저장 자체는 됐다 + } finally { savingCount--; } + return true; }); return saveChain; } + function warnMentionSkipped(emails) { + showToast("태그하지 못한 사람(이 작업을 볼 수 없음): " + emails.map(idOf).join(", "), "error"); + } // 새 작업 — 제목이 처음 생기는 순간 지금 칸 값으로 만든 뒤, 기존 작업 화면 // (댓글·첨부·하위 작업 등)으로 바꿔 연다. 그 사이 더 입력한 내용은 이어서 저장한다. function createTaskFromPanel() { const title = el("pj-t-title").value.trim(); - if (!title) return Promise.resolve(); + if (!title) return Promise.resolve(true); if (creatingTask) return creatingTask; + const gen = taskGen; const sentDesc = descEditor ? descEditor.getHtml() : ""; const payload = Object.assign({ title: title, @@ -5339,23 +5543,28 @@ const stageVal = parseInt(el("pj-t-stage").value, 10); if (stageVal) payload.stage_id = stageVal; setAutoState("saving"); + savingCount++; creatingTask = saveChain = saveChain.then(async function () { try { const res = await api("POST", "/project/api/projects/" + projectId + "/tasks", payload); mergeTask(res.task); refreshActiveView(); - if (!taskModal.hidden && !el("pj-t-id").value) { + if (gen === taskGen && !taskModal.hidden && !el("pj-t-id").value) { + failedFields.delete("create"); const nowTitle = el("pj-t-title").value.trim(); const nowDesc = descEditor ? descEditor.getHtml() : ""; - openTaskModal(res.task); + openTaskModalNow(res.task); // 만든 작업 화면으로 — 방금 만든 것이라 저장 확인은 필요 없다 if (nowTitle && nowTitle !== res.task.title) { el("pj-t-title").value = nowTitle; fitTitleHeight(); saveField("title"); } if (descEditor && nowDesc !== sentDesc) { descEditor.setHtml(nowDesc); saveField("desc"); } + if (res.mention_skipped && res.mention_skipped.length) warnMentionSkipped(res.mention_skipped); + setAutoState("saved"); } - setAutoState("saved"); + return true; } catch (e) { - setAutoState("error"); + if (gen === taskGen) { failedFields.add("create"); setAutoState("error"); } showToast("작업 만들기 실패: " + e.message, "error"); - } finally { creatingTask = null; } + return false; + } finally { creatingTask = null; savingCount--; } }); return creatingTask; } @@ -5363,13 +5572,41 @@ clearTimeout(descTimer); descTimer = setTimeout(function () { descTimer = null; saveField("desc"); }, 1200); } - // 창을 닫거나 다른 작업으로 넘어가기 직전 — 아직 안 보낸 제목·설명을 보낸다. - function flushAutoSave() { - if (taskModal.hidden) return saveChain; + // 창을 닫거나 다른 작업으로 넘어가기 직전 — 이미지 업로드·만들기가 끝나길 기다리고, 아직 안 보낸 + // 제목·설명과 실패했던 칸을 다시 보낸 뒤 모든 저장이 끝날 때까지 기다린다. + // 반환: Promise — 남은 실패가 없으면 true. + async function flushAutoSave() { + if (taskModal.hidden || taskReadOnly) { await saveChain; return true; } + const gen = taskGen; clearTimeout(descTimer); descTimer = null; - if (el("pj-t-id").value) { saveField("title"); saveField("desc"); } - return saveChain; + if (descEditor && descEditor.isUploading()) { + setAutoState("saving"); + await descEditor.whenIdle(); + } + if (creatingTask) await creatingTask; + if (gen !== taskGen) return true; // 기다리는 사이 창이 바뀌었다(버리기 등) + if (el("pj-t-id").value) { + saveField("title"); + saveField("desc"); + Array.from(failedFields).forEach(function (k) { if (k !== "title" && k !== "desc" && k !== "create") saveField(k); }); + } else if (el("pj-t-title").value.trim()) { + saveField("title"); // 새 작업 — 제목이 있으면 만든다 + } + await saveChain; + return gen !== taskGen || failedFields.size === 0; + } + // 닫기·다른 작업 열기 전 — 저장이 끝나야 넘어간다. 끝내 실패하면 사용자가 고른다. + async function settleBeforeLeave() { + if (taskModal.hidden || taskReadOnly) return true; + if (await flushAutoSave()) return true; + const discard = await confirm( + "저장하지 못한 내용이 있습니다(" + failedLabels() + ").\n" + + "버리고 넘어갈까요? '계속 편집'을 고르면 창이 그대로 남고, 위쪽 '저장 실패 · 다시 시도'로 다시 저장할 수 있습니다.", + { okText: "버리고 넘어가기", cancelText: "계속 편집" }); + if (!discard) return false; + discardTaskEdits(); + return true; } el("pj-t-title").addEventListener("blur", function () { saveField("title"); }); el("pj-t-assignee").addEventListener("change", function () { saveField("assignee"); }); @@ -5393,7 +5630,8 @@ if (taskModal.hidden || taskClosing) return; taskClosing = true; try { - await flushAutoSave(); + if (!(await settleBeforeLeave())) return; // 계속 편집 — 창과 입력을 그대로 둔다 + taskGen++; // 닫은 창의 늦은 응답은 버린다 closeSlidePanel(taskModal); } finally { taskClosing = false; } } @@ -5473,26 +5711,37 @@ } async function loadTaskExtras(task) { - if (!task || (!subtaskBlock && !linksBlock)) return; + if (!task) return; + const gen = taskGen; try { const res = await api("GET", "/project/api/tasks/" + task.id); + // 늦게 온 A 응답이 지금 열린 B(또는 다시 연 A)의 하위 작업·연결 대상을 바꾸지 않게. + if (gen !== taskGen) return; const detail = res.task; - if (currentTaskId === task.id) showFollowers(task, detail.followers); + if (detail.access === "read" && !taskReadOnly) applyTaskReadOnly(true, detail); + showFollowers(task, detail.followers); if (subtaskBlock) { subtaskBlock.setContext({ taskId: task.id, projectId: task.project_id, canDelete: canDelete, + readOnly: taskReadOnly, onOpen: function (sub) { openTaskById(sub.id); }, }); subtaskBlock.render(detail.subtasks || []); } if (linksBlock) { linksBlock.setContext({ - taskId: task.id, projectId: task.project_id, - onChange: function () { loadTaskExtras(task); }, + taskId: task.id, projectId: task.project_id, readOnly: taskReadOnly, + onChange: function () { if (gen === taskGen) loadTaskExtras(task); }, }); linksBlock.render(detail.links || []); } - } catch (_) { /* 조용히 무시 — 본편집은 계속 가능해야 한다 */ } + } catch (e) { + // 권한이 없어졌으면(403) 편집을 멈추고 알린다. 그 밖엔 조용히 — 본편집은 계속 가능해야 한다. + if (gen === taskGen && e.status === 403) { + applyTaskReadOnly(true, null); + showToast("이 작업을 볼 권한이 없어졌습니다: " + e.message, "error"); + } + } } // 단계 select 를 해당 업무가 속한 프로젝트의 단계로 채운다(전체 뷰에서 타 프로젝트 업무 편집 대비). @@ -5508,10 +5757,12 @@ // (전체 뷰/좌측 트리에서 타 프로젝트 업무를 열 때 담당자 옵션이 비어 보이는 문제 방지). async function fillAssigneeSelect(projId, currentEmail) { const sel = el("pj-t-assignee"); + const gen = taskGen; let list = members; if (projId != null && projId !== projectId) { try { list = (await api("GET", "/project/api/projects/" + projId + "/members")).members || []; } catch (_) { list = []; } + if (gen !== taskGen) return; // 그 사이 다른 작업 창 — 그 창의 담당자 칸을 덮지 않는다 } const emails = list.map(function (m) { return m.user_email; }); // 지금 담당자가 멤버 목록에 없어도(프로젝트를 만든 owner, 멤버에서 빠진 사람) @@ -5525,9 +5776,62 @@ sel.value = currentEmail || ""; } - function openTaskModal(task, presetStageId) { - // 다른 작업으로 바로 넘어가는 경우 — 보낼 값·id 를 지금 잡아 먼저 저장 요청. - flushAutoSave(); + // 작업 창 열기(보드·목록·캘린더·하위 작업 등 모든 곳). 다른 작업이 열려 있으면 그 창의 저장이 + // 끝나야(또는 사용자가 버리기로 해야) 넘어간다 — 저장 실패를 모른 채 넘어가 입력이 사라지지 않게. + // 같은 작업을 다시 누르면 그대로 둔다(쓰던 내용 유지). + let opening = null; + async function openTaskModal(task, presetStageId) { + if (opening) return opening; + opening = (async function () { + if (!taskModal.hidden) { + const curId = el("pj-t-id").value; + if (task && curId && String(task.id) === curId) return true; + if (!(await settleBeforeLeave())) return false; + } + openTaskModalNow(task, presetStageId); + return true; + })(); + try { return await opening; } finally { opening = null; } + } + + // 읽기 전용(연결된 프로젝트에서 연 작업·권한 회수) — 입력을 막고 안내줄을 보인다. 서버도 거절한다. + function applyTaskReadOnly(ro, detail) { + taskReadOnly = !!ro; + if (ro) { failedFields.clear(); clearTimeout(descTimer); descTimer = null; setAutoState(""); } + el("pj-t-title").readOnly = !!ro; + const desc = el("pj-t-desc"); + if (desc) desc.contentEditable = ro ? "false" : "true"; + ["pj-t-assignee", "pj-t-stage", "pj-t-priority", "pj-t-due-btn"].forEach(function (id) { + const x = el(id); if (x) x.disabled = !!ro; + }); + taskModal.classList.toggle("is-readonly", !!ro); + const upBtn = document.querySelector("#pj-attach-block .pj-upload-btn"); + if (upBtn) upBtn.hidden = !!ro; + const fmtbar = el("pj-desc-fmtbar"); + if (fmtbar) fmtbar.hidden = !!ro; + const note = el("pj-t-readonly"); + if (note) { + note.hidden = !ro; + const home = el("pj-t-readonly-home"); + if (home) home.textContent = (detail && detail.project_name) || (currentTaskData && currentTaskData.project_name) || "원 소속 프로젝트"; + } + if (ro) { + el("pj-toggle-complete").hidden = true; + el("pj-delete-task").hidden = true; + el("pj-comment-dock").hidden = true; + if (followersRow) followersRow.hidden = true; + } + } + // 이 화면에서 작업의 권한 — 서버 상세가 준 값이 있으면 그것, 없으면 원 소속 프로젝트를 이 화면이 + // 들고 있는지(=지금 관리할 수 있는 프로젝트)로 판단한다(연결돼 온 행은 원 소속이 목록에 없다). + function taskAccessLevel(task) { + if (!task) return "full"; + if (task.access) return task.access; + return projectsMeta.some(function (p) { return String(p.id) === String(task.project_id); }) ? "full" : "read"; + } + + function openTaskModalNow(task, presetStageId) { + taskGen++; el("pj-t-id").value = task ? task.id : ""; el("pj-t-title").value = task ? task.title : ""; if (descEditor) { descEditor.setTaskId(task ? task.id : null); descEditor.setHtml(task ? (task.description || "") : ""); } @@ -5583,10 +5887,11 @@ subtaskBlock.reset(); } if (linksBlock) el("pj-links-block").hidden = !task || isSub; + resetAutoSave(); + applyTaskReadOnly(taskAccessLevel(task) === "read", task); if (task) { loadAttachments(task.id); loadComments(task.id); loadTaskExtras(task); } openSlidePanel(taskModal); fitTitleHeight(); - resetAutoSave(); if (!task) setTimeout(function () { el("pj-t-title").focus(); }, 0); } @@ -5626,10 +5931,9 @@ // 없으면 서버에서 받아 연다(상세 응답엔 parent_title 도 들어 있다). // 팝업에서 다른 업무로 넘어갈 때 아직 안 보낸 제목·설명은 먼저 저장한다. async function openTaskById(id) { - await flushAutoSave(); const t = tasks.find(function (x) { return x.id === id && x.context_project_id === x.project_id; }) || tasks.find(function (x) { return x.id === id; }); - if (t) { openTaskModal(t); return; } + if (t) { openTaskModal(t); return; } // 저장 확인은 openTaskModal 이 한다 try { const res = await api("GET", "/project/api/tasks/" + id); if (res && res.task) openTaskModal(res.task); @@ -5697,18 +6001,22 @@ } async function loadAttachments(taskId) { const ul = el("pj-attach-list"); + const gen = taskGen; ul.innerHTML = "
  • 불러오는 중…
  • "; try { const res = await api("GET", "/project/api/tasks/" + taskId + "/attachments"); + if (gen !== taskGen) return; // 그 사이 다른 작업 창 if (!res.attachments.length) { ul.innerHTML = "
  • 없음
  • "; return; } ul.innerHTML = ""; res.attachments.forEach(function (a) { const li = document.createElement("li"); li.className = "pj-attach-item"; + // 댓글에 붙은 파일은 "댓글" 표시 — 아래 댓글 목록에도 같은 파일이 보인다(같은 파일임을 알 수 있게). li.innerHTML = '' + escapeHtml(a.filename) + "" + + (a.comment_id != null ? '댓글' : "") + '' + fmtSize(a.size_bytes) + "" + - (canManage ? '' : ""); + (canManage && !taskReadOnly ? '' : ""); ul.appendChild(li); }); ul.querySelectorAll(".pj-attach-del").forEach(function (b) { @@ -5738,16 +6046,26 @@ // 마우스를 올리면 오른쪽 위에 반응·답글·수정·삭제 도구 모음. async function loadComments(taskId) { const ul = el("pj-comment-list"); + const gen = taskGen; ul.innerHTML = "
  • 불러오는 중…
  • "; try { const both = await Promise.all([ api("GET", "/project/api/tasks/" + taskId + "/comments"), + api("GET", "/project/api/tasks/" + taskId + "/attachments").catch(function () { return { attachments: [] }; }), ensureMentionTokens(), ]); const res = both[0]; - if (String(currentTaskId) !== String(taskId)) return; // 그 사이 다른 작업을 열었다 + // 그 사이 다른 작업을 열었다(A→B→A 로 같은 작업을 다시 연 경우도 이전 요청은 버린다). + if (gen !== taskGen || String(currentTaskId) !== String(taskId)) return; const comments = res.comments || []; const feats = res.features || {}; + // 댓글에 붙은 파일 — 댓글 대화창과 같은 방식으로 댓글마다 보여 준다(파일만 있는 댓글도 비어 보이지 않게). + const attByComment = {}; + (both[1].attachments || []).forEach(function (a) { + if (a.comment_id == null) return; + (attByComment[a.comment_id] = attByComment[a.comment_id] || []).push(a); + }); + feats._atts = attByComment; // 메모리 업무의 댓글 수 동기화(아이콘 표시용) const tt = tasks.find(function (x) { return String(x.id) === String(taskId); }); if (tt) tt.comment_count = comments.length; @@ -5799,9 +6117,10 @@ escapeHtml(idOf(c.author_email)) + ' ' + escapeHtml(fmtCommentTime(c.created_at)) + "
    " + // 주소 → 새 탭 링크, @태그 → 칩. 나머지 글자는 전부 이스케이프(XSS 안전). - '
    ' + commentBodyHtml(c.body) + "
    " + + (c.body ? '
    ' + commentBodyHtml(c.body) + "
    " : "") + + commentAttachmentsHtml((feats._atts || {})[c.id] || []) + '
    ' + reactionRowHtml(c, me, feats.reactions) + "
    " + - commentHoverBarHtml(feats, { reply: true, edit: mine || isAdmin, del: mine || isAdmin }); + (taskReadOnly ? "" : commentHoverBarHtml(feats, { reply: true, edit: (mine || isAdmin) && !!c.body, del: mine || isAdmin })); wireCommentReactions(item, c, function () { item.querySelector(".pj-react-slot").innerHTML = reactionRowHtml(c, me, feats.reactions); }); @@ -5832,22 +6151,32 @@ attachMentionInput(inp); attachEmojiPicker(inp); attachMentionButton(inp); + let replySending = false; + let replyToken = null; async function send() { const body = inp.value.trim(); - if (!body) return; + if (!body || replySending) return; + replySending = true; + replyToken = replyToken || newClientToken(); try { - await api("POST", "/project/api/tasks/" + taskId + "/comments", - { body: body, parent_id: rootId, mentions: takeMentions(inp) }); + const res = await api("POST", "/project/api/tasks/" + taskId + "/comments", + { body: body, parent_id: rootId, mentions: takeMentions(inp), client_token: replyToken }); + replyToken = null; + if (res.mention_skipped && res.mention_skipped.length) warnMentionSkipped(res.mention_skipped); if (followersTask && !followersRow.hidden && followers.indexOf(me) < 0) { followers.push(me); renderFollowers(); } loadComments(taskId); - } catch (err) { alert("답글 등록 실패: " + err.message); } + } catch (err) { + if (err.status && err.status < 500) replyToken = null; + alert("답글 등록 실패: " + err.message); + } finally { replySending = false; } } form.querySelector("button.pj-btn").addEventListener("click", send); + inp.addEventListener("input", function () { replyToken = null; }); inp.addEventListener("keydown", function (e) { - if (e.isComposing) return; + if (isImeEnter(e)) return; if (e.key === "Enter") { e.preventDefault(); send(); } else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); form.remove(); } }); @@ -5897,28 +6226,48 @@ }); } + // 전송 중엔 다시 보내지 않는다(더블클릭·Enter 연타). 같은 입력의 재전송은 같은 client_token 이라 + // 응답을 못 받고 다시 보내도 서버가 한 번만 만든다. 실패하면 입력은 그대로 남아 다시 보낼 수 있다. + let commentSending = false; + let commentToken = null; async function sendComment() { const inp = el("pj-comment-input"); const body = inp.value.trim(); - if (!currentTaskId || !body) return; + const taskId = currentTaskId; + if (!taskId || !body || commentSending || taskReadOnly) return; + const gen = taskGen; + commentSending = true; + commentToken = commentToken || newClientToken(); + el("pj-comment-send").disabled = true; try { - await api("POST", "/project/api/tasks/" + currentTaskId + "/comments", - { body: body, mentions: takeMentions(inp) }); + const res = await api("POST", "/project/api/tasks/" + taskId + "/comments", + { body: body, mentions: takeMentions(inp), client_token: commentToken }); + commentToken = null; + if (gen !== taskGen) return; // 그 사이 다른 작업 창 — 그 창의 입력칸을 비우지 않는다 inp.value = ""; clearMentions(inp); - loadComments(currentTaskId); + loadComments(taskId); + if (res.mention_skipped && res.mention_skipped.length) warnMentionSkipped(res.mention_skipped); // 댓글을 달면(서버가) 자동 팔로우 — 화면의 팔로워 목록도 맞춘다. if (followersTask && !followersRow.hidden && followers.indexOf(me) < 0) { followers.push(me); renderFollowers(); } - } catch (e) { alert("등록 실패: " + e.message); } + } catch (e) { + if (e.status && e.status < 500) commentToken = null; // 거절(권한·검증)은 새 요청으로 + alert("등록 실패: " + e.message); + } finally { + commentSending = false; + el("pj-comment-send").disabled = false; + } } attachMentionInput(el("pj-comment-input")); attachEmojiPicker(el("pj-comment-input")); attachMentionButton(el("pj-comment-input")); el("pj-comment-send").addEventListener("click", sendComment); + el("pj-comment-input").addEventListener("input", function () { commentToken = null; }); // 내용이 바뀌면 새 댓글 el("pj-comment-input").addEventListener("keydown", function (e) { + if (isImeEnter(e)) return; // 한글 조합 확정 Enter 는 전송하지 않는다 if (e.key === "Enter") { e.preventDefault(); sendComment(); } }); @@ -5952,6 +6301,7 @@ try { await deleteTaskRequest(id); tasks = tasks.filter(function (x) { return String(x.id) !== String(id); }); + discardTaskEdits(); // 지운 작업의 남은 저장·실패 표시는 버린다 closeSlidePanel(taskModal); refreshActiveView(); } catch (e) { alert("삭제 실패: " + e.message); } @@ -6100,24 +6450,81 @@ // 통째로 바꿔 끼워 삭제된 업무도 사라지게 한다(live-version 이 007 // 마이그레이션부터 삭제·세션 변경까지 감지한다). "전체 프로젝트" 스코프의 // 다른 프로젝트 행은 공통 필드(제목·담당자·완료 등)만 따라 고친다. + // + // 이 화면은 "이 프로젝트"·"전체 프로젝트" 어느 범위든 접근 가능한 모든 최상위 프로젝트의 작업을 + // 들고 있으므로, 같은 범위(scope=all)를 통째로 받아 바꿔 끼운다 — 다른 프로젝트의 새 작업·삭제· + // 섹션 변경·프로젝트 변경·권한 회수까지 반영(예전엔 지금 연 프로젝트 것만 받아 다른 프로젝트 행이 + // 남거나 빠졌다). 멀티호밍 작업은 서버가 context_project_id 별로 한 행씩 주므로 그대로 쓴다. + // 필터·정렬·보기·스크롤은 화면 상태라 그대로, 열린 작업 창의 입력도 건드리지 않는다. + // 성공하면 true(반영 완료) — 실패면 false 로 initLiveRefresh 가 다음 주기에 다시 시도. + let syncSeq = 0; + let accessLost = false; softSyncProjectRef = async function () { + if (accessLost) return true; + const seq = ++syncSeq; + let snap; try { - const snap = await api("GET", "/project/api/projects/" + projectId + "/snapshot"); - const fresh = snap.tasks || []; - tasks = tasks.filter(function (t) { return t.context_project_id !== projectId; }); - fresh.forEach(function (t) { - mergeTask(t, { noInsert: true }); // 다른 맥락 행(같은 id)의 공통 필드 갱신 - tasks.push(t); // 이 맥락 행은 서버 값 그대로(context_project_id 포함) - }); - stages = snap.stages || []; - stagesByProject[projectId] = stages; - members = snap.members || []; - fillAssigneeFilter(); - renderMemberList(); - refreshActiveView(); - refreshMyOpenBadge(); - } catch (_) {} + snap = await api("GET", "/project/api/projects/" + projectId + "/snapshot?scope=all"); + } catch (e) { + if (e.status === 403 || e.status === 404) { onProjectAccessLost(); return true; } + return false; + } + if (seq !== syncSeq) return true; // 더 나중에 시작한 동기화가 있다 — 늦은 응답은 버린다 + tasks = snap.tasks || []; + Object.keys(stagesByProject).forEach(function (k) { delete stagesByProject[k]; }); + Object.keys(snap.stages_by_project || {}).forEach(function (k) { + stagesByProject[k] = snap.stages_by_project[k]; + }); + stages = snap.stages || stagesByProject[projectId] || []; + // 보드("전체 프로젝트") 칼럼 이름 — 아는 순서는 그대로, 새 섹션 이름은 뒤에. + const names = []; + Object.keys(stagesByProject).forEach(function (k) { + stagesByProject[k].forEach(function (s) { if (names.indexOf(s.name) < 0) names.push(s.name); }); + }); + const known = boardStages.filter(function (n) { return names.indexOf(n) >= 0; }); + boardStages.splice(0, boardStages.length); + Array.prototype.push.apply(boardStages, known.concat(names.filter(function (n) { return known.indexOf(n) < 0; }))); + if (snap.projects) { // 사이드바·타임라인 그룹 — 권한이 없어진 프로젝트는 빠진다 + projectsMeta.splice(0, projectsMeta.length); + Array.prototype.push.apply(projectsMeta, snap.projects); + renderTree(); + } + if (snap.project) Object.assign(currentProject, snap.project); + members = snap.members || []; + fillAssigneeFilter(); + renderMemberList(); + refreshActiveView(); + refreshMyOpenBadge(); + return true; }; + // 이 프로젝트 권한을 잃었다(멤버에서 빠짐·프로젝트 삭제) — 화면의 작업을 비우고, 열린 작업 창은 + // 저장 없이 닫고(서버가 어차피 거절한다), 이유를 알린다. 새로고침하면 서버가 안내 화면을 보여 준다. + function onProjectAccessLost() { + if (accessLost) return; + accessLost = true; + tasks = []; + discardTaskEdits(); + if (!taskModal.hidden) closeSlidePanel(taskModal); + refreshActiveView(); + const bar = document.createElement("div"); + bar.className = "pj-access-lost"; + bar.innerHTML = "이 프로젝트에 대한 권한이 없어져 작업을 더 볼 수 없습니다. " + + '내 작업으로 이동'; + const head = root.querySelector(".pj-main") || root; + head.insertBefore(bar, head.firstChild); + } + // 자동 테스트(tests/js/project_ui.test.js)에서만 — window.__PJ_TEST__ 가 있을 때 내부 동작을 연다. + if (window.__PJ_TEST__) { + window.__pjProject = { + openTaskModal: openTaskModal, openTaskById: openTaskById, attemptClose: attemptCloseTaskModal, + flush: flushAutoSave, sync: function () { return softSyncProjectRef(); }, + state: function () { + return { taskGen: taskGen, failed: Array.from(failedFields), readOnly: taskReadOnly, tasks: tasks, + stagesByProject: stagesByProject, projectsMeta: projectsMeta, boardStages: boardStages, + unsaved: hasUnsavedTaskEdits() }; + }, + }; + } } // ════════════════════════════════════════════════════════════ @@ -6412,6 +6819,7 @@ function setTaskId(id) { taskId = id; + editorGen++; // 작업이 바뀌었다 — 이전 작업에서 시작한 이미지 업로드는 이 설명란에 넣지 않는다 const enabled = !!id; if (imgInput) { imgInput.disabled = !enabled; @@ -6457,6 +6865,8 @@ // 업로드 중엔 저장을 막는다(안 그러면 업로드가 끝나기 전에 저장을 눌러 // 방금 넣은 이미지가 설명에서 통째로 빠진 채 저장되는 경우가 있었다). let pendingUploads = 0; + let idleWaiters = []; + let editorGen = 0; function beginUpload() { pendingUploads++; if (hint) hint.textContent = "이미지 업로드 중…"; @@ -6464,10 +6874,20 @@ function endUpload() { pendingUploads = Math.max(0, pendingUploads - 1); if (pendingUploads === 0 && hint) hint.textContent = taskId ? "" : "저장 후 이미지를 추가할 수 있습니다."; + if (pendingUploads === 0) { const w = idleWaiters; idleWaiters = []; w.forEach(function (fn) { fn(); }); } + } + // 업로드가 모두 끝날 때까지 기다린다 — 창 닫기·다른 작업 열기 전에 작업 창이 부른다. + function whenIdle() { + if (pendingUploads === 0) return Promise.resolve(); + return new Promise(function (resolve) { idleWaiters.push(resolve); }); } async function insertImageFile(file) { if (!taskId) { alert("먼저 저장한 뒤 이미지를 추가할 수 있습니다."); return; } + if (box.getAttribute("contenteditable") === "false") return; // 읽기 전용 + // 업로드를 시작한 작업·세대 — 끝났을 때 창이 다른 작업(또는 다시 연 같은 작업)으로 바뀌었으면 + // 그 설명란에 넣지 않는다. 파일은 원래 작업의 첨부 파일로 이미 저장돼 있다. + const myTaskId = taskId, myGen = editorGen; // 업로드는 비동기라 그 사이 포커스가 파일선택창 등으로 빠져나가면서 // contenteditable 의 선택범위가 사라지거나(브라우저가 엉뚱한 위치로 // 되살리기도 한다) 커서 위치가 틀어진다 — 업로드 시작 "직전"의 커서를 @@ -6481,11 +6901,15 @@ try { const results = await Promise.all([ naturalImageSize(file), - fetch("/project/api/tasks/" + taskId + "/attachments", { method: "POST", body: fd }), + fetch("/project/api/tasks/" + myTaskId + "/attachments", { method: "POST", body: fd }), ]); const dims = results[0], res = results[1]; if (!res.ok) { let m = res.statusText; try { m = (await res.json()).detail; } catch (_) {} throw new Error(m); } const data = await res.json(); + if (myGen !== editorGen || myTaskId !== taskId) { + showToast("이미지는 원래 작업의 첨부 파일로 저장됐습니다(작업 창이 바뀌어 설명에는 넣지 않았습니다)."); + return; + } const boxW = box.clientWidth || 0; const widthAttr = (dims && dims.width && boxW && dims.width > boxW) ? ' width="' + Math.round(boxW * 0.9) + '"' : ""; @@ -6530,6 +6954,7 @@ }, getHtml: function () { return box.innerHTML; }, isUploading: function () { return pendingUploads > 0; }, + whenIdle: whenIdle, setOnImageRemoved: function (fn) { onImageRemoved = fn; }, }; } @@ -6544,7 +6969,12 @@ const addDue = el("pj-subtask-add-due"); enhanceDateInput(addDue, { placeholder: "마감일" }); // 아사나식 날짜 팝업 const addBtn = el("pj-subtask-add"); + const formEl = listEl.parentNode ? listEl.parentNode.querySelector(".pj-subtask-form") : null; let taskId = null, projectId = null, canDeleteFn = function () { return false; }, onChange = null, onOpen = null; + // ctxSeq — 작업 창이 바뀔 때마다 1 올린다. 늦게 온 담당자 후보·목록 그리기는 버린다(A→B 전환 중 + // A 의 응답이 B 의 추가 칸·목록을 덮지 않게). readOnly — 연결된 프로젝트에서 본 작업(보기만). + let ctxSeq = 0; + let readOnly = false; // 담당자 후보(프로젝트 멤버) — 줄마다 다시 받지 않게 프로젝트별로 한 번만. const memberCache = {}; @@ -6715,6 +7145,18 @@ li.classList.remove("is-dragging"); dragRow = null; }); + if (readOnly) { + // 읽기 전용 — 제목·완료·마감일·담당자·순서·삭제 메뉴를 막고 "열기"만 남긴다(서버도 거절). + li.classList.add("is-readonly"); + titleInp.readOnly = true; + handle.hidden = true; + li.addEventListener("click", function (e) { + if (e.target.closest(".pj-subtask-check,.pj-subtask-due,.pj-subtask-av")) { + e.preventDefault(); e.stopImmediatePropagation(); + } + }, true); + li.addEventListener("contextmenu", function (e) { e.stopImmediatePropagation(); }, true); + } return li; } @@ -6749,30 +7191,39 @@ }); async function render(subtasks) { + const seq = ctxSeq; listEl.innerHTML = subtasks.length ? "" : "
  • 없음
  • "; if (!subtasks.length) return; - const emails = projectId ? await memberEmails(projectId) : []; + const emails = projectId && !readOnly ? await memberEmails(projectId) : []; + if (seq !== ctxSeq) return; // 그 사이 다른 작업 창 — 이 목록을 그리지 않는다 listEl.innerHTML = ""; subtasks.forEach(function (sub) { listEl.appendChild(rowEl(sub, emails)); }); listEl.querySelectorAll(".pj-subtask-title").forEach(fitTitle); } + let adding = false; if (addBtn) addBtn.addEventListener("click", async function () { const title = (input.value || "").trim(); - if (!title) return; + if (!title || adding || readOnly) return; if (!taskId) { alert("먼저 작업을 저장한 뒤 하위 작업을 추가할 수 있습니다."); return; } + // 누른 순간의 상위 작업·프로젝트를 잡아 둔다 — 응답을 기다리는 동안 창이 바뀌어도 엉뚱한 작업에 붙지 않게. + const tid = taskId, pid = projectId, seq = ctxSeq; const assigneeOpt = addAssignee ? addAssignee.selectedOptions[0] : null; + adding = true; + if (addBtn) addBtn.disabled = true; try { - const res = await api("POST", "/project/api/projects/" + projectId + "/tasks", { - title: title, parent_task_id: taskId, + const res = await api("POST", "/project/api/projects/" + pid + "/tasks", { + title: title, parent_task_id: tid, assignee_email: addAssignee ? addAssignee.value : "", assignee_name: assigneeOpt ? assigneeOpt.textContent : "", due_date: addDue ? (addDue.value || null) : null, }); + if (seq !== ctxSeq) return; // 다른 작업 창으로 바뀌었다 — 그 창의 목록·입력칸은 건드리지 않는다 input.value = ""; if (addAssignee) addAssignee.value = ""; if (addDue) addDue.value = ""; - const emails = await memberEmails(projectId); + const emails = await memberEmails(pid); + if (seq !== ctxSeq) return; const empty = listEl.querySelector(".pj-empty-sm"); if (empty) empty.remove(); const row = rowEl(res.task, emails); @@ -6780,8 +7231,10 @@ fitTitle(row.querySelector(".pj-subtask-title")); if (onChange) onChange(); } catch (e) { alert("추가 실패: " + e.message); } + finally { adding = false; if (addBtn) addBtn.disabled = false; } }); if (input) input.addEventListener("keydown", function (e) { + if (isImeEnter(e)) return; // 한글 조합 확정 Enter 는 추가하지 않는다 if (e.key === "Enter") { e.preventDefault(); if (addBtn) addBtn.click(); } }); @@ -6789,18 +7242,25 @@ // 다른 작업을 열 때 — 추가 칸에 쓰다 만 제목·담당자·마감일이 새 작업으로 따라가지 않게 // 비우고, 상세를 다 받기 전(setContext 전)에 Enter 를 눌러도 이전 작업에 붙지 않게 끊는다. reset: function () { + ctxSeq++; taskId = null; + readOnly = false; + if (formEl) formEl.hidden = false; if (input) input.value = ""; if (addAssignee) addAssignee.value = ""; if (addDue) addDue.value = ""; }, setContext: function (opts) { + const seq = ++ctxSeq; taskId = opts.taskId; projectId = opts.projectId; canDeleteFn = opts.canDelete || function () { return false; }; onChange = opts.onChange || null; onOpen = opts.onOpen || null; - if (addAssignee && projectId) { + readOnly = !!opts.readOnly; + if (formEl) formEl.hidden = readOnly; + if (addAssignee && projectId && !readOnly) { membersOptionsHtml(projectId).then(function (html) { + if (seq !== ctxSeq) return; // 늦게 온 A 의 담당자 후보가 B 의 추가 칸을 덮지 않게 addAssignee.innerHTML = "" + html; }); } @@ -6816,20 +7276,24 @@ const projSel = el("pj-link-project"); const stageSel = el("pj-link-stage"); const saveBtn = el("pj-link-save"); + const linkForm = el("pj-link-form"); let taskId = null, homeProjectId = null, onChange = null; + let ctxSeq = 0, readOnly = false; function chipEl(link) { const span = document.createElement("span"); span.className = "pj-link-chip"; span.innerHTML = - '● ' + + '● ' + escapeHtml(link.project_name || "") + (link.stage_name ? " · " + escapeHtml(link.stage_name) : "") + - ' '; + (readOnly ? "" : ' '); + if (readOnly) return span; + const tid = taskId; span.querySelector(".pj-link-del").addEventListener("click", async function () { if (!(await confirm("'" + (link.project_name || "") + "' 연결을 해제할까요?"))) return; try { - await api("DELETE", "/project/api/tasks/" + taskId + "/links/" + link.project_id); + await api("DELETE", "/project/api/tasks/" + tid + "/links/" + link.project_id); span.remove(); if (onChange) onChange(); } catch (e) { alert("해제 실패: " + e.message); } @@ -6843,10 +7307,12 @@ } async function loadProjects() { + const seq = ctxSeq; projSel.innerHTML = ""; stageSel.innerHTML = ""; try { const res = await api("GET", "/project/api/projects"); + if (seq !== ctxSeq) return; const list = (res.projects || []).filter(function (p) { return p.id !== homeProjectId && !p.parent_id; }); @@ -6869,10 +7335,12 @@ if (saveBtn) saveBtn.addEventListener("click", async function () { const pid = parseInt(projSel.value, 10); if (!pid) { alert("프로젝트를 선택하세요."); return; } - if (!taskId) { alert("먼저 작업을 저장한 뒤 연결할 수 있습니다."); return; } + if (!taskId || readOnly) { alert("먼저 작업을 저장한 뒤 연결할 수 있습니다."); return; } + const tid = taskId, seq = ctxSeq; // 누른 순간의 작업 — 창이 바뀌어도 엉뚱한 작업을 연결하지 않게 try { - await api("POST", "/project/api/tasks/" + taskId + "/links", + await api("POST", "/project/api/tasks/" + tid + "/links", { project_id: pid, stage_id: stageSel.value ? parseInt(stageSel.value, 10) : null }); + if (seq !== ctxSeq) return; projSel.value = ""; stageSel.innerHTML = ""; if (onChange) onChange(); @@ -6881,8 +7349,11 @@ return { setContext: function (opts) { + ctxSeq++; taskId = opts.taskId; homeProjectId = opts.projectId; onChange = opts.onChange || null; - loadProjects(); + readOnly = !!opts.readOnly; + if (linkForm) linkForm.hidden = readOnly; + if (!readOnly) loadProjects(); }, render: render, }; @@ -7241,8 +7712,29 @@ if (!document.querySelector(".pj-wrap, .pj-project-view")) return; // 탭이 안 보이는 동안(다른 탭/최소화)은 묻지 않는다 — 열어둔 탭 수만큼 // 서버에 헛요청이 쌓였다. 다시 보이면 바로 한 번 확인한다. - let baseline = null; + // observed = 서버에서 마지막으로 본 버전, applied = 화면에 성공적으로 반영한 버전. + // 예전엔 동기화 전에 기준값을 바꿔서, 스냅샷이 한 번 실패하면 같은 버전은 영영 다시 받지 + // 않았다. 이제 반영에 성공해야 applied 를 올리고, 실패하면 다음 주기(실패가 이어지면 + // 16·32·60초로 늘려 폭주 없이)에 다시 시도한다. 동기화 중에는 겹쳐 돌지 않고, 그 사이 + // 버전이 또 바뀌면 끝난 뒤 다음 주기에 한 번 더 받는다. + let observed = null; + let applied = null; + let syncing = false; + let failures = 0; let timer = null; + async function syncOnce() { + if (syncing || observed === null || observed === applied) return; + syncing = true; + const target = observed; + let ok = true; + try { + initBell(); + initMentionBadge(); + if (softSyncProjectRef) ok = (await softSyncProjectRef()) !== false; + } catch (_) { ok = false; } + syncing = false; + if (ok) { applied = target; failures = 0; } else { failures++; } + } async function poll() { timer = null; if (document.hidden) return; @@ -7250,18 +7742,18 @@ const res = await fetch("/project/api/live-version"); if (res.ok) { const d = await res.json(); - if (baseline === null) { - baseline = d.ts; - } else if (d.ts !== baseline) { - baseline = d.ts; - initBell(); - initMentionBadge(); - if (softSyncProjectRef) softSyncProjectRef(); - } + if (observed === null) { observed = applied = d.ts; } // 처음 본 값은 이미 화면에 있는 값 + else observed = d.ts; } } catch (_) {} - if (!timer && !document.hidden) timer = setTimeout(poll, 8000); + await syncOnce(); + const delay = failures ? Math.min(60000, 8000 * Math.pow(2, Math.min(failures, 3))) : 8000; + if (!timer && !document.hidden) timer = setTimeout(poll, delay); } + window.pjLiveRefreshState = function () { // 테스트·점검용 + return { observed: observed, applied: applied, syncing: syncing, failures: failures }; + }; + if (window.__PJ_TEST__) window.__pjLivePoll = poll; // 자동 테스트 전용 — 타이머 없이 한 번 확인 document.addEventListener("visibilitychange", function () { if (document.hidden) { if (timer) { clearTimeout(timer); timer = null; } @@ -7780,6 +8272,9 @@ }); } + if (window.__PJ_TEST__) { // 자동 테스트 전용 — 순수 도우미 + window.__pjHelpers = { kstTodayIso: kstTodayIso, dueInfo: dueInfo, isImeEnter: isImeEnter }; + } document.addEventListener("DOMContentLoaded", function () { // 좌측 프로젝트 목록 — 프로젝트 화면은 initProject 가 자기 데이터로 직접 연다. if (!document.querySelector(".pj-project-view")) initSideTree(); diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index c05a5da..bf3df2d 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -33,11 +33,13 @@ | 연결 env | `PROJECT_DB_URL` (미설정 시 "설정 필요" 안내, 앱은 죽지 않음) | | 진입 권한 | 권한키 `project` (관리자 페이지 토글로 직원별 부여, admin 자동) | | 멤버 배정 후보 | `project` 권한 보유 등록 사용자 자동 목록 (`GET /project/api/assignable-users`) | -| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. | -| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`) | -| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다 | -| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다 | -| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일 | +| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 건 관리자만(비관리자가 `owner_email` 을 남으로 보내면 403) | +| 소유자 변경 | **관리자만**(2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) | +| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) | +| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) | +| 지금 권한 기준 | 모든 판단은 **지금** 권한(`app/modules/project/access.py`) — 멤버에서 빠진 사람은 예전 담당자·멘션·협업자 기록이 있어도 내 작업·수신함·알림·검색·상세·공유 링크·댓글·첨부에서 그 작업이 보이지 않고, 새 알림·메일도 받지 않는다(기록은 이력으로 남김) | +| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다. 새 담당자는 그 프로젝트를 볼 수 있는 사람만(400). 날짜 범위(시작 ≤ 마감, 같은 날이면 시작 시각 ≤ 마감 시각)는 부분 수정도 기존 값과 합친 최종 상태로 검사(400) | +| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일. **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) | | 멤버 배정 | 여전히 관리자(`is_admin`) 전용. 비관리자가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) | | 메일 알림 | `app/mail.py` (stdlib smtplib). 작업 배정/완료 시 관리자에게 발송 | @@ -507,6 +509,76 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중 영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지). - 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기. +## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음) + +**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙) +- 프로젝트 관리 = 관리자 · owner · 배정 멤버, 모두 `project` 모듈 권한이 있어야 한다(`can_manage_project`). +- 작업 권한 `task_access`: **FULL** = 원 소속 프로젝트 관리 가능 / **READ** = 원 소속 권한은 없지만 이 작업(또는 상위 작업)이 + 연결된 프로젝트를 관리 가능(`task_link_scope`, 재귀 CTE) / 없음. 라우터 `_require_task(write=)` 가 FULL/READ 를 검사. +- READ 로 되는 것: 작업 상세(`access:"read"`)·하위 작업 목록·댓글 목록·첨부 목록/다운로드/미리보기·공유 링크(연결된 프로젝트 + 화면으로 이동). 안 되는 것: 제목·설명·담당자·완료·섹션(원 소속)·댓글/답글/반응·첨부 추가/삭제·협업자·삭제·하위 작업 변경. + 이미 연결된 작업을 연결된 프로젝트 안에서 섹션 이동(`POST /links`)은 예전처럼 허용, 새 연결은 양쪽 권한. 상세의 `links` 는 + 내가 볼 수 있는 프로젝트만(다른 연결 프로젝트 이름도 숨김), `followers` 는 READ 면 null. 원 소속의 다른 작업·멤버는 계속 403. +- 목록·배지·알림: 내 작업(`_my_visible_tasks`/`_my_open_count`)·수신함 태그(`_safe_mentions`)·알림(`_visible_notifications`)을 + 지금 권한으로 거른다(FULL 또는 READ). 기존 기록은 지우지 않는다. +- 알림·메일·멘션 수신자: `filter_recipients` — 지금 그 작업을 볼 수 있는 등록 사용자만(담당자·협업자여도 권한을 잃었으면 제외). + @태그는 볼 수 없는 사람(비멤버·권한 회수·미등록 이메일)을 기록·알림·자동 협업자 등록 없이 건너뛰고 응답 `mention_skipped` 로 + 알려 준다(payload 에 이메일을 직접 넣어도 같음). 멘션이 권한을 만들지 않는다. 태그 후보 `GET /api/all-users?task_id=`. +- 새 담당자는 그 프로젝트를 볼 수 있는 사람만(`_check_assignee`, 400). 비우거나 예전 값 유지는 허용. +- 댓글 수정·삭제도 지금 원 소속 권한이 있어야 한다(작성자라도 멤버에서 빠지면 403). 첨부는 본인 댓글에만 붙일 수 있다. + +**저장·동기화** +- 작업 창 세대(`taskGen`): 창을 열 때마다 +1. 상세·하위 작업·연결·첨부·댓글·담당자 후보·저장 결과는 요청 때 세대를 잡고, 돌아왔을 + 때 다르면 반영하지 않는다(A→B, A→B→A). 하위 작업·연결 블록도 자체 `ctxSeq` 로 늦은 응답을 버리고, 추가·연결은 누른 순간의 + 작업 id 로 보낸다. 설명 이미지 업로드는 시작한 작업·세대가 바뀌었으면 설명에 넣지 않는다(파일은 원래 작업 첨부로 남음). +- 자동 저장(`saveField`)은 성공/실패를 돌려준다. 실패한 칸은 `failedFields` 에 남고 "저장 실패 · 다시 시도"(눌러 재시도). + 닫기·Esc·다른 작업 열기(`openTaskModal` → `settleBeforeLeave`)는 이미지 업로드·만들기·저장 큐가 끝나길 기다리고 실패한 칸을 + 한 번 더 보낸 뒤, 그래도 실패하면 "버리고 넘어가기 / 계속 편집"을 묻는다. 버리기를 고를 때만 초안을 버린다(`discardTaskEdits`). + 저장 성공 뒤 화면 다시 그리기 오류는 저장 실패로 표시하지 않는다. 미저장(실패·대기·업로드 중)일 때만 페이지 이탈 경고. +- 읽기 전용 작업 창: 제목·설명·담당자·섹션·우선순위·마감일 잠금, 완료·삭제·댓글 입력·첨부 추가·서식 도구·하위 작업 추가· + 연결 추가/해제 숨김, 안내줄 `#pj-t-readonly`. 댓글 대화창도 `GET /comments` 의 `access` 로 입력칸을 숨긴다. +- 실시간 동기화(`initLiveRefresh`): `observed`(서버에서 본 버전)와 `applied`(화면에 반영 성공한 버전)를 나눈다. 반영이 + 성공해야 applied 를 올리고, 실패하면 다음 주기(8→16→32→60초)에 같은 버전을 다시 받는다. 동기화 중엔 겹쳐 돌지 않고, 늦게 온 + 응답은 버린다(`syncSeq`). 프로젝트 화면은 `GET /api/projects/{id}/snapshot?scope=all` — 화면이 들고 있는 범위(볼 수 있는 모든 + 최상위 프로젝트의 작업·섹션·프로젝트 목록)를 통째로 바꿔 끼운다(다른 프로젝트의 생성·삭제·섹션 변경·권한 회수 반영, 멀티호밍은 + `context_project_id` 별 한 행). 이 프로젝트 권한을 잃으면(403) 작업을 비우고 창을 닫고 안내줄 `.pj-access-lost`. +- 날짜: 업무 기준 "오늘" = 한국시간(`kstTodayIso`, UTC+9 고정) — 대시보드 지연 수·마감 색·오늘/내일·내 작업 필터가 브라우저 + 시간대와 무관하게 서버(`today_kst`)·마감 알림과 같다. + +**댓글 파일** — 파일이 있는 댓글은 `POST /api/tasks/{id}/comments/files`(multipart: `files[]`·`body`·`parent_id`·`mentions`(JSON)· +`client_token`) 한 요청으로, 댓글+첨부를 한 트랜잭션(`add_comment_with_attachments`)에 만든다. 빈 파일·20MB 초과가 하나라도 +있으면 아무것도 만들지 않고 400 `detail.failed=[{index,name,reason}]` → 화면은 그 파일만 빨갛게 표시하고 입력·파일을 유지. +DB 실패면 방금 쓴 파일도 지운다. 글 댓글(`POST /comments`)은 본문 필수 — 예전 `has_attachment` 플래그는 받지 않는다. +`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리, 단일 워커 기준). +작업 창 댓글 목록도 댓글별 첨부(이미지 미리보기·파일명 다운로드, 이스케이프)를 보여 주고, 첨부 파일 목록엔 "댓글" 표시. + +**마감 알림** — `add_reminder_notification`: 발송 기록(`task_reminders`)과 수신함 알림을 한 트랜잭션에. 알림 생성이 실패하면 +기록도 되돌려져 다음 실행에서 다시 시도, 동시 실행도 UNIQUE 로 한 번만. 수신자는 지금 볼 수 있는 사람만. 보장 범위는 수신함 +알림까지 — 메일(`PROJECT_REMINDER_EMAIL`)은 새로 만든 알림만 요약해 보내고 메일 실패는 재시도하지 않는다. + +**완료 섹션에 바로 만든 작업** — `create_task` 가 완료 섹션이면 `completed_at`·완료 이력(1건)을 넣고, 라우터가 완료 섹션 이동과 +같은 완료 알림(`_notify_completed`)을 보낸다. 섹션 없는 하위 작업·수동 완료/취소는 그대로. + +**테스트** — `tests/test_project_module.py`(로컬 테스트용 PostgreSQL + FastAPI TestClient, `PROJECT_TEST_DB_URL` 가 +localhost 일 때만), `tests/js/project_ui.test.js`(jsdom, `python tests/js/render_project.py` 후 실행, `PJ_TEST_TZ` 로 해외 시간대). +프런트 테스트 훅은 `window.__PJ_TEST__` 가 있을 때만 열린다. + +**기존 데이터 점검(조회만 — 운영 교정은 따로 승인 후)** +```sql +-- 시작일 > 마감일(프로젝트·작업), 같은 날 시각 역전 +SELECT id, name, start_date, due_date FROM projects WHERE start_date > due_date; +SELECT id, project_id, title, start_date, due_date, start_time, due_time FROM tasks + WHERE start_date > due_date OR (start_date = due_date AND start_time > due_time); +-- 본문도 첨부도 없는 빈 댓글(예전 파일 업로드 실패 흔적) +SELECT c.id, c.task_id, c.author_email, c.created_at FROM task_comments c + WHERE btrim(c.body) = '' AND NOT EXISTS (SELECT 1 FROM task_attachments a WHERE a.comment_id = c.id); +-- 완료 섹션에 있는데 미완료인 작업(예전 완료 섹션 직접 생성) +SELECT t.id, t.title FROM tasks t JOIN project_stages s ON s.id = t.stage_id + WHERE s.is_done_stage AND t.completed_at IS NULL; +``` +교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다. +권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다). + ## 7. 추후 단계 작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩, diff --git a/tests/js/project_ui.test.js b/tests/js/project_ui.test.js new file mode 100644 index 0000000..403a443 --- /dev/null +++ b/tests/js/project_ui.test.js @@ -0,0 +1,425 @@ +// 프로젝트 관리 화면(project/project.html + static/project.js) UI 회귀 테스트 — jsdom. +// 서버 응답은 가짜(fetch 대체)로, 지연·실패·순서 역전을 직접 만든다. 실제 브라우저 레이아웃·입력기는 아니다. +// +// python tests/js/render_project.py # 템플릿 렌더 → tests/js/.out/project_render.html +// npm install jsdom # (최초 1회) +// TZ=America/Los_Angeles node tests/js/project_ui.test.js # 해외 시간대 브라우저 흉내 +// +// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1. +// Git Bash 는 윈도우 프로그램에 TZ 를 넘기지 않아 PJ_TEST_TZ 로도 받는다(날짜 객체를 만들기 전에 설정). +if (process.env.PJ_TEST_TZ) process.env.TZ = process.env.PJ_TEST_TZ; +const fs = require("fs"); +const path = require("path"); +const { JSDOM } = require("jsdom"); +const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 90000); + +const ROOT = path.join(__dirname, "..", ".."); +const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8"); +const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8"); + +const fails = []; +function check(name, cond, extra) { + if (cond) console.log("PASS " + name); + else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); } +} + +function deferred() { + let resolve, reject; + const p = new Promise(function (a, b) { resolve = a; reject = b; }); + return { promise: p, resolve: resolve, reject: reject }; +} + +function makeEnv() { + const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" }); + const w = dom.window, d = w.document; + w.__PJ_TEST__ = true; + w.HTMLCanvasElement.prototype.getContext = function () { return null; }; + w.URL.createObjectURL = function () { return "blob:x"; }; + w.URL.revokeObjectURL = function () {}; + w.Image = function () { const self = this; Object.defineProperty(self, "src", { set: function () { setTimeout(function () { if (self.onerror) self.onerror(); }, 0); } }); }; + w.console.error = function () {}; + let confirmAnswer = false; + w.erpConfirm = function () { env.confirms++; return Promise.resolve(confirmAnswer); }; + w.erpAlert = function (m) { env.alerts.push(m); }; + w.alert = function (m) { env.alerts.push(m); }; + // 8초 이상 타이머(실시간 새로고침)는 붙잡아 두고 테스트가 직접 돌린다. + const realSetTimeout = w.setTimeout.bind(w); + const slow = []; + w.setTimeout = function (fn, ms) { + if (ms >= 8000) { slow.push({ fn: fn, ms: ms }); return 999000 + slow.length; } + return realSetTimeout(fn, ms); + }; + const env = { + w: w, d: d, calls: [], routes: [], slow: slow, confirms: 0, alerts: [], + setConfirm: function (v) { confirmAnswer = v; }, + route: function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); }, + runSlow: async function () { const t = slow.shift(); if (t) { t.fn(); await settle(); } return t; }, + }; + w.fetch = async function (url, opts) { + const method = (opts && opts.method) || "GET"; + let body = opts && opts.body; + if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} } + env.calls.push({ method: method, url: String(url), body: body }); + if (process.env.PJ_TEST_TRACE && method === "PUT") console.log(" TRACE PUT", url, new Error().stack.split("\n").slice(2, 7).join(" | ")); + for (const r of env.routes) { + if (r.method === method && r.re.test(String(url))) { + const out = await r.fn(String(url), body); + if (out === "NETWORK") throw new TypeError("Failed to fetch"); + const status = out.status || 200; + return { ok: status < 400, status: status, statusText: "x", json: async function () { return out.body; } }; + } + } + return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; } }; + }; + return env; +} + +function settle(n) { + return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 30)) return r(); setImmediate(spin); })(); }); +} + +function detail(id, title, extra) { + return Object.assign({ id: id, title: title, project_id: 1, stage_id: 11, description: "", priority: "normal", + assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null }, extra || {}); +} + +function baseRoutes(env) { + env.route("GET", /\/project\/api\/tasks\/\d+\/attachments/, function () { return { body: { attachments: [] } }; }); + env.route("GET", /\/project\/api\/tasks\/\d+\/comments/, function () { return { body: { comments: [], events: [], features: {} } }; }); + env.route("GET", /\/project\/api\/projects\/\d+\/members/, function () { return { body: { members: [{ user_email: "me@test.local" }] } }; }); + env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [] } }; }); + env.route("GET", /\/project\/api\/all-users/, function () { return { body: { users: [] } }; }); + env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: "v1" } }; }); + env.route("GET", /\/project\/api\/tasks\/101$/, function () { return { body: { task: detail(101, "작업 A") } }; }); + env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B") } }; }); +} + +async function boot(env) { + // jsdom 이 문서를 다 읽고 DOMContentLoaded 를 보낸 뒤에 넣는다 — 먼저 넣으면 초기화가 두 번 돈다. + if (env.d.readyState === "loading") { + await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); }); + } + // jsdom 의