From 78b6e8df114bf8b8c4b1951e5cee909ccfeeca11 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 23 Sep 2026 13:28:19 +0900 Subject: [PATCH] =?UTF-8?q?feat(project):=20=EA=B2=80=EC=83=89=C2=B7?= =?UTF-8?q?=ED=95=84=ED=84=B0=C2=B7=EC=A0=95=EB=A0=AC=20+=20=ED=8C=94?= =?UTF-8?q?=EB=A1=9C=EC=9B=8C=20+=20=EB=A7=88=EA=B0=90=20=EC=95=8C?= =?UTF-8?q?=EB=A6=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 검색·필터·정렬 - 좌측 사이드바 전체 검색(/api/search): 제목·설명·댓글, 볼 수 있는 프로젝트의 업무(하위 업무 포함). 설명 HTML 태그에만 걸린 결과는 본문 텍스트로 재확인해 제거. 어디서 걸렸는지 + 미리보기, 키보드(/ ↑↓ Enter). - 프로젝트 화면 필터 바: 찾기·상태·담당자·마감·우선순위·정렬. visibleTasks() 에서 걸러 보드/리스트/달력/타임라인/대시보드 모두 적용, 프로젝트별 기억. 필터·정렬 중엔 보드 카드 순서 드래그 차단. - 내 업무 화면에도 찾기·마감·우선순위 필터. 팔로워 · 알림 - task_followers(008): 만든 사람·담당자·댓글 작성자·@태그된 사람 자동 팔로우, 기존 업무 백필. 업무 팝업에서 추가/빼기/내 팔로우 토글. - 완료·댓글 인앱 알림 수신자: 프로젝트 멤버 전원 → 담당자 + 팔로워. 008 미적용이면 예전 방식 폴백. - 마감 알림(reminders.py, lifespan 에서 데몬 스레드): 영업일(주말·공휴일 skip) 09시 KST 1회, 다음 영업일까지 마감/오늘 마감/지남(7일 이내). 수신자 담당자(없으면 팔로워). task_reminders UNIQUE 로 중복 방지, 마감일 바뀌면 재알림. PROJECT_REMINDER_EMAIL=true 면 요약 메일. - 008: pg_trgm GIN 인덱스(제목·설명·댓글), 미완료 마감일 부분 인덱스. 버그 - 업무 팝업 담당자 선택지가 프로젝트 멤버뿐이라, 멤버 목록에 없는 담당자 (프로젝트 owner, 멤버에서 빠진 사람)의 업무를 열고 저장하면 담당자가 지워지던 문제 수정. Co-Authored-By: Claude Opus 5.5 --- .env.example | 10 +- CLAUDE.md | 2 +- app/main.py | 14 +- app/modules/project/__init__.py | 6 +- app/modules/project/db.py | 121 ++++++ app/modules/project/reminders.py | 183 +++++++++ app/modules/project/router.py | 147 ++++++- app/modules/project/store.py | 34 ++ .../project/templates/project/_side.html | 7 + .../project/templates/project/inbox.html | 7 +- .../project/templates/project/mytasks.html | 24 +- .../project/templates/project/project.html | 62 ++- app/static/project.css | 73 ++++ app/static/project.js | 360 +++++++++++++++++- docs/PROJECT_MODULE.md | 40 +- ...ject_db_008_followers_reminders_search.sql | 75 ++++ 16 files changed, 1141 insertions(+), 24 deletions(-) create mode 100644 app/modules/project/reminders.py create mode 100644 scripts/sql/project_db_008_followers_reminders_search.sql diff --git a/.env.example b/.env.example index b29bf27..6e98a98 100644 --- a/.env.example +++ b/.env.example @@ -67,7 +67,7 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/ # ─── 프로젝트 관리 모듈 (project_db) — 아사나식 ─── # 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음). # DB/역할/스키마 생성: scripts/sql/project_db_init.sql 참고. -# 진입 권한: 로그인한 회사 직원 전원(별도 권한키 없음). 프로젝트 생성/배정은 관리자만. +# 진입 권한: 권한키 project. 프로젝트 생성은 누구나, 멤버 배정은 관리자만, 조회·수정은 멤버만. # PROJECT_DB_URL=postgresql://project_app:replace-me@postgres-db:5432/project_db # ─── 메일 알림 (SMTP) — 프로젝트 업무 배정/완료 시 관리자 알림 ─── @@ -82,6 +82,14 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/ # 알림 수신자(쉼표구분). 비워두면 ERP 관리자(admin) 전원에게 발송. # PROJECT_NOTIFY_EMAIL=king@dbxcorp.co.kr +# ─── 프로젝트 마감 알림 (project_db_008 필요) ─── +# 매일 1회(영업일만, 주말·공휴일 skip) 미완료 업무의 D-1/당일/지연 알림을 수신함에 만든다. +# 수신자 = 담당자(없으면 팔로워). 같은 알림은 한 번만(task_reminders 로 중복 방지). +# PROJECT_REMINDERS=true # false 면 끔 +# PROJECT_REMINDER_HOUR=9 # 실행 시각(KST, 0~23) +# PROJECT_REMINDER_EMAIL=false # true 면 수신자에게 요약 메일도(SMTP_* 필요) +# PUBLIC_BASE_URL=https://erp.example.com # 메일 속 업무 링크 앞부분 + # ─── 카페24 상품 상세페이지 관리 모듈 (cafe24_db) ─── # 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음). # DB/역할/스키마 생성: scripts/sql/cafe24_db_init.sql 참고. diff --git a/CLAUDE.md b/CLAUDE.md index d552e06..6762927 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/images` → PUT `detail_image`+`image_upload_type=A`), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페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)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 업무 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 달력(FullCalendar)/타임라인(vis-timeline)/보드/리스트/대시보드 뷰 토글. 좌측 사이드바는 두 화면 공용(`templates/project/_side.html`). 보드는 아사나처럼 세션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 업무(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 업무가 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/업무/단계 CRUD — URL 의 세션·부모 업무가 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md` +- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 업무 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 달력(FullCalendar)/타임라인(vis-timeline)/보드/리스트/대시보드 뷰 토글. 좌측 사이드바는 두 화면 공용(`templates/project/_side.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`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+팔로워에게만. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md` 상세는 `docs/PROJECT_OVERVIEW.md`. diff --git a/app/main.py b/app/main.py index 8833969..2e776fc 100644 --- a/app/main.py +++ b/app/main.py @@ -1,5 +1,6 @@ import inspect import os +from contextlib import asynccontextmanager from pathlib import Path from typing import Any @@ -102,7 +103,18 @@ def build_google_oauth() -> OAuth: return oauth -app = FastAPI(title="DBX 메인 페이지") +@asynccontextmanager +async def _lifespan(app_: FastAPI): # noqa: ANN201 + """앱 시작 시 백그라운드 작업 시작. + - 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드. + PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.""" + from .modules.project.reminders import start_reminder_thread # noqa: WPS433 + + start_reminder_thread(getattr(app_.state, "project_store", None)) + yield + + +app = FastAPI(title="DBX 메인 페이지", lifespan=_lifespan) app.add_middleware( SessionMiddleware, secret_key=_require_session_secret(), diff --git a/app/modules/project/__init__.py b/app/modules/project/__init__.py index eee1842..4480088 100644 --- a/app/modules/project/__init__.py +++ b/app/modules/project/__init__.py @@ -10,8 +10,10 @@ build_project_store 는 None 을 반환하고, 라우터가 "설정 필요" 안내 페이지를 보여준다(앱은 죽지 않음). -권한: 로그인한 회사(dbxcorp.co.kr) 직원은 모듈 진입 가능. 프로젝트 생성/삭제· -사용자 배정은 ERP 관리자(is_admin)만. 배정된 멤버는 서브프로젝트/업무/단계 관리. +권한: 권한키 `project` 보유자는 모듈 진입·프로젝트 생성 가능. 삭제는 만든 사람만, +사용자 배정은 ERP 관리자(is_admin)만. 배정된 멤버(또는 owner/관리자)만 그 프로젝트를 +조회하고 서브프로젝트/업무/단계를 관리한다. +마감 알림 스레드: `reminders.py` (app.main 의 startup 에서 시작). """ from typing import Any diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 64c1b2e..f963a5e 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -1155,6 +1155,127 @@ class ProjectStore: ) return cur.rowcount or 0 + # ════════════════════════════════════════════════════════════ + # 팔로워(task_followers, 마이그레이션 008) — 아사나의 "협업자". + # 업무 알림(완료·댓글)은 담당자 + 팔로워에게만 간다. 008 미적용이면 + # psycopg_errors.UndefinedTable 이 나고, 라우터가 예전 동작으로 폴백한다. + # ════════════════════════════════════════════════════════════ + def list_followers(self, *, task_id: int) -> list[str]: + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT user_email FROM task_followers WHERE task_id = %s " + "ORDER BY created_at ASC, user_email ASC", + (task_id,), + ).fetchall() + return [r["user_email"] for r in rows] + + def add_followers(self, *, task_id: int, emails: list[str]) -> list[str]: + """팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다.""" + targets = store.normalize_emails(emails) + if not targets: + return [] + with self._pool.connection() as conn: + rows = conn.execute( + "INSERT INTO task_followers (task_id, user_email) " + "SELECT %s, e FROM unnest(%s::text[]) AS e " + "ON CONFLICT DO NOTHING RETURNING user_email", + (task_id, targets), + ).fetchall() + return [r["user_email"] for r in rows] + + def remove_follower(self, *, task_id: int, user_email: str) -> None: + with self._pool.connection() as conn: + conn.execute( + "DELETE FROM task_followers WHERE task_id = %s AND user_email = %s", + (task_id, store.norm_str(user_email, lower=True)), + ) + + # ════════════════════════════════════════════════════════════ + # 전체 검색 — 제목·설명·댓글 (008 의 pg_trgm 인덱스가 있으면 그걸 탄다) + # ════════════════════════════════════════════════════════════ + def search_tasks( + self, *, query: str, project_ids: set[int] | None, limit: int = 30, + ) -> list[dict[str, Any]]: + """제목/설명/댓글에 검색어가 들어간 업무(하위 업무 포함). + + project_ids 가 None 이면 전체(관리자), 아니면 그 프로젝트들만. + 설명은 HTML 이라 태그 이름·속성에만 걸린 경우(예: "img")를 걸러내려고 + 넉넉히 가져온 뒤 라우터가 본문 텍스트로 다시 확인한다. + """ + q = store.norm_str(query) + if not q: + return [] + if project_ids is not None and not project_ids: + return [] + pat = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" + params: dict[str, Any] = {"pat": pat, "limit": int(limit)} + scope = "" + if project_ids is not None: + scope = "AND t.project_id = ANY(%(ids)s)" + params["ids"] = sorted(project_ids) + with self._pool.connection() as conn: + rows = conn.execute( + f""" + SELECT t.id, t.title, t.description, t.project_id, t.parent_task_id, + t.completed_at, t.due_date, t.assignee_email, + p.name AS project_name, p.color AS project_color, + pt.title AS parent_title, + (t.title ILIKE %(pat)s) AS hit_title, + (SELECT c.body FROM task_comments c + WHERE c.task_id = t.id AND c.body ILIKE %(pat)s + ORDER BY c.created_at DESC LIMIT 1) AS comment_hit + FROM tasks t + JOIN projects p ON p.id = t.project_id + LEFT JOIN tasks pt ON pt.id = t.parent_task_id + WHERE (t.title ILIKE %(pat)s + OR t.description ILIKE %(pat)s + OR t.id IN (SELECT c.task_id FROM task_comments c WHERE c.body ILIKE %(pat)s)) + {scope} + ORDER BY (t.title ILIKE %(pat)s) DESC, (t.completed_at IS NULL) DESC, + t.updated_at DESC, t.id DESC + LIMIT %(limit)s + """, + params, + ).fetchall() + return [self._serialize(r) for r in rows] + + # ════════════════════════════════════════════════════════════ + # 마감 알림 (task_reminders, 마이그레이션 008) — reminders.py 가 부른다 + # ════════════════════════════════════════════════════════════ + def list_open_tasks_due_between(self, *, start: date, end: date) -> list[dict[str, Any]]: + """미완료 + 마감일이 [start, end] 인 업무(하위 업무 포함) + 팔로워 목록. + 보관(archived) 프로젝트는 뺀다.""" + with self._pool.connection() as conn: + rows = conn.execute( + """ + SELECT t.id, t.title, t.due_date, t.assignee_email, t.project_id, + t.parent_task_id, p.name AS project_name, + COALESCE((SELECT array_agg(f.user_email ORDER BY f.user_email) + FROM task_followers f WHERE f.task_id = t.id), + '{}'::text[]) AS followers + FROM tasks t + JOIN projects p ON p.id = t.project_id + WHERE t.completed_at IS NULL + AND t.due_date BETWEEN %s AND %s + AND p.status <> 'archived' + ORDER BY t.due_date ASC, t.id ASC + """, + (start, end), + ).fetchall() + return [self._serialize(r) for r in rows] + + def record_reminder( + self, *, task_id: int, kind: str, due_date: str, recipient_email: str, + ) -> bool: + """이 알림을 처음 보내는 거면 기록하고 True. 이미 보냈으면 False(중복 방지).""" + with self._pool.connection() as conn: + 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, store.norm_str(recipient_email, lower=True)), + ).fetchone() + return row is not None + # ════════════════════════════════════════════════════════════ # 실시간 새로고침 — 프로젝트/업무/댓글/멤버/단계 중 가장 최근 변경 시각 # ════════════════════════════════════════════════════════════ diff --git a/app/modules/project/reminders.py b/app/modules/project/reminders.py new file mode 100644 index 0000000..67bc814 --- /dev/null +++ b/app/modules/project/reminders.py @@ -0,0 +1,183 @@ +"""프로젝트 업무 마감 알림 — 아사나의 "마감일 임박/지남" 알림. + +매일 한 번(기본 09시 KST, 영업일만) 미완료 업무를 훑어 수신함 알림을 만든다. + · due_soon — 다음 영업일까지 마감(금요일이면 토·일·월 마감분까지) + · due_today — 오늘 마감 + · overdue — 마감이 지남(최근 7일 이내 마감분만 — 첫 적용 때 오래된 업무가 + 한꺼번에 쏟아지지 않게, 연휴로 며칠 건너뛰어도 놓치지 않게) +수신자는 담당자. 담당자가 없으면 팔로워 전원. + +중복 방지: task_reminders(업무, 종류, 마감일, 수신자) UNIQUE — 같은 알림은 한 번만 +간다(재기동·여러 번 실행해도 안전). 마감일을 바꾸면 새 마감일 기준으로 다시 알린다. + +실행 방식: 웹 프로세스 안의 데몬 스레드(start_reminder_thread). 5분마다 깨어나 +"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가 +동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다. + +환경변수: + PROJECT_REMINDERS false 면 끈다(기본 켜짐) + PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9) + PROJECT_REMINDER_EMAIL true 면 수신자에게 메일도 보낸다(사람별 1통 요약, 기본 끔). + SMTP_* 설정이 있어야 실제로 나간다. + PUBLIC_BASE_URL 메일 속 업무 링크의 앞부분(예: https://erp.dbxcorp.co.kr) +""" + +from __future__ import annotations + +import logging +import os +import threading +import time +from datetime import date, timedelta +from typing import Any + +from app.timezone import now_kst + +from . import store + +logger = logging.getLogger("project.reminders") + +KIND_DUE_SOON = "due_soon" +KIND_DUE_TODAY = "due_today" +KIND_OVERDUE = "overdue" +OVERDUE_WINDOW_DAYS = 7 + + +def _env(name: str, default: str = "") -> str: + return (os.getenv(name, "") or "").strip() or default + + +def _env_bool(name: str, default: bool) -> bool: + v = _env(name).lower() + if not v: + return default + return v in ("1", "true", "yes", "on") + + +def is_workday(d: date) -> bool: + return d.weekday() < 5 and not store.holiday_name(d.isoformat()) + + +def next_workday(d: date) -> date: + n = d + timedelta(days=1) + while not is_workday(n): + n += timedelta(days=1) + return n + + +def classify(due: date, today: date) -> str | None: + """마감일 → 알림 종류(없으면 None).""" + if due == today: + return KIND_DUE_TODAY + if today < due <= next_workday(today): + return KIND_DUE_SOON + if today - timedelta(days=OVERDUE_WINDOW_DAYS) <= due < today: + return KIND_OVERDUE + return None + + +def _title_for(kind: str, task: dict[str, Any], today: date) -> str: + due = date.fromisoformat(task["due_date"][:10]) + if kind == KIND_DUE_TODAY: + return f"오늘 마감: {task['title']}" + if kind == KIND_DUE_SOON: + days = (due - today).days + when = "내일" if days == 1 else f"{days}일 후" + return f"마감 임박({when}): {task['title']}" + return f"마감 지남({(today - due).days}일): {task['title']}" + + +def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]: + """한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다.""" + today = today or now_kst().date() + start = today - timedelta(days=OVERDUE_WINDOW_DAYS) + end = next_workday(today) + counts = {KIND_DUE_SOON: 0, KIND_DUE_TODAY: 0, KIND_OVERDUE: 0} + digest: dict[str, list[tuple[str, dict[str, Any]]]] = {} + + for t in st.list_open_tasks_due_between(start=start, end=end): + due = date.fromisoformat(t["due_date"][:10]) + kind = classify(due, today) + 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 []) + 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, + body=f"{t.get('project_name') or ''} · 마감 {t['due_date'][:10]}", + ) + except Exception: # noqa: BLE001 + logger.warning("마감 알림 생성 실패: task=%s", t["id"]) + continue + counts[kind] += 1 + digest.setdefault(rcpt, []).append((title, t)) + + if digest and _env_bool("PROJECT_REMINDER_EMAIL", False): + _send_digests(digest, today) + return counts + + +def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None: + from app.mail import send_email # noqa: WPS433 + + base = _env("PUBLIC_BASE_URL").rstrip("/") + for rcpt, items in digest.items(): + lines = [f"{today.isoformat()} 마감 알림 — {len(items)}건", ""] + for title, t in items: + lines.append(f"· {title} [{t.get('project_name') or ''}]") + if base: + lines.append(f" {base}/project/t/{t['id']}") + send_email( + to=[rcpt], + subject=f"[DBX 프로젝트] 마감 알림 {len(items)}건 ({today.isoformat()})", + body="\n".join(lines) + "\n", + ) + + +_started = False +_start_lock = threading.Lock() + + +def start_reminder_thread(st: Any) -> bool: + """웹 프로세스 시작 시 1번. 이미 돌고 있거나 꺼져 있으면 False.""" + global _started # noqa: PLW0603 + if st is None or not _env_bool("PROJECT_REMINDERS", True): + return False + with _start_lock: + if _started: + return False + _started = True + try: + hour = min(23, max(0, int(_env("PROJECT_REMINDER_HOUR", "9")))) + except ValueError: + hour = 9 + + def _loop() -> None: + last_run: date | None = None + while True: + try: + now = now_kst() + today = now.date() + if last_run != today and now.hour >= hour and is_workday(today): + counts = run_due_reminders(st, today=today) + last_run = today + logger.info("마감 알림 실행: %s", counts) + except Exception as exc: # noqa: BLE001 + if type(exc).__name__ == "UndefinedTable": + # 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지) + logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요") + last_run = now_kst().date() + else: + logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__) + time.sleep(300) + + threading.Thread(target=_loop, name="project-reminders", daemon=True).start() + return True diff --git a/app/modules/project/router.py b/app/modules/project/router.py index fea4df3..12c7c1c 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -177,13 +177,33 @@ def _notify( bg.add_task(send_email, to=recipients, subject=subject, body=body) +def _follow(st: Any, task_id: int, emails: list[str]) -> None: + """자동 팔로우(만든 사람·담당자·댓글 작성자·@태그된 사람). 부가 기능이라 + 실패해도(008 미적용 등) 본 작업은 막지 않는다.""" + try: + st.add_followers(task_id=task_id, emails=emails) + except Exception: # noqa: BLE001 + pass + + def _task_recipients( st: Any, project: dict[str, Any], task: dict[str, Any], *, exclude: str = "" ) -> list[str]: - """업무 관련 인앱 알림 수신자 = 담당자 + 프로젝트 owner + 멤버 (행위자 제외).""" + """업무 관련 인앱 알림 수신자 (행위자 제외). + + = 담당자 + 팔로워(아사나의 협업자). 예전엔 프로젝트 멤버 전원에게 갔는데 + 알림이 너무 많아 정작 중요한 게 묻혔다. 팔로워 표(008)가 없으면 예전처럼 + 담당자 + owner + 멤버 전원. + """ emails: set[str] = set() if task.get("assignee_email"): emails.add(store.norm_str(task["assignee_email"], lower=True)) + try: + emails.update(st.list_followers(task_id=task["id"])) + emails.discard(store.norm_str(exclude, lower=True)) + return [e for e in emails if e] + except Exception: # noqa: BLE001 - 008 미적용 → 예전 방식 + pass if project.get("owner_email"): emails.add(store.norm_str(project["owner_email"], lower=True)) try: @@ -232,6 +252,7 @@ def _record_mentions( return if not added: return + _follow(st, task["id"], added) # 태그된 사람은 이후 소식도 받도록 팔로워로 where = "댓글" if source == "comment" else "설명" _inbox( st, recipients=added, actor=actor, @@ -1090,6 +1111,8 @@ def api_create_task( raise HTTPException(status_code=400, detail=str(exc)) except KeyError as exc: raise HTTPException(status_code=404, detail=str(exc)) + # 만든 사람·담당자는 자동 팔로워(아사나와 같은 규칙) + _follow(st, task["id"], [user["email"], task.get("assignee_email") or ""]) # 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림 if task.get("assignee_email"): _notify( @@ -1147,6 +1170,7 @@ def api_update_task( project_name = task.get("project_name") or "" project = st.get_project(project_id=existing["project_id"]) or {"id": existing["project_id"], "name": project_name} if task.get("_newly_assigned"): + _follow(st, task_id, [task["_newly_assigned"]]) _notify( bg, request, subject=store.build_subject_assigned( @@ -1224,9 +1248,129 @@ def api_get_task(request: Request, task_id: int) -> JSONResponse: _require_manage(request, st, user, task["project_id"]) 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 return JSONResponse({"task": task}) +# ──────────────────────────────────────────────────────────── +# 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"]) + return task + + +def _followers_response(st: Any, task_id: int) -> JSONResponse: + try: + return JSONResponse({"followers": st.list_followers(task_id=task_id)}) + except Exception: # noqa: BLE001 + raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.") + + +@router.get("/api/tasks/{task_id}/followers") +def api_list_followers(request: Request, task_id: int) -> JSONResponse: + user = _require_user(request) + st = _db_or_503(request) + _task_for_followers(request, st, user, task_id) + return _followers_response(st, task_id) + + +@router.post("/api/tasks/{task_id}/followers") +def api_add_follower( + request: Request, task_id: int, payload: dict[str, Any] = Body(default={}) +) -> JSONResponse: + """팔로워 추가. email 을 안 주면 나 자신(팔로우). 다른 사람은 그 프로젝트를 + 볼 수 있는 사람(멤버·owner·관리자)만 추가할 수 있다 — 못 보는 업무의 알림이 + 가면 안 되므로.""" + from app.main import user_store # noqa: WPS433 + from app.store import is_admin # noqa: WPS433 + + user = _require_user(request) + st = _db_or_503(request) + task = _task_for_followers(request, st, user, task_id) + email = store.norm_str(payload.get("email") or user["email"], lower=True) + if email != store.norm_str(user["email"], lower=True): + target = user_store.get(email) + allowed = (target is not None and is_admin(target)) or st.is_member( + project_id=task["project_id"], user_email=email + ) + if not allowed: + raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 팔로워로 추가할 수 있습니다.") + try: + st.add_followers(task_id=task_id, emails=[email]) + except Exception: # noqa: BLE001 + raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.") + return _followers_response(st, task_id) + + +@router.delete("/api/tasks/{task_id}/followers/{email}") +def api_remove_follower(request: Request, task_id: int, email: str) -> JSONResponse: + user = _require_user(request) + st = _db_or_503(request) + _task_for_followers(request, st, user, task_id) + try: + st.remove_follower(task_id=task_id, user_email=email) + except Exception: # noqa: BLE001 + raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.") + return _followers_response(st, task_id) + + +# ──────────────────────────────────────────────────────────── +# JSON API — 전체 검색 (좌측 사이드바 검색창) +# ──────────────────────────────────────────────────────────── +@router.get("/api/search") +def api_search(request: Request, q: str = "", limit: int = 20) -> JSONResponse: + """제목·설명·댓글 검색 — 내가 볼 수 있는 프로젝트의 업무(하위 업무 포함). + + 설명은 HTML 이라 DB 에서는 넉넉히 가져온 뒤 본문 텍스트에 실제로 검색어가 + 있는지 다시 확인한다(태그 이름·속성에만 걸린 결과 제거). 결과마다 어디서 + 걸렸는지(match: title/description/comment)와 미리보기(snippet)를 붙인다. + """ + user = _require_user(request) + st = _db_or_503(request) + query = store.norm_str(q)[:100] + if len(query) < 2: + return JSONResponse({"results": [], "query": query}) + limit = max(1, min(int(limit), 50)) + rows = st.search_tasks( + query=query, project_ids=_accessible_project_ids(st, user), limit=limit * 3, + ) + ql = query.lower() + out: list[dict[str, Any]] = [] + for r in rows: + desc_text = store.html_to_text(r.get("description") or "") + if r.get("hit_title"): + match, snippet = "title", store.search_snippet(desc_text, query) if ql in desc_text.lower() else "" + elif ql in desc_text.lower(): + match, snippet = "description", store.search_snippet(desc_text, query) + elif r.get("comment_hit"): + match, snippet = "comment", store.search_snippet(r["comment_hit"], query) + else: + continue # 설명 HTML 태그에만 걸린 경우 + out.append({ + "id": r["id"], + "title": r["title"], + "project_id": r["project_id"], + "project_name": r.get("project_name") or "", + "project_color": r.get("project_color") or "#4573d2", + "parent_title": r.get("parent_title") or "", + "completed": bool(r.get("completed_at")), + "due_date": r.get("due_date"), + "assignee_email": r.get("assignee_email") or "", + "match": match, + "snippet": snippet, + }) + if len(out) >= limit: + break + return JSONResponse({"results": out, "query": query}) + + # ──────────────────────────────────────────────────────────── # JSON API — 업무 멀티호밍 (다른 프로젝트/세션에 연결) # ──────────────────────────────────────────────────────────── @@ -1328,6 +1472,7 @@ def api_add_comment( ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) + _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", "")} _inbox( st, recipients=_task_recipients(st, project, task, exclude=user["email"]), diff --git a/app/modules/project/store.py b/app/modules/project/store.py index 4409b11..6ff516d 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -441,6 +441,40 @@ def extract_mentions_from_html(html: str) -> list[str]: return parser.emails +class _TextCollector(HTMLParser): + _BREAK_TAGS = frozenset({"br", "p", "div", "li", "blockquote", "pre"}) + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: list[str] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag in self._BREAK_TAGS: + self.parts.append(" ") + + def handle_data(self, data: str) -> None: + self.parts.append(data) + + +def html_to_text(html: str) -> str: + """설명 HTML → 한 줄 평문(검색 확인·미리보기용). 공백은 하나로 줄인다.""" + parser = _TextCollector() + parser.feed(html or "") + parser.close() + return re.sub(r"\s+", " ", "".join(parser.parts)).strip() + + +def search_snippet(text: str, query: str, *, width: int = 60) -> str: + """text 에서 query 주변만 잘라 보여준다(앞뒤 … 표시). 없으면 앞부분.""" + t = text or "" + i = t.lower().find((query or "").lower()) + if i < 0: + return t[:width * 2] + ("…" if len(t) > width * 2 else "") + start = max(0, i - width) + end = min(len(t), i + len(query) + width) + return ("…" if start else "") + t[start:end] + ("…" if end < len(t) else "") + + def normalize_emails(values: Any) -> list[str]: """임의 입력(리스트/문자열)을 소문자 이메일 목록으로 정리한다.""" if isinstance(values, str): diff --git a/app/modules/project/templates/project/_side.html b/app/modules/project/templates/project/_side.html index 4ed6030..dcdf581 100644 --- a/app/modules/project/templates/project/_side.html +++ b/app/modules/project/templates/project/_side.html @@ -11,6 +11,13 @@ 프로젝트 수정/삭제(✎/×) 버튼은 그 동작을 배선하는 initProject 가 도는 프로젝트 화면에서만 그린다(current_pid 로 판별). #}