feat(project): 검색·필터·정렬 + 팔로워 + 마감 알림
검색·필터·정렬 - 좌측 사이드바 전체 검색(/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 <noreply@anthropic.com>
This commit is contained in:
+9
-1
@@ -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 참고.
|
||||
|
||||
@@ -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`.
|
||||
|
||||
|
||||
+13
-1
@@ -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(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 실시간 새로고침 — 프로젝트/업무/댓글/멤버/단계 중 가장 최근 변경 시각
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -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
|
||||
@@ -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"]),
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -11,6 +11,13 @@
|
||||
프로젝트 수정/삭제(✎/×) 버튼은 그 동작을 배선하는 initProject 가 도는
|
||||
프로젝트 화면에서만 그린다(current_pid 로 판별). #}
|
||||
<aside class="pj-side">
|
||||
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(하위 업무 포함).
|
||||
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
||||
<div class="pj-side-search">
|
||||
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
||||
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="업무 전체 검색" />
|
||||
<div class="pj-search-results" id="pj-search-results" hidden></div>
|
||||
</div>
|
||||
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
|
||||
패널이 아니라 오른쪽 화면 전체에 목록을 띄우는 별도 페이지다. -->
|
||||
<nav class="pj-side-nav">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260923b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260923c" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,6 +70,9 @@
|
||||
{% elif n.type == 'completed' %}task_alt
|
||||
{% elif n.type == 'comment' %}chat_bubble
|
||||
{% elif n.type == 'mention' %}alternate_email
|
||||
{% elif n.type == 'due_soon' %}schedule
|
||||
{% elif n.type == 'due_today' %}today
|
||||
{% elif n.type == 'overdue' %}alarm
|
||||
{% else %}notifications{% endif %}
|
||||
</span>
|
||||
<div class="pj-inbox-body">
|
||||
@@ -93,5 +96,5 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/project.js?v=20260923b" defer></script>
|
||||
<script src="/static/project.js?v=20260923c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260923b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260923c" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -34,6 +34,26 @@
|
||||
</div>
|
||||
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
|
||||
</div>
|
||||
<!-- 검색·필터 — 정렬은 표 머리글 클릭(마감·우선순위 등). -->
|
||||
<div class="pj-filterbar" id="pj-mt-filterbar">
|
||||
<label class="pj-fb-search">
|
||||
<span class="material-symbols-outlined">filter_list</span>
|
||||
<input type="search" id="pj-mt-q" placeholder="내 업무에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
||||
</label>
|
||||
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
|
||||
<option value="all">마감: 전체</option>
|
||||
<option value="overdue">마감 지남</option>
|
||||
<option value="today">오늘 마감</option>
|
||||
<option value="week">이번 주 마감</option>
|
||||
<option value="none">마감일 없음</option>
|
||||
</select>
|
||||
<select id="pj-mt-priority" class="pj-fb-select" title="우선순위">
|
||||
<option value="all">우선순위: 전체</option>
|
||||
<option value="high">높음</option>
|
||||
<option value="normal">보통</option>
|
||||
<option value="low">낮음</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="pj-view pj-mytasks-pane">
|
||||
<table class="pj-table pj-mytasks-table" id="pj-mytasks-table">
|
||||
@@ -97,5 +117,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20260923b" defer></script>
|
||||
<script src="/static/project.js?v=20260923c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260923b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260923c" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -74,6 +74,49 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 필터 바 — 보드·리스트·달력·타임라인·대시보드 모두에 적용(이미 받은 업무를
|
||||
화면에서 거른다). 설정은 프로젝트별로 이 브라우저에 기억한다.
|
||||
정렬은 보드 카드 순서와 리스트 기본 순서(열 제목 클릭 정렬이 우선). -->
|
||||
<div class="pj-filterbar" id="pj-filterbar">
|
||||
<label class="pj-fb-search">
|
||||
<span class="material-symbols-outlined">filter_list</span>
|
||||
<input type="search" id="pj-fb-q" placeholder="이 화면에서 찾기 (제목·설명·담당자)" autocomplete="off" />
|
||||
</label>
|
||||
<select id="pj-fb-status" class="pj-fb-select" title="완료 상태">
|
||||
<option value="all">상태: 전체</option>
|
||||
<option value="open">미완료</option>
|
||||
<option value="done">완료</option>
|
||||
</select>
|
||||
<select id="pj-fb-assignee" class="pj-fb-select" title="담당자">
|
||||
<option value="all">담당자: 전체</option>
|
||||
<option value="me">나</option>
|
||||
<option value="none">담당자 없음</option>
|
||||
</select>
|
||||
<select id="pj-fb-due" class="pj-fb-select" title="마감일">
|
||||
<option value="all">마감: 전체</option>
|
||||
<option value="overdue">마감 지남</option>
|
||||
<option value="today">오늘 마감</option>
|
||||
<option value="week">이번 주 마감</option>
|
||||
<option value="none">마감일 없음</option>
|
||||
</select>
|
||||
<select id="pj-fb-priority" class="pj-fb-select" title="우선순위">
|
||||
<option value="all">우선순위: 전체</option>
|
||||
<option value="high">높음</option>
|
||||
<option value="normal">보통</option>
|
||||
<option value="low">낮음</option>
|
||||
</select>
|
||||
<select id="pj-fb-sort" class="pj-fb-select" title="정렬">
|
||||
<option value="manual">정렬: 기본</option>
|
||||
<option value="due">마감일순</option>
|
||||
<option value="priority">우선순위순</option>
|
||||
<option value="title">제목순</option>
|
||||
<option value="assignee">담당자순</option>
|
||||
<option value="created">최근 생성순</option>
|
||||
</select>
|
||||
<span class="pj-fb-count" id="pj-fb-count" hidden></span>
|
||||
<button type="button" class="pj-fb-reset" id="pj-fb-reset" hidden>초기화</button>
|
||||
</div>
|
||||
|
||||
<!-- 달력 (휴가 모듈과 동일한 월간 그리드) -->
|
||||
<div class="pj-view" data-view="calendar" hidden>
|
||||
<div class="pj-cal-head">
|
||||
@@ -291,6 +334,18 @@
|
||||
<input type="date" id="pj-t-due" />
|
||||
</span>
|
||||
</div>
|
||||
<!-- 팔로워(아사나의 협업자) — 완료·댓글 알림을 받는 사람. 만든 사람·담당자·
|
||||
댓글 단 사람·@태그된 사람은 자동으로 들어온다. 저장 버튼과 무관하게 즉시 반영.
|
||||
기존 업무에서만, 008 마이그레이션이 있어야 보인다. -->
|
||||
<div class="pj-meta-row2" id="pj-followers-row" hidden>
|
||||
<span class="pj-meta-label2">팔로워</span>
|
||||
<span class="pj-meta-value2 pj-followers">
|
||||
<span class="material-symbols-outlined pj-meta-ic">group</span>
|
||||
<span class="pj-follower-chips" id="pj-follower-chips"></span>
|
||||
<button type="button" class="pj-follower-add" id="pj-follower-add" title="팔로워 추가">+</button>
|
||||
<button type="button" class="pj-follow-toggle" id="pj-follow-toggle">팔로우</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -458,10 +513,11 @@
|
||||
"projects": {{ projects_meta | tojson }},
|
||||
"stagesByProject": {{ stages_by_project | tojson }},
|
||||
"boardStages": {{ board_stage_names | tojson }},
|
||||
"avatars": {{ avatars | tojson }}
|
||||
"avatars": {{ avatars | tojson }},
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20260923b" defer></script>
|
||||
<script src="/static/project.js?v=20260923c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1076,3 +1076,76 @@ label.pj-desc-fmtbtn { line-height: 26px; }
|
||||
.pj-btn-share { display: inline-flex; align-items: center; gap: 5px; }
|
||||
.pj-btn-share .material-symbols-outlined { font-size: 14px; }
|
||||
.pj-btn-share[hidden] { display: none; }
|
||||
|
||||
/* ── 좌측 사이드바 전체 검색 ── */
|
||||
.pj-side-search { position: relative; display: flex; align-items: center; margin-bottom: 10px; }
|
||||
.pj-side-search-ic { position: absolute; left: 9px; font-size: 18px; color: #8a9099; pointer-events: none; }
|
||||
.pj-side-search input {
|
||||
width: 100%; box-sizing: border-box; height: 34px; padding: 0 10px 0 32px;
|
||||
border: 1px solid var(--pj-border); border-radius: 8px; background: #f7f8f9;
|
||||
font-size: 13px; font-family: inherit; color: var(--pj-ink);
|
||||
}
|
||||
.pj-side-search input:focus { outline: none; background: #fff; border-color: var(--pj-accent); box-shadow: 0 0 0 3px var(--pj-accent-tint); }
|
||||
.pj-search-results {
|
||||
position: fixed; z-index: 1200; overflow-y: auto; background: #fff;
|
||||
border: 1px solid var(--pj-border); border-radius: 10px; box-shadow: 0 12px 32px rgba(16,24,40,.16);
|
||||
padding: 4px;
|
||||
}
|
||||
.pj-search-results[hidden] { display: none; }
|
||||
.pj-sr-item { padding: 8px 10px; border-radius: 8px; cursor: pointer; }
|
||||
.pj-sr-item:hover, .pj-sr-item.is-active { background: var(--pj-accent-tint); }
|
||||
.pj-sr-title { font-size: 13.5px; font-weight: 700; color: var(--pj-ink); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
|
||||
.pj-sr-item.is-done .pj-sr-title { color: var(--pj-ink-soft); }
|
||||
.pj-sr-check { font-size: 16px; color: #1e8e5a; }
|
||||
.pj-sr-parent { font-weight: 500; color: var(--pj-ink-soft); }
|
||||
.pj-sr-meta { margin-top: 2px; font-size: 12px; color: var(--pj-ink-soft); }
|
||||
.pj-sr-snippet { margin-top: 3px; font-size: 12px; color: #525860; line-height: 1.45; }
|
||||
.pj-sr-where { display: inline-block; padding: 0 5px; margin-right: 2px; border-radius: 4px; background: #eef0f2; font-size: 11px; font-weight: 700; color: #6b6f76; }
|
||||
.pj-search-results mark { background: #fff3b0; color: inherit; border-radius: 2px; padding: 0 1px; }
|
||||
.pj-sr-empty { padding: 14px 12px; font-size: 13px; color: var(--pj-ink-soft); }
|
||||
|
||||
/* ── 필터 바 (프로젝트 화면 / 내 업무) ── */
|
||||
.pj-filterbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; flex: none; margin: -6px 0 14px; }
|
||||
.pj-fb-search {
|
||||
display: flex; align-items: center; gap: 6px; height: 32px; padding: 0 10px;
|
||||
border: 1px solid var(--pj-border); border-radius: 8px; background: #fff; flex: 0 1 280px; min-width: 180px;
|
||||
}
|
||||
.pj-fb-search .material-symbols-outlined { font-size: 18px; color: #8a9099; }
|
||||
.pj-fb-search input { border: none; outline: none; background: transparent; font-size: 13px; font-family: inherit; width: 100%; color: var(--pj-ink); }
|
||||
.pj-fb-search.is-set { border-color: var(--pj-accent); background: var(--pj-accent-tint); }
|
||||
.pj-fb-search:focus-within { border-color: var(--pj-accent); }
|
||||
.pj-fb-select {
|
||||
height: 32px; padding: 0 8px; border: 1px solid var(--pj-border); border-radius: 8px; background: #fff;
|
||||
font-size: 12.5px; font-weight: 600; font-family: inherit; color: #525860; cursor: pointer;
|
||||
}
|
||||
.pj-fb-select:hover { background: #f6f7f8; }
|
||||
.pj-fb-select.is-set { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); }
|
||||
.pj-fb-count { font-size: 12.5px; font-weight: 700; color: var(--pj-accent-dark); }
|
||||
.pj-fb-count[hidden], .pj-fb-reset[hidden] { display: none; }
|
||||
.pj-fb-reset { border: none; background: transparent; color: var(--pj-ink-soft); font-size: 12.5px; font-weight: 600; cursor: pointer; text-decoration: underline; padding: 0 4px; }
|
||||
.pj-fb-reset:hover { color: var(--pj-ink); }
|
||||
|
||||
/* ── 업무 팝업 — 팔로워 ── */
|
||||
.pj-followers { flex-wrap: wrap; row-gap: 6px; padding: 5px 0; }
|
||||
.pj-follower-chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.pj-follower-chip {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 4px 0 4px;
|
||||
border-radius: 999px; background: #f1f2f4; font-size: 12.5px; font-weight: 600; color: var(--pj-ink);
|
||||
}
|
||||
.pj-follower-chip .pj-gicon-sm { font-size: 18px; }
|
||||
.pj-follower-x {
|
||||
border: none; background: transparent; color: #8a9099; cursor: pointer; font-size: 14px; line-height: 1;
|
||||
width: 18px; height: 18px; border-radius: 50%; padding: 0; display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.pj-follower-x:hover { background: #dfe2e6; color: #1e1f21; }
|
||||
.pj-follower-add {
|
||||
width: 26px; height: 26px; border-radius: 50%; border: 1px dashed #b8bec6; background: #fff;
|
||||
color: #6b6f76; font-size: 16px; line-height: 1; cursor: pointer; padding: 0; display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.pj-follower-add:hover { border-color: var(--pj-accent); color: var(--pj-accent); }
|
||||
.pj-follow-toggle {
|
||||
margin-left: auto; height: 26px; padding: 0 10px; border-radius: 999px; border: 1px solid var(--pj-border);
|
||||
background: #fff; font-size: 12px; font-weight: 700; color: #525860; cursor: pointer;
|
||||
}
|
||||
.pj-follow-toggle:hover { background: #f6f7f8; }
|
||||
.pj-follow-toggle.is-on { background: var(--pj-accent-tint); border-color: var(--pj-accent); color: var(--pj-accent-dark); }
|
||||
|
||||
+352
-8
@@ -946,10 +946,32 @@
|
||||
},
|
||||
];
|
||||
|
||||
// 검색어·마감·우선순위(필터 바) — 상태(진행 중/완료/전체)는 위 탭이 맡는다.
|
||||
const mtFilter = Object.assign({}, TASK_FILTER_DEFAULT);
|
||||
const mtQ = el("pj-mt-q"), mtDue = el("pj-mt-due"), mtPri = el("pj-mt-priority");
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem("pj_mt_filter") || "{}");
|
||||
["q", "due", "priority"].forEach(function (k) { if (saved[k]) mtFilter[k] = saved[k]; });
|
||||
} catch (_) {}
|
||||
function saveMtFilter() {
|
||||
try { localStorage.setItem("pj_mt_filter", JSON.stringify({ q: mtFilter.q, due: mtFilter.due, priority: mtFilter.priority })); } catch (_) {}
|
||||
render();
|
||||
}
|
||||
if (mtQ) {
|
||||
mtQ.value = mtFilter.q; mtDue.value = mtFilter.due; mtPri.value = mtFilter.priority;
|
||||
let qt = null;
|
||||
mtQ.addEventListener("input", function () {
|
||||
clearTimeout(qt);
|
||||
qt = setTimeout(function () { mtFilter.q = mtQ.value.trim(); saveMtFilter(); }, 150);
|
||||
});
|
||||
mtDue.addEventListener("change", function () { mtFilter.due = mtDue.value; saveMtFilter(); });
|
||||
mtPri.addEventListener("change", function () { mtFilter.priority = mtPri.value; saveMtFilter(); });
|
||||
}
|
||||
|
||||
function passFilter(t) {
|
||||
if (filter === "open") return !t.completed_at;
|
||||
if (filter === "done") return !!t.completed_at;
|
||||
return true;
|
||||
if (filter === "open" && t.completed_at) return false;
|
||||
if (filter === "done" && !t.completed_at) return false;
|
||||
return taskMatchesFilter(t, mtFilter, me, today);
|
||||
}
|
||||
|
||||
// 최상위 업무만 — 하위 업무(parent_task_id 있음)는 render() 에서 해당
|
||||
@@ -1235,11 +1257,82 @@
|
||||
// 프로젝트 양쪽에서 각각 한 번씩 나온다 — 그래야 각 화면에 다 보인다).
|
||||
// "전체" 모드는 원 소속(context_project_id === project_id)만 세어 중복을 없앤다.
|
||||
let viewScope = "project";
|
||||
function visibleTasks() {
|
||||
// 필터 바(#pj-filterbar) 상태 — 프로젝트별로 이 브라우저에 기억한다.
|
||||
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());
|
||||
function scopeTasks() {
|
||||
return viewScope === "project"
|
||||
? tasks.filter(function (t) { return t.context_project_id === projectId; })
|
||||
: tasks.filter(function (t) { return t.context_project_id === t.project_id; });
|
||||
}
|
||||
// 모든 뷰가 이 함수로 업무를 받는다 — 스코프 → 필터 → 정렬 순.
|
||||
function visibleTasks() {
|
||||
const rows = scopeTasks().filter(function (t) { return taskMatchesFilter(t, taskFilter, me, todayIso); });
|
||||
return sortTasksBy(rows, taskFilter.sort);
|
||||
}
|
||||
// 보드 카드 순서 바꾸기는 "기본 정렬 + 필터 없음"일 때만 — 가려진 카드가 있거나
|
||||
// 다른 기준으로 정렬돼 있으면 놓은 자리가 실제 순서와 어긋난다(아사나도 같다).
|
||||
function manualOrderAllowed() {
|
||||
return taskFilter.sort === "manual" && !taskFilterActive(taskFilter);
|
||||
}
|
||||
|
||||
const FB = {
|
||||
q: el("pj-fb-q"), status: el("pj-fb-status"), assignee: el("pj-fb-assignee"),
|
||||
due: el("pj-fb-due"), priority: el("pj-fb-priority"), sort: el("pj-fb-sort"),
|
||||
count: el("pj-fb-count"), reset: el("pj-fb-reset"),
|
||||
};
|
||||
// 담당자 선택지 = 이 프로젝트 멤버 + 지금 목록에 나오는 담당자(전체 스코프 대비).
|
||||
function fillAssigneeFilter() {
|
||||
if (!FB.assignee) return;
|
||||
const emails = [];
|
||||
members.forEach(function (m) { const e = (m.user_email || "").toLowerCase(); if (e && emails.indexOf(e) < 0) emails.push(e); });
|
||||
scopeTasks().forEach(function (t) { const e = (t.assignee_email || "").toLowerCase(); if (e && emails.indexOf(e) < 0) emails.push(e); });
|
||||
if (taskFilter.assignee.indexOf("@") > 0 && emails.indexOf(taskFilter.assignee) < 0) emails.push(taskFilter.assignee);
|
||||
emails.sort(function (a, b) { return idOf(a).localeCompare(idOf(b)); });
|
||||
FB.assignee.innerHTML =
|
||||
'<option value="all">담당자: 전체</option><option value="me">나</option><option value="none">담당자 없음</option>' +
|
||||
emails.map(function (e) { return '<option value="' + escapeHtml(e) + '">' + escapeHtml(idOf(e)) + "</option>"; }).join("");
|
||||
FB.assignee.value = taskFilter.assignee;
|
||||
}
|
||||
function updateFilterSummary() {
|
||||
if (!FB.count) return;
|
||||
const active = taskFilterActive(taskFilter);
|
||||
if (active) {
|
||||
FB.count.textContent = visibleTasks().length + " / " + scopeTasks().length + "건";
|
||||
}
|
||||
FB.count.hidden = !active;
|
||||
FB.reset.hidden = !(active || taskFilter.sort !== "manual");
|
||||
Object.keys(FB).forEach(function (k) {
|
||||
if (FB[k] && FB[k].tagName === "SELECT") FB[k].classList.toggle("is-set", FB[k].value !== TASK_FILTER_DEFAULT[k]);
|
||||
});
|
||||
if (FB.q) FB.q.parentNode.classList.toggle("is-set", !!taskFilter.q);
|
||||
}
|
||||
function applyFilterChange() {
|
||||
try { localStorage.setItem(FILTER_KEY, JSON.stringify(taskFilter)); } catch (_) {}
|
||||
refreshActiveView();
|
||||
}
|
||||
if (FB.q) {
|
||||
FB.q.value = taskFilter.q;
|
||||
["status", "due", "priority", "sort"].forEach(function (k) { FB[k].value = taskFilter[k]; });
|
||||
fillAssigneeFilter();
|
||||
let qTimer = null;
|
||||
FB.q.addEventListener("input", function () {
|
||||
clearTimeout(qTimer);
|
||||
qTimer = setTimeout(function () { taskFilter.q = FB.q.value.trim(); applyFilterChange(); }, 150);
|
||||
});
|
||||
FB.q.addEventListener("keydown", function (e) { if (e.key === "Escape") { FB.q.value = ""; taskFilter.q = ""; applyFilterChange(); } });
|
||||
["status", "assignee", "due", "priority", "sort"].forEach(function (k) {
|
||||
FB[k].addEventListener("change", function () { taskFilter[k] = FB[k].value; applyFilterChange(); });
|
||||
});
|
||||
FB.reset.addEventListener("click", function () {
|
||||
taskFilter = Object.assign({}, TASK_FILTER_DEFAULT);
|
||||
FB.q.value = "";
|
||||
["status", "assignee", "due", "priority", "sort"].forEach(function (k) { FB[k].value = taskFilter[k]; });
|
||||
applyFilterChange();
|
||||
});
|
||||
}
|
||||
|
||||
// ── 뷰 토글 ──
|
||||
const tabs = el("pj-view-tabs");
|
||||
@@ -1280,7 +1373,9 @@
|
||||
scopeToggle.querySelectorAll("[data-scope]").forEach(function (b) {
|
||||
b.classList.toggle("is-active", b === btn);
|
||||
});
|
||||
fillAssigneeFilter(); // 스코프가 바뀌면 담당자 후보도 달라진다
|
||||
renderView(currentView);
|
||||
updateFilterSummary();
|
||||
});
|
||||
}
|
||||
if (moveScopeHighlight) moveScopeHighlight(false);
|
||||
@@ -2083,6 +2178,10 @@
|
||||
const t = tasks.find(function (x) { return x.id === taskId; });
|
||||
if (!t) return;
|
||||
if (t.stage_id === stageId) {
|
||||
if (!manualOrderAllowed()) {
|
||||
showToast("필터·정렬을 쓰는 중에는 카드 순서를 바꿀 수 없습니다. (정렬: 기본, 필터 초기화 후 가능)", "error");
|
||||
return;
|
||||
}
|
||||
// 같은 세션 안에서 카드 위치만 이동 — 세션 이동이 아니라 정렬.
|
||||
const currentOrder = tasks.filter(function (x) { return x.stage_id === stageId; });
|
||||
const idx = cardDropIndex(body, e.clientY, taskId);
|
||||
@@ -2668,6 +2767,7 @@
|
||||
// 모든 뷰 + 좌측 트리 클라이언트 재렌더(새로고침 없음).
|
||||
renderView(currentView);
|
||||
if (typeof renderTree === "function") renderTree();
|
||||
updateFilterSummary();
|
||||
}
|
||||
|
||||
// 업무 우클릭 메뉴 공용 항목 — 보드 카드·리스트 행·달력 막대·타임라인
|
||||
@@ -2794,11 +2894,71 @@
|
||||
if (e.key === "Escape" && !taskModal.hidden) { e.preventDefault(); attemptCloseTaskModal(); }
|
||||
});
|
||||
|
||||
// ── 팔로워 (아사나의 협업자) — 완료·댓글 알림을 받는 사람 ──
|
||||
// 저장 버튼과 무관하게 누르는 즉시 서버에 반영된다.
|
||||
const followersRow = el("pj-followers-row");
|
||||
let followersTask = null;
|
||||
let followers = [];
|
||||
function renderFollowers() {
|
||||
const box = el("pj-follower-chips");
|
||||
if (!box) return;
|
||||
box.innerHTML = followers.map(function (e) {
|
||||
return '<span class="pj-follower-chip" data-tip="' + escapeHtml(e) + '">' +
|
||||
avatarHtml(e, "pj-gicon-sm") + '<span class="pj-follower-name">' + escapeHtml(idOf(e)) + "</span>" +
|
||||
'<button type="button" class="pj-follower-x" data-email="' + escapeHtml(e) + '" title="팔로워에서 빼기">×</button></span>';
|
||||
}).join("") || '<span class="pj-muted-sm">없음</span>';
|
||||
box.querySelectorAll(".pj-follower-x").forEach(function (b) {
|
||||
b.addEventListener("click", function () { setFollower(b.dataset.email, false); });
|
||||
});
|
||||
const followingMe = followers.indexOf(me) >= 0;
|
||||
const tog = el("pj-follow-toggle");
|
||||
tog.textContent = followingMe ? "팔로우 취소" : "팔로우";
|
||||
tog.classList.toggle("is-on", followingMe);
|
||||
}
|
||||
async function setFollower(email, on) {
|
||||
if (!followersTask) return;
|
||||
const tid = followersTask.id;
|
||||
try {
|
||||
const res = on
|
||||
? await api("POST", "/project/api/tasks/" + tid + "/followers", { email: email })
|
||||
: await api("DELETE", "/project/api/tasks/" + tid + "/followers/" + encodeURIComponent(email));
|
||||
if (!followersTask || followersTask.id !== tid) return; // 그 사이 다른 업무를 열었다
|
||||
followers = res.followers || [];
|
||||
renderFollowers();
|
||||
} catch (e) { showToast("팔로워 변경 실패: " + e.message, "error"); }
|
||||
}
|
||||
function showFollowers(task, list) {
|
||||
followersTask = task;
|
||||
if (!followersRow) return;
|
||||
if (!task || list == null) { followersRow.hidden = true; return; } // 새 업무 / 008 미적용
|
||||
followers = list.map(function (e) { return String(e).toLowerCase(); });
|
||||
followersRow.hidden = false;
|
||||
renderFollowers();
|
||||
}
|
||||
if (followersRow) {
|
||||
el("pj-follow-toggle").addEventListener("click", function () {
|
||||
setFollower(me, followers.indexOf(me) < 0);
|
||||
});
|
||||
el("pj-follower-add").addEventListener("click", async function (e) {
|
||||
if (!followersTask) return;
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
let list = [];
|
||||
try { list = await membersOfProject(followersTask.project_id); } catch (_) {}
|
||||
const cands = list.map(function (m) { return (m.user_email || "").toLowerCase(); })
|
||||
.filter(function (em) { return em && followers.indexOf(em) < 0; });
|
||||
if (!cands.length) { showToast("추가할 수 있는 멤버가 없습니다."); return; }
|
||||
showContextMenu(r.left, r.bottom + 4, cands.map(function (em) {
|
||||
return { label: idOf(em), onClick: function () { setFollower(em, true); } };
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function loadTaskExtras(task) {
|
||||
if (!task || (!subtaskBlock && !linksBlock)) return;
|
||||
try {
|
||||
const res = await api("GET", "/project/api/tasks/" + task.id);
|
||||
const detail = res.task;
|
||||
if (currentTaskId === task.id) showFollowers(task, detail.followers);
|
||||
if (subtaskBlock) {
|
||||
subtaskBlock.setContext({ taskId: task.id, projectId: task.project_id, canDelete: canDelete });
|
||||
subtaskBlock.render(detail.subtasks || []);
|
||||
@@ -2831,9 +2991,14 @@
|
||||
try { list = (await api("GET", "/project/api/projects/" + projId + "/members")).members || []; }
|
||||
catch (_) { list = []; }
|
||||
}
|
||||
sel.innerHTML = '<option value="">담당자 없음</option>' + list.map(function (m) {
|
||||
const name = idOf(m.user_email);
|
||||
return '<option value="' + m.user_email + '" data-name="' + escapeHtml(name) + '">' + escapeHtml(name) + "</option>";
|
||||
const emails = list.map(function (m) { return m.user_email; });
|
||||
// 지금 담당자가 멤버 목록에 없어도(프로젝트를 만든 owner, 멤버에서 빠진 사람)
|
||||
// 선택지에 넣는다 — 없으면 칸이 비고, 저장하면 담당자가 지워졌다.
|
||||
const cur = (currentEmail || "").toLowerCase();
|
||||
if (cur && !emails.some(function (e) { return (e || "").toLowerCase() === cur; })) emails.push(currentEmail);
|
||||
sel.innerHTML = '<option value="">담당자 없음</option>' + emails.map(function (e) {
|
||||
const name = idOf(e);
|
||||
return '<option value="' + escapeHtml(e) + '" data-name="' + escapeHtml(name) + '">' + escapeHtml(name) + "</option>";
|
||||
}).join("");
|
||||
sel.value = currentEmail || "";
|
||||
}
|
||||
@@ -2861,8 +3026,9 @@
|
||||
const shareBtn = el("pj-share-task");
|
||||
if (shareBtn) shareBtn.hidden = !task;
|
||||
if (task) setCompleteBtn(!!task.completed_at);
|
||||
// 댓글·첨부·하위업무·연결은 기존 업무 편집 시에만
|
||||
// 댓글·첨부·하위업무·연결·팔로워는 기존 업무 편집 시에만
|
||||
currentTaskId = task ? task.id : null;
|
||||
showFollowers(null, null); // 상세를 받으면(loadTaskExtras) 다시 그린다
|
||||
el("pj-attach-block").hidden = !task;
|
||||
el("pj-comment-block").hidden = !task;
|
||||
if (subtaskBlock) el("pj-subtask-block").hidden = !task;
|
||||
@@ -3015,6 +3181,11 @@
|
||||
inp.value = "";
|
||||
clearMentions(inp);
|
||||
loadComments(currentTaskId);
|
||||
// 댓글을 달면(서버가) 자동 팔로우 — 화면의 팔로워 목록도 맞춘다.
|
||||
if (followersTask && !followersRow.hidden && followers.indexOf(me) < 0) {
|
||||
followers.push(me);
|
||||
renderFollowers();
|
||||
}
|
||||
} catch (e) { alert("등록 실패: " + e.message); }
|
||||
}
|
||||
attachMentionInput(el("pj-comment-input"));
|
||||
@@ -3515,6 +3686,7 @@
|
||||
// 최초 렌더 — 아사나처럼 프로젝트에 들어오면 보드(세션)가 기본 화면이다
|
||||
// (달력을 보던 중이었다면 그 기억된 뷰를 그린다, 위 VIEW_KEY 복원 참고).
|
||||
renderView(currentView);
|
||||
updateFilterSummary(); // 기억된 필터가 있으면 개수·초기화 버튼 표시
|
||||
|
||||
// 사이드 트리에서 업무 클릭(?task=ID)으로 들어오면 해당 업무 모달 자동 열기.
|
||||
// 단, 처리 후 URL 에서 task 파라미터를 제거한다 — 같은 페이지에 머무는 동안
|
||||
@@ -3555,6 +3727,7 @@
|
||||
stages = snap.stages || [];
|
||||
stagesByProject[projectId] = stages;
|
||||
members = snap.members || [];
|
||||
fillAssigneeFilter();
|
||||
renderMemberList();
|
||||
refreshActiveView();
|
||||
refreshMyOpenBadge();
|
||||
@@ -4038,6 +4211,176 @@
|
||||
return String(email == null ? "" : email).split("@")[0];
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════
|
||||
// 업무 필터·정렬 (프로젝트 화면 필터 바 + 내 업무 화면 공용)
|
||||
// f = { q, status, assignee, due, priority, sort }
|
||||
// status : all | open | done
|
||||
// assignee : all | me | none | <email>
|
||||
// due : all | overdue | today | week | none
|
||||
// priority : all | high | normal | low
|
||||
// sort : manual | due | priority | title | assignee | created
|
||||
// 서버 재조회 없이 이미 받은 업무 목록에서 거른다.
|
||||
// ════════════════════════════════════════════════════════════
|
||||
const TASK_FILTER_DEFAULT = { q: "", status: "all", assignee: "all", due: "all", priority: "all", sort: "manual" };
|
||||
|
||||
function localIso(d) {
|
||||
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
|
||||
}
|
||||
// "이번 주" 마감 = 오늘부터 이번 주 일요일까지(월~일을 한 주로 본다).
|
||||
function endOfWeekIso(todayIso) {
|
||||
const d = new Date(todayIso + "T00:00:00");
|
||||
const add = (7 - d.getDay()) % 7; // 일요일=0 → 오늘이 일요일이면 오늘까지
|
||||
d.setDate(d.getDate() + add);
|
||||
return localIso(d);
|
||||
}
|
||||
// 설명 HTML → 검색용 평문(업무 객체에 캐시 — 설명이 바뀌면 다시 만든다).
|
||||
function taskSearchText(t) {
|
||||
if (t._searchSrc !== t.description) {
|
||||
t._searchSrc = t.description;
|
||||
t._searchDesc = String(t.description || "").replace(/<[^>]*>/g, " ")
|
||||
.replace(/ /g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&")
|
||||
.toLowerCase();
|
||||
}
|
||||
return t._searchDesc;
|
||||
}
|
||||
function taskFilterActive(f) {
|
||||
return !!(f.q || f.status !== "all" || f.assignee !== "all" || f.due !== "all" || f.priority !== "all");
|
||||
}
|
||||
function taskMatchesFilter(t, f, me, todayIso) {
|
||||
if (f.status === "open" && t.completed_at) return false;
|
||||
if (f.status === "done" && !t.completed_at) return false;
|
||||
const a = (t.assignee_email || "").toLowerCase();
|
||||
if (f.assignee === "me" && a !== me) return false;
|
||||
if (f.assignee === "none" && a) return false;
|
||||
if (f.assignee !== "all" && f.assignee !== "me" && f.assignee !== "none" && a !== f.assignee) return false;
|
||||
if (f.priority !== "all" && (t.priority || "normal") !== f.priority) return false;
|
||||
const due = t.due_date ? t.due_date.slice(0, 10) : "";
|
||||
if (f.due === "none" && due) return false;
|
||||
if (f.due === "overdue" && !(due && due < todayIso && !t.completed_at)) return false;
|
||||
if (f.due === "today" && due !== todayIso) return false;
|
||||
if (f.due === "week" && !(due && due >= todayIso && due <= endOfWeekIso(todayIso))) return false;
|
||||
if (f.q) {
|
||||
const q = f.q.toLowerCase();
|
||||
const hay = [t.title, idOf(a), t.project_name, t.stage_name].join(" ").toLowerCase();
|
||||
if (hay.indexOf(q) < 0 && taskSearchText(t).indexOf(q) < 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const PRIORITY_RANK = { high: 0, normal: 1, low: 2 };
|
||||
function sortTasksBy(rows, sort) {
|
||||
if (!sort || sort === "manual") return rows;
|
||||
const key = {
|
||||
due: function (t) { return t.due_date || "9999-99-99"; },
|
||||
priority: function (t) { return PRIORITY_RANK[t.priority || "normal"]; },
|
||||
title: function (t) { return (t.title || "").toLowerCase(); },
|
||||
assignee: function (t) { return t.assignee_email ? idOf(t.assignee_email).toLowerCase() : ""; },
|
||||
created: function (t) { return -t.id; },
|
||||
}[sort];
|
||||
if (!key) return rows;
|
||||
return rows.slice().sort(function (a, b) {
|
||||
const va = key(a), vb = key(b);
|
||||
if (va < vb) return -1;
|
||||
if (va > vb) return 1;
|
||||
return (a.due_date || "9999").localeCompare(b.due_date || "9999") || a.id - b.id;
|
||||
});
|
||||
}
|
||||
|
||||
// ── 좌측 사이드바 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트 ──
|
||||
function initGlobalSearch() {
|
||||
const input = el("pj-global-search");
|
||||
const box = el("pj-search-results");
|
||||
if (!input || !box) return;
|
||||
let timer = null, seq = 0, items = [], active = -1;
|
||||
|
||||
function close() { box.hidden = true; active = -1; }
|
||||
// 사이드바는 자체 스크롤 영역이라 안에 두면 결과창이 잘린다 — 화면 기준(fixed)으로 띄운다.
|
||||
function place() {
|
||||
const r = input.getBoundingClientRect();
|
||||
box.style.left = r.left + "px";
|
||||
box.style.top = (r.bottom + 6) + "px";
|
||||
box.style.width = Math.max(380, r.width) + "px";
|
||||
box.style.maxHeight = Math.max(200, window.innerHeight - r.bottom - 24) + "px";
|
||||
}
|
||||
function show() { place(); box.hidden = false; }
|
||||
window.addEventListener("resize", function () { if (!box.hidden) place(); });
|
||||
function highlight(text, q) {
|
||||
const s = String(text || "");
|
||||
const i = s.toLowerCase().indexOf(q.toLowerCase());
|
||||
if (!q || i < 0) return escapeHtml(s);
|
||||
return escapeHtml(s.slice(0, i)) + "<mark>" + escapeHtml(s.slice(i, i + q.length)) + "</mark>" + escapeHtml(s.slice(i + q.length));
|
||||
}
|
||||
function go(r) { location.href = "/project/t/" + r.id; }
|
||||
function setActive(i) {
|
||||
const rows = box.querySelectorAll(".pj-sr-item");
|
||||
rows.forEach(function (r, k) { r.classList.toggle("is-active", k === i); });
|
||||
active = i;
|
||||
if (rows[i]) rows[i].scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
const MATCH_LABEL = { title: "제목", description: "설명", comment: "댓글" };
|
||||
function render(q) {
|
||||
if (!items.length) {
|
||||
box.innerHTML = '<div class="pj-sr-empty">"' + escapeHtml(q) + '" 검색 결과가 없습니다.</div>';
|
||||
show();
|
||||
return;
|
||||
}
|
||||
box.innerHTML = items.map(function (r, i) {
|
||||
return '<div class="pj-sr-item' + (r.completed ? " is-done" : "") + '" data-i="' + i + '">' +
|
||||
'<div class="pj-sr-title">' +
|
||||
(r.completed ? '<span class="material-symbols-outlined pj-sr-check">check_circle</span>' : "") +
|
||||
(r.parent_title ? '<span class="pj-sr-parent">' + escapeHtml(r.parent_title) + " ›</span> " : "") +
|
||||
highlight(r.title, q) + "</div>" +
|
||||
'<div class="pj-sr-meta"><span style="color:' + escapeHtml(r.project_color) + '">●</span> ' +
|
||||
escapeHtml(r.project_name) +
|
||||
(r.assignee_email ? " · " + escapeHtml(idOf(r.assignee_email)) : "") +
|
||||
(r.due_date ? " · 마감 " + escapeHtml(fmtDateKr(r.due_date)) : "") + "</div>" +
|
||||
(r.snippet && r.match !== "title"
|
||||
? '<div class="pj-sr-snippet"><span class="pj-sr-where">' + MATCH_LABEL[r.match] + "</span> " + highlight(r.snippet, q) + "</div>"
|
||||
: "") +
|
||||
"</div>";
|
||||
}).join("");
|
||||
show();
|
||||
box.querySelectorAll(".pj-sr-item").forEach(function (row) {
|
||||
row.addEventListener("mousedown", function (e) { e.preventDefault(); go(items[+row.dataset.i]); });
|
||||
});
|
||||
active = -1;
|
||||
}
|
||||
async function search() {
|
||||
const q = input.value.trim();
|
||||
if (q.length < 2) { items = []; close(); return; }
|
||||
const my = ++seq;
|
||||
try {
|
||||
const res = await api("GET", "/project/api/search?q=" + encodeURIComponent(q));
|
||||
if (my !== seq) return; // 더 늦게 친 검색어의 결과가 이미 왔다
|
||||
items = res.results || [];
|
||||
render(q);
|
||||
} catch (e) {
|
||||
if (my === seq) { box.innerHTML = '<div class="pj-sr-empty">검색 실패: ' + escapeHtml(e.message) + "</div>"; show(); }
|
||||
}
|
||||
}
|
||||
input.addEventListener("input", function () { clearTimeout(timer); timer = setTimeout(search, 250); });
|
||||
input.addEventListener("focus", function () { if (items.length && input.value.trim().length >= 2) show(); });
|
||||
input.addEventListener("blur", function () { setTimeout(close, 150); });
|
||||
input.addEventListener("keydown", function (e) {
|
||||
if (e.key === "ArrowDown" && items.length) { e.preventDefault(); setActive(Math.min(items.length - 1, active + 1)); }
|
||||
else if (e.key === "ArrowUp" && items.length) { e.preventDefault(); setActive(Math.max(0, active - 1)); }
|
||||
else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
if (active >= 0 && items[active]) go(items[active]);
|
||||
else if (items.length === 1) go(items[0]);
|
||||
else { clearTimeout(timer); search(); }
|
||||
} else if (e.key === "Escape") { close(); input.blur(); }
|
||||
});
|
||||
// 어디서든 "/" 를 누르면 검색창으로(입력칸·편집 중일 땐 제외) — 아사나 단축키와 같다.
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (e.key !== "/" || e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
const t = e.target;
|
||||
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
|
||||
e.preventDefault();
|
||||
input.focus();
|
||||
input.select();
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s == null ? "" : s)
|
||||
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
||||
@@ -4301,6 +4644,7 @@
|
||||
initInbox();
|
||||
initMentionInbox();
|
||||
initLiveRefresh();
|
||||
initGlobalSearch();
|
||||
initScrollIndicators();
|
||||
initHoverTips();
|
||||
});
|
||||
|
||||
+37
-3
@@ -140,7 +140,7 @@ docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" \
|
||||
# PROJECT_DB_URL=postgresql://project_app:<APP_PWD>@postgres-db:5432/project_db
|
||||
# (메일 쓰려면 SMTP_* 추가)
|
||||
|
||||
# 3) 마이그레이션 002~007 적용 (첨부/알림, 세션 생성자·하위업무·멀티호밍,
|
||||
# 3) 마이그레이션 002~008 적용 (첨부/알림, 세션 생성자·하위업무·멀티호밍,
|
||||
# 업무 시간, 세션 색상, 댓글 첨부, @태그)
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_002_attachments_notifications.sql
|
||||
@@ -154,7 +154,10 @@ docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_005_comment_attachments.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_006_mentions.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db < scripts/sql/project_db_007_live_version.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_007_live_version.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_008_followers_reminders_search.sql
|
||||
|
||||
# 4) 재배포 (git pull 후 반드시 --build)
|
||||
cd /opt/www/main && docker compose up -d --build web
|
||||
@@ -238,7 +241,38 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
- 설명란 sanitizer 는 URL 을 허용 목록(http/https/mailto/tel/상대경로, img 는 png·jpeg 등
|
||||
data: 이미지)으로 검사한다 — 금지 목록은 `jav	ascript:` 로 우회됐다.
|
||||
|
||||
## 6-2. 검색 · 필터 · 정렬
|
||||
|
||||
- **전체 검색** — 좌측 사이드바 맨 위 검색창(`#pj-global-search`, 어디서든 `/` 키). 2글자 이상이면
|
||||
`GET /api/search?q=` 로 내가 볼 수 있는 프로젝트의 업무(하위 업무 포함)를 제목·설명·댓글에서
|
||||
찾는다. 설명은 HTML 이라 DB 에서 넉넉히 가져와 본문 텍스트로 다시 확인한다(태그 이름에만
|
||||
걸린 결과 제거). 결과에 "설명/댓글" 어디서 걸렸는지와 미리보기. 누르면 `/project/t/{id}`.
|
||||
008 의 pg_trgm GIN 인덱스(title·description·comment body)가 `ILIKE '%…%'` 를 받쳐준다.
|
||||
- **필터 바** — 프로젝트 화면(`#pj-filterbar`): 찾기(제목·설명·담당자·세션) · 상태 · 담당자
|
||||
(나/없음/특정인) · 마감(지남/오늘/이번 주/없음) · 우선순위 · 정렬(기본/마감일/우선순위/제목/
|
||||
담당자/최근 생성). 서버 재조회 없이 `visibleTasks()`(스코프 → 필터 → 정렬)에서 거르므로
|
||||
보드·리스트·달력·타임라인·대시보드 모두에 적용된다. 프로젝트별로 localStorage 에 기억.
|
||||
필터나 정렬이 켜져 있으면 보드 카드 순서 드래그는 막는다(가려진 카드 때문에 순서가 어긋남).
|
||||
리스트는 열 제목 클릭 정렬이 우선. 내 업무 화면에도 찾기·마감·우선순위 필터(`#pj-mt-filterbar`).
|
||||
공용 로직: `taskMatchesFilter` / `sortTasksBy`.
|
||||
|
||||
## 6-3. 팔로워 · 마감 알림
|
||||
|
||||
- **팔로워**(`task_followers`, 008) — 아사나의 협업자. 업무 팝업 메타 목록의 "팔로워" 줄에서
|
||||
추가(+ → 프로젝트 멤버)/빼기(×)/내 팔로우 토글. 즉시 저장(저장 버튼과 무관).
|
||||
자동 팔로우: 만든 사람 · 담당자(배정 시) · 댓글 단 사람 · @태그된 사람. 008 이 기존 업무에도
|
||||
같은 규칙으로 백필한다. API: `GET/POST /api/tasks/{id}/followers`(body `email`, 없으면 나),
|
||||
`DELETE /api/tasks/{id}/followers/{email}` — 다른 사람은 그 프로젝트 멤버·owner·관리자만 추가 가능.
|
||||
- **알림 수신자 변경** — 완료·댓글 인앱 알림은 이제 "담당자 + 팔로워"에게만 간다(예전: 프로젝트
|
||||
멤버 전원). 008 미적용이면 예전 방식으로 폴백.
|
||||
- **마감 알림**(`reminders.py`) — 웹 프로세스 안 데몬 스레드가 5분마다 깨어, 영업일(주말·
|
||||
`KR_HOLIDAYS` 제외) 설정 시각(`PROJECT_REMINDER_HOUR`, 기본 9시 KST) 이후 하루 한 번 돈다.
|
||||
`due_soon`(다음 영업일까지 마감 — 금요일이면 주말·월요일분까지) · `due_today` · `overdue`
|
||||
(최근 7일 이내 마감분). 수신자는 담당자, 없으면 팔로워. `task_reminders` UNIQUE(업무·종류·
|
||||
마감일·수신자)로 한 번만 — 재기동·중복 실행에도 안전, 마감일을 바꾸면 다시 알린다.
|
||||
`PROJECT_REMINDER_EMAIL=true` 면 사람별 요약 메일 1통(SMTP 필요). `PROJECT_REMINDERS=false` 로 끔.
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
검색/필터 · 업무 라벨(태그 분류) · 하위 업무의 하위 업무(다단계 중첩,
|
||||
업무 라벨(태그 분류) · 반복 업무 · 템플릿 · 업무 의존성 · 하위 업무의 하위 업무(다단계 중첩,
|
||||
아사나도 UI상 1단계만 허용해 현재 의도적으로 안 함).
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
-- project_db 008 — 팔로워 · 마감 알림 · 검색 인덱스
|
||||
--
|
||||
-- 1) task_followers — 아사나의 "협업자(Collaborators)". 업무 알림(완료·댓글)은
|
||||
-- 이제 프로젝트 멤버 전원이 아니라 "담당자 + 팔로워"에게만 간다.
|
||||
-- 업무를 만든 사람·담당자·댓글 단 사람·@태그된 사람은 자동으로 팔로워가 된다.
|
||||
-- 기존 업무는 아래 백필로 같은 규칙을 소급 적용한다.
|
||||
-- 2) task_reminders — 마감 알림(D-1 / 당일 / 지연)을 이미 보냈는지 기록.
|
||||
-- (업무, 종류, 마감일, 수신자) 가 같으면 다시 보내지 않는다 — 마감일을 바꾸면
|
||||
-- 새 마감일 기준으로 다시 알린다. 여러 번 돌아도 중복 발송이 없다.
|
||||
-- 3) pg_trgm 인덱스 — 전체 검색(제목·설명·댓글 ILIKE '%...%')이 풀스캔하지 않게.
|
||||
--
|
||||
-- 적용 (superuser, 1회 — 여러 번 돌려도 안전. pg_trgm 확장 생성 때문에 superuser 필요):
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
-- < scripts/sql/project_db_008_followers_reminders_search.sql
|
||||
--
|
||||
-- 미적용 환경에서도 앱은 동작한다(팔로워 기능만 숨고, 알림 수신자는 예전처럼
|
||||
-- 멤버 전원, 마감 알림은 skip, 검색은 인덱스 없이 동작).
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect project_db
|
||||
|
||||
-- ── 1) 팔로워 ─────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS task_followers (
|
||||
task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
user_email TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, user_email)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_followers_email ON task_followers (user_email);
|
||||
|
||||
-- 백필(멱등): 만든 사람 · 담당자 · 댓글 작성자 · @태그된 사람
|
||||
INSERT INTO task_followers (task_id, user_email)
|
||||
SELECT id, lower(created_by) FROM tasks WHERE created_by <> ''
|
||||
UNION
|
||||
SELECT id, lower(assignee_email) FROM tasks WHERE assignee_email <> ''
|
||||
UNION
|
||||
SELECT task_id, lower(author_email) FROM task_comments WHERE author_email <> ''
|
||||
UNION
|
||||
SELECT task_id, lower(mentioned_email) FROM task_mentions WHERE mentioned_email <> ''
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- 팔로워가 바뀌어도 열린 화면이 새로 받도록(007 카운터)
|
||||
DROP TRIGGER IF EXISTS trg_task_followers_live_version ON task_followers;
|
||||
CREATE TRIGGER trg_task_followers_live_version
|
||||
AFTER INSERT OR UPDATE OR DELETE ON task_followers
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION project_bump_live_version();
|
||||
|
||||
-- ── 2) 마감 알림 발송 기록 ─────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS task_reminders (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, -- due_soon | due_today | overdue
|
||||
due_date DATE NOT NULL,
|
||||
recipient_email TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (task_id, kind, due_date, recipient_email)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_reminders_created ON task_reminders (created_at);
|
||||
|
||||
-- ── 3) 검색 인덱스 ─────────────────────────────────────────
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_title_trgm
|
||||
ON tasks USING gin (title gin_trgm_ops);
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_desc_trgm
|
||||
ON tasks USING gin (description gin_trgm_ops);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_comments_body_trgm
|
||||
ON task_comments USING gin (body gin_trgm_ops);
|
||||
-- 마감 알림 조회(미완료 + 마감일)
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_open_due
|
||||
ON tasks (due_date) WHERE completed_at IS NULL;
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON task_followers, task_reminders TO project_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
|
||||
|
||||
SELECT 'project_db 008 followers/reminders/search ready' AS status;
|
||||
Reference in New Issue
Block a user