diff --git a/app/modules/cupang/templates/cupang/index.html b/app/modules/cupang/templates/cupang/index.html index 6b3a1ee..171dfb9 100644 --- a/app/modules/cupang/templates/cupang/index.html +++ b/app/modules/cupang/templates/cupang/index.html @@ -2,7 +2,7 @@ {% block head_extra %} {# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + @@ -249,7 +249,7 @@ {% endblock %} {% block scripts %} - + {% endblock %} @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/project/CLAUDE.md b/app/modules/project/CLAUDE.md index be83feb..bc77f0e 100644 --- a/app/modules/project/CLAUDE.md +++ b/app/modules/project/CLAUDE.md @@ -96,6 +96,13 @@ ## 알림 +- **매일 하는 업무**(2026-11-11, 마이그레이션 033 `tasks.repeat_daily`) — 날짜 팝업 `openDatePopover({allowDaily, daily})` 아래 [매일](repeat 아이콘) = + `{due_date: null, repeat_daily: true}`(서버 `db.update_task` 가 마감일·시각 비움, 마감일을 고르면 자동으로 꺼짐). 업무 행에 `repeat_daily` 키가 있을 때만(=033 적용) 버튼이 보인다. + 카드·목록·내 업무·세부 업무·업무 창 마감 칸 = `dueInfo(…, daily)` → `.is-daily`(CSS ::before repeat 아이콘 + "매일", 노랑). + 알림 = `reminders.run_daily_alerts`(데몬 1분 주기, 영업일, `daily_alert_times` 중 지난 가장 늦은 시각 하나 — `task_reminders` kind `daily@HH:MM`·그날로 중복 방지) + → 담당자(없으면 협업자)에게 `type=daily` 알림 → 큰 팝업 `_ALERT_TYPES` 에 포함, 줄 배경 노랑(`.pj-alert-item.is-daily`), PC 알림 프로그램 `Alert.IsDaily`. + 새 업무 만들기 칸(보드 아래 추가·세부 업무 추가 줄)에는 [매일] 없음 — 만든 뒤 날짜 칸에서. 033 미적용이면 [매일] 숨김·PUT 503·알림 skip. + - 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐. - 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`). - **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17). @@ -115,6 +122,7 @@ - **"전체 보기" 메뉴를 볼 사람**(2026-11-11) = 프로젝트 화면 분류에 처음 여는 탭과 묶음. 옵션 키 `all_view_users`(이메일 목록, DB 변경 없음 — 029 키·값 표), `null`(설정 전) = 예전처럼 Pro user 이상. 후보 = `GET /api/assignable-users`(아이콘+이름 `memberPickHtml`, `pro` 표시로 기본 체크) + [전체 선택/해제]. 메뉴 표시만 정함(데이터는 멤버 범위 그대로) — 사이드바 `pj_all_view`(`_role_ctx(user, request)`), `project.js canAllView`(`data-all-view`). 대시보드 담당자별 합계는 여전히 Pro user 이상. +- **알림 분류 — 매일 하는 업무 알림 시각**(2026-11-11) = 옵션 키 `daily_alert_times`(["HH:MM"…] 최대 12, 기본 ["09:00"], 빈 목록 = 끔). 행마다 시각 칸 + 휴지통, [알림 추가]. - 긴급 공지 = 수퍼관리자만. ## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9) diff --git a/app/modules/project/db.py b/app/modules/project/db.py index d0be6fb..e4f7b61 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -888,6 +888,14 @@ class ProjectStore: for k in ("start_time", "due_time"): if k in fields: clean[k] = store.validate_time(fields[k]) + # 매일 하는 업무(033) — 켜면 마감일·마감 시각을 비운다(마감일 없이 매일). + if "repeat_daily" in fields: + if not isinstance(fields["repeat_daily"], bool): + raise ValueError("매일 반복 값이 올바르지 않습니다.") + clean["repeat_daily"] = fields["repeat_daily"] + if fields["repeat_daily"]: + clean["due_date"] = None + clean["due_time"] = None newly_assigned: str | None = None newly_completed = False @@ -899,7 +907,11 @@ class ProjectStore: prev = self._serialize(row) sets: list[str] = [] params: list[Any] = [] - for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"): + # 마감일을 고르면 매일 반복은 꺼진다(열이 있을 때만 — 033 미적용이면 키가 없다) + if clean.get("due_date") and prev.get("repeat_daily") and "repeat_daily" not in clean: + clean["repeat_daily"] = False + for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time", + "repeat_daily"): if k in clean: sets.append(f"{k} = %s") params.append(clean[k]) @@ -2268,9 +2280,27 @@ class ProjectStore: ).fetchall() return [self._serialize(r) for r in rows] + def list_open_daily_tasks(self) -> list[dict[str, Any]]: + """매일 하는 업무(033 repeat_daily) 중 미완료 + 팔로워 목록. 보관 프로젝트는 뺀다. + 033 미적용이면 psycopg_errors.UndefinedColumn(알림 데몬이 그날은 건너뜀).""" + with self._pool.connection() as conn: + rows = conn.execute( + """ + SELECT t.id, t.title, 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.repeat_daily AND t.completed_at IS NULL AND p.status <> 'archived' + ORDER BY t.id + """, + ).fetchall() + return [self._serialize(r) for r in rows] + def add_reminder_notification( self, *, task_id: int, kind: str, due_date: str, recipient_email: str, - project_id: int | None, title: str, body: str, + project_id: int | None, title: str, body: str, ntype: str | None = None, ) -> bool: """마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True, 이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서 @@ -2289,7 +2319,7 @@ class ProjectStore: "INSERT INTO project_notifications " "(recipient_email, actor_email, project_id, task_id, type, title, body) " "VALUES (%s,'',%s,%s,%s,%s,%s)", - (rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)), + (rcpt, project_id, task_id, ntype or kind, store.norm_str(title), store.norm_str(body)), ) return True diff --git a/app/modules/project/reminders.py b/app/modules/project/reminders.py index ea22564..3655ef9 100644 --- a/app/modules/project/reminders.py +++ b/app/modules/project/reminders.py @@ -15,6 +15,11 @@ "오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가 동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다. +매일 하는 업무(033 tasks.repeat_daily, run_daily_alerts) — Project 옵션 daily_alert_times 시각(KST, 영업일)이 +지나면 미완료 매일 업무의 담당자(없으면 협업자)에게 수신함 알림(type=daily, 큰 팝업에 따로 색). 데몬은 1분마다 깨어 +지난 시각 중 가장 늦은 것 하나만 보낸다(서버가 꺼져 있다 켜져도 몇 번씩 쏟아지지 않게). 중복 방지는 같은 +task_reminders(kind='daily@HH:MM', due_date=그날). + 환경변수: PROJECT_REMINDERS false 면 끈다(기본 켜짐) PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9) @@ -41,6 +46,7 @@ logger = logging.getLogger("project.reminders") KIND_DUE_SOON = "due_soon" KIND_DUE_TODAY = "due_today" KIND_OVERDUE = "overdue" +NTYPE_DAILY = "daily" OVERDUE_WINDOW_DAYS = 7 @@ -139,6 +145,39 @@ def run_due_reminders( return counts +def daily_slot(times: list[str], hhmm: str) -> str | None: + """설정 시각들 중 지금(hhmm)까지 지난 가장 늦은 시각 — 없으면 None.""" + passed = [t for t in times if t <= hhmm] + return max(passed) if passed else None + + +def run_daily_alerts( + st: Any, *, today: date, slot: str, lookup: access.UserLookup | None = None, +) -> int: + """매일 하는 업무 알림 한 번(그날 slot 시각분). 새로 만든 알림 수. 수신자·권한·중복 규칙은 마감 알림과 같다.""" + made = 0 + for t in st.list_open_daily_tasks(): + assignee = store.norm_str(t.get("assignee_email"), lower=True) + wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or []) + try: + recipients = access.filter_recipients(st, t, wanted, lookup) + except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다 + logger.warning("매일 업무 알림 수신자 확인 실패: task=%s", t["id"]) + continue + for rcpt in recipients: + try: + created = st.add_reminder_notification( + task_id=t["id"], kind=f"daily@{slot}", due_date=today.isoformat(), recipient_email=rcpt, + project_id=t["project_id"], title=f"매일 업무: {t['title']}", + body=f"{t.get('project_name') or ''} · 매일 {slot}", ntype=NTYPE_DAILY, + ) + except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도 + logger.warning("매일 업무 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"]) + continue + made += int(bool(created)) + return made + + def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None: from app.mail import send_email # noqa: WPS433 @@ -176,22 +215,41 @@ def start_reminder_thread(st: Any) -> bool: def _loop() -> None: last_run: date | None = None + last_due_try = 0.0 + daily_done: tuple[date, str] | None = None # 마지막으로 보낸 (날짜, 시각) while True: + now = now_kst() + today = now.date() + if time.monotonic() - last_due_try >= 300: # 마감 알림은 예전처럼 5분마다 확인 + last_due_try = time.monotonic() + try: + 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__) 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) + if is_workday(today): + times = store.normalize_project_options(st.get_project_options())["daily_alert_times"] + slot = daily_slot(times, now.strftime("%H:%M")) + if slot and daily_done not in ((today, slot), (today, "skip")): + made = run_daily_alerts(st, today=today, slot=slot) + daily_done = (today, slot) + if made: + logger.info("매일 업무 알림 %s: %d건", slot, made) except Exception as exc: # noqa: BLE001 - if type(exc).__name__ == "UndefinedTable": - # 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지) - logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요") - last_run = now_kst().date() + if type(exc).__name__ in ("UndefinedColumn", "UndefinedTable"): + daily_done = (today, "skip") # 033(또는 008) 미적용 — 오늘은 그만(로그 도배 방지) + logger.warning("매일 업무 알림 skip — project_db_033 마이그레이션 필요") else: - logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__) - time.sleep(300) + logger.warning("매일 업무 알림 실패(%s) — 1분 뒤 재시도", type(exc).__name__) + time.sleep(60) 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 ef181f4..86f6fb3 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -1677,6 +1677,8 @@ def api_update_task( try: task = st.update_task(task_id=task_id, fields=payload, actor=user["email"], assignee_allowed=_registered_project_user) + except UndefinedColumn: + raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.") except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError: @@ -2817,7 +2819,7 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any] return out -_ALERT_TYPES = ("mention", "assigned") +_ALERT_TYPES = ("mention", "assigned", "daily") # daily = 매일 하는 업무(reminders.run_daily_alerts, 033) _ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것) _ALERT_PAGE = 200 _ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게 diff --git a/app/modules/project/store.py b/app/modules/project/store.py index 1e685c8..549213b 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -384,8 +384,28 @@ PROJECT_OPTION_DEFAULTS: dict[str, Any] = { "default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭 "board_cover": True, # 보드 카드 표지(설명의 첫 이미지) "all_view_users": None, # 왼쪽 "전체 보기" 메뉴를 볼 사람(이메일 목록) — None = 예전처럼 Pro user 이상 + "daily_alert_times": ["09:00"], # 매일 업무(033 repeat_daily) 알림 시각들(KST, 영업일) } ALL_VIEW_USERS_MAX = 2000 +DAILY_ALERT_TIMES_MAX = 12 + + +def _time_list(raw: Any) -> list[str] | None: + """'HH:MM' 목록 → 정규화·중복 제거·정렬. 목록이 아니거나 잘못된 시각이 끼면 None(빈 목록 = 알림 끔).""" + if not isinstance(raw, list) or len(raw) > DAILY_ALERT_TIMES_MAX: + return None + out: set[str] = set() + for t in raw: + if not isinstance(t, str): + return None + try: + v = validate_time(t) + except ValueError: + return None + if v is None: + return None + out.add(v) + return sorted(out) def _email_list(raw: Any) -> list[str] | None: @@ -410,6 +430,11 @@ def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]: out["board_cover"] = raw["board_cover"] if raw.get("all_view_users") is not None: out["all_view_users"] = _email_list(raw["all_view_users"]) + times = _time_list(raw.get("daily_alert_times")) + if times is not None: + out["daily_alert_times"] = times + else: + out["daily_alert_times"] = list(PROJECT_OPTION_DEFAULTS["daily_alert_times"]) return out @@ -434,6 +459,11 @@ def validate_project_options(payload: Any) -> dict[str, Any]: out["all_view_users"] = None if v is None else _email_list(v) if v is not None and out["all_view_users"] is None: raise ValueError("전체 보기 대상자 값이 올바르지 않습니다.") + if "daily_alert_times" in payload: + times = _time_list(payload["daily_alert_times"]) + if times is None: + raise ValueError(f"매일 업무 알림 시각이 올바르지 않습니다(HH:MM, 최대 {DAILY_ALERT_TIMES_MAX}개).") + out["daily_alert_times"] = times return out diff --git a/app/modules/project/templates/project/_options.html b/app/modules/project/templates/project/_options.html index c4b732c..997758a 100644 --- a/app/modules/project/templates/project/_options.html +++ b/app/modules/project/templates/project/_options.html @@ -3,6 +3,7 @@ · 프로젝트 화면(처음 여는 탭·"전체 보기" 메뉴 대상자)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에 저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view· data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영. + · 알림(매일 하는 업무 알림 시각 여러 개) — 수퍼관리자·Admin, 모든 사용자. · 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #} + {% endif %} {% if user and user.is_super_admin %} + 알림이 하나도 없으면 매일 업무 알림을 보내지 않습니다. + + + {% endif %} {% if user and user.is_super_admin %} @@ -524,6 +526,7 @@ 업무 완료 · 새 댓글담당자와 협업자 마감 알림담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다. @태그태그된 사람(수신함의 “나를 태그한 업무”) + 매일 업무담당자(없으면 협업자). 매일 하는 업무(마감일 칸 repeat매일)가 끝나지 않았으면 평일(공휴일 제외) Project 옵션 → 알림에서 정한 시각마다 화면 아래 큰 알림에 노란 줄로 뜹니다(PC 알림 프로그램도).

내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.

diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index 2c09882..1a3c338 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -106,5 +106,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index c7a19df..a1451f6 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html index 7124e26..067bff6 100644 --- a/app/modules/project/templates/project/notifier.html +++ b/app/modules/project/templates/project/notifier.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -108,5 +108,5 @@ }); })(); - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index c1d469c..92974a0 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -476,5 +476,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index 1c60b8f..b3e349d 100644 --- a/app/modules/project/templates/project/trash.html +++ b/app/modules/project/templates/project/trash.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -70,5 +70,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/static/project-options.js b/app/static/project-options.js index b81c15e..bf0826f 100644 --- a/app/static/project-options.js +++ b/app/static/project-options.js @@ -8,7 +8,7 @@ const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"]; const FONT_DEFAULT = "system"; // 서버 store.PROJECT_OPTION_DEFAULTS 와 같게 — all_view_users null = Pro user 이상(후보 목록의 pro 표시) - const SYS_DEFAULTS = { default_view: "board", board_cover: true, all_view_users: null }; + const SYS_DEFAULTS = { default_view: "board", board_cover: true, all_view_users: null, daily_alert_times: ["09:00"] }; const form = document.getElementById("pj-options-form"); const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview"); const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save"); @@ -25,6 +25,10 @@ const allPicker = document.getElementById("pj-options-allview"); const allBtn = document.getElementById("pj-options-allview-all"); const allCount = document.getElementById("pj-options-allview-count"); + // 매일 하는 업무 알림 시각(여러 개) — 알림 분류(수퍼관리자·Admin 창에만) + const timesBox = document.getElementById("pj-options-daily-times"); + const timesAdd = document.getElementById("pj-options-daily-add"); + const TIMES_MAX = 12; // 서버 store.DAILY_ALERT_TIMES_MAX let users = null; // 후보(project 권한자) — 못 읽었으면 null(그때는 대상자를 저장하지 않음) const localControls = [select, cancel, closeX, reset]; let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장) @@ -43,7 +47,38 @@ function currentFont() { const f = document.documentElement.dataset.pjFont; return Object.hasOwn(names, f) ? f : FONT_DEFAULT; } // 서버 응답 → 비교용 값. 대상자는 지금 후보에 있는 사람만, 설정 전(null)이면 Pro user 이상. function sysFrom(o) { - return { default_view: o.default_view, board_cover: !!o.board_cover, all_view_users: resolveAllView(o.all_view_users) }; + return { default_view: o.default_view, board_cover: !!o.board_cover, all_view_users: resolveAllView(o.all_view_users), + daily_alert_times: (o.daily_alert_times || []).slice().sort() }; + } + function timeInputs() { return timesBox ? Array.from(timesBox.querySelectorAll("input[type=time]")) : []; } + // 고른 시각들 — 빈 칸은 빼고 중복 제거·정렬(서버도 같게 정규화) + function pickedTimes() { + const out = []; + timeInputs().forEach(function (i) { const v = (i.value || "").slice(0, 5); if (v && out.indexOf(v) < 0) out.push(v); }); + return out.sort(); + } + function renumberTimes() { + if (!timesBox) return; + Array.from(timesBox.children).forEach(function (li, i) { li.firstChild.textContent = "알림 " + (i + 1); }); + timesAdd.disabled = !sys || timesBox.children.length >= TIMES_MAX; + } + function addTimeRow(v) { + const li = document.createElement("li"); + li.innerHTML = '' + + ''; + li.querySelector("input").value = v || ""; + li.querySelector("input").disabled = !sys; + li.querySelector("button").disabled = !sys; + li.querySelector("button").addEventListener("click", function () { li.remove(); renumberTimes(); }); + timesBox.appendChild(li); + renumberTimes(); + return li; + } + function fillTimes(list) { + if (!timesBox) return; + timesBox.innerHTML = ""; + (list || []).forEach(addTimeRow); + renumberTimes(); } function resolveAllView(list) { if (!users) return null; @@ -71,6 +106,7 @@ function fillSys(o) { if (views) views.value = o.default_view; if (cover) cover.checked = o.board_cover; + fillTimes(o.daily_alert_times); if (allPicker && users) { const on = Array.isArray(o.all_view_users) ? o.all_view_users : resolveAllView(null); allBoxes().forEach(function (b) { b.checked = on.indexOf(b.value.toLowerCase()) >= 0; }); @@ -96,6 +132,10 @@ localControls.forEach(function (c) { c.disabled = on; }); sysControls.forEach(function (c) { c.disabled = on || !sys; }); allBoxes().concat(allBtn ? [allBtn] : []).forEach(function (c) { c.disabled = on || !sys || !users; }); + if (timesBox) { + timesBox.querySelectorAll("input, button").forEach(function (c) { c.disabled = on || !sys; }); + timesAdd.disabled = on || !sys || timesBox.children.length >= TIMES_MAX; + } } function close() { if (!save.disabled) dialog.close(); } async function loadSys() { @@ -137,6 +177,10 @@ showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true); }); select.addEventListener("change", paint); + if (timesAdd) timesAdd.addEventListener("click", function () { + if (timesBox.children.length >= TIMES_MAX) return; + addTimeRow("").querySelector("input").focus(); + }); if (allPicker) { allPicker.addEventListener("change", paintAllView); allBtn.addEventListener("click", function () { @@ -162,6 +206,10 @@ if (sys) { if (views && VIEWS.indexOf(views.value) >= 0 && views.value !== sys.default_view) sysChanges.default_view = views.value; if (cover && cover.checked !== sys.board_cover) sysChanges.board_cover = cover.checked; + if (timesBox) { + const t = pickedTimes(); + if (t.join(",") !== sys.daily_alert_times.join(",")) sysChanges.daily_alert_times = t; + } if (allPicker && users && sys.all_view_users) { const picked = pickedAllView(); if (picked.join(",") !== sys.all_view_users.join(",")) sysChanges.all_view_users = picked; diff --git a/app/static/project.css b/app/static/project.css index bfdc94b..140d23c 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2021,6 +2021,15 @@ img.pj-person-ic { width: 22px; height: 22px; } /* 마감일 표기 색 — 오늘·내일 초록, 어제·지남 빨강(아사나) */ .pj-card-due.is-soon, .pj-card-sub-due.is-soon, .pj-due-label.is-soon, .pj-due-btn.is-soon { color: #3f8f6b; } .pj-card-due.is-overdue, .pj-card-sub-due.is-overdue, .pj-due-label.is-overdue { color: #c22b10; } +/* 매일 하는 업무(033) — 마감일 자리에 반복 아이콘 + "매일"(업무 창 버튼은 JS 가 아이콘을 repeat 로) */ +.pj-card-due.is-daily, .pj-card-sub-due.is-daily, .pj-due-label.is-daily, .pj-subtask-due.is-daily, .pj-due-btn.is-daily { color: #b07a00; } +.pj-card-due.is-daily::before, .pj-card-sub-due.is-daily::before, .pj-due-label.is-daily::before, .pj-subtask-due.is-daily::before { + content: "repeat"; font-family: "Material Symbols Outlined"; font-size: 1.15em; line-height: 1; vertical-align: -0.2em; margin-right: 2px; + font-feature-settings: "liga"; -webkit-font-smoothing: antialiased; +} +.pj-dp-daily { display: inline-flex; align-items: center; gap: 2px; } +.pj-dp-daily .material-symbols-outlined { font-size: 17px; } +.pj-dp-daily.is-on { background: #fff5d6; color: #b07a00; } /* ── 멘션(@태그) ── */ .pj-mention { @@ -3166,6 +3175,12 @@ input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); } .pj-alert-kind { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 700; } .pj-alert-kind.is-mention { background: #eef2ff; color: #4053c8; } .pj-alert-kind.is-assigned { background: #e7f6ec; color: #1f8a4c; } +/* 매일 하는 업무(033) 알림 — 줄 배경을 따로(노랑) */ +.pj-alert-item.is-daily { background: #fff5d6; box-shadow: inset 3px 0 0 #f0a800; } +.pj-alert-item.is-daily + .pj-alert-item.is-daily { margin-top: 4px; } +.pj-alert-item.is-daily:hover { background: #ffedb8; } +.pj-alert-kind.is-daily { display: inline-flex; align-items: center; gap: 2px; background: #f0a800; color: #fff; } +.pj-alert-kind.is-daily .material-symbols-outlined { font-size: 14px; } .pj-alert-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; } .pj-alert-text b { font-size: 14.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pj-alert-text small { color: var(--pj-ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -3287,6 +3302,14 @@ label.pj-options-row[for] { cursor: pointer; } .pj-options-allview-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; } .pj-options-allview-all { flex: none; white-space: nowrap; } .pj-options-allview { max-height: 220px; margin-top: 0; } +/* 알림 — 매일 하는 업무 알림 시각(여러 개) */ +.pj-options-times { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; } +.pj-options-times li { display: flex; align-items: center; gap: 8px; font-size: 13px; } +.pj-options-times li > span:first-child { min-width: 52px; color: var(--pj-ink-soft); } +.pj-options-times input[type=time] { padding: 6px 8px; border: 1px solid #d8dce2; border-radius: 6px; font: inherit; } +.pj-options-times button { display: inline-flex; padding: 4px; border: 0; border-radius: 6px; background: none; color: #6d6e6f; cursor: pointer; } +.pj-options-times button:hover { background: #fdecec; color: #b42318; } +.pj-options-times:empty::before { content: "알림 없음"; font-size: 12px; color: var(--pj-ink-soft); } .pj-options-allview:empty::before { content: "불러오는 중…"; padding: 6px; font-size: 12px; color: var(--pj-ink-soft); } /* 켜기/끄기 스위치 */ .pj-switch { position: relative; flex: none; display: inline-block; width: 40px; height: 22px; } diff --git a/app/static/project.js b/app/static/project.js index 1a7d14c..f4a5f89 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -448,7 +448,9 @@ const a = new Date(String(iso).slice(0, 10) + "T00:00:00"), b = new Date(baseIso + "T00:00:00"); return Math.round((a - b) / 86400000); } - function dueInfo(iso, done) { + // daily = 매일 하는 업무(033 repeat_daily) — 마감일 대신 반복 아이콘(CSS .is-daily::before) + "매일". + function dueInfo(iso, done, daily) { + if (daily) return { text: "매일", cls: "is-daily" }; if (!iso) return null; const diff = dayDiff(iso, isoToday()); let text, cls = ""; @@ -460,10 +462,11 @@ return { text: text, cls: cls }; } // 마감일 칸 말풍선 — 지난 날짜(빨강)면 "마감일 지남", 아니면 "마감일 변경". - function dueTip(di) { return di && di.cls === "is-overdue" ? "마감일 지남" : "마감일 변경"; } + function dueTip(di) { return di && di.cls === "is-overdue" ? "마감일 지남" : di && di.cls === "is-daily" ? "매일 하는 업무(눌러서 변경)" : "마감일 변경"; } // ── 아사나식 날짜 팝업 — 마감일(과 선택적으로 시작일)을 월 달력에서 고른다. - // opts: { start, due, allowStart, onChange(patch) }. 날짜를 누를 때마다 + // opts: { start, due, allowStart, daily, allowDaily, onChange(patch) }. allowDaily = 아래 [매일] 버튼(매일 하는 업무, + // 033) — 누르면 onChange({due_date: null, repeat_daily: true}) 하고 닫힘, 날짜를 고르면 repeat_daily: false. 날짜를 누를 때마다 // onChange({due_date[, start_date]}) 로 바로 저장하고, 마감일을 고르면 팝업을 // 닫는다(시작일을 고른 땐 마감일을 이어서 고르게 열어 둠). 바깥 클릭·Esc 로 닫힘. "지우기" = 둘 다 비우고 닫기. 앵커 아래(자리가 // 없으면 위)에 뜨고 꼬리가 앵커를 가리킨다. 한 번에 하나만. @@ -504,6 +507,7 @@ let start = opts.start ? String(opts.start).slice(0, 10) : ""; let due = opts.due ? String(opts.due).slice(0, 10) : ""; let showStart = !!(opts.allowStart && start); + let daily = !!(opts.allowDaily && opts.daily); let active = "due"; const base = new Date((due || start || today) + "T00:00:00"); let viewY = base.getFullYear(), viewM = base.getMonth(); @@ -518,6 +522,7 @@ function emit() { const patch = { due_date: due || null }; if (opts.allowStart) patch.start_date = start || null; + if (opts.allowDaily) patch.repeat_daily = daily; if (opts.onChange) opts.onChange(patch); } function field(kind, val, ph) { @@ -554,7 +559,7 @@ (opts.allowStart ? (showStart ? field("start", start, "시작일") : '') : "") + - field("due", due, "마감일") + + field("due", due, daily ? "매일 하는 업무" : "마감일") + "" + '
' + '' + @@ -569,6 +574,10 @@ "
" + '
' + '' + + (opts.allowDaily + ? '' + : "") + '' + "
"; wire(); @@ -587,6 +596,7 @@ return; } due = iso; + daily = false; if (start && start > iso) start = iso; emit(); closeDatePopover(); @@ -636,7 +646,13 @@ pick(today); }); pop.querySelector(".pj-dp-clear").addEventListener("click", function () { - start = ""; due = ""; emit(); closeDatePopover(); + start = ""; due = ""; daily = false; emit(); closeDatePopover(); + }); + const dailyBtn = pop.querySelector(".pj-dp-daily"); + if (dailyBtn) dailyBtn.addEventListener("click", function () { + daily = !daily; + if (daily) due = ""; + emit(); closeDatePopover(); }); } function focusActive() { @@ -3230,8 +3246,8 @@ { key: "due", label: "마감", cls: "pj-mtk-date", html: function (t) { - if (!t.due_date) return "-"; - const di = dueInfo(t.due_date, !!t.completed_at); + if (!t.due_date && !t.repeat_daily) return "-"; + const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily); return '' + escapeHtml(di.text) + ""; }, @@ -5716,7 +5732,8 @@ // 없으면 applyTaskPatch 로 업무에 저장. function openDuePicker(t, anchorEl, onPick) { const save = onPick || function (patch) { applyTaskPatch(t, patch, "마감일 변경 실패"); }; - openDatePopover(anchorEl, { start: t.start_date, due: t.due_date, allowStart: true, onChange: save }); + openDatePopover(anchorEl, { start: t.start_date, due: t.due_date, allowStart: true, + daily: !!t.repeat_daily, allowDaily: "repeat_daily" in t, onChange: save }); // repeat_daily 키 = 033 적용됨 } // ── 카드 세부 업무 펼치기(아사나처럼) — 카드의 "N ⤷ ▾" 버튼을 누르면 카드 @@ -5736,7 +5753,7 @@ }); } function cardSubRowHtml(sub) { - const di = dueInfo(sub.due_date, !!sub.completed_at); + const di = dueInfo(sub.due_date, !!sub.completed_at, sub.repeat_daily); return '
' + '' + @@ -5744,7 +5761,7 @@ subMetaHtml(sub, "pj-card-sub-nsubs") + // 마감일 — 있으면 날짜, 없으면 아사나처럼 점선 원 달력 아이콘(줄에 마우스를 // 올리면 보임). 둘 다 누르면 날짜 선택. - (sub.due_date + (di ? '' + escapeHtml(di.text) + "" : '' + DUE_EMPTY_ICON_SVG + "") + // 담당자 — 있으면 아바타, 없으면 아사나처럼 점선 원 사람 아이콘(줄에 @@ -6270,9 +6287,9 @@ // 누르면 서버에서 받아 멤버 메뉴. 한 번 받은(고른) 협업자는 이 화면에 머무는 동안 카드에 보인다(cardFollowers). (canManage ? cardFolHtml(cardFollowers[t.id]) : "") + (function () { - const di = dueInfo(t.due_date, !!t.completed_at); + const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily); return '' + + '" title="' + (di ? dueTip(di) : "마감일 추가") + '">' + // 마감일 없음 — 세부 업무 줄과 같은 점선 원 달력 아이콘만(카드에 마우스를 올리면 보임). (di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG) + ""; })() + @@ -6456,7 +6473,7 @@ { key: "stage", label: "섹션", text: function (t) { return t.stage_name || "-"; }, sort: function (t) { return t.stage_name || ""; } }, { key: "priority", label: "우선순위", text: function (t) { return priorityLabels[t.priority] || t.priority || "-"; }, sort: function (t) { return ({ low: 0, normal: 1, high: 2 })[t.priority]; } }, { key: "start", label: "시작", text: function (t) { return t.start_date || "-"; }, sort: function (t) { return t.start_date || ""; } }, - { key: "due", label: "마감", text: function (t) { const di = dueInfo(t.due_date, !!t.completed_at); return di ? di.text : "-"; }, sort: function (t) { return t.due_date || ""; } }, + { key: "due", label: "마감", text: function (t) { const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily); return di ? di.text : "-"; }, sort: function (t) { return t.due_date || ""; } }, ]; // "이 프로젝트" 스코프 — 아사나 리스트 뷰처럼 세션이 컬럼이 아니라 그룹 // 구분선이 된다(renderListGrouped). 그래서 세션 컬럼은 뺀다. @@ -6529,9 +6546,9 @@ tr.innerHTML = cols.map(function (c) { let inner = escapeHtml(String(c.text(t))); if (c.key === "title") inner += cmtBadge(t); - if (c.key === "due" && t.due_date) { - const di = dueInfo(t.due_date, !!t.completed_at); - inner = '' + escapeHtml(di.text) + ""; + if (c.key === "due" && (t.due_date || t.repeat_daily)) { + const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily); + inner = '' + escapeHtml(di.text) + ""; } if (c.key === "assignee" && t.assignee_email) { inner = '' + avatarHtml(t.assignee_email, "pj-gicon-sm") + escapeHtml(idOf(t.assignee_email)) + ""; @@ -7352,6 +7369,7 @@ body = { priority: el("pj-t-priority").value }; } else if (key === "due") { body = { due_date: el("pj-t-due").value || null }; + if (el("pj-t-due").dataset.daily) body.repeat_daily = el("pj-t-due").dataset.daily === "1"; } if (!body) return Promise.resolve(true); setAutoState("saving"); @@ -7757,6 +7775,8 @@ : (presetStageId != null ? presetStageId : (stages[0] ? stages[0].id : "")); el("pj-t-priority").value = task ? (task.priority || "normal") : "normal"; el("pj-t-due").value = task ? (task.due_date || "") : ""; + // 매일 하는 업무(033) — "" = 열 없음(미적용, [매일] 숨김), "0"/"1" = 꺼짐/켜짐 + el("pj-t-due").dataset.daily = task && "repeat_daily" in task ? (task.repeat_daily ? "1" : "0") : ""; currentTaskData = task || null; syncDueBtn(); // 완료 여부(지남 표시)를 보려면 currentTaskData 다음에 el("pj-delete-task").hidden = !task; @@ -7873,12 +7893,16 @@ const v = el("pj-t-due").value; const btn = el("pj-t-due-btn"); if (!btn) return; - const di = dueInfo(v, !!(currentTaskData && currentTaskData.completed_at)); + const daily = el("pj-t-due").dataset.daily === "1"; + const di = dueInfo(v, !!(currentTaskData && currentTaskData.completed_at), daily); el("pj-t-due-text").textContent = di ? di.text : ""; - btn.classList.toggle("has-date", !!v); + btn.classList.toggle("has-date", !!di); + btn.classList.toggle("is-daily", daily); + const ic = btn.querySelector(".material-symbols-outlined"); + if (ic) ic.textContent = daily ? "repeat" : "calendar_month"; btn.classList.toggle("is-overdue", !!di && di.cls === "is-overdue"); btn.classList.toggle("is-soon", !!di && di.cls === "is-soon"); - btn.title = v ? "마감일 " + v + " (눌러서 변경)" : "마감일 지정"; + btn.title = daily ? "매일 하는 업무 (눌러서 변경)" : v ? "마감일 " + v + " (눌러서 변경)" : "마감일 지정"; } if (el("pj-t-due-btn")) { // 아사나식 날짜 팝업 — 숨긴 #pj-t-due 값을 바꾸고 change 를 보내면 @@ -7886,9 +7910,10 @@ el("pj-t-due-btn").addEventListener("click", function () { const inp = el("pj-t-due"); openDatePopover(el("pj-t-due-btn"), { - due: inp.value, allowStart: false, + due: inp.value, allowStart: false, daily: inp.dataset.daily === "1", allowDaily: !!inp.dataset.daily, onChange: function (patch) { inp.value = patch.due_date || ""; + if ("repeat_daily" in patch) inp.dataset.daily = patch.repeat_daily ? "1" : "0"; inp.dispatchEvent(new Event("change", { bubbles: true })); }, }); @@ -9547,10 +9572,10 @@ checkBtn.title = sub.completed_at ? "완료 취소" : "완료로 표시"; } function renderDue() { - const di = dueInfo(sub.due_date, !!sub.completed_at); + const di = dueInfo(sub.due_date, !!sub.completed_at, sub.repeat_daily); dueEl.className = "pj-subtask-due" + (di ? " " + di.cls : " is-empty"); dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG; - dueEl.title = sub.due_date ? dueTip(di) : "마감일 추가"; + dueEl.title = di ? dueTip(di) : "마감일 추가"; } function renderAv() { const e = sub.assignee_email || ""; @@ -9599,12 +9624,14 @@ dueEl.addEventListener("click", function (e) { e.stopPropagation(); openDatePopover(dueEl, { - due: sub.due_date, allowStart: false, + due: sub.due_date, allowStart: false, daily: !!sub.repeat_daily, allowDaily: "repeat_daily" in sub, onChange: async function (p) { - const prev = sub.due_date; - sub.due_date = p.due_date || null; + const prev = { due_date: sub.due_date, repeat_daily: sub.repeat_daily }; + const body = { due_date: p.due_date || null }; + if ("repeat_daily" in p) body.repeat_daily = p.repeat_daily; + Object.assign(sub, body); renderDue(); - if (!(await patch({ due_date: sub.due_date }))) { sub.due_date = prev; renderDue(); } + if (!(await patch(body))) { Object.assign(sub, prev); renderDue(); } }, }); }); @@ -13548,14 +13575,14 @@ "새 알림 " + items.length + "건" + '
' + '
' + items.map(function (n) { - const isMention = n.type === "mention"; + const isMention = n.type === "mention", isDaily = n.type === "daily"; // daily = 매일 하는 업무(033) — 줄 배경 따로 // 서버가 준 주소(작업 = /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 작업도 열린다) const href = n.href || (n.task_id ? "/project/t/" + n.task_id : n.project_id ? "/project/p/" + n.project_id : "/project/inbox"); - return '' + - '' + - (isMention ? "나를 태그" : "업무 배정") + "" + - '' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|업무 배정|작업 배정):\s*/, "")) + "" + + return '' + + '' + + (isDaily ? 'repeat매일 업무' : isMention ? "나를 태그" : "업무 배정") + "" + + '' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|업무 배정|작업 배정|매일 업무):\s*/, "")) + "" + "" + escapeHtml((n.body || "") + (n.actor_email ? " · " + capName(idOf(n.actor_email)) : "")) + "" + '열기 ›'; }).join("") + "
"; diff --git a/desktop/notifier/AlertForm.cs b/desktop/notifier/AlertForm.cs index 963b5e5..8dac42b 100644 --- a/desktop/notifier/AlertForm.cs +++ b/desktop/notifier/AlertForm.cs @@ -225,13 +225,15 @@ namespace DbxNotifier private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover) { float s = _s; - if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8")); + // 매일 하는 업무 = 노란 줄 배경(웹 팝업 .pj-alert-item.is-daily 와 같은 색) + if (a.IsDaily) Fill(g, r, 10 * s, Gfx.Hex(hover ? "#ffedb8" : "#fff5d6")); + else if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8")); - string kind = a.IsMention ? "나를 태그" : "업무 배정"; + string kind = a.IsDaily ? "매일 업무" : a.IsMention ? "나를 태그" : "업무 배정"; SizeF ks = g.MeasureString(kind, _fBadge, PointF.Empty, StringFormat.GenericTypographic); var kr = new RectangleF(r.X + 10 * s, r.Y + (r.Height - 22 * s) / 2, ks.Width + 18 * s, 22 * s); - Fill(g, kr, 11 * s, a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec")); - DrawText(g, kind, _fBadge, a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center); + Fill(g, kr, 11 * s, a.IsDaily ? Gfx.Hex("#f0a800") : a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec")); + DrawText(g, kind, _fBadge, a.IsDaily ? Color.White : a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center); const string go = "열기 ›"; SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic); diff --git a/desktop/notifier/Api.cs b/desktop/notifier/Api.cs index e8066f0..945eff8 100644 --- a/desktop/notifier/Api.cs +++ b/desktop/notifier/Api.cs @@ -20,13 +20,14 @@ namespace DbxNotifier public long ProjectId; public bool IsMention => Type == "mention"; + public bool IsDaily => Type == "daily"; // 매일 하는 업무(project_db 033) — 줄 배경을 따로 /// 제목 앞 "나를 태그함: " / "업무 배정: "(예전 알림은 "작업 배정: ") 은 배지로 보여 주므로 뗀다(웹 팝업과 같게). public string CleanTitle { get { - foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:" }) + foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:", "매일 업무:" }) if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim(); return Title; } diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 7c5c152..8474146 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -426,6 +426,16 @@ cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres proj cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_032_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_032_link_sort_order.sql && docker compose up --build -d --no-deps web ``` +## 매일 하는 업무 마이그레이션 (project_db 033) + +033은 `tasks` 에 `repeat_daily` 열(기본 false)과 부분 인덱스 하나만 추가한다(다시 실행 가능, 기존 값 변경 없음, 새 환경변수 없음). +날짜 팝업 [매일]·마감 칸 반복 아이콘·매일 업무 알림(Project 옵션 → 알림 시각, 영업일) — 미적용이면 앱은 예전 그대로([매일] 숨김, 알림 skip). +되돌리기 = `ALTER TABLE tasks DROP COLUMN repeat_daily;`(앱은 열이 없으면 예전 방식). + +```bash +cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_033_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_033_repeat_daily.sql && docker compose up --build -d --no-deps web +``` + ## 안내문 발송 DM 본문 저장 마이그레이션 (outreach_db 002) 002는 `outreach_dm_bodies` 표 하나만 추가한다(다시 실행 가능, 기존 표·값 변경 없음, 새 환경변수 없음, `outreach_app` 에 CRUD·시퀀스 권한). diff --git a/scripts/sql/project_db_033_repeat_daily.sql b/scripts/sql/project_db_033_repeat_daily.sql new file mode 100644 index 0000000..6cfdaf8 --- /dev/null +++ b/scripts/sql/project_db_033_repeat_daily.sql @@ -0,0 +1,19 @@ +-- ===================================================================== +-- project_db 마이그레이션 033 — 매일 하는 업무(마감일 없이 매일 반복) +-- ===================================================================== +-- 멱등(idempotent). tasks 에 repeat_daily 열 하나만 추가(기존 값 변경 없음, 새 환경변수 없음). +-- 운영: /opt/www/main 에서 기존 project_db 에 적용(적용 전 pg_dump 백업). +-- +-- 날짜 팝업 [매일]로 켠다 — 켜면 마감일·마감 시각은 비운다(마감일을 고르면 다시 꺼짐). +-- 마감일 칸에는 반복 아이콘, 알림 데몬(reminders.py)이 Project 옵션 daily_alert_times 시각마다(영업일) +-- 담당자(없으면 협업자)에게 "매일 업무" 알림(type=daily)을 만든다 — 중복 방지는 기존 task_reminders +-- (kind = 'daily@HH:MM', due_date = 그날). +-- 미적용이면 앱은 예전 그대로(날짜 팝업에 [매일] 없음, 매일 알림 skip). +-- 되돌리기: ALTER TABLE tasks DROP COLUMN repeat_daily; +-- ===================================================================== +BEGIN; + +ALTER TABLE tasks ADD COLUMN IF NOT EXISTS repeat_daily BOOLEAN NOT NULL DEFAULT false; +CREATE INDEX IF NOT EXISTS idx_tasks_repeat_daily_open ON tasks (id) WHERE repeat_daily AND completed_at IS NULL; + +COMMIT; diff --git a/tests/test_project_daily_tasks.py b/tests/test_project_daily_tasks.py new file mode 100644 index 0000000..6aaba95 --- /dev/null +++ b/tests/test_project_daily_tasks.py @@ -0,0 +1,62 @@ +"""매일 하는 업무(033 tasks.repeat_daily) 알림 — 시각 고르기·수신자·중복. DB 없이 가짜 저장소로. + +실제 DB(열·update_task 규칙)는 tests/test_project_module.py test_repeat_daily_* 가 본다. +""" +import importlib +import unittest +from datetime import date +from unittest.mock import patch + +rem = importlib.import_module("app.modules.project.reminders") + + +class FakeStore: + def __init__(self, tasks): + self.tasks = tasks + self.sent = set() + self.made = [] + + def list_open_daily_tasks(self): + return list(self.tasks) + + def add_reminder_notification(self, **kw): + key = (kw["task_id"], kw["kind"], kw["due_date"], kw["recipient_email"]) + if key in self.sent: + return False + self.sent.add(key) + self.made.append(kw) + return True + + +def _visible(st, task, wanted, lookup=None): + return [e for e in wanted if e != "gone@x.kr"] # 권한 잃은 사람은 뺀다 + + +class DailyAlertTests(unittest.TestCase): + def test_slot_is_latest_passed_time(self): + self.assertIsNone(rem.daily_slot(["09:00", "14:00"], "08:59")) + self.assertEqual(rem.daily_slot(["09:00", "14:00"], "09:00"), "09:00") + self.assertEqual(rem.daily_slot(["09:00", "14:00"], "23:59"), "14:00") + self.assertIsNone(rem.daily_slot([], "12:00")) + + def test_assignee_else_followers_once_per_slot(self): + st = FakeStore([ + {"id": 1, "title": "청소", "assignee_email": "A@x.kr", "followers": ["b@x.kr"], "project_id": 7, "project_name": "P"}, + {"id": 2, "title": "보고", "assignee_email": "", "followers": ["b@x.kr", "gone@x.kr"], "project_id": 7}, + ]) + with patch.object(rem.access, "filter_recipients", side_effect=_visible): + self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="09:00"), 2) + self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="09:00"), 0) # 같은 시각은 한 번 + self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="14:00"), 2) # 다음 시각은 또 + first = st.made[0] + self.assertEqual((first["recipient_email"], first["kind"], first["ntype"]), ("a@x.kr", "daily@09:00", "daily")) + self.assertEqual(first["title"], "매일 업무: 청소") + self.assertEqual({m["recipient_email"] for m in st.made if m["task_id"] == 2}, {"b@x.kr"}) + + def test_daily_is_popup_alert_type(self): + api = importlib.import_module("app.modules.project.router") + self.assertIn("daily", api._ALERT_TYPES) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_project_module.py b/tests/test_project_module.py index 23f176e..7edcb33 100644 --- a/tests/test_project_module.py +++ b/tests/test_project_module.py @@ -1653,6 +1653,32 @@ def test_reorder_keeps_linked_card_position(): assert ST.get_task(task_id=lk["id"])["sort_order"] == lk["sort_order"] +def test_repeat_daily_task_and_alerts(): + """매일 하는 업무(2026-11-11, 마이그레이션 033) — [매일]이면 마감일을 비우고, 마감일을 고르면 꺼짐. + 알림 데몬은 미완료 매일 업무의 담당자에게 시각마다 한 번(type=daily, 큰 팝업).""" + from datetime import date as _d + from app.modules.project import reminders + a = _project("P-daily", ADMIN, (ALICE,)) + sa = _stage(a["id"], by=ADMIN) + t = ST.create_task(project_id=a["id"], title="매일 청소", stage_id=sa["id"], assignee_email=ALICE, + due_date="2026-12-01", created_by=ALICE) + r = req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"due_date": None, "repeat_daily": True}) + assert r.status_code == 200, r.text + got = r.json()["task"] + assert got["repeat_daily"] is True and got["due_date"] is None, got + assert req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"repeat_daily": "yes"}).status_code == 400 + assert t["id"] in [x["id"] for x in ST.list_open_daily_tasks()] + today = _d(2026, 11, 11) + assert reminders.run_daily_alerts(ST, today=today, slot="09:00") >= 1 + assert reminders.run_daily_alerts(ST, today=today, slot="09:00") == 0 # 같은 시각은 한 번 + alerts = req("GET", "/project/api/notifications/alerts?after=0", ALICE).json()["alerts"] + assert any(n["type"] == "daily" and n["task_id"] == t["id"] for n in alerts), alerts + # 마감일을 고르면 매일 반복은 꺼진다(repeat_daily 를 안 보내도) + got = req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"due_date": "2026-12-05"}).json()["task"] + assert got["repeat_daily"] is False and got["due_date"] == "2026-12-05", got + assert t["id"] not in [x["id"] for x in ST.list_open_daily_tasks()] + + def test_move_stage_to_other_project(): """섹션째 다른 프로젝트로(2026-10-26) — 섹션 + 업무 + 세부 업무(모든 단계), 섹션은 맨 끝, 연결 정리, 권한.""" a = _project("P-smA", ADMIN, (ALICE, BOB)) diff --git a/tests/test_project_options_api.py b/tests/test_project_options_api.py index 43b4672..1d85964 100644 --- a/tests/test_project_options_api.py +++ b/tests/test_project_options_api.py @@ -59,6 +59,18 @@ class NormalizeTests(unittest.TestCase): self.assertEqual(store.validate_project_options({"all_view_users": ["Me@X.kr"]}), {"all_view_users": ["me@x.kr"]}) self.assertEqual(store.validate_project_options({"all_view_users": None}), {"all_view_users": None}) + def test_daily_alert_times(self): + self.assertEqual(D["daily_alert_times"], ["09:00"]) + out = store.normalize_project_options({"daily_alert_times": ["14:00", "9:00", "09:00"]}) + self.assertEqual(out["daily_alert_times"], ["09:00", "14:00"]) + self.assertEqual(store.normalize_project_options({"daily_alert_times": []})["daily_alert_times"], []) # 빈 목록 = 끔 + self.assertEqual(store.normalize_project_options({"daily_alert_times": ["25:00"]})["daily_alert_times"], ["09:00"]) + self.assertEqual(store.validate_project_options({"daily_alert_times": ["18:30", "08:05"]}), + {"daily_alert_times": ["08:05", "18:30"]}) + for bad in ("09:00", ["9시"], [""], [None], ["24:00"], ["09:00"] * 0 + [f"{h:02d}:00" for h in range(13)]): + with self.subTest(bad=bad), self.assertRaises(ValueError): + store.validate_project_options({"daily_alert_times": bad}) + def test_can_all_view(self): access = importlib.import_module("app.modules.project.access") self.assertTrue(access.can_all_view(PRO, None)) # 설정 전 = Pro user 이상(예전 그대로)