60 Commits

Author SHA1 Message Date
king 89ad338024 fix(project): review fixes — access leaks, open paths, save safety, concurrency
- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
  old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
  my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
  header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
  read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:08:56 +09:00
king c07a3466a0 Merge branch 'feat/project-role-tiers' 2026-10-12 01:10:33 +09:00
king 5d054e59b6 feat(project): 4-tier roles (super/admin/pro/user), meeting header 구분
- app.store: role "pro" (ROLES, ROLE_LABELS); admin page grade select
  Admin / Pro user / User, super admin fixed to one account.
- project.access: role_of, is_pro, is_project_admin.
- router: _require_admin -> _require_pro (goals, meetings complete/delete,
  members, reorder, trash restore, assignable users); new project and
  project edit/owner change need Pro user+; task delete open to any member;
  project/section delete = Admin+ or creator; comment edit/delete of others
  and workload summary = Pro user+. Templates get pj_pro / pj_admin.
- Weekly meeting table first header "구역" -> "구분".
- Docs (CLAUDE.md, PROJECT_MODULE 6-14, overview, help page) and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 01:10:25 +09:00
king 061f18d081 Merge branch 'feat/workload-nested-subtasks' 2026-10-08 16:57:40 +09:00
king ee9c04147a feat(project): workload chart counts nested subtasks
subtasks-summary now returns every level under the scope's main tasks
(recursive CTE, depth <= 20) with root_task_id and parent_title; the
dashboard groups by root_task_id. Also fix drawer header '세부 작업 작업'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:57:36 +09:00
king 6a1c437635 Merge branch 'feat/inbox-click-terms-boardcopy' 2026-10-08 16:03:03 +09:00
king 8045d06362 feat(project): click-to-open inbox, 세부 작업 terms, board link copy
- Inbox lists only unread notifications / unchecked mentions; no
  [확인] button: clicking a row marks it (and same-task rows) seen and
  opens the task side panel; picking another row switches the panel and
  removes the previously seen rows; closing removes them too
- Project module wording: 하위 작업 -> 세부 작업, 작업 추가 -> 메인 작업 추가;
  dashboard workload bars "메인 작업" / "세부 작업"
- Meeting: link icon next to 회의록 보드 copies the board URL
- Bump project asset versions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:02:58 +09:00
king 85e91ca882 Merge branch 'feat/project-ui-batch-1008' 2026-10-08 13:22:40 +09:00
king 11e9803965 feat(project): asana icons, 12-col colors, bold sections, all-view menu, desc text color/size
- Project edit modal: color palette 12 columns; icon tabs [기본 아이콘] /
  [아사나 아이콘] (33 filled icons, value "asana:<name>", 6KB subset font
  material-symbols-asana.woff2)
- Section names bold (board column, list group, rename input)
- Inbox: clicking the left inbox area closes the task side panel
- Replace top-right scope toggle with admin-only sidebar "전체 보기"
  (?scope=all, switches in place on project pages)
- Description editor: text color and size; server keeps only validated
  color / font-size on plain spans (desc_inline_style)
- Fix goals_meeting_ui [2e] for manual monthly target; bump asset versions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:22:35 +09:00
king 90fb06c48c Merge branch 'feat/login-orbit-sparkle' 2026-10-08 12:32:50 +09:00
king ac3b90f2be feat(login): orbit names sparkle like King
Same glow keyframes as King (text-shadow only, depth opacity stays in
script), random start offset per name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:32:46 +09:00
king a664c4a9fc Merge branch 'feat/login-orbit-size' 2026-10-08 12:30:10 +09:00
king 64aabdfbda feat(login): orbit names up to 80% of King size
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:30:05 +09:00
king 98fda9923e Merge branch 'feat/login-orbit-names' 2026-10-08 11:47:25 +09:00
king 53c7c85caf feat(login): 100px logo, user ids orbit around King
Login brand panel logo is 100px wide (height by ratio). Registered user
ids (email local part, no full email/real name) float around the King
label on random tilted, wobbling elliptical paths; respects
prefers-reduced-motion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:47:21 +09:00
king c380b5e411 Merge branch 'feat/notifier-silence-web' 2026-10-08 11:35:19 +09:00
king 84113d1fd7 feat(project): silence web alert popup while PC notifier is running
If the user has a non-revoked notifier token seen in the last 3 minutes,
/api/notifications/alerts returns only the baseline with desktop=true;
the web marks it seen so alerts resume on the web after the app stops.
A failing check keeps the web popup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:35:14 +09:00
king 4715de9b5b Merge branch 'feat/notifier-in-inbox' 2026-10-08 11:13:31 +09:00
king d7d4f61bfb feat(project): move PC notifier entry into inbox header
Sidebar 'PC 알림' item removed; inbox header gets a [PC 알림] button,
and the notifier page keeps the inbox highlighted with a breadcrumb.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:13:27 +09:00
king 69e594ac54 Merge branch 'feat/home-remove-tiles' 2026-10-08 10:40:51 +09:00
king f69219919d feat(home): remove default shortcut/notice tiles from ERP home
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:40:46 +09:00
king 972c94d86c docs(notifier): correct exe size in README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:22:15 +09:00
king f4606bddc6 Merge branch 'feat/pc-notifier' 2026-10-08 10:22:02 +09:00
king 06af036f86 feat(project): PC tray notifier for mentions and assignments
Windows tray app (desktop/notifier, C# .NET Framework 4.8 WinForms,
single exe, no installer/admin) that shows the same big alert popup as
the web even when the browser is in the background: layered topmost
window that does not steal focus, blinking border, open/close actions,
sound, autostart toggle, DPAPI-encrypted token.

Server side (project_db migration 023):
- notifier_links / notifier_tokens (SHA-256 hashes only)
- device link flow: link/start -> browser approve at /project/notifier
  -> link/poll issues token once
- Bearer API for alerts/read/logout reusing _alerts_payload; token
  re-checks current user record and project permission each call
- /project/notifier page (approve, connected PCs, revoke, download)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:21:58 +09:00
king 8f46d6c13a Merge branch 'feat/week-target-month-manual' 2026-10-08 09:20:17 +09:00
king 701f43a1f8 feat(project): manual monthly sales target with weekly diff
Week target popup now has its own "month total" input at the top; the
monthly target is saved as entered instead of being the sum of weeks.
Bottom shows week sum and diff (month target - week sum), colored
for remaining / over / even. Requests without `month` (stale cached JS)
still fall back to the week sum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:20:07 +09:00
king 9eea1a073a Merge branch 'feat/stage-color-alerts-meeting-lock' 2026-10-07 17:37:28 +09:00
king 5278d568de feat(project): weekly meetings editable by anyone, admin completes to lock
Meeting write APIs now accept any project user; deleting a meeting and the
new POST /api/goals/meetings/{week}/complete (complete/reopen) stay admin
only. A completed meeting (migration 022: completed_at, completed_by)
rejects edits with 409; last-week result fields follow the next meeting's
lock instead. The page shows a complete button / locked badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:37:23 +09:00
king 21fc78adb9 feat(project): blinking popup for new mentions and task assignments
Project pages poll GET /api/notifications/alerts every 20s (and when the
tab becomes visible). New unread mention/assigned notifications show in a
large blinking popup at the bottom center until closed; closing in one tab
closes it in the others. A new browser starts from the latest id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:30:15 +09:00
king 4bdab1de3d feat(project): uniform #f3f3f3 section headers, remove section color picker
Stored stage colors are ignored; timeline rows use the project color.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:27:59 +09:00
king f90884e028 Merge branch 'feat/quick-task-delete' 2026-10-07 16:57:02 +09:00
king 6959941128 feat(project): delete registered tasks from the meeting task table
Registered rows get a delete button that, after confirmation, deletes the
task from its project (trash). Unapplied rows get an x to drop the row.
Registered rows now stay in the browser list so they can be deleted later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:56:57 +09:00
king 18dd9531ad Merge branch 'fix/member-modal-height' 2026-10-07 16:53:22 +09:00
king 28d56fc3c5 fix(project): member dialog grows to fit everyone instead of scrolling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:53:18 +09:00
king b8d944b3ef Merge branch 'feat/meeting-units-members' 2026-10-07 16:50:46 +09:00
king a0722f26ca feat(project): meeting numbers in sales unit, member add/remove, quick-task polish
- Header numbers use the goal table sales unit (e.g. 백만원); exact won
  amounts in tooltips.
- Notes title: 결정사항 : 진행상황 수시 공유 및 완료 되어야 함.
- Member dialog shows current members checked: check to add, uncheck to
  remove (owner locked); member APIs also require project access.
- Quick task table: centered bold headers, assignee shown as avatar + name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:50:42 +09:00
king 261267a523 Merge branch 'feat/meeting-top-areas' 2026-10-07 16:24:27 +09:00
king da27c9990a feat(project): meeting header with plan, notes and quick task table
Three header areas that stay visible while the table scrolls:
month plan with the four numbers in one compact line, decisions/notes,
and a task table (title, assignee, project, section) whose cells open
pick lists; Apply creates the task in that project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:24:23 +09:00
king 50153139fc Merge branch 'feat/member-no-role' 2026-10-07 15:49:59 +09:00
king c4fb7761ad feat(project): drop member role from assignment
The role select (member/manager) had no effect on permissions; every
assigned member can view and edit the project. Remove it from the
assign dialog and avatar tooltip; new assignments are always member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:49:54 +09:00
king fb7b25ba2c Merge branch 'fix/asset-monitor-same-model' 2026-10-07 15:14:27 +09:00
king e9be17faab fix(asset): allow registering a monitor of an already-registered model
Registration was blocked whenever same-model candidates existed, so a
second monitor of the same model (e.g. dual monitors) could not be added.
Now only an existing asset with the same serial blocks a new one; the
UI tells serial and model candidates apart and hides 'register' only
for serial matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:14:22 +09:00
king 133df472d1 Merge branch 'fix/dash-workload-bar-ratio' 2026-10-07 14:43:27 +09:00
king 569b33ece4 fix(project): workload bars fill by completion rate, not task count
Bar height was scaled to the largest count, so 9/13 looked nearly empty
and 1/1 short. Each bar is now the whole set; green fill = done ratio,
with count and percent above.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:43:21 +09:00
king 452e8a9093 Merge branch 'feat/dash-workload-bars' 2026-10-07 14:24:07 +09:00
king 1cfcec2bef feat(project): workload as vertical bars with task list drawer
Per assignee, main and subtask bars (height = count, green = done).
Clicking a bar slides in a right-side panel listing those tasks;
clicking an item opens the task editor. Closing the editor refreshes
the counts. Subtask summary API now returns id, title, due date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:24:02 +09:00
king 2d638804d1 Merge branch 'feat/project-members-only' 2026-10-07 14:16:41 +09:00
king b6dc82c0b3 feat(project): projects visible to members only, admins included
Admins no longer see projects they are not owner/member of: sidebar list,
project list API, project pages, search, inbox, notifications, reminders
and trash all follow access.visible_project_ids. Only the super admin
still sees every project. Member assignment stays admin-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:16:36 +09:00
king 2a01d97dd0 Merge branch 'feat/dash-assignee-workload' 2026-10-07 14:09:11 +09:00
king fc3a2d0b9b feat(project): dashboard workload by assignee with subtasks and completion
Replace the scheduled-tasks bar chart with a table of all tasks assigned
per person in scope (no due date needed, filters ignored): main tasks,
subtasks (new GET /api/projects/{id}/subtasks-summary), done counts and
completion rate, plus a total row. Admin only, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:09:06 +09:00
king c766af691a Merge branch 'feat/goals-no-cell-move' 2026-10-07 14:03:34 +09:00
king b7c24c07e7 feat(project): remove drag-to-move for annual goal cells
Goal text cells no longer get move borders or drag handling; clicking a
cell still highlights it. The weekly meeting table keeps its move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:02:51 +09:00
king fbb6c648a5 Merge branch 'feat/board-btn-color' 2026-10-07 13:58:18 +09:00
king 8b664fc216 style(project): pastel PowerPoint colors for meeting board button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:58:14 +09:00
king 5f10f9ce45 Merge branch 'fix/board-refresh-error-code' 2026-10-07 12:59:38 +09:00
king 46dc038e26 fix(project): show OAuth error code when meeting board token refresh fails
RefreshError showed only a generic message; include Google's error code
and explain client ID/secret mismatch (unauthorized_client).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:59:33 +09:00
king c0b742af8a Merge branch 'fix/authorize-port-18765' 2026-10-07 12:50:19 +09:00
king 80c9904771 fix(scripts): move OAuth callback port to 18765
8765-8767 are taken by local preview servers on the dev PC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:50:14 +09:00
king 8885bbce6b Merge branch 'fix/authorize-fixed-port' 2026-10-07 12:42:30 +09:00
king e9618d93d6 fix(scripts): use fixed OAuth callback port 8765 for token issue
A web-application OAuth client needs the exact redirect URI registered;
a random port made that impossible (redirect_uri_mismatch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:42:26 +09:00
69 changed files with 6955 additions and 1308 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성/삭제·사용자 배정은 `is_admin` 만, 배정 멤버(또는 owner)는 서브프로젝트/업무/단계 CRUD. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 권한은 등급(수퍼관리자 > Admin > Pro user > User, 2026-10-12)과 멤버십 기준 — 표는 `docs/PROJECT_MODULE.md` 6-14, 공통 판단 `access.py`(관리자도 멤버가 아니면 프로젝트가 안 보임, 예외는 수퍼관리자). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
상세는 `docs/PROJECT_OVERVIEW.md`.
+2 -1
View File
File diff suppressed because one or more lines are too long
+8 -1
View File
@@ -20,6 +20,7 @@ from __future__ import annotations
import json
import os
import re
import threading
from typing import Any
@@ -153,6 +154,12 @@ def _friendly(exc: Exception) -> str:
"""Google API 오류 → 화면용 문구(비밀값·원문 응답 미포함)."""
status = getattr(getattr(exc, "resp", None), "status", None)
text = str(exc)
# 토큰 갱신 실패(RefreshError) — Google 이 준 OAuth 오류 코드(비밀값 아님)를 보여 원인을 바로 알 수 있게
m = re.search(r"\b(invalid_scope|invalid_grant|invalid_client|unauthorized_client|deleted_client|access_denied|invalid_request)\b", text)
code = m.group(1) if m else ""
if code in ("unauthorized_client", "invalid_client", "deleted_client"):
return (f"Google 토큰 갱신 실패({code}) — 토큰을 발급한 OAuth 클라이언트와 서버 .env 의 "
"GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET(없으면 GOOGLE_CLIENT_ID/SECRET)이 다릅니다.")
if "invalid_scope" in text or "insufficient" in text.lower() or "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text:
return "Google 권한(Drive·Slides)이 없는 토큰입니다. 토큰을 다시 발급해 주세요(scripts/google_sheets_authorize.py)."
if "invalid_grant" in text:
@@ -161,7 +168,7 @@ def _friendly(exc: Exception) -> str:
return "회의록 보드 폴더를 찾을 수 없습니다(MEETING_BOARD_FOLDER_ID·공유 드라이브 접근 권한 확인)."
if status == 403:
return "Google Drive·Slides 접근이 거부되었습니다(API 사용 설정·공유 드라이브 권한 확인)."
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''})."
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''}{f' {code}' if code else ''})."
_CLIENT: GoogleSlidesClient | None = None
+26 -2
View File
@@ -35,6 +35,8 @@ from .modules.vacation import router as vacation_router
from .store import (
APPROVER_KEYS,
MODULE_KEYS,
ROLE_LABELS,
ROLES,
SUPER_ADMIN_EMAIL,
UserStore,
allowed_modules,
@@ -488,16 +490,36 @@ def build_erp_nav(
return items
def _login_orbit_names(limit: int = 40) -> list[str]:
"""로그인 화면 왼쪽 패널 — King 주위를 도는 사용자 아이디(이메일 @ 앞, 첫 글자 대문자). 이메일·실명은 내보내지 않는다."""
names: set[str] = set()
try:
users = user_store.list_all()
except Exception: # noqa: BLE001 — 장식이라 실패해도 로그인 화면은 그대로
return []
for u in users:
email = str(u.get("email") or "").lower().strip()
local = email.split("@", 1)[0]
if not local or email == SUPER_ADMIN_EMAIL:
continue
names.add(local[:1].upper() + local[1:])
return sorted(names)[:limit]
def _render_login(request: Request) -> HTMLResponse:
return render_template(request, "login.html", {"orbit_names": _login_orbit_names()})
@app.get("/", response_class=HTMLResponse)
async def home(request: Request) -> HTMLResponse:
sess = get_session_user(request)
if not sess:
return render_template(request, "login.html")
return _render_login(request)
user_rec = user_store.get(sess["email"])
if user_rec is None:
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
request.session.clear()
return render_template(request, "login.html")
return _render_login(request)
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
@@ -643,6 +665,8 @@ async def admin_page(request: Request) -> HTMLResponse:
"module_keys": list(MODULE_KEYS),
"module_labels": MODULE_LABELS,
"approver_keys": list(APPROVER_KEYS),
"roles": list(ROLES),
"role_labels": ROLE_LABELS,
"super_admin_email": SUPER_ADMIN_EMAIL,
"is_admin": True,
},
+9 -2
View File
@@ -229,9 +229,14 @@ class AssetStore:
compatible = [a for a in matches if compatible_monitor(a, device)]
asset = linked or (compatible[0] if len(compatible) == 1 else None)
candidates = matches if not asset else []
# candidate_by — 후보가 같은 시리얼(같은 실물일 가능성)인지, 참고용 같은 모델·이름인지.
# 같은 모델은 여러 대일 수 있으므로(듀얼 모니터 등) 새 등록을 막지 않는다(2026-10-07).
candidate_by = "serial" if candidates else ""
if not asset and not candidates:
candidates = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND (lower(btrim(model))=%s OR lower(btrim(name))=%s) ORDER BY id LIMIT 20", (device["model"].casefold(), device["name"].casefold())).fetchall()
candidate_by = "model" if candidates else ""
result.append({**device, "asset": serialize(asset), "candidates": [serialize(r) for r in candidates],
"candidate_by": candidate_by,
"match": "linked" if linked else "serial" if asset else "unconfirmed"})
return result
@@ -263,8 +268,10 @@ class AssetStore:
monitor_id = target["id"]
else:
match = self._monitor_matches(conn, computer_id, row["parsed"])[index]
if match["asset"] or (device["serial"] and match["candidates"]):
raise AssetConflict("이미 등록된 모니터가 있습니다. 기존 자산을 확인하고 연결하세요.")
# 같은 시리얼(같은 실물)만 막는다 — 같은 모델이지만 시리얼이 다른 모니터는 새 자산으로 등록된다.
if match["asset"] or match["candidate_by"] == "serial":
raise AssetConflict(f"같은 시리얼({device['serial']})의 모니터가 이미 등록되어 있습니다. 기존 자산에 연결하세요."
if device["serial"] else "이 모니터는 이미 자산에 연결되어 있습니다.")
# 보고서의 실제 시리얼을 유지해야 이후 보고서에서도 같은 장비를 찾습니다.
data = payload.asset.model_copy(update={"serial": device["serial"] or payload.asset.serial})
monitor_id = self._create(conn, data, actor)
+1 -1
View File
@@ -67,4 +67,4 @@
<dialog id="am-photo" class="am-dialog" aria-labelledby="am-photo-title"><div class="am-dialog-head"><h2 id="am-photo-title">자산 사진 등록</h2><button type="button" class="am-close" data-close="am-photo" aria-label="사진 등록 닫기">×</button></div><form id="am-photo-form" class="am-form"><p class="am-form-hint">JPG · PNG · WebP, 파일당 8 MB 이하 · 자산당 최대 10장. 촬영 위치 정보는 제거해 보관합니다.</p><label>사진 선택<input id="am-photo-file" type="file" accept="image/jpeg,image/png,image/webp" required></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-photo">취소</button><button type="submit" class="erp-btn erp-btn-primary">사진 저장</button></div></form></dialog>
<dialog id="am-delete" class="am-dialog" aria-labelledby="am-delete-title"><div class="am-dialog-head"><h2 id="am-delete-title">자산 삭제</h2><button type="button" class="am-close" data-close="am-delete" aria-label="삭제 창 닫기">×</button></div><form id="am-delete-form" class="am-form"><p class="am-warning" id="am-delete-hint"></p><p class="am-form-hint">자산대장과 현황에서 제외됩니다. 사진·보고서·처리 이력은 보존됩니다.</p><label>삭제할 자산번호 확인<input id="am-delete-confirm" required autocomplete="off"></label><label>삭제 사유<textarea id="am-delete-note" required maxlength="2000" rows="3"></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-delete">취소</button><button type="submit" class="erp-btn am-danger">자산 삭제</button></div></form></dialog>
{% endblock %}
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261006c" defer></script>{% endblock %}
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261007a" defer></script>{% endblock %}
+46 -11
View File
@@ -5,12 +5,23 @@
바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다).
프로젝트
관리(=보기·작업 CRUD) : 관리자(is_admin) · 프로젝트 owner · 배정 멤버. 모두 `project` 모듈 권한이 있어야 한다.
관리(=보기·작업 CRUD) : 프로젝트 owner · 배정 멤버 · 슈퍼관리자. 모두 `project` 모듈 권한이 있어야 한다.
(2026-10-07 — 관리자(is_admin)도 멤버가 아닌 프로젝트는 보이지 않는다. 예외는 슈퍼관리자 한 명뿐.
멤버 배정은 Pro user 이상(2026-10-12) — 라우터의 _require_pro, 아래 등급 표.)
등급(2026-10-12, app.store.ROLES) — 수퍼관리자 > admin > pro > user
is_project_admin : 수퍼관리자·admin — 남이 만든 프로젝트·섹션도 삭제.
is_pro : 수퍼관리자·admin·pro — 새 프로젝트 만들기, 프로젝트 이름·색·아이콘·소유자 수정,
멤버 배정·제외(자기가 멤버인 프로젝트), 사이드바 순서, 남의 댓글 수정·삭제,
휴지통 보기·복구, 전체 보기, 대시보드 담당자별 합계, 전체 멤버 메뉴,
목표 표 입력·구조 변경·주차별 목표·연도 추가/삭제, 회의 완료·완료 해제·회의록 삭제.
user : 멤버인 프로젝트의 작업·섹션·서브프로젝트·작업 삭제, 회의록 작성(완료 전까지).
프로젝트 단위 권한은 등급과 상관없이 멤버(owner)여야 한다 — 위 is_pro 권한도 멤버인 프로젝트 안에서만.
작업
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙)
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(작업 삭제는 멤버 누구나, 2026-10-12)
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
→ 그 작업의 상세·하위 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
→ 그 작업의 상세·세부 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외
"""
@@ -34,10 +45,34 @@ def default_user_lookup(email: str) -> dict[str, Any] | None:
return user_store.get(store.norm_str(email, lower=True))
def _is_admin(user: dict[str, Any] | None) -> bool:
from app.store import is_admin # noqa: WPS433
def _is_super(user: dict[str, Any] | None) -> bool:
"""슈퍼관리자(app.store.SUPER_ADMIN_EMAIL) — 모든 프로젝트를 보는 유일한 예외."""
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
return is_admin(user)
return bool(user) and email_of(user) == SUPER_ADMIN_EMAIL
def role_of(user: dict[str, Any] | None) -> str:
"""등급 — 'super' · 'admin' · 'pro' · 'user'. 모르는 role 값은 user 로 본다."""
if _is_super(user):
return "super"
role = (user or {}).get("role")
return role if role in ("admin", "pro") else "user"
def is_project_admin(user: dict[str, Any] | None) -> bool:
"""수퍼관리자·admin — 만든 사람이 아니어도 프로젝트·섹션을 지운다."""
return role_of(user) in ("super", "admin")
def is_pro(user: dict[str, Any] | None) -> bool:
"""수퍼관리자·admin·pro — 프로젝트 관리·목표 입력 등 운영 권한(모듈 docstring 의 등급 표)."""
return role_of(user) in ("super", "admin", "pro")
def sees_all_projects(user: dict[str, Any] | None) -> bool:
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
return can_use_module(user) and _is_super(user)
def can_use_module(user: dict[str, Any] | None) -> bool:
@@ -51,10 +86,10 @@ def email_of(user: dict[str, Any] | None) -> str:
def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool:
"""프로젝트 관리(=보기·작업 CRUD) — 관리자 또는 owner/멤버. 모듈 권한이 없으면 False."""
"""프로젝트 관리(=보기·작업 CRUD) — owner/멤버(관리자도 마찬가지), 슈퍼관리자는 전부. 모듈 권한이 없으면 False."""
if not can_use_module(user):
return False
if _is_admin(user):
if _is_super(user):
return True
try:
pid = int(project_id)
@@ -64,11 +99,11 @@ def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) ->
def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
"""관리할 수 있는 프로젝트 id 집합. 관리자는 None(=전체)."""
if _is_admin(user):
return None
"""관리할 수 있는 프로젝트 id 집합. 슈퍼관리자는 None(=전체), 그 밖(관리자 포함)은 owner·멤버인 프로젝트만."""
if not can_use_module(user):
return set()
if _is_super(user):
return None
return {
int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user))
}
+488 -175
View File
@@ -12,8 +12,10 @@
from __future__ import annotations
import hashlib
import logging
import re
import secrets
import time
import uuid
from datetime import date, datetime, timedelta
@@ -96,7 +98,10 @@ class ProjectStore:
created_by: str = "",
seed_stages: bool = False,
icon: str | None = None,
member_emails: list[str] | None = None,
) -> dict[str, Any]:
"""member_emails — 만들면서 같이 넣을 멤버(같은 트랜잭션). 남을 소유자로 지정해 만든 사람이
만든 직후 자기 프로젝트를 못 여는 일이 없게 라우터가 만든 사람을 넣는다(일반 멤버 — 나중에 뺄 수 있다)."""
nm = store.validate_project_name(name)
col = store.validate_color(color)
ic = store.validate_project_icon(icon)
@@ -134,6 +139,12 @@ class ProjectStore:
vals,
).fetchone()
pid = row["id"]
for em in store.normalize_emails(member_emails or []):
conn.execute(
"INSERT INTO project_members (project_id, user_email, user_name, role) "
"VALUES (%s,%s,'','member') ON CONFLICT (project_id, user_email) DO NOTHING",
(pid, em),
)
if seed_stages:
for i, (stage_name, is_done) in enumerate(store.DEFAULT_STAGES):
conn.execute(
@@ -172,21 +183,26 @@ class ProjectStore:
if existing is None:
raise KeyError(project_id)
return existing
if "start_date" in clean or "due_date" in clean:
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다.
existing = self.get_project(project_id=project_id)
if existing is None:
raise KeyError(project_id)
store.validate_date_range(
clean["start_date"] if "start_date" in clean else existing.get("start_date"),
clean["due_date"] if "due_date" in clean else existing.get("due_date"),
)
params.append(project_id)
with self._pool.connection() as conn:
row = conn.execute(
f"UPDATE projects SET {', '.join(sets)} WHERE id = %s RETURNING *",
params,
).fetchone()
with conn.transaction():
if "start_date" in clean or "due_date" in clean:
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다 — 그 행을 잠근 뒤 읽어서(FOR UPDATE)
# 두 사람이 시작일·마감일을 동시에 바꿔도 각자 옛 값으로 검사해 역전되지 않게.
existing = conn.execute(
"SELECT start_date, due_date FROM projects WHERE id = %s FOR UPDATE", (project_id,)
).fetchone()
if existing is None:
raise KeyError(project_id)
existing = self._serialize(existing)
store.validate_date_range(
clean["start_date"] if "start_date" in clean else existing.get("start_date"),
clean["due_date"] if "due_date" in clean else existing.get("due_date"),
)
row = conn.execute(
f"UPDATE projects SET {', '.join(sets)} WHERE id = %s RETURNING *",
params,
).fetchone()
if not row:
raise KeyError(project_id)
return self._serialize(row)
@@ -332,9 +348,11 @@ class ProjectStore:
return self._serialize(row) if row else None
@staticmethod
def _stage_default_assignee(conn: Any, stage_id: Any, project_id: int) -> tuple[str, str]:
def _stage_default_assignee(conn: Any, stage_id: Any, project_id: int,
allowed: Any = None) -> tuple[str, str]:
"""세션 기본 담당자(마이그레이션 009) → (email, name). 미지정·009 미적용·
그 사람이 이제 프로젝트 멤버가 아니면 ('', '').
그 사람이 이제 프로젝트 멤버가 아니면 ('', ''). allowed(email) 가 있으면 그것도 통과해야 한다 —
삭제된 사용자·project 모듈 권한을 잃은 사람에게 자동 배정(과 배정 알림)이 가지 않게(라우터가 넘김).
컬럼이 없어도 에러가 나지 않게 to_jsonb(행) 에서 키로 읽는다."""
if stage_id in (None, ""):
@@ -358,8 +376,17 @@ class ProjectStore:
).fetchone()
if not m:
return "", ""
if allowed is not None and not allowed(email):
return "", ""
return email, m["user_name"] or ""
@staticmethod
def _stage_is_done_conn(conn: Any, stage_id: Any) -> bool:
if stage_id is None:
return False
row = conn.execute("SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)).fetchone()
return bool(row and row["is_done_stage"])
@staticmethod
def _check_stage_in_project(conn: Any, stage_id: Any, project_id: int) -> int | None:
"""세션이 그 프로젝트 것인지 확인하고 int 로 돌려준다(None 은 그대로).
@@ -415,9 +442,9 @@ class ProjectStore:
) -> list[dict[str, Any]]:
"""업무 목록.
기본은 최상위 업무만(`parent_task_id IS NULL`) — 하위 업무는 부모 안에서만
기본은 최상위 업무만(`parent_task_id IS NULL`) — 세부 업무는 부모 안에서만
보인다(아사나와 동일, 보드/캘린더/리스트 카드로 따로 뜨지 않는다).
`parent_task_id` 를 주면 그 부모의 하위 업무만 받는다.
`parent_task_id` 를 주면 그 부모의 세부 업무만 받는다.
`project_id` 하나만 지정하고(`include_subprojects=False`, 최상위 조회일
때) `include_links=True`(기본값)이면, 그 프로젝트에 멀티호밍
@@ -484,6 +511,34 @@ class ProjectStore:
project_ids=[project_id], assignee_email=assignee_email, limit=limit,
)
def list_subtasks_of(self, *, parent_ids: list[int]) -> list[dict[str, Any]]:
"""세부 업무 요약(대시보드 담당자별 집계·업무 목록 패널용) — id·부모·제목·마감일·완료·담당자.
세부 업무의 세부 업무까지 모든 단계(2026-10-08) — root_task_id = 맨 위 메인 업무(parent_ids 중 하나),
parent_title = 바로 위 업무 제목(목록 패널 "상위:" 표시). 깊이 20 단계에서 멈춘다(잘못된 순환 방어)."""
ids = sorted({int(i) for i in parent_ids})
if not ids:
return []
with self._pool.connection() as conn:
rows = conn.execute(
"WITH RECURSIVE sub AS ("
" SELECT t.id, t.parent_task_id, t.parent_task_id AS root_task_id, 1 AS depth"
" FROM tasks t WHERE t.parent_task_id = ANY(%s)"
" UNION ALL"
" SELECT c.id, c.parent_task_id, s.root_task_id, s.depth + 1"
" FROM tasks c JOIN sub s ON c.parent_task_id = s.id WHERE s.depth < 20"
") "
"SELECT DISTINCT ON (t.id) t.id, t.parent_task_id, s.root_task_id, s.depth, t.title, t.due_date, t.completed_at,"
" t.assignee_email, t.assignee_name, p.title AS parent_title "
"FROM sub s JOIN tasks t ON t.id = s.id LEFT JOIN tasks p ON p.id = t.parent_task_id "
"ORDER BY t.id, s.depth", (ids,),
).fetchall()
return [{"id": int(r["id"]), "parent_task_id": int(r["parent_task_id"]), "root_task_id": int(r["root_task_id"]),
"depth": int(r["depth"]), "parent_title": r["parent_title"] or "", "title": r["title"] or "",
"due_date": r["due_date"].isoformat() if r["due_date"] else None,
"completed_at": r["completed_at"].isoformat() if r["completed_at"] else None,
"assignee_email": r["assignee_email"] or "", "assignee_name": r["assignee_name"] or "",
"done": r["completed_at"] is not None} for r in rows]
def list_tasks_for_projects(
self, *, project_ids: list[int], assignee_email: str | None = None,
limit: int = 20000,
@@ -547,7 +602,7 @@ class ProjectStore:
return [self._serialize(r) for r in rows]
def count_my_open(self, *, assignee_email: str) -> int:
"""사이드바 "내 업무" 배지 — 내가 담당인 미완료 업무 수(하위 업무 포함,
"""사이드바 "내 업무" 배지 — 내가 담당인 미완료 업무 수(세부 업무 포함,
내 업무 화면 목록과 같은 기준)."""
with self._pool.connection() as conn:
row = conn.execute(
@@ -557,11 +612,13 @@ class ProjectStore:
).fetchone()
return int(row["n"] or 0)
def list_my_tasks(self, *, assignee_email: str, limit: int = 1000) -> list[dict[str, Any]]:
""""내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이
전부 반환한다. 하위 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이
붙여서, 부모가 내 업무가 아니어도(다른 사람 담당) 화면에서 트리로 묶어
보여줄 수 있게 한다.
def list_my_tasks(self, *, assignee_email: str, completed_limit: int = 1000) -> list[dict[str, Any]]:
""""내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이 반환한다.
세부 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이 붙여서, 부모가 내 업무가 아니어도
(다른 사람 담당) 화면에서 트리로 묶어 보여줄 수 있게 한다.
미완료는 **전부**, 완료는 최근에 완료한 completed_limit 건까지 — 예전엔 전체를 1000건에서 잘라
오래된 완료 업무가 새 미완료 업무를 목록 밖으로 밀어낼 수 있었다.
"""
email = store.norm_str(assignee_email, lower=True)
with self._pool.connection() as conn:
@@ -577,8 +634,11 @@ class ProjectStore:
f"LEFT JOIN project_stages s ON s.id = t.stage_id "
f"LEFT JOIN tasks pt ON pt.id = t.parent_task_id "
f"WHERE t.assignee_email = %s "
"ORDER BY t.sort_order ASC, t.id ASC LIMIT %s",
(email, int(limit)),
" AND (t.completed_at IS NULL OR t.id IN ("
" SELECT d.id FROM tasks d WHERE d.assignee_email = %s AND d.completed_at IS NOT NULL "
" ORDER BY d.completed_at DESC, d.id DESC LIMIT %s)) "
"ORDER BY t.sort_order ASC, t.id ASC",
(email, email, int(completed_limit)),
).fetchall()
return [self._serialize(r) for r in rows]
@@ -612,7 +672,9 @@ class ProjectStore:
due_time: str | None = None,
created_by: str = "",
parent_task_id: int | None = None,
assignee_allowed: Any = None,
) -> dict[str, Any]:
"""assignee_allowed — update_task 와 같이 섹션 기본 담당자 자동 배정 전 지금 권한 확인(라우터가 넘김)."""
ttl = store.validate_task_title(title)
pr = store.validate_priority(priority)
sd = store.validate_date(start_date)
@@ -625,7 +687,7 @@ class ProjectStore:
with self._pool.connection() as conn:
with conn.transaction():
if parent_task_id is not None:
# 하위 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이
# 세부 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이
# 맞아떨어지게), 보드에는 안 보이므로 세션을 갖지 않는다.
parent = conn.execute(
"SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,)
@@ -634,7 +696,7 @@ class ProjectStore:
raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}")
# 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트
# 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는
# 프로젝트에 하위 업무를 만들 수 있었다).
# 프로젝트에 세부 업무를 만들 수 있었다).
if int(parent["project_id"]) != int(project_id):
raise ValueError("상위 작업이 이 프로젝트에 속하지 않습니다.")
stage_id = None
@@ -648,10 +710,11 @@ class ProjectStore:
(project_id,),
).fetchone()
stage_id = st["id"] if st else None
# 담당자 없이 만들면 그 세션의 기본 담당자를 배정(하위 업무는
# 담당자 없이 만들면 그 세션의 기본 담당자를 배정(세부 업무는
# 세션이 없어 해당 없음).
if not assignee and stage_id is not None:
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id)
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id,
allowed=assignee_allowed)
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
if stage_id is not None:
done_row = conn.execute(
@@ -693,12 +756,12 @@ class ProjectStore:
def move_subtask(
self, *, task_id: int, parent_task_id: int, actor: str = ""
) -> dict[str, Any]:
"""하위 업무를 다른 상위 업무 밑으로 옮긴다(보드 카드로 드래그).
"""세부 업무를 다른 상위 업무 밑으로 옮긴다(보드 카드로 드래그).
받는 쪽은 보드 카드 = 최상위 업무만 허용한다 — 그래서 자기 자신이나
자기 하위로 옮기는 순환이 생기지 않는다. 같은 프로젝트 안에서만
(하위 업무는 부모와 같은 프로젝트에 속한다 — create_task 와 같은 규칙).
하위 업무의 하위 업무는 그대로 따라간다. 목록 끝(sort_order 최대+1)으로.
(세부 업무는 부모와 같은 프로젝트에 속한다 — create_task 와 같은 규칙).
세부 업무의 세부 업무는 그대로 따라간다. 목록 끝(sort_order 최대+1)으로.
"""
with self._pool.connection() as conn:
with conn.transaction():
@@ -710,7 +773,7 @@ class ProjectStore:
if not sub:
raise KeyError(f"작업을 찾을 수 없습니다: {task_id}")
if sub["parent_task_id"] is None:
raise ValueError("하위 작업만 다른 작업으로 옮길 수 있습니다.")
raise ValueError("세부 작업만 다른 작업으로 옮길 수 있습니다.")
parent = conn.execute(
"SELECT id, project_id, parent_task_id, title FROM tasks WHERE id = %s",
(parent_task_id,),
@@ -718,7 +781,7 @@ class ProjectStore:
if not parent:
raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}")
if parent["parent_task_id"] is not None:
raise ValueError("하위 작업 안으로는 옮길 수 없습니다.")
raise ValueError("세부 작업 안으로는 옮길 수 없습니다.")
if int(parent["project_id"]) != int(sub["project_id"]):
raise ValueError("다른 프로젝트의 작업으로는 옮길 수 없습니다.")
if int(parent["id"]) != int(sub["parent_task_id"]):
@@ -737,129 +800,132 @@ class ProjectStore:
return self.get_task(task_id=task_id)
def update_task(
self, *, task_id: int, fields: dict[str, Any], actor: str = ""
self, *, task_id: int, fields: dict[str, Any], actor: str = "",
assignee_allowed: Any = None,
) -> dict[str, Any]:
"""업무 수정. 반환에 알림 힌트를 담는다(라우터가 메일 발송 판단).
반환 dict 에 추가되는 키:
_newly_assigned: 새 담당자 이메일 or None
_newly_completed: 완료로 전환됐으면 True
"""
prev = self.get_task(task_id=task_id)
if prev is None:
raise KeyError(task_id)
sets: list[str] = []
params: list[Any] = []
동시성 — 기존 값 읽기·최종 날짜 검사·변경·이력을 **한 트랜잭션에서 그 작업 행을 잠그고**
(SELECT … FOR UPDATE) 한다. 두 사람이 시작일·마감일을 동시에 바꿔도 각자 옛 값으로 검사해
날짜가 역전되지 않고, 동시에 완료해도 완료 이력·알림 힌트는 실제로 완료로 바뀐 한 요청에서만 생긴다.
섹션 확인·기본 담당자·완료 섹션 여부도 같은 연결로 읽는다(다른 연결을 다시 빌리지 않는다).
assignee_allowed(email) — 섹션 기본 담당자를 자동 배정하기 전에 그 사람이 지금 등록된 project
권한 사용자인지(사용자 목록은 DB 밖이라 라우터가 넘긴다). 없으면 멤버·owner 여부만 본다.
"""
# 형식 검사는 잠그기 전에(잠금을 짧게) — 값이 틀리면 DB 에 가지 않는다.
clean: dict[str, Any] = {}
if "title" in fields:
clean["title"] = store.validate_task_title(fields["title"])
if "description" in fields:
clean["description"] = store.norm_str(fields["description"])
if "priority" in fields:
clean["priority"] = store.validate_priority(fields["priority"])
for k in ("start_date", "due_date"):
if k in fields:
clean[k] = store.validate_date(fields[k])
for k in ("start_time", "due_time"):
if k in fields:
clean[k] = store.validate_time(fields[k])
newly_assigned: str | None = None
newly_completed = False
new_stage: Any = None
if "stage_id" in fields:
new_stage = self.stage_in_project(
stage_id=fields["stage_id"], project_id=prev["project_id"]
)
# 다른 세션으로 옮겨왔고 (옮긴 뒤에도) 담당자가 비어 있으면 그 세션의
# 기본 담당자를 배정한다. 이미 담당자가 있으면 그대로 둔다.
if new_stage is not None and new_stage != prev.get("stage_id"):
final_assignee = (
store.norm_str(fields["assignee_email"], lower=True)
if "assignee_email" in fields else (prev.get("assignee_email") or "")
)
if not final_assignee:
with self._pool.connection() as conn:
dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"])
if dae:
fields = {**fields, "assignee_email": dae, "assignee_name": dan}
if "title" in fields:
sets.append("title = %s")
params.append(store.validate_task_title(fields["title"]))
if "description" in fields:
sets.append("description = %s")
params.append(store.norm_str(fields["description"]))
if "priority" in fields:
sets.append("priority = %s")
params.append(store.validate_priority(fields["priority"]))
if "start_date" in fields:
sets.append("start_date = %s")
params.append(store.validate_date(fields["start_date"]))
if "due_date" in fields:
sets.append("due_date = %s")
params.append(store.validate_date(fields["due_date"]))
if "start_time" in fields:
sets.append("start_time = %s")
params.append(store.validate_time(fields["start_time"]))
if "due_time" in fields:
sets.append("due_time = %s")
params.append(store.validate_time(fields["due_time"]))
if "assignee_email" in fields:
new_assignee = store.norm_str(fields["assignee_email"], lower=True)
sets.append("assignee_email = %s")
params.append(new_assignee)
if "assignee_name" in fields:
sets.append("assignee_name = %s")
params.append(store.norm_str(fields["assignee_name"]))
if new_assignee and new_assignee != (prev.get("assignee_email") or ""):
newly_assigned = new_assignee
elif "assignee_name" in fields:
sets.append("assignee_name = %s")
params.append(store.norm_str(fields["assignee_name"]))
# 단계 변경 → 완료단계 진입 시 completed_at 자동 세팅. 단, 실제로 단계가
# 바뀐 경우에만 판정한다 — 업무 편집 모달의 "저장"은 매번 현재 stage_id
# 를 그대로 다시 보내는데, 여기서 무조건 판정하면 방금 "완료로 표시"로
# 켠 completed_at 을(단계는 그대로인데) 다시 꺼버리는 버그가 있었다.
if "stage_id" in fields:
sets.append("stage_id = %s")
params.append(new_stage)
if new_stage != prev.get("stage_id"):
done = self._stage_is_done(new_stage)
if done and not prev.get("completed_at"):
sets.append("completed_at = %s")
params.append(now_kst())
newly_completed = True
elif not done and prev.get("completed_at"):
sets.append("completed_at = NULL")
# 직접 완료 토글 — 하위 업무는 세션(칸반 컬럼)이 없어 위 자동 세팅이
# 적용되지 않는다. "stage_id" 를 같이 보냈으면 그쪽 판정이 우선한다.
elif "completed" in fields:
if fields["completed"] and not prev.get("completed_at"):
sets.append("completed_at = %s")
params.append(now_kst())
newly_completed = True
elif not fields["completed"] and prev.get("completed_at"):
sets.append("completed_at = NULL")
if not sets:
return {**prev, "_newly_assigned": None, "_newly_completed": False}
# 날짜 범위 — 한쪽만 바꾸거나 지워도 기존 값과 합친 최종 상태로 검사.
if any(k in fields for k in ("start_date", "due_date", "start_time", "due_time")):
def final(key: str, fn: Any) -> Any:
return fn(fields[key]) if key in fields else prev.get(key)
store.validate_date_range(
final("start_date", store.validate_date), final("due_date", store.validate_date),
final("start_time", store.validate_time), final("due_time", store.validate_time),
)
params.append(task_id)
with self._pool.connection() as conn:
with conn.transaction():
conn.execute(
f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", params
)
if newly_assigned:
self._log(conn, project_id=prev["project_id"], task_id=task_id,
actor=actor, action=store.ACTION_ASSIGNED,
detail=f"{prev['title']} → {newly_assigned}")
if newly_completed:
self._log(conn, project_id=prev["project_id"], task_id=task_id,
actor=actor, action=store.ACTION_COMPLETED,
detail=prev["title"])
row = conn.execute("SELECT * FROM tasks WHERE id = %s FOR UPDATE", (task_id,)).fetchone()
if row is None:
raise KeyError(task_id)
prev = self._serialize(row)
sets: list[str] = []
params: list[Any] = []
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"):
if k in clean:
sets.append(f"{k} = %s")
params.append(clean[k])
assignee_fields = {k: fields[k] for k in ("assignee_email", "assignee_name") if k in fields}
new_stage: Any = None
if "stage_id" in fields:
new_stage = self._check_stage_in_project(conn, fields["stage_id"], prev["project_id"])
# 다른 세션으로 옮겨왔고 (옮긴 뒤에도) 담당자가 비어 있으면 그 세션의
# 기본 담당자를 배정한다. 이미 담당자가 있으면 그대로 둔다.
if new_stage is not None and new_stage != prev.get("stage_id"):
final_assignee = (
store.norm_str(fields["assignee_email"], lower=True)
if "assignee_email" in fields else (prev.get("assignee_email") or "")
)
if not final_assignee:
dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"],
allowed=assignee_allowed)
if dae:
assignee_fields = {"assignee_email": dae, "assignee_name": dan}
if "assignee_email" in assignee_fields:
new_assignee = store.norm_str(assignee_fields["assignee_email"], lower=True)
sets.append("assignee_email = %s")
params.append(new_assignee)
if "assignee_name" in assignee_fields:
sets.append("assignee_name = %s")
params.append(store.norm_str(assignee_fields["assignee_name"]))
if new_assignee and new_assignee != (prev.get("assignee_email") or ""):
newly_assigned = new_assignee
elif "assignee_name" in assignee_fields:
sets.append("assignee_name = %s")
params.append(store.norm_str(assignee_fields["assignee_name"]))
# 단계 변경 → 완료단계 진입 시 completed_at 자동 세팅. 단, 실제로 단계가
# 바뀐 경우에만 판정한다 — 업무 편집 모달의 "저장"은 매번 현재 stage_id
# 를 그대로 다시 보내는데, 여기서 무조건 판정하면 방금 "완료로 표시"로
# 켠 completed_at 을(단계는 그대로인데) 다시 꺼버리는 버그가 있었다.
if "stage_id" in fields:
sets.append("stage_id = %s")
params.append(new_stage)
if new_stage != prev.get("stage_id"):
done = self._stage_is_done_conn(conn, new_stage)
if done and not prev.get("completed_at"):
sets.append("completed_at = %s")
params.append(now_kst())
newly_completed = True
elif not done and prev.get("completed_at"):
sets.append("completed_at = NULL")
# 직접 완료 토글 — 세부 업무는 세션(칸반 컬럼)이 없어 위 자동 세팅이
# 적용되지 않는다. "stage_id" 를 같이 보냈으면 그쪽 판정이 우선한다.
elif "completed" in fields:
if fields["completed"] and not prev.get("completed_at"):
sets.append("completed_at = %s")
params.append(now_kst())
newly_completed = True
elif not fields["completed"] and prev.get("completed_at"):
sets.append("completed_at = NULL")
if not sets:
changed = False
else:
changed = True
# 날짜 범위 — 한쪽만 바꾸거나 지워도 (잠근) 기존 값과 합친 최종 상태로 검사.
if any(k in clean for k in ("start_date", "due_date", "start_time", "due_time")):
def final(key: str) -> Any:
return clean[key] if key in clean else prev.get(key)
store.validate_date_range(final("start_date"), final("due_date"),
final("start_time"), final("due_time"))
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
if newly_assigned:
self._log(conn, project_id=prev["project_id"], task_id=task_id,
actor=actor, action=store.ACTION_ASSIGNED,
detail=f"{prev['title']} → {newly_assigned}")
if newly_completed:
self._log(conn, project_id=prev["project_id"], task_id=task_id,
actor=actor, action=store.ACTION_COMPLETED,
detail=prev["title"])
out = self.get_task(task_id=task_id)
out["_newly_assigned"] = newly_assigned
out["_newly_completed"] = newly_completed
if out is None:
raise KeyError(task_id)
out["_newly_assigned"] = newly_assigned if changed else None
out["_newly_completed"] = newly_completed if changed else False
return out
# ════════════════════════════════════════════════════════════
@@ -899,7 +965,7 @@ class ProjectStore:
return payload
def delete_task(self, *, task_id: int, deleted_by: str = "") -> tuple[list[int], int | None]:
"""업무(+하위 업무 CASCADE) 삭제 → (지워진 업무 id 목록, 휴지통 id).
"""업무(+세부 업무 CASCADE) 삭제 → (지워진 업무 id 목록, 휴지통 id).
휴지통 테이블(010)이 있으면 지우기 직전 스냅샷을 같은 트랜잭션에서 남긴다
(스냅샷 저장이 실패하면 삭제도 취소). 없으면 휴지통 id 는 None — 예전처럼
@@ -989,7 +1055,7 @@ class ProjectStore:
행은 지운다. 복구할 수 없으면 ValueError(사유), 없으면 KeyError.
- 같은 id 의 업무가 이미 있으면 거부(두 번 복구 방지).
- 프로젝트가 지워졌으면 거부. 하위 업무만 지웠던 경우 상위 업무가 없으면 거부.
- 프로젝트가 지워졌으면 거부. 세부 업무만 지웠던 경우 상위 업무가 없으면 거부.
- 세션이 지워졌으면 세션 없이(미지정), 연결/이력 중 지워진 프로젝트를
가리키는 행은 뺀다."""
with self._pool.connection() as conn:
@@ -1042,15 +1108,6 @@ class ProjectStore:
conn.execute("DELETE FROM project_trash WHERE id = %s", (trash_id,))
return {"task_id": int(root["id"]), "project_id": int(root["project_id"]), "task_ids": ids}
def _stage_is_done(self, stage_id: Any) -> bool:
if stage_id is None:
return False
with self._pool.connection() as conn:
row = conn.execute(
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
).fetchone()
return bool(row and row["is_done_stage"])
# ════════════════════════════════════════════════════════════
# 멀티호밍 (task_project_links) — 업무 1개가 여러 프로젝트/세션에 동시 소속.
# 원래 소속(tasks.project_id/stage_id)은 여기서 건드리지 않는다("기본 홈"은
@@ -1468,7 +1525,7 @@ class ProjectStore:
)
def reorder_subtasks(self, *, parent_task_id: int, ordered_ids: list[int]) -> None:
"""작업 팝업의 하위 작업 목록 드래그 재정렬 — 이 상위 작업의 하위 작업만
"""작업 팝업의 세부 작업 목록 드래그 재정렬 — 이 상위 작업의 세부 작업만
0부터 다시 매긴다(목록은 parent_task_id 로 먼저 거른 뒤 sort_order 순)."""
with self._pool.connection() as conn:
conn.execute(
@@ -1518,6 +1575,31 @@ class ProjectStore:
).fetchall()
return [self._serialize(r) for r in rows]
def list_unread_after(
self, *, recipient_email: str, after_id: int, types: tuple[str, ...], limit: int = 200,
) -> list[dict[str, Any]]:
"""큰 팝업 알림 후보 — 이 사람·읽지 않음·종류·id > after_id 를 DB 에서 먼저 걸러 **오래된 것(id)부터**.
라우터가 지금 볼 수 있는 것만 남기며 마지막 id 를 다음 after_id 로 넘겨 끝까지 읽는다."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM project_notifications "
"WHERE recipient_email = %s AND is_read = FALSE AND id > %s AND type = ANY(%s) "
"ORDER BY id ASC LIMIT %s",
(store.norm_str(recipient_email, lower=True), int(after_id), list(types), int(limit)),
).fetchall()
return [self._serialize(r) for r in rows]
def list_unread_refs(self, *, recipient_email: str) -> list[dict[str, Any]]:
"""읽지 않은 알림 전부의 (id, project_id, task_id) — 수신함 배지를 개수 제한 없이 정확히 세려고
가벼운 열만 읽는다(지금 권한 거르기는 라우터)."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT id, project_id, task_id FROM project_notifications "
"WHERE recipient_email = %s AND is_read = FALSE",
(store.norm_str(recipient_email, lower=True),),
).fetchall()
return [dict(r) for r in rows]
def count_unread(self, *, recipient_email: str) -> int:
with self._pool.connection() as conn:
row = conn.execute(
@@ -1544,6 +1626,137 @@ class ProjectStore:
)
return cur.rowcount or 0
# ════════════════════════════════════════════════════════════
# PC 알림 프로그램 연결(023) — notifier_links → notifier_tokens. 원문은 저장하지 않고 SHA-256 만.
# ════════════════════════════════════════════════════════════
NOTIFIER_LINK_TTL_MIN = 10
NOTIFIER_MAX_PENDING = 200 # 로그인 없이 부르는 연결 요청이 쌓이지 않게(만료 전 대기 건 상한)
_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 헷갈리는 0·O·1·I 제외
@staticmethod
def _sha(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def notifier_enabled(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "notifier_tokens")
def notifier_start_link(self, *, device_name: str) -> dict[str, Any]:
"""연결 요청 — 화면 코드와 poll 비밀값(원문은 여기서만 돌려준다)."""
poll = secrets.token_urlsafe(32)
with self._pool.connection() as conn:
with conn.transaction():
conn.execute("DELETE FROM notifier_links WHERE expires_at < now() - interval '1 day'")
row = conn.execute("SELECT count(*) AS n FROM notifier_links WHERE expires_at > now() AND approved_at IS NULL").fetchone()
if int(row["n"]) >= self.NOTIFIER_MAX_PENDING:
raise OverflowError("연결 요청이 너무 많습니다. 잠시 뒤 다시 시도하세요.")
for _ in range(5):
raw = "".join(secrets.choice(self._CODE_ALPHABET) for _ in range(8))
code = raw[:4] + "-" + raw[4:]
hit = conn.execute(
"INSERT INTO notifier_links (code, poll_hash, device_name, expires_at) "
"VALUES (%s, %s, %s, now() + make_interval(mins => %s)) ON CONFLICT (code) DO NOTHING RETURNING id",
(code, self._sha(poll), device_name[:80], self.NOTIFIER_LINK_TTL_MIN),
).fetchone()
if hit:
return {"code": code, "poll": poll, "expires_in": self.NOTIFIER_LINK_TTL_MIN * 60}
raise RuntimeError("연결 코드를 만들지 못했습니다.")
def notifier_get_link(self, *, code: str) -> dict[str, Any] | None:
"""승인 화면용 — 아직 유효한(만료 전·토큰 미발급) 요청만."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT code, device_name, email, approved_at, expires_at FROM notifier_links "
"WHERE code = %s AND expires_at > now() AND consumed_at IS NULL",
(store.norm_str(code).upper(),),
).fetchone()
return self._serialize(row) if row else None
def notifier_approve_link(self, *, code: str, email: str) -> bool:
"""[연결] — 아직 아무도 승인하지 않은 유효한 요청만 이 사용자로 승인."""
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE notifier_links SET email = %s, approved_at = now() "
"WHERE code = %s AND expires_at > now() AND approved_at IS NULL AND consumed_at IS NULL",
(store.norm_str(email, lower=True), store.norm_str(code).upper()),
)
return bool(cur.rowcount)
def notifier_poll_link(self, *, poll: str) -> dict[str, Any]:
"""프로그램의 확인 — 승인됐으면 토큰을 한 번만 발급. {"status": pending|expired|ok, ...}"""
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"SELECT id, email, device_name, approved_at, consumed_at, expires_at > now() AS alive "
"FROM notifier_links WHERE poll_hash = %s FOR UPDATE",
(self._sha(poll),),
).fetchone()
if not row or row["consumed_at"] or not row["alive"]:
return {"status": "expired"}
if not row["approved_at"]:
return {"status": "pending"}
token = secrets.token_urlsafe(32)
conn.execute("UPDATE notifier_links SET consumed_at = now() WHERE id = %s", (row["id"],))
conn.execute(
"INSERT INTO notifier_tokens (email, token_hash, device_name) VALUES (%s, %s, %s)",
(row["email"], self._sha(token), row["device_name"]),
)
return {"status": "ok", "token": token, "email": row["email"]}
def notifier_token_email(self, *, token: str) -> str | None:
"""토큰 → 사용자 이메일(해제된 토큰은 None). 마지막 접속 시각은 1분에 한 번만 갱신."""
if not token:
return None
with self._pool.connection() as conn:
row = conn.execute(
"UPDATE notifier_tokens SET last_seen_at = now() "
"WHERE token_hash = %s AND revoked_at IS NULL "
"AND (last_seen_at IS NULL OR last_seen_at < now() - interval '1 minute') RETURNING email",
(self._sha(token),),
).fetchone()
if row is None:
row = conn.execute(
"SELECT email FROM notifier_tokens WHERE token_hash = %s AND revoked_at IS NULL",
(self._sha(token),),
).fetchone()
return row["email"] if row else None
def notifier_active(self, *, email: str, within_sec: int = 180) -> bool:
"""이 사용자의 PC 알림 프로그램이 지금 돌고 있나 — 해제 안 된 토큰 중 최근(기본 3분) 확인한 것이 있으면 True.
프로그램은 20초마다 확인하고 last_seen_at 은 1분에 한 번 갱신되므로 3분이면 꺼진 PC 는 곧 빠진다. 023 미적용이면 False."""
try:
with self._pool.connection() as conn:
row = conn.execute(
"SELECT 1 FROM notifier_tokens WHERE email = %s AND revoked_at IS NULL "
"AND last_seen_at > now() - make_interval(secs => %s) LIMIT 1",
(store.norm_str(email, lower=True), within_sec),
).fetchone()
except psycopg_errors.UndefinedTable:
return False
return row is not None
def notifier_revoke_token(self, *, token: str) -> None:
with self._pool.connection() as conn:
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
(self._sha(token),))
def notifier_list_devices(self, *, email: str) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT id, device_name, created_at, last_seen_at FROM notifier_tokens "
"WHERE email = %s AND revoked_at IS NULL ORDER BY created_at DESC",
(store.norm_str(email, lower=True),),
).fetchall()
return [self._serialize(r) for r in rows]
def notifier_revoke_device(self, *, device_id: int, email: str) -> bool:
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE notifier_tokens SET revoked_at = now() WHERE id = %s AND email = %s AND revoked_at IS NULL",
(device_id, store.norm_str(email, lower=True)),
)
return bool(cur.rowcount)
# ════════════════════════════════════════════════════════════
# 멘션(@태그) — task_mentions
#
@@ -1605,6 +1818,27 @@ class ProjectStore:
).fetchall()
return [self._serialize(r) for r in rows]
def list_unread_mention_refs(self, *, mentioned_email: str) -> list[dict[str, Any]]:
"""미확인 태그가 있는 작업마다 (id, project_id, unread_mentions) — 배지를 제한 없이 세는 가벼운 조회."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT t.id, t.project_id, m.unread AS unread_mentions "
"FROM (SELECT task_id, COUNT(*) AS unread FROM task_mentions "
" WHERE mentioned_email = %s AND is_read = FALSE GROUP BY task_id) m "
"JOIN tasks t ON t.id = m.task_id",
(store.norm_str(mentioned_email, lower=True),),
).fetchall()
return [dict(r) for r in rows]
def list_my_open_refs(self, *, assignee_email: str) -> list[dict[str, Any]]:
"""내가 담당인 미완료 작업 전부의 (id, project_id) — "내 작업" 배지를 제한 없이 정확히 센다."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT id, project_id FROM tasks WHERE assignee_email = %s AND completed_at IS NULL",
(store.norm_str(assignee_email, lower=True),),
).fetchall()
return [dict(r) for r in rows]
def count_unread_mentions(self, *, mentioned_email: str) -> int:
with self._pool.connection() as conn:
row = conn.execute(
@@ -1669,7 +1903,7 @@ class ProjectStore:
def search_tasks(
self, *, query: str, project_ids: set[int] | None, limit: int = 30,
) -> list[dict[str, Any]]:
"""제목/설명/댓글에 검색어가 들어간 업무(하위 업무 포함).
"""제목/설명/댓글에 검색어가 들어간 업무(세부 업무 포함).
project_ids 가 None 이면 전체(관리자), 아니면 그 프로젝트들만.
설명은 HTML 이라 태그 이름·속성에만 걸린 경우(예: "img")를 걸러내려고
@@ -1716,7 +1950,7 @@ class ProjectStore:
# 마감 알림 (task_reminders, 마이그레이션 008) — reminders.py 가 부른다
# ════════════════════════════════════════════════════════════
def list_open_tasks_due_between(self, *, start: date, end: date) -> list[dict[str, Any]]:
"""미완료 + 마감일이 [start, end] 인 업무(하위 업무 포함) + 팔로워 목록.
"""미완료 + 마감일이 [start, end] 인 업무(세부 업무 포함) + 팔로워 목록.
보관(archived) 프로젝트는 뺀다."""
with self._pool.connection() as conn:
rows = conn.execute(
@@ -1764,7 +1998,7 @@ class ProjectStore:
def task_link_scope(self, *, task_ids: list[int]) -> dict[int, set[int]]:
"""작업 id → 이 작업 또는 그 상위 작업들이 연결(멀티호밍)된 프로젝트 id 집합.
연결된 프로젝트 멤버가 그 작업(과 하위 작업)을 읽기 전용으로 볼 수 있는지 판단한다."""
연결된 프로젝트 멤버가 그 작업(과 세부 작업)을 읽기 전용으로 볼 수 있는지 판단한다."""
ids = sorted({int(i) for i in task_ids})
if not ids:
return {}
@@ -2557,6 +2791,60 @@ class ProjectStore:
self._meeting_v20_ok = True
return ok
def _meeting_v22(self, conn: Any) -> bool:
"""마이그레이션 022 — 회의 완료(goal_meetings.completed_at, 수정 잠금)."""
if getattr(self, "_meeting_v22_ok", False):
return True
ok = self._column_exists(conn, "goal_meetings", "completed_at")
if ok:
self._meeting_v22_ok = True
return ok
def _check_meeting_open(self, conn: Any, week_start: Any) -> None:
"""그 주차 회의록이 완료(잠금)됐으면 MeetingLocked. 022 전이면 잠금 없음."""
if not self._meeting_v22(conn):
return
row = conn.execute("SELECT completed_at FROM goal_meetings WHERE week_start = %s", (week_start,)).fetchone()
if row and row["completed_at"] is not None:
raise store.MeetingLocked()
def _check_result_open(self, conn: Any, own_week: Any) -> None:
"""결과 칸(result_*·status)만 고칠 때 — 그 주 결과는 다음 주 회의에서 리뷰하며 적는다(6-14 표).
· 다음 주차 회의록이 있으면 그 회의록이 열려 있을 때만(완료되면 잠금 — 그 주 회의록 완료 여부와 무관)
· 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있을 때만(예전엔 그 주가 완료돼도 다음 회의록이
없으면 고칠 수 있었다)
다음 주차 = 바로 다음 주차 시작일(store.week_period 끝 + 1일 — 달이 바뀌어도, 월요일이 아닌 시작일도
get_meeting 이 "지난주"를 찾는 규칙과 같다). 다음 회의록 행도 잠근다(FOR SHARE) — 이미 그 주 회의록을
잠근 뒤라 잠금 순서는 늘 주차 오름차순(교착 없음), 확인 뒤 다음 회의록이 완료돼도 끼어들지 못한다.
022 전이면 잠금 없음."""
if not self._meeting_v22(conn):
return
nxt = store.week_period(own_week)[1] + timedelta(days=1)
row = conn.execute("SELECT completed_at FROM goal_meetings WHERE week_start = %s FOR SHARE",
(nxt,)).fetchone()
if row is None:
self._check_meeting_open(conn, own_week)
elif row["completed_at"] is not None:
raise store.MeetingLocked()
def set_meeting_completed(self, *, week_start: date, done: bool, by: str = "") -> dict[str, Any]:
"""회의 완료(잠금)·완료 해제 — 관리자만(라우터). 바뀐 상태를 돌려준다."""
with self._pool.connection() as conn:
self._require_meetings(conn)
if not self._meeting_v22(conn):
raise store.MeetingMigration022Needed()
row = conn.execute(
"UPDATE goal_meetings SET completed_at = CASE WHEN %s THEN COALESCE(completed_at, now()) ELSE NULL END, "
"completed_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() "
"WHERE week_start = %s RETURNING completed_at, completed_by",
(done, done, store.norm_str(by, lower=True), week_start),
).fetchone()
if row is None:
raise KeyError(str(week_start))
return {"completed": row["completed_at"] is not None,
"completed_at": row["completed_at"].astimezone(KST).isoformat(timespec="minutes") if row["completed_at"] else "",
"completed_by": row["completed_by"] or ""}
def meetings_v20(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "goal_meetings") and self._meeting_v20(conn)
@@ -2569,14 +2857,16 @@ class ProjectStore:
self._meeting_cells_ok = True
return ok
def _locked_meeting_items(self, conn: Any, item_id: int) -> list[dict[str, Any]]:
"""글 저장·이동·병합·줄 변경이 같은 주 잠금을 공유한다."""
def _locked_meeting_items(self, conn: Any, item_id: int, *, check_open: bool = True) -> list[dict[str, Any]]:
"""글 저장·이동·병합·줄 변경이 같은 주 잠금을 공유한다. check_open — 회의 완료(022)된 주면 MeetingLocked."""
me = conn.execute("SELECT week_start FROM goal_meeting_items WHERE id = %s", (item_id,)).fetchone()
if me is None:
raise KeyError(item_id)
if not conn.execute("SELECT week_start FROM goal_meetings WHERE week_start = %s FOR UPDATE",
(me["week_start"],)).fetchone():
raise KeyError(item_id)
if check_open:
self._check_meeting_open(conn, me["week_start"])
rows = conn.execute(f"SELECT {self._meeting_cols(conn)} FROM goal_meeting_items "
"WHERE week_start = %s ORDER BY sort_order, id FOR UPDATE", (me["week_start"],)).fetchall()
if not any(int(r["id"]) == item_id for r in rows):
@@ -2639,6 +2929,9 @@ class ProjectStore:
keyed = self._meeting_keys(conn)
cell_merges = self._meeting_cells(conn)
result_notes = self._meeting_v20(conn)
v22 = self._meeting_v22(conn)
done_row = conn.execute("SELECT completed_at, completed_by FROM goal_meetings WHERE week_start = %s",
(week_start,)).fetchone() if v22 else None
head = conn.execute(
"SELECT week_start, week_target, attendees, notes, updated_by, updated_at "
"FROM goal_meetings WHERE week_start = %s", (week_start,),
@@ -2679,6 +2972,11 @@ class ProjectStore:
"line_keys": keyed,
"cell_merges": cell_merges,
"result_notes": result_notes,
"can_complete": v22,
"completed": bool(done_row and done_row["completed_at"] is not None),
"completed_at": done_row["completed_at"].astimezone(KST).strftime("%Y-%m-%d %H:%M")
if done_row and done_row["completed_at"] else "",
"completed_by": (done_row["completed_by"] or "") if done_row else "",
}
def create_meeting(self, *, week_start: date, sections: list[tuple[str, str]], created_by: str = "") -> bool:
@@ -2787,12 +3085,19 @@ class ProjectStore:
if not sets:
return
with self._pool.connection() as conn:
self._require_meetings(conn)
row = conn.execute(
f"UPDATE goal_meetings SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
"WHERE week_start = %s RETURNING week_start",
(*params, store.norm_str(updated_by, lower=True), week_start),
).fetchone()
with conn.transaction():
self._require_meetings(conn)
# 완료 확인과 머리 변경을 한 트랜잭션에서 그 회의록 행을 잠그고 — [회의 완료](set_meeting_completed
# 의 UPDATE 도 같은 행을 잠근다)와 동시에 와도 완료된 회의록이 바뀌지 않는다.
if not conn.execute("SELECT week_start FROM goal_meetings WHERE week_start = %s FOR UPDATE",
(week_start,)).fetchone():
raise KeyError(str(week_start))
self._check_meeting_open(conn, week_start)
row = conn.execute(
f"UPDATE goal_meetings SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
"WHERE week_start = %s RETURNING week_start",
(*params, store.norm_str(updated_by, lower=True), week_start),
).fetchone()
if row is None:
raise KeyError(str(week_start))
@@ -2814,6 +3119,7 @@ class ProjectStore:
"SELECT 1 FROM goal_meetings WHERE week_start = %s FOR UPDATE", (week_start,)
).fetchone():
raise KeyError(str(week_start))
self._check_meeting_open(conn, week_start)
rows = conn.execute(
f"SELECT {self._meeting_cols(conn)} FROM goal_meeting_items WHERE week_start = %s "
"ORDER BY sort_order, id", (week_start,),
@@ -2886,13 +3192,17 @@ class ProjectStore:
self._require_meetings(conn)
if "result_note" in fields and not self._meeting_v20(conn):
raise store.MeetingMigration020Needed()
result_only = bool(fields) and set(fields) <= {"result_note", "result_amount", "status"}
if self._meeting_v21(conn):
for col, text, _err in texts:
sets.append(f"{col} = %s")
params.append(text)
elif any(text for _c, text, _e in texts):
raise ValueError(next(e for _c, t, e in texts if t)) # 021 전 — 예전처럼 숫자만
rows = self._locked_meeting_items(conn, item_id)
rows = self._locked_meeting_items(conn, item_id, check_open=not result_only)
if result_only:
own = next(r for r in rows if int(r["id"]) == item_id)["week_start"]
self._check_result_open(conn, own)
if "content" in fields:
self._require_meeting_cell_visible(rows, item_id)
if sets:
@@ -3022,7 +3332,7 @@ class ProjectStore:
return {"sales_unit": head["sales_unit"] if head else "", "sales_target": vals.get(("sales", "target")),
"sales_actual": vals.get(("sales", "actual")), "roas_target": vals.get(("roas", "target"))}
# ── 주차별 매출 목표(020) — 목표 표 매출 단위 그대로, 월 목표 = 그 달 주차 합계 ──
# ── 주차별 매출 목표(020) — 목표 표 매출 단위 그대로, 월 목표는 따로 직접 입력(주차 합계와 다를 수 있음) ──
def week_targets_enabled(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "goal_week_targets")
@@ -3039,10 +3349,13 @@ class ProjectStore:
return {r["week_start"].isoformat(): float(r["value"]) for r in rows}
def set_goal_week_targets(
self, *, year: int, month: int, values: dict[date, float | None], updated_by: str = ""
self, *, year: int, month: int, values: dict[date, float | None], month_value: float | None,
updated_by: str = ""
) -> float | None:
"""그 달 주차별 목표 저장(None = 지움) → 그 달 주차 합계를 매출 목표(goal_metrics sales/target)로.
주차가 모두 비면 월 목표도 지운다(월 목표 = 주차 합계). 합계를 돌려준다(없으면 None)."""
"""그 달 주차별 목표 저장(None = 지움) + 월 매출 목표(goal_metrics sales/target)는 month_value 그대로
(None = 지움). 월 목표는 주차 합계와 따로 — 차이는 화면이 계산한다. 그 달 주차 합계를 돌려준다(없으면 None)."""
if month_value is not None and month_value < 0:
raise ValueError("월 목표는 0 이상이어야 합니다.")
m = store.validate_goal_month(month)
periods = {a for a, _ in store.month_weeks(year, m)}
if any(d not in periods for d in values):
@@ -3071,7 +3384,7 @@ class ProjectStore:
(year, m),
).fetchone()
total = float(row["total"]) if row["n"] else None
if total is None:
if month_value is None:
conn.execute("DELETE FROM goal_metrics WHERE year=%s AND metric='sales' AND kind='target' AND month=%s",
(year, m))
else:
@@ -3079,7 +3392,7 @@ class ProjectStore:
"INSERT INTO goal_metrics (year, metric, kind, month, value, updated_by) "
"VALUES (%s,'sales','target',%s,%s,%s) ON CONFLICT (year, metric, kind, month) DO UPDATE "
"SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()",
(year, m, total, who),
(year, m, month_value, who),
)
return total
File diff suppressed because it is too large Load Diff
+50 -3
View File
@@ -40,7 +40,7 @@ ACTION_ASSIGNED = "assigned"
ACTION_COMPLETED = "completed"
ACTION_STAGE_CHANGED = "stage_changed"
ACTION_REOPENED = "reopened"
ACTION_SUBTASK_MOVED = "subtask_moved" # 하위 업무를 다른 상위 업무로 옮김(보드 드래그)
ACTION_SUBTASK_MOVED = "subtask_moved" # 세부 업무를 다른 상위 업무로 옮김(보드 드래그)
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
@@ -131,6 +131,22 @@ PROJECT_ICONS: tuple[str, ...] = (
"build", # 도구
)
# 아사나 아이콘(2026-10-08) — 아사나 프로젝트 아이콘과 같은 채워진 모양. 저장 값은 "asana:" + 이름,
# 글꼴은 이 33개만 담은 채워진 Material Symbols(static/vendor/material-symbols/material-symbols-asana.woff2).
# 이름을 늘리면 그 글꼴도 다시 받아야 한다(docs/PROJECT_MODULE.md 6-12).
ASANA_ICON_PREFIX = "asana:"
PROJECT_ASANA_ICONS: tuple[str, ...] = (
"format_list_bulleted", "view_kanban", "view_timeline", "calendar_month",
"rocket_launch", "group", "monitoring", "stars",
"bug_report", "lightbulb", "language", "settings",
"book_2", "desktop_windows", "check_circle", "adjust",
"code_blocks", "campaign", "forum", "work",
"article", "landscape", "extension", "id_card",
"conversion_path", "speed", "workspace_premium", "steps",
"shopping_basket", "map", "confirmation_number", "toll",
"web",
)
# 섹션(칸반 컬럼) 색상표 — 모든 편집창이 프로젝트 색상표(32색) 하나를 쓴다.
# 섹션에서는 첫 칸(연회색 #c7c4c4, 아사나의 "색 없음")을 고르면 색 없음(NULL, 기본 회색 머리).
STAGE_COLOR_PALETTE: tuple[str, ...] = COLOR_PALETTE
@@ -288,8 +304,10 @@ def validate_color(color: Any) -> str:
def validate_project_icon(icon: Any) -> str | None:
"""프로젝트 아이콘 — PROJECT_ICONS 안의 이름만, 빈값/목록 밖은 None(첫 글자 표시)."""
"""프로젝트 아이콘 — PROJECT_ICONS 안의 이름 또는 "asana:" + PROJECT_ASANA_ICONS 이름만, 빈값/목록 밖은 None(첫 글자 표시)."""
v = norm_str(icon)
if v.startswith(ASANA_ICON_PREFIX):
return v if v[len(ASANA_ICON_PREFIX):] in PROJECT_ASANA_ICONS else None
return v if v in PROJECT_ICONS else None
@@ -405,6 +423,14 @@ class MeetingCellMigrationNeeded(RuntimeError):
"""회의록 셀 병합 메타데이터(019)가 아직 없다."""
class MeetingLocked(RuntimeError):
"""회의 완료(022)된 회의록은 고칠 수 없다(관리자가 완료 해제하면 다시)."""
class MeetingMigration022Needed(RuntimeError):
"""회의 완료(잠금)는 마이그레이션 022 뒤에만 된다."""
class MeetingMigration020Needed(RuntimeError):
"""새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다."""
@@ -859,6 +885,23 @@ _DESC_ALLOWED_CLASS: dict[str, str] = {"span": _MENTION_CLASS, "ul": "pj-checkli
# 허용 태그 목록에 없어 태그는 이미 안 남지만, HTMLParser는 이 둘의 내용을
# 별도 데이터로 넘기므로 handle_data 에서 따로 걸러야 한다.
_DESC_RAW_TEXT_TAGS: frozenset[str] = frozenset({"script", "style"})
# 글자 색·크기(서식 도구, 2026-10-08) — 평범한 span 의 style 에서 이 둘만, 정해진 형식만 남긴다.
_DESC_STYLE_COLOR = re.compile(r"^(#[0-9a-f]{3}|#[0-9a-f]{6}|rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\))$", re.I)
DESC_FONT_SIZES: frozenset[str] = frozenset({"12px", "18px", "22px", "28px"})
def desc_inline_style(value: str) -> str:
"""span style → "color: …; font-size: …" 중 허용된 것만(나머지 선언·url()·expression 등은 버림)."""
kept: list[str] = []
for decl in (value or "").split(";"):
if ":" not in decl:
continue
prop, val = (x.strip().lower() for x in decl.split(":", 1))
if prop == "color" and _DESC_STYLE_COLOR.match(val) and not any(k.startswith("color:") for k in kept):
kept.append(f"color: {val}")
elif prop == "font-size" and val in DESC_FONT_SIZES and not any(k.startswith("font-size:") for k in kept):
kept.append(f"font-size: {val}")
return "; ".join(kept)
def _desc_escape_text(text: str) -> str:
@@ -915,7 +958,7 @@ class _DescriptionSanitizer(HTMLParser):
# span 은 멘션 칩일 때만 속성을 갖는다 — class 가 pj-mention 이 아니면
# data-email 까지 통째로 버린다(평범한 span 으로만 남는다).
if tag == "span" and (dict(attrs).get("class") or "").strip() != _MENTION_CLASS:
allowed = frozenset()
allowed = frozenset({"style"}) # 평범한 span — 글자 색·크기만(desc_inline_style)
kept: list[str] = []
for name, value in attrs:
if name not in allowed:
@@ -931,6 +974,10 @@ class _DescriptionSanitizer(HTMLParser):
continue
if name == "data-checked" and value.strip() != "true":
continue
if name == "style":
value = desc_inline_style(value)
if not value:
continue
kept.append(f'{name}="{_desc_escape_attr(value)}"')
attr_text = (" " + " ".join(kept)) if kept else ""
self.out.append(f"<{tag}{attr_text}>")
@@ -1,6 +1,6 @@
{# ── 프로젝트 모듈 좌측 사이드바 (공용) ──────────────────────────────
수신함·내 업무·휴지통·프로젝트 화면이 함께 쓴다 — 어느 화면이든 프로젝트
목록은 똑같다(관리자: 드래그 순서 변경·✎ 수정·× 삭제·우클릭 메뉴).
목록은 똑같다(Pro user 이상: 드래그 순서 변경·✎ 수정·× 삭제·우클릭 메뉴).
변수:
mention_unread 미확인 @태그 개수 (수신함 배지)
@@ -10,7 +10,8 @@
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
goal_year_active 목표 화면에서 보고 있는 연도
is_admin 프로젝트 생성/수정/삭제 권한
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·전체 보기·휴지통·전체 멤버·연도 추가
pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만)
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
{# 날짜 팝업(openDatePopover)이 공휴일을 빨강으로 칠할 때 쓰는 표 — 이 사이드바는
@@ -19,10 +20,10 @@
{# 모든 프로젝트 화면에서 같은 회의록 트리를 사용한다. #}
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
<script src="/static/project-goal-nav.js?v=20261004d" defer></script>
<aside class="pj-side" data-is-admin="{{ 'true' if is_admin else 'false' }}"
<aside class="pj-side" data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
data-me="{{ user.email }}">
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(하위 업무 포함).
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(세부 업무 포함).
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
<div class="pj-side-search">
<span class="material-symbols-outlined pj-side-search-ic">search</span>
@@ -38,14 +39,25 @@
<span class="pj-side-navbadge" id="pj-mention-badge"
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
</a>
{# 전체 보기(2026-10-08, Pro user 이상 — 멤버인 프로젝트 범위) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #}
{% if pj_pro %}
{% set _all_pid = current_pid or ((nav_projects | rejectattr("status", "equalto", "completed") | list | first or {}).id or 0) %}
{% if _all_pid %}
<a class="pj-side-navlink" id="pj-side-allview" href="/project/p/{{ _all_pid }}?scope=all">
<span class="material-symbols-outlined pj-side-navic">apps</span>
<span class="pj-side-navtext">전체 보기</span>
</a>
{% endif %}
{% endif %}
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
<span class="material-symbols-outlined pj-side-navic">checklist</span>
<span class="pj-side-navtext">내 작업</span>
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
</a>
{# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #}
{% if is_admin %}
{# 휴지통 — Pro user 이상만 보이고(화면·복구 API 도 같음), 지운 업무를 3개월 보관. #}
{% if pj_pro %}
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
<span class="material-symbols-outlined pj-side-navic">delete</span>
<span class="pj-side-navtext">휴지통</span>
@@ -53,7 +65,7 @@
{% endif %}
{# 목표 — 누르면 바로 아래에 연도가 펼쳐지고, 연도를 누르면 오른쪽에 그해 전체 목표
(/project/goals/{연도}). 펼침 상태는 localStorage(pj_goal_open), 목표 화면에서는 항상 펼침.
연도 추가는 관리자만(마이그레이션 013). #}
연도 추가는 Pro user 이상(마이그레이션 013). #}
{% set goal_open = side_active == 'goals' %}
<div class="pj-side-goal{% if goal_open %} is-open{% endif %}" id="pj-side-goal"
data-force-open="{{ 'true' if goal_open else 'false' }}">
@@ -78,7 +90,7 @@
<div class="pj-side-meeting-months" id="pj-side-meeting-months-{{ y }}" data-current-week="{{ week if goal_month is defined else '' }}"></div>
</div>
{% endfor %}
{% if is_admin %}
{% if pj_pro %}
<button type="button" class="pj-side-goal-add" id="pj-goal-year-add"
data-next="{{ ((goal_years or [0]) | max) + 1 }}">+ 연도 추가</button>
{% endif %}
@@ -89,23 +101,23 @@
<div class="pj-side-block pj-tree-block">
<div class="pj-side-head">
<span>프로젝트</span>
{% if is_admin %}
{% if pj_pro %}
<button type="button" class="pj-icon-btn" id="pj-new-project-side" title="새 프로젝트">+</button>
{% endif %}
</div>
{% macro nav_li(p) %}
<li class="pj-tree-li" data-id="{{ p.id }}"{% if is_admin %} draggable="true"{% endif %}
<li class="pj-tree-li" data-id="{{ p.id }}"{% if pj_pro %} draggable="true"{% endif %}
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
data-start="{{ p.start_date or '' }}" data-due="{{ p.due_date or '' }}"
data-color="{{ p.color }}" data-status="{{ p.status or 'active' }}"
data-creator="{{ p.created_by or '' }}" data-icon="{{ p.icon or '' }}">
<div class="pj-tree-row {% if p.id == current_pid %}is-active{% endif %}">
{% if is_admin %}<span class="pj-tree-handle" title="드래그로 순서 변경">⣿</span>{% endif %}
<a class="pj-tree-link" href="/project/p/{{ p.id }}"{% if is_admin %} draggable="false"{% endif %}>
<span class="pj-tree-avatar{% if p.icon %} has-icon{% endif %}" style="background: {{ p.color }}">{% if p.icon %}<span class="material-symbols-outlined pj-proj-ic">{{ p.icon }}</span>{% else %}{{ p.name[0] | upper }}{% endif %}</span>
{% if pj_pro %}<span class="pj-tree-handle" title="드래그로 순서 변경">⣿</span>{% endif %}
<a class="pj-tree-link" href="/project/p/{{ p.id }}"{% if pj_pro %} draggable="false"{% endif %}>
<span class="pj-tree-avatar{% if p.icon %} has-icon{% endif %}" style="background: {{ p.color }}">{% if p.icon %}{% set _a = p.icon.startswith("asana:") %}<span class="material-symbols-outlined pj-proj-ic{% if _a %} pj-ic-asana{% endif %}">{{ p.icon[6:] if _a else p.icon }}</span>{% else %}{{ p.name[0] | upper }}{% endif %}</span>
<span class="pj-tree-name">{{ p.name }}</span>
</a>
{% if is_admin %}
{% if pj_pro %}
<span class="pj-tree-acts">
<button type="button" class="pj-icon-btn pj-tree-edit" data-id="{{ p.id }}"
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
@@ -134,11 +146,11 @@
{% endif %}
</div>
<!-- 전체 멤버 — 등록된 전체 직원(프로젝트 권한 보유자). 관리자 전용
(/api/all-users 도 관리자만). 아이콘 클릭 시 그 사람이 담당자인 업무를
<!-- 전체 멤버 — 등록된 전체 직원(프로젝트 권한 보유자). Pro user 이상
(/api/all-users 는 @태그 후보로 누구나 부른다). 아이콘 클릭 시 그 사람이 담당자인 업무를
팝업으로 보여준다(프로젝트/세션/마감일). 수신함·내 업무·프로젝트 화면
모두에서 보인다 — 팝업 마크업은 _member_tasks_modal.html. -->
{% if is_admin %}
{% if pj_pro %}
<div class="pj-side-block">
<div class="pj-side-head"><span>전체 멤버</span></div>
<div class="pj-allmembers-grid" id="pj-allmembers-grid">불러오는 중…</div>
@@ -1,13 +1,14 @@
{# ── 좌측 프로젝트 목록(project/_side.html)용 모달 (공용) ──────────────
"+" 새 프로젝트 / ✎ 프로젝트 수정 — 수신함·내 업무·휴지통·프로젝트 화면이
모두 include 한다(동작은 project.js 의 initSideTree). 관리자만 쓰므로
관리자에게만 그린다. 색상 원은 window.PJ_COLORS(color_palette, 32색),
모두 include 한다(동작은 project.js 의 initSideTree). Pro user 이상만 쓰므로
그들에게만 그린다. 색상 원은 window.PJ_COLORS(color_palette, 32색),
아이콘은 window.PJ_ICONS(project_icons — Material Symbols 이름). #}
<script>
window.PJ_COLORS = {{ color_palette | tojson }};
window.PJ_ICONS = {{ (project_icons or []) | tojson }};
window.PJ_ASANA_ICONS = {{ (project_asana_icons or []) | tojson }}; {# 아사나 아이콘 탭 — 값은 "asana:" + 이름 #}
</script>
{% if is_admin %}
{% if pj_pro %}
<!-- 새 프로젝트 모달 — 좌측 프로젝트 목록의 + 버튼 -->
<div class="pj-modal" id="pj-modal-project" hidden>
<div class="pj-modal-card">
@@ -21,12 +22,13 @@
<div class="pj-field-label">색상
<span class="pj-color-palette" id="pj-f-colors"></span>
</div>
<div class="pj-field-label">아이콘
<div class="pj-field-label">아이콘<span class="pj-icon-tabs"></span>
<div class="pj-icon-palette" id="pj-f-icons"></div>
</div>
<div class="pj-field-label">멤버
<div class="pj-member-picker" id="pj-f-members">불러오는 중…</div>
</div>
<p class="pj-modal-msg" id="pj-f-project-msg" role="status" hidden></p>
<div class="pj-modal-actions">
<button type="button" class="pj-btn" data-close>취소</button>
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-project">만들기</button>
@@ -49,7 +51,7 @@
<div class="pj-field-label">색상
<span class="pj-color-palette" id="pj-e-colors"></span>
</div>
<div class="pj-field-label">아이콘
<div class="pj-field-label">아이콘<span class="pj-icon-tabs"></span>
<div class="pj-icon-palette" id="pj-e-icons"></div>
</div>
<label class="pj-time-toggle">
@@ -1,7 +1,7 @@
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261007c" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -11,17 +11,22 @@
{%- macro num(v) -%}{% if v is not none %}{% if v == v | int %}{{ "{:,}".format(v | int) }}{% else %}{{ "{:,.2f}".format(v) }}{% endif %}{% endif %}{%- endmacro -%}
{% block content %}
{% set h = head if head is defined and head else {} %}
{% set unk = h.unknown or [] %}
{#- 머리 숫자 — 목표 표 매출 단위(예: 백만원)로, 원이거나 모르는 단위면 원. 정확한 원 금액은 말풍선 -#}
{%- macro unitv(v) -%}{% if h.unit_mult and h.unit_mult > 1 %}{{ "{:,.1f}".format(v / h.unit_mult).rstrip('0').rstrip('.') }}<small>{{ h.sales_unit }}</small>{% else %}{{ won(v) }}<small>원</small>{% endif %}{%- endmacro -%}
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
{# 주간 회의록 — 목표 표 월 머리를 누르면 열린다(/project/goals/{연도}/meetings/{월}?week=주차 시작일).
주차(store.month_weeks — 그 달 안, 1주차는 1일부터)마다 회의록 하나: 위쪽 고정 영역(왼쪽 숫자 4칸 | 오른쪽 결정 사항·메모)
주차(store.month_weeks — 그 달 안, 1주차는 1일부터)마다 회의록 하나: 머리 영역 3칸(월 계획 + 숫자 한 줄 | 결정 사항·메모 | 작업 등록)
+ 구역(목표 표 업무 영역)별 줄 — 주요 업무·정량 목표 | 지난주: 전주 업무·결과(글)·전주 목표·결과(금액).
지난주 칸은 바로 앞 주차 회의록의 같은 줄(연결키). 월 누적 실적은 실적 모듈, 월 누적 목표는 목표 표 주차별 목표 합.
입력은 관리자만(칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015·020. #}
입력은 누구나(완료 전까지, 칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015·020. #}
<div class="pj-wrap pj-inbox-view pj-goal-view pj-meet-view" data-me="{{ (user.email if user else '') | lower }}">
<div class="pj-layout">
{% if not meeting_embedded %}{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}{% endif %}
<section class="pj-main">
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력 #}
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 영역 3칸(월 계획·숫자 | 결정 사항 | 작업 등록) / 오른쪽 위: 작은 달력 #}
<div class="pj-meet-headgrid">
<div class="pj-meet-headleft">
<div class="pj-meet-title">
@@ -33,10 +38,16 @@
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ py }}/meetings/{{ pm }}">‹ {{ pm }}월</a>
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ ny }}/meetings/{{ nm }}">{{ nm }}월 ›</a>
{% if meeting %}
{# 회의록은 프로젝트 권한이 있는 누구나 고친다. [회의 완료](Pro user 이상) = 수정 잠금, 완료 뒤 [완료 해제](Pro user 이상) — 마이그레이션 022 #}
<span class="pj-meet-title-acts">
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
{% if is_admin %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>
{% else %}<span class="pj-goal-note">회의록은 관리자만 입력할 수 있습니다.</span>{% endif %}
{% if pj_pro %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>{% endif %}
{% if meeting.can_complete %}
{% if meeting.completed %}
<span class="pj-meet-done-badge" title="{{ meeting.completed_at }}{% if meeting.completed_by %} · {{ meeting.completed_by }}{% endif %} — 완료된 회의록은 고칠 수 없습니다"><span class="material-symbols-outlined">lock</span>회의 완료</span>
{% if pj_pro %}<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-reopen" title="다시 고칠 수 있게 엽니다">완료 해제</button>{% endif %}
{% elif pj_pro %}<button type="button" class="pj-btn pj-btn-sm pj-meet-complete-btn" id="pj-meet-complete" title="이 회의록을 더 고칠 수 없게 잠급니다(Pro user 이상)"><span class="material-symbols-outlined">task_alt</span>회의 완료</button>{% endif %}
{% endif %}
</span>
{% endif %}
{# 주차 탭 — 주차는 그 달 안(1일이 월~금이면 1일~일요일, 토·일이면 1일~다음 주 일요일, 말일이 월·화면 앞 주차에 붙음). 점 = 회의록 있음 #}
@@ -53,24 +64,69 @@
{% endfor %}
</nav>
</div>
{# 이 달 계획 — 연간 목표 표의 그 달 열 글(업무 영역별, router._month_plan) #}
{% if month_plan is not none %}
<section class="pj-meet-plan">
<div class="pj-meet-plan-head"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</div>
{% if month_plan %}
<div class="pj-meet-plan-grid">
{% for a in month_plan %}
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
<b class="pj-meet-plan-name">{{ a.name }}</b>
{% for it in a.lines %}
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text_html | safe }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
{# ── 머리 영역 3칸(스크롤해도 보임 — 표만 아래 .pj-meet-pane 에서 스크롤) ──
① 월 계획 + 머리 줄 오른쪽에 숫자 4개를 작게 한 줄로 ② 결정 사항·메모 ③ 작업 빠른 등록 표(project.js initMeetQuickTasks) #}
<div class="pj-meet-board">
<section class="pj-meet-area pj-meet-plan">
<div class="pj-meet-plan-head">
<span class="pj-meet-plan-title"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</span>
{% if h %}
<div class="pj-meet-kpiline">
<span class="pj-meet-kpi" title="월 목표 매출(연간 목표 표){% if h.month_target_won is not none %} = {{ won(h.month_target_won) }}원{% endif %}">
<span class="pj-meet-kpi-label">월 목표</span>
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</span>
<span class="pj-meet-kpi" title="월 누적 목표 매출{% if h.cum_target_won is not none %} {{ won(h.cum_target_won) }}원{% endif %} — 연간 목표 표에서 입력한 주차별 매출 목표의 1주차~{{ week_n }}주차 합계{% if not h.week_targets_set %} — 목표 표에서 주차별 목표를 입력하세요{% endif %}">
<span class="pj-meet-kpi-label">누적 목표 <small>({{ week_n }}주차)</small></span>
<span class="pj-meet-kpi-val">{% if h.cum_target_won is not none %}{{ unitv(h.cum_target_won) }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</span>
<span class="pj-meet-kpi" title="월 누적 실적{% if h.mtd is not none %} {{ won(h.mtd) }}원{% endif %}(1일~{{ h.mtd_end[5:] | replace('-', '/') if h.mtd_end else '' }}){% if h.fresh_tip %} · {{ h.fresh_tip }}{% endif %}">
<span class="pj-meet-kpi-label">누적 실적 {% if h.mtd_end %}<small>({{ h.mtd_end[5:] | replace('-', '/') }})</small>{% endif %}</span>
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ unitv(h.mtd) }}{% elif 'mtd' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</span>
<span class="pj-meet-kpi" title="누적 목표 대비 달성{% if h.gap is not none %} {{ '+' if h.gap > 0 else '' }}{{ won(h.gap) }}원{% endif %} — 월 누적 실적 − 월 누적 목표 매출 (월 누적 실적 ÷ 월 누적 목표 매출)">
<span class="pj-meet-kpi-label">목표 대비</span>
{% if h.gap is not none %}<span class="pj-meet-kpi-val {{ 'is-good' if h.gap >= 0 else 'is-low' }}">{{ '+' if h.gap > 0 else '' }}{{ unitv(h.gap) }}{% if h.rate is not none %} <small class="pj-meet-kpi-rate">{{ h.rate }}%</small>{% endif %}</span>
{% elif 'mtd' in unk and h.cum_target_won is not none %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</span>
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
</span>
</div>
{% endif %}
</div>
<div class="pj-meet-area-body">
{% if month_plan is none %}<p class="pj-meet-plan-empty">연간 목표 표가 없어 월 계획을 보여 줄 수 없습니다.</p>
{% elif month_plan %}
<div class="pj-meet-plan-grid">
{% for a in month_plan %}
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
<b class="pj-meet-plan-name">{{ a.name }}</b>
{% for it in a.lines %}
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text_html | safe }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
{% endfor %}
</div>
{% endfor %}
</div>
{% endfor %}
</div>
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
</section>
{% endif %}
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
</div>
</section>
<section class="pj-meet-area pj-meet-notes">
<h3>결정사항 : 진행상황 수시 공유 및 완료 되어야 함</h3>
{% if meeting %}
{% if not meeting.completed %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
{% else %}<p class="pj-meet-plan-empty">이 주차 회의록을 만들면 적을 수 있습니다.</p>{% endif %}
</section>
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick">
<h3>작업 등록 <small>제목을 쓰고 담당자·프로젝트·섹션 칸을 눌러 고른 뒤 [적용]</small></h3>
<div class="pj-meet-area-body">
<table class="pj-meet-quick-table">
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th></th></tr></thead>
<tbody></tbody>
</table>
<button type="button" class="pj-meet-quick-add" data-quick="add">+ 줄 추가</button>
</div>
</section>
</div>
</div>
{# 작은 달력 — 월요일 시작 줄, 줄을 누르면 그 줄의 이 달 날짜가 든 주차 회의록(보고 있는 주차의 줄은 영역 표시). 점 = 회의록 있음. #}
<div class="pj-meet-cal" aria-label="{{ goal_month }}월 달력">
@@ -86,59 +142,24 @@
</div>
</div>
{% if is_admin and meeting %}{% include "project/_cell_format.html" %}{% endif %}
{% if meeting and not meeting.completed %}{% include "project/_cell_format.html" %}{% endif %}
<div class="pj-view pj-meet-pane" id="pj-meet-pane" data-week="{{ week }}" data-year="{{ goal_year }}"
data-month="{{ goal_month }}" data-admin="{{ 'true' if is_admin else 'false' }}">
data-month="{{ goal_month }}" data-pro="{{ 'true' if pj_pro else 'false' }}"
data-edit="{{ 'true' if meeting and not meeting.completed else 'false' }}">
{% if not meetings_enabled %}
<div class="pj-empty">주간 회의록이 아직 준비되지 않았습니다(DB 마이그레이션 015 필요).</div>
{% elif not meeting %}
<div class="pj-empty pj-goal-empty">
<p>{{ week_n }}주차({{ week }} ~ {{ week_end }}) 회의록이 아직 없습니다.</p>
{% if is_admin %}
{% if true %}
<p class="pj-goal-empty-sub">만들면 앞선 회의록의 줄(구역·항목)을 이어받아, 지난주 업무·목표·결과를 나란히 리뷰할 수 있습니다.
처음이면 {{ goal_year }}년 목표 표의 업무 영역과 기본 양식 줄로 시작합니다.</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-meet-create">{{ week_n }}주차 회의록 만들기</button>
{% endif %}
</div>
{% else %}
{% set h = head %}
{% set edit = is_admin %}
{% set unk = h.unknown or [] %}
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
{# ── 위쪽 고정 영역(스크롤해도 보임) — 왼쪽 절반: 숫자 4칸 / 오른쪽 절반: 결정 사항·메모.
높이는 project.js initMeetTop 이 --pj-meet-top-h 로 알려 표 머리 줄이 그 아래에 붙는다 ── #}
<div class="pj-meet-top" id="pj-meet-top">
<div class="pj-meet-kpibar">
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">월 목표 매출</span>
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">목표 표에 없음</span>{% endif %}</span>
{% if h.month_target_won is not none and h.sales_unit and h.sales_unit != '원' %}<span class="pj-meet-kpi-sub">= {{ won(h.month_target_won) }}원</span>{% endif %}
</div>
<div class="pj-meet-kpi" title="연간 목표 표에서 입력한 주차별 매출 목표의 1주차~{{ week_n }}주차 합계">
<span class="pj-meet-kpi-label">월 누적 목표 매출 <small>({{ week_n }}주차까지)</small></span>
<span class="pj-meet-kpi-val">{% if h.cum_target_won is not none %}{{ won(h.cum_target_won) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
{% if not h.week_targets_set %}<a class="pj-meet-kpi-sub pj-meet-kpi-link" href="/project/goals/{{ goal_year }}">목표 표에서 주차별 목표 입력</a>{% endif %}
</div>
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
<span class="pj-meet-kpi-label">월 누적 실적 {% if h.mtd_end %}<small>({{ h.mtd_end[5:] | replace('-', '/') }}까지)</small>{% endif %}</span>
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ won(h.mtd) }}<small>원</small>{% elif 'mtd' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</div>
<div class="pj-meet-kpi is-accent" title="월 누적 실적 − 월 누적 목표 매출 (월 누적 실적 ÷ 월 누적 목표 매출)">
<span class="pj-meet-kpi-label">누적 목표 대비 달성</span>
{% if h.gap is not none %}
<span class="pj-meet-kpi-val {{ 'is-good' if h.gap >= 0 else 'is-low' }}">{{ '+' if h.gap > 0 else '' }}{{ won(h.gap) }}<small>원</small></span>
{% if h.rate is not none %}<span class="pj-meet-kpi-sub {{ 'is-good' if h.rate >= 100 else 'is-low' }}">{{ h.rate }}%</span>{% endif %}
{% elif 'mtd' in unk and h.cum_target_won is not none %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</span>
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
</div>
</div>
<div class="pj-meet-notes">
<h3>결정 사항 · 메모</h3>
{% if edit %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
</div>
</div>
{% set edit = not meeting.completed %} {# 누구나 고친다 — 회의 완료(022)면 잠금 #}
{# 매출 자료 갱신 — 주차를 열면 실적 모듈 매출 업데이트(지난 주차 시작 ~ 이 주차 오늘)를 한 번 더 돌리고 숫자 칸만 다시 그린다
(project.js initMeetingSync, 같은 주는 10분에 한 번). 정상이면 아무것도 보이지 않는다(2026-10-01 요청 — 큰 상태 줄 없음).
실패·일부 실패면 이 작은 안내 + [다시 시도], 실적 권한이 없으면 부르지 않고 한 줄 설명. 마지막 갱신 성공 시각은 서버 기록(data-fresh). #}
@@ -166,6 +187,9 @@
<button type="button" class="pj-btn pj-btn-sm pj-meet-board-btn" id="pj-meet-board"
title="이 주차의 Google 슬라이드 보드를 새 창으로 엽니다(처음이면 공유 드라이브에 빈 슬라이드를 만듭니다)">
<span class="material-symbols-outlined">co_present</span>회의록 보드</button>
{# 회의록 보드 링크 복사(2026-10-08) — 같은 주차 보드 주소(없으면 만든 뒤)를 클립보드로 #}
<button type="button" class="pj-icon-btn pj-meet-board-copy" id="pj-meet-board-copy"
title="회의록 보드 링크 복사" aria-label="회의록 보드 링크 복사"><span class="material-symbols-outlined">link</span></button>
</div>
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
@@ -186,7 +210,7 @@
<th colspan="4" class="is-prev">지난주 리뷰 ({{ prev_week[5:] | replace('-', '/') }} ~ {{ prev_week_end[5:] | replace('-', '/') }}){% if not h.prev_exists %} <span class="pj-meet-noprev">— 이 주 회의록 없음</span>{% endif %}</th>
</tr>
<tr>
<th class="pj-meet-c-sec">구역</th>
<th class="pj-meet-c-sec">구분</th>
<th class="pj-meet-c-label">항목</th>
<th class="pj-meet-c-text">주요 업무</th>
<th class="pj-meet-c-amt">정량 목표</th>
@@ -267,5 +291,5 @@
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project-meeting-cells.js?v=20261007a" defer></script>
<script src="/static/project.js?v=20261007d" defer></script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261007b" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -11,7 +11,7 @@
{# 연간 목표 — 좌측 사이드바 "목표" → 연도. 스프레드시트처럼 한 표에
① 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자
② 업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글.
입력·구조 변경은 관리자만(칸별 즉시 저장, project.js initGoals), 나머지는 보기만.
입력·구조 변경은 Pro user 이상(칸별 즉시 저장, project.js initGoals), 나머지는 보기만.
DB: project_db 013 (goal_years·goal_metrics·goal_areas·goal_rows·goal_cells). #}
<div class="pj-wrap pj-inbox-view pj-goal-view">
<div class="pj-layout">
@@ -22,7 +22,7 @@
<h2 class="pj-goal-title">{{ goal_year }}년 목표</h2>
{% if board %}
<div class="pj-goal-head-acts">
{% if is_admin %}
{% if pj_pro %}
<label class="pj-goal-unit">매출 단위
<input type="text" id="pj-goal-unit" maxlength="20" placeholder="예: 백만원"
value="{{ board.sales_unit }}" data-year="{{ goal_year }}" />
@@ -31,13 +31,13 @@
data-year="{{ goal_year }}">연도 삭제</button>
{% else %}
{% if board.sales_unit %}<span class="pj-goal-unit-ro">매출 단위: {{ board.sales_unit }}</span>{% endif %}
<span class="pj-goal-note">목표는 관리자만 입력할 수 있습니다.</span>
<span class="pj-goal-note">목표는 Pro user 이상만 입력할 수 있습니다.</span>
{% endif %}
</div>
{% endif %}
</div>
{% if is_admin and goals_enabled and board %}
{% if pj_pro and goals_enabled and board %}
{% include "project/_cell_format.html" %}
{% endif %}
<div class="pj-view pj-goal-pane" id="pj-goal-pane">
@@ -46,7 +46,7 @@
{% elif not board %}
<div class="pj-empty pj-goal-empty">
<p>{{ goal_year }}년 목표가 아직 없습니다.</p>
{% if is_admin %}
{% if pj_pro %}
<p class="pj-goal-empty-sub">만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-goal-create" data-year="{{ goal_year }}">{{ goal_year }}년 목표 만들기</button>
{% endif %}
@@ -56,14 +56,14 @@
{% set rm = board.metrics.roas %}
{# 월 칸은 pj-goal-m + data-h(분기 1~4) — 분기 접기(initGoals)가 이걸로 숨긴다.
분기 칸 클래스는 예전 이름 pj-goal-half-col 그대로(연간 칸처럼 굵게·회색 합계) #}
{# 매출 목표 칸(020) — 누르면 그 달 주차별 목표 입력 창(project.js initGoalWeekTargets), 합계 = 월 목표 #}
{# 매출 목표 칸(020) — 누르면 그 달 월 목표(직접 입력)·주차별 목표 입력 창, 맨 아래 차이(월 목표 − 주차 합계) #}
{% macro num_cell(metric, kind, labels, mo) -%}
{%- set weekly = week_targets and metric == 'sales' and kind == 'target' -%}
<td class="pj-goal-numtd pj-goal-m{% if mo == this_month %} is-now{% endif %}{% if weekly %} is-weekly{% endif %}" data-h="{{ (mo - 1) // 3 + 1 }}">
{%- if is_admin -%}
{%- if pj_pro -%}
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
{%- if weekly %} readonly data-weekly="1" title="{{ mo }}월 주차별 목표 입력(합계 = 월 목표)"{% endif %}
{%- if weekly %} readonly data-weekly="1" title="{{ mo }}월 목표·주차별 목표 입력"{% endif %}
value="{{ labels.get(mo, '') }}" />
{%- else -%}
<span class="pj-goal-num" data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
@@ -72,7 +72,7 @@
</td>
{%- endmacro %}
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
data-admin="{{ 'true' if is_admin else 'false' }}"
data-pro="{{ 'true' if pj_pro else 'false' }}"
data-halves="{{ 'true' if board.halves else 'false' }}">
<thead>
<tr>
@@ -144,7 +144,7 @@
</tr>
</tbody>
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(관리자) ── #}
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(Pro user 이상) ── #}
{% for area in board.areas %}
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" data-color="{{ area.color }}" style="--goal-bg: {{ area.color or '#fff' }}">
{% for row in area.rows %}
@@ -152,22 +152,22 @@
{% if loop.first %}
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
{# 구역 메뉴(색·위로·아래로·줄 추가·영역 삭제) — 우클릭 또는 ⋮ 버튼(키보드 Tab → Enter/Space, 터치 탭). project.js areaMenuItems #}
<span class="pj-goal-area-text"{% if is_admin %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
<span class="pj-goal-area-text"{% if pj_pro %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
{% if pj_pro %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
aria-label="{{ area.name }} 구역 메뉴" title="구역 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
</th>
{% endif %}
{# 항목 칸(2열) — 같은 항목 칸으로 묶인 줄(016 label_cont)은 묶음 첫 줄이 rowspan 으로 덮는다 #}
{% if not row.label_cont %}
<th class="pj-goal-c2 pj-goal-row-label"{% if (row.label_span or 1) > 1 %} rowspan="{{ row.label_span }}"{% endif %} data-label-span="{{ row.label_span or 1 }}">
<span class="pj-goal-row-text"{% if is_admin %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
<span class="pj-goal-row-text"{% if pj_pro %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
{% if pj_pro %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
aria-label="{{ (row.label or '이름 없는') }} 줄 메뉴" title="줄 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
</th>
{% endif %}
{# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #}
{% for c in row.layout %}
{% set editable = is_admin and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
{% set editable = pj_pro and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
{% set merged = c.span > 1 or c.rspan > 1 %}
<td class="pj-goal-texttd {{ 'pj-goal-m' if c.kind == 'month' else ('pj-goal-year-col' if c.kind == 'year' else 'pj-goal-half-col') }}{% if merged %} is-merged{% endif %}{% if c.now %} is-now{% endif %}"
{% if c.kind in ('month', 'quarter') %}data-h="{{ c.h }}" {% endif %}data-month="{{ c.m }}" data-span="{{ c.span }}" data-rspan="{{ c.rspan }}"
@@ -186,11 +186,11 @@
</tbody>
{% endfor %}
</table>
{% if is_admin %}
{% if pj_pro %}
<div class="pj-goal-foot">
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 글자를 드래그해 선택하면 선택한 셀 상단에서 12색 견본·크기 2px 증감·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다. 모든 행의 셀 오른쪽 경계를 끌어 열 너비를 조절하고, 더블클릭하면 그 열의 가장 긴 문단에 맞춥니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함). 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 끌면 내용과 서식이 함께 이동합니다(대상에 글이 있으면 덮어쓰기 확인, Esc로 취소).
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함).
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
</div>
@@ -207,5 +207,5 @@
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project.js?v=20261007d" defer></script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
+134 -93
View File
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -21,9 +21,9 @@
<li><a href="#project">프로젝트 만들기·고치기</a></li>
<li><a href="#views">보기 전환과 필터</a></li>
<li><a href="#board">보드 — 섹션과 작업 카드</a></li>
<li><a href="#card-subtasks">카드에서 하위 작업 다루기</a></li>
<li><a href="#card-subtasks">카드에서 세부 작업 다루기</a></li>
<li><a href="#task">작업 편집 창</a></li>
<li><a href="#subtasks">작업 창의 하위 작업</a></li>
<li><a href="#subtasks">작업 창의 세부 작업</a></li>
<li><a href="#dates">날짜 고르기</a></li>
<li><a href="#list">목록 보기</a></li>
<li><a href="#calendar">캘린더 보기</a></li>
@@ -33,7 +33,7 @@
<li><a href="#comments">댓글과 @태그</a></li>
<li><a href="#inbox">수신함과 알림</a></li>
<li><a href="#search">전체 검색과 공유 링크</a></li>
<li><a href="#trash">휴지통 (관리자)</a></li>
<li><a href="#trash">휴지통 (Pro user 이상)</a></li>
<li><a href="#goals">연간 목표</a></li>
<li><a href="#meetings">주간 회의록</a></li>
<li><a href="#tips">단축키와 자주 묻는 질문</a></li>
@@ -63,7 +63,7 @@
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
<div class="pjh-quick">
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 작업 추가</span>로 할 일을 만듭니다.</div>
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 작업 추가</span>로 할 일을 만듭니다.</div>
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
@@ -80,7 +80,7 @@
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</td></tr>
<tr><td>작업</td><td>실제 할 일 하나입니다. 보드의 카드 한 장이 작업 하나입니다.</td></tr>
<tr><td>하위 작업</td><td>작업을 더 잘게 나눈 할 일입니다. 작업 안에 목록으로 붙습니다. 원래 작업은 <b>상위 작업</b>이라고 부릅니다.</td></tr>
<tr><td>세부 작업</td><td>작업을 더 잘게 나눈 할 일입니다. 작업 안에 목록으로 붙습니다. 원래 작업은 <b>상위 작업</b>이라고 부릅니다.</td></tr>
<tr><td>담당자</td><td>그 작업을 책임지고 하는 사람 한 명입니다.</td></tr>
<tr><td>협업자</td><td>작업의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
@@ -96,20 +96,20 @@
<h2><span class="pjh-num">2</span>화면 구성</h2>
<div class="pjh-map" aria-hidden="true">
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>오른쪽 위: 범위(이 프로젝트 / 전체 프로젝트)<br>필터 바<br>작업들</div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>작업들</div>
</div>
<h3>왼쪽 사이드바</h3>
<ul>
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 작업을 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
</ul>
<h3>위쪽 바</h3>
<ul>
@@ -120,7 +120,7 @@
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
</ul>
<h3>프로젝트 제목</h3>
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버·관리자만)</p>
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
<div>여러 사람이 동시에 써도 걱정 없습니다. 다른 사람이 바꾼 내용은 <b>약 8초 안에</b> 내 화면에 자동으로 반영됩니다(새로고침하지 않아도 됩니다). 내가 입력 중인 창은 건드리지 않습니다.</div></div>
</section>
@@ -128,27 +128,52 @@
<!-- 3. 권한 -->
<section class="pjh-sec" id="roles">
<h2><span class="pjh-num">3</span>누가 무엇을 할 수 있나요</h2>
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.</p>
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.
등급은 <b>수퍼관리자 · Admin · Pro user · User</b> 네 가지이며(관리자 페이지에서 지정, 수퍼관리자는 한 명으로 고정), 등급과 상관없이
<b>그 프로젝트의 멤버·소유자만</b> 프로젝트를 볼 수 있습니다(수퍼관리자만 예외).</p>
<h3>프로젝트</h3>
<table class="pjh-table">
<tr><th>할 수 있는 일</th><th>누가</th></tr>
<tr><td>프로젝트 보기</td><td>그 프로젝트의 <b>멤버·소유자</b>(또는 관리자). 멤버가 아니면 주소를 알아도 열리지 않습니다.</td></tr>
<tr><td>작업·하위 작업·댓글</td><td>그 프로젝트의 멤버·소유자·관리자가 만들고 고칠 수 있습니다.</td></tr>
<tr><td>작업·섹션·프로젝트 삭제</td><td><b>만든 사람만</b> 지울 수 있습니다(최고 관리자는 예외).</td></tr>
<tr><td>댓글 고치기·지우기</td><td>댓글을 쓴 사람(또는 관리자)만.</td></tr>
<tr><td>새 프로젝트, 사이드바의 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
<tr><td>멤버 배정·제외, 프로젝트 소유자 바꾸기</td><td>관리자</td></tr>
<tr><td>다른 프로젝트에서 연결돼 온 작업</td><td>원래 프로젝트 멤버가 아니면 <b>읽기만</b> — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다).</td></tr>
<tr><td>멤버에서 빠졌을 때</td><td>그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다.</td></tr>
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
<tr><td>목표·주간 회의록 보기</td><td>프로젝트 관리 권한이 있는 직원 누구나 · <b>입력·생성·삭제·구조 편집</b>은 관리자</td></tr>
<tr><td>프로젝트 제목 바로 고치기</td><td>그 프로젝트 멤버·소유자·관리자</td></tr>
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
<tr><td>프로젝트 보기, 작업·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
<tr><td>작업 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</td></tr>
<tr><td>섹션 삭제</td><td>O</td><td>만든 사람만</td><td>만든 사람만</td></tr>
<tr><td>서브프로젝트 만들기</td><td>O</td><td>O</td><td>O</td></tr>
<tr><td>새 프로젝트 만들기 (<span class="pjh-ui">+</span>)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>프로젝트 이름·색·아이콘 수정 (<span class="pjh-ui">✎</span>·제목 바로 고치기)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>프로젝트 소유자 바꾸기</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>프로젝트 삭제</td><td>O</td><td>만든 사람만</td><td>만든 사람만</td></tr>
<tr><td>멤버 배정·제외</td><td>O</td><td>O (자기가 멤버인 프로젝트)</td><td>X</td></tr>
<tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr>
<tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>전체 보기(모든 프로젝트 작업 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr>
<tr><td>대시보드 “담당자별 작업 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
<tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>수신함·내 작업·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
</table>
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 작업은 원래 프로젝트 멤버가 아니면
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고,
예전 링크로도 열리지 않습니다.</p>
<h3>목표·주간 회의록</h3>
<table class="pjh-table">
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
<tr><td>연간 목표 표 보기</td><td>O</td><td>O</td><td>O</td></tr>
<tr><td>목표 표 입력·구조 변경(매출·로아스, 영역·줄, 칸 병합·이동)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>주차별 매출 목표·월 전체 목표 입력</td><td>O</td><td>O</td><td>X (값 보기만)</td></tr>
<tr><td>연도 추가·삭제</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>회의록 만들기·글 수정·줄 추가·삭제·칸 병합</td><td>O</td><td>O</td><td>O (완료 전까지)</td></tr>
<tr><td>지난주 결과 입력</td><td>O</td><td>O</td><td>O (다음 주 회의록이 열려 있는 동안)</td></tr>
<tr><td>회의 완료·완료 해제(완료하면 수정 잠금)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>회의록 삭제</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>회의록 보드 열기·링크 복사</td><td>O</td><td>O</td><td>O</td></tr>
<tr><td>회의록 “작업 등록 표”로 작업 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
</table>
</section>
<!-- 4. 프로젝트 -->
<section class="pjh-sec" id="project">
<h2><span class="pjh-num">4</span>프로젝트 만들기·고치기</h2>
<h3>새 프로젝트 만들기 (관리자)</h3>
<h3>새 프로젝트 만들기 (Pro user 이상)</h3>
<ol class="pjh-steps">
<li>왼쪽 사이드바 <b>프로젝트</b> 제목 옆의 <span class="pjh-ui">+</span>를 누릅니다.</li>
<li><b>이름</b>(필수)과 <b>설명</b>을 적습니다.</li>
@@ -156,9 +181,13 @@
<li><b>색상</b>(32가지)과 <b>아이콘</b>을 고릅니다. 아이콘 첫 칸 <span class="pjh-ui">Aa</span>를 고르면 아이콘 대신 이름 첫 글자가 나옵니다.</li>
<li>함께할 <b>멤버</b>에 체크하고 <span class="pjh-ui">만들기</span>를 누릅니다. 만든 사람은 자동으로 프로젝트 주인이 됩니다.</li>
</ol>
<p>프로젝트는 만들어졌는데 일부 멤버를 배정하지 못하면 창이 닫히지 않고 <b>배정하지 못한 멤버</b>가 빨갛게 표시됩니다.
<span class="pjh-ui">실패한 멤버 다시 배정</span>을 누르면 그 멤버만 다시 배정합니다(프로젝트를 또 만들지 않습니다).
창을 닫으면 만든 프로젝트로 넘어가며, 남은 멤버는 프로젝트 화면에서 배정하면 됩니다.
다른 사람을 소유자로 정해 만들면 만든 사람은 일반 멤버로 함께 들어갑니다(나중에 멤버에서 뺄 수 있습니다).</p>
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
<div>새 프로젝트는 섹션 없이 빈 보드로 시작합니다. 보드의 <span class="pjh-ui">+ 섹션 추가</span>로 “할 일 · 진행 중 · 완료”처럼 단계를 먼저 만들어 두면 편합니다. (<a href="#board">6장</a>)</div></div>
<h3>프로젝트 수정 (관리자)</h3>
<h3>프로젝트 수정 (Pro user 이상)</h3>
<p>사이드바의 프로젝트 이름에 마우스를 올리면 오른쪽에 <span class="pjh-ui">✎</span>(수정)과 <span class="pjh-ui">×</span>(삭제)가 나옵니다.
이름에서 <b>마우스 오른쪽 버튼</b>을 눌러도 <span class="pjh-ui">열기 · 수정 · 삭제</span> 메뉴가 나옵니다.</p>
<ul>
@@ -166,16 +195,17 @@
<li><b>프로젝트 완료</b>에 체크하면 목록 맨 아래 “완료 프로젝트”로 옮겨지고 흐리게 보입니다.</li>
<li>색이 밝으면(연노랑·하늘색 등) 글자와 아이콘이 자동으로 어둡게 바뀌어 잘 보입니다.</li>
</ul>
<h3>순서 바꾸기 (관리자)</h3>
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.</p>
<h3>순서 바꾸기 (Pro user 이상)</h3>
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
<h3>프로젝트 삭제</h3>
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람만</b> 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
<h3>멤버 배정 (관리자)</h3>
<h3>멤버 배정 (Pro user 이상)</h3>
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
<ul>
<li><span class="pjh-ui">+</span> — 멤버를 추가합니다(프로젝트 관리 권한이 있는 직원 중에서 고릅니다).</li>
<li><span class="pjh-ui">+</span> — 멤버 배정·제외 창이 열립니다. 지금 멤버는 체크된 채로 나오며, <b>체크하면 배정, 체크를 풀면 제외</b>됩니다(제외는 확인 후). 후보는 프로젝트 관리 권한이 있는 직원이고, 소유자는 뺄 수 없습니다.</li>
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 작업 목록이 뜹니다.</li>
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
</ul>
@@ -195,8 +225,10 @@
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
</table>
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
<p>화면 오른쪽 위 토글입니다. <b>이 프로젝트</b>는 지금 프로젝트만, <b>전체 프로젝트</b>는 내가 볼 수 있는 모든 프로젝트의 작업을 함께 보여줍니다.
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.</p>
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 작업을 함께 봅니다
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 작업</b>도 한 번씩 함께 보입니다.</p>
<h3>필터 바</h3>
<p>탭 아래 한 줄로 작업을 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
<ul>
@@ -224,7 +256,7 @@
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
<ul>
<li><span class="pjh-ui">작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
<li><span class="pjh-ui">메인 작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
<li><span class="pjh-ui">섹션 작업 모두 완료</span> — 그 섹션의 미완료 작업을 한 번에 완료합니다.</li>
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
@@ -236,8 +268,8 @@
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 작업을 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
<h3>작업 카드 다루기</h3>
<ul>
<li><b>상단 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
<li><b>하단 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
<li><b>상단 메인 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
<li><b>하단 메인 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
<li><b>열기</b> — 카드를 누르면 오른쪽에 작업 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 작업은 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 작업은 상태만 표시합니다.</li>
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
@@ -254,24 +286,24 @@
</table>
</section>
<!-- 7. 카드의 하위 작업 -->
<!-- 7. 카드의 세부 작업 -->
<section class="pjh-sec" id="card-subtasks">
<h2><span class="pjh-num">7</span>카드에서 하위 작업 다루기</h2>
<p class="pjh-lead">하위 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 하위 작업 목록이 펼쳐집니다.</p>
<h2><span class="pjh-num">7</span>카드에서 세부 작업 다루기</h2>
<p class="pjh-lead">세부 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 작업 목록이 펼쳐집니다.</p>
<ul>
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
<li><b>열기</b> — 줄을 누르면 그 하위 작업이 작업처럼 편집 창으로 열립니다.</li>
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 하위 작업 삭제</span></li>
<li><b>순서 바꾸기</b> — 펼친 하위 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
<li><b>다른 작업으로 옮기기</b> — 하위 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 하위 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
<li><b>열기</b> — 줄을 누르면 그 세부 작업이 작업처럼 편집 창으로 열립니다.</li>
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 세부 작업 삭제</span></li>
<li><b>순서 바꾸기</b> — 펼친 세부 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
<li><b>다른 작업으로 옮기기</b> — 세부 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 세부 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
</ul>
<h3>+ 하위 작업 추가</h3>
<h3>+ 세부 작업 추가</h3>
<ol class="pjh-steps">
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 하위 작업 추가</span>를 누릅니다.</li>
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 작업 추가</span>를 누릅니다.</li>
<li>새 줄의 “작업 이름 입력” 칸에 이름을 씁니다.</li>
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 하위 작업을 이어서 쓸 수 있습니다.</li>
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 작업을 이어서 쓸 수 있습니다.</li>
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
</ol>
@@ -286,11 +318,11 @@
<tr><th>버튼</th><th>하는 일</th></tr>
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다.</td></tr>
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>작업을 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 하위 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 세부 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
</table>
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 하위 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
<h3>제목과 기본 정보</h3>
<ul>
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
@@ -329,22 +361,22 @@
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
</section>
<!-- 9. 작업 창의 하위 작업 -->
<!-- 9. 작업 창의 세부 작업 -->
<section class="pjh-sec" id="subtasks">
<h2><span class="pjh-num">9</span>작업 창의 하위 작업</h2>
<p class="pjh-lead">작업 편집 창 가운데 “하위 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
<h2><span class="pjh-num">9</span>작업 창의 세부 작업</h2>
<p class="pjh-lead">작업 편집 창 가운데 “세부 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
<ul>
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 하위 작업이 편집 창으로 열립니다.</li>
<li><b>하위 작업의 하위 작업</b> — 그 하위 작업 안에도 하위 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">하위 작업 삭제</span>.</li>
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 작업이 편집 창으로 열립니다.</li>
<li><b>세부 작업의 세부 작업</b> — 그 세부 작업 안에도 세부 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 작업 삭제</span>.</li>
</ul>
<h3>하위 작업을 열었을 때</h3>
<p>하위 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 하위 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
<h3>세부 작업을 열었을 때</h3>
<p>세부 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 세부 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
</section>
<!-- 10. 날짜 -->
@@ -359,7 +391,7 @@
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
</ul>
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
<div>보드 카드와 하위 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
<div>보드 카드와 세부 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
</section>
<!-- 11. 목록 -->
@@ -390,9 +422,9 @@
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
<ul>
<li>기간이 있는(시작일 또는 마감일이 있는) 작업이 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 하위 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
<li>카드에 하위 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “하위 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 하위 작업은 작업 편집 창에서 봅니다.</li>
<li>줄 색은 <b>섹션 편집에서 정한 섹션 색</b>입니다(색이 없는 섹션은 프로젝트 색). 왼쪽 섹션 이름 앞에도 같은 색 네모가 붙습니다. 주말은 세로줄이 옅은 회색입니다.</li>
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
<li>카드에 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 작업은 작업 편집 창에서 봅니다.</li>
<li>줄 색은 <b>프로젝트 색</b>입니다(섹션별 색 지정은 없앴습니다 — 보드의 섹션 머리는 모두 같은 연회색). 주말은 세로줄이 옅은 회색입니다.</li>
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 작업은 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
@@ -407,7 +439,7 @@
<li>위쪽 숫자 카드 4개: <b>완료된 작업 합계 · 미완료 작업 합계 · 마감일이 지난 작업 합계 · 작업 합계</b></li>
<li><b>미완료 작업 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
<li><b>작업 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
<li><b>예정된 작업 합계(담당자별)</b> — 사람별로 일정이 잡힌 미완료 작업 수(상위 10명). <b>관리자에게만</b> 보입니다.</li>
<li><b>담당자별 작업 합계(메인·세부 작업, 완료)</b> — 이 범위에서 사람별로 배정된 작업 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 작업·세부 작업 세로 막대</b>로 보여 줍니다(막대 하나 = 그 작업 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 작업 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 작업은 세부 작업에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
</ul>
</section>
@@ -421,7 +453,7 @@
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
<li>칸 제목을 누르면 정렬합니다.</li>
<li>줄을 누르면 그 작업의 프로젝트 화면으로 가서 작업 편집 창이 바로 열립니다. 우클릭하면 작업 메뉴가 나옵니다.</li>
<li>내가 담당자인 하위 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
<li>내가 담당자인 세부 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
</ul>
</section>
@@ -458,7 +490,10 @@
<h3>수신함 화면</h3>
<ul>
<li><b>나를 태그한 작업</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 항목을 누르면 읽음이 되고, <span class="pjh-ui">확인</span>을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열립니다(나를 태그한 작업도 같음). 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.</li>
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열리고(나를 태그한 작업도 같음), 작업 창이 열린 채 다른 줄을 누르면 작업 창이 그 작업으로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 작업의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
작업 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(작업 창을 직접 닫을 때와 같음).
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
다른 프로젝트에서 연결돼 와 읽기만 되는 작업의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
</ul>
<h3>어떤 알림이 누구에게 가나요?</h3>
@@ -478,39 +513,39 @@
<h3>전체 검색</h3>
<ul>
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(하위 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(세부 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
<li>결과를 누르면 그 작업이 열립니다.</li>
</ul>
<h3>공유 링크</h3>
<ul>
<li>작업 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">작업 링크 복사</span>로 주소를 복사합니다.</li>
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 하위 작업 링크는 하위 작업 자체가 열립니다.</li>
<li>현재 그 작업을 볼 수 있는 멤버·소유자·관리자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 세부 작업 링크는 세부 작업 자체가 열립니다.</li>
<li>현재 그 작업을 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
</ul>
</section>
<!-- 19. 휴지통 -->
<section class="pjh-sec" id="trash">
<h2><span class="pjh-num">19</span>휴지통 (관리자)</h2>
<h2><span class="pjh-num">19</span>휴지통 (Pro user 이상)</h2>
<ul>
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 하위 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
<li>관리자는 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다.</li>
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 작업만 보입니다.</li>
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
<li>3개월이 지나면 영구 삭제됩니다.</li>
</ul>
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
<div>하위 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
<div>세부 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
</section>
<!-- 20. 연간 목표 -->
<section class="pjh-sec" id="goals">
<h2><span class="pjh-num">20</span>연간 목표</h2>
<p class="pjh-lead">한 해의 매출 목표·실적과 업무 계획을 한 표에서 관리합니다. 숫자는 위쪽 지표에, 실행 계획은 아래쪽 업무 영역에 적습니다. 프로젝트 관리 권한이 있는 직원은 볼 수 있고, 입력·구조 변경은 관리자만 할 수 있습니다.</p>
<p class="pjh-lead">한 해의 매출 목표·실적과 업무 계획을 한 표에서 관리합니다. 숫자는 위쪽 지표에, 실행 계획은 아래쪽 업무 영역에 적습니다. 프로젝트 관리 권한이 있는 직원은 볼 수 있고, 입력·구조 변경은 Pro user 이상만 할 수 있습니다.</p>
<h3 id="goals-start">목표 열기와 연도 만들기</h3>
<ol class="pjh-steps">
<li>왼쪽 사이드바 <span class="pjh-ui">목표</span>를 눌러 연도 목록을 펼친 뒤 원하는 연도를 누릅니다. 올해는 목표가 아직 없어도 목록에 보입니다.</li>
<li>관리자는 빈 연도 화면에서 <span class="pjh-ui">해당 연도 목표 만들기</span>, 또는 사이드바의 <span class="pjh-ui">+ 연도 추가</span>로 새 표를 만듭니다.</li>
<li>Pro user 이상은 빈 연도 화면에서 <span class="pjh-ui">해당 연도 목표 만들기</span>, 또는 사이드바의 <span class="pjh-ui">+ 연도 추가</span>로 새 표를 만듭니다.</li>
<li>가장 가까운 이전 연도의 업무 영역·줄 구성을 가져옵니다. 이전 연도가 없으면 다음 연도의 구성을 사용하고, 처음이면 상품·마케팅·컨텐츠·유통으로 시작합니다. 이전 숫자와 계획 글은 복사하지 않습니다.</li>
<li>위쪽 <span class="pjh-ui">매출 단위</span>를 확인한 뒤 월별 숫자와 계획을 입력합니다.</li>
</ol>
@@ -518,8 +553,8 @@
<h3 id="goals-metrics">매출·로아스 입력과 달성률 계산</h3>
<table class="pjh-table">
<tr><th>칸</th><th>입력·계산 방법</th></tr>
<tr><td>매출 목표</td><td>월 칸을 누르면 그 달 <b>주차별 목표</b> 입력 창이 열립니다. 주차마다 금액(매출 단위)을 넣고 <span class="pjh-ui">저장</span>하면 주차 합계가 그 달 매출 목표가 됩니다. 주차는 <a href="#meetings-week">주간 회의록 주차</a>와 같습니다. 주차를 모두 비우고 저장하면 월 목표도 지워집니다.</td></tr>
<tr><td>매출 실적</td><td>관리자가 월별 숫자를 직접 입력합니다. 목표 표의 실적은 회의록의 자동 매출과 별도로 관리하므로 실적 모듈에서 자동으로 채워지지 않습니다.</td></tr>
<tr><td>매출 목표</td><td>월 칸을 누르면 그 달 입력 창이 열립니다. 맨 위 <b>월 전체 목표</b>를 직접 넣고, 아래에 <b>주차별 목표</b>(매출 단위)를 넣은 뒤 <span class="pjh-ui">저장</span>합니다. 월 목표는 주차 합계와 따로 저장되고, 맨 아래에 <b>주차 합계</b>와 <b>차이(월 목표 − 주차 합계)</b>가 나옵니다 — +면 아직 주차에 못 나눈 금액, −면 주차 합계가 월 목표를 넘은 것입니다. 주차는 <a href="#meetings-week">주간 회의록 주차</a>와 같습니다.</td></tr>
<tr><td>매출 실적</td><td>Pro user 이상이 월별 숫자를 직접 입력합니다. 목표 표의 실적은 회의록의 자동 매출과 별도로 관리하므로 실적 모듈에서 자동으로 채워지지 않습니다.</td></tr>
<tr><td>매출 단위</td><td>예를 들어 단위가 <b>백만원</b>이면 30은 30,000,000원입니다. 단위를 바꿔도 이미 적은 숫자는 자동 환산되지 않으므로 숫자와 단위를 함께 확인하세요.</td></tr>
<tr><td>연간·분기 매출</td><td>해당 기간에 입력한 월 숫자의 합계입니다. 합계 칸에 따로 입력하지 않습니다.</td></tr>
<tr><td>달성</td><td>실적 ÷ 목표 × 100입니다. 월별로 계산하며, 연간·분기는 <b>기간 전체 목표 합계</b> 대비 입력된 실적 합계로 계산합니다. 목표가 없거나 0이면 달성률을 표시하지 않습니다. 100% 이상은 초록으로 표시됩니다.</td></tr>
@@ -552,24 +587,24 @@
<li><b>월 이름</b>을 누르면 그 달의 <a href="#meetings">주간 회의록</a>으로 이동합니다.</li>
</ul>
<h3 id="goals-merge">셀 병합·병합 해제·내용 이동</h3>
<h3 id="goals-merge">셀 병합·병합 해제</h3>
<ol class="pjh-steps">
<li>관리자는 업무 영역의 글 칸을 마우스로 끌어 여러 칸을 선택한 뒤 우클릭 → <span class="pjh-ui">셀 병합</span>을 누릅니다.</li>
<li>Pro user 이상은 업무 영역의 글 칸을 마우스로 끌어 여러 칸을 선택한 뒤 우클릭 → <span class="pjh-ui">셀 병합</span>을 누릅니다.</li>
<li>가로 병합은 <b>같은 분기의 월 칸끼리</b> 가능합니다. 연간·분기 칸은 세로로만 병합합니다. 선택한 칸들의 글은 순서대로 첫 칸에 모입니다.</li>
<li>병합된 칸을 우클릭 → <span class="pjh-ui">병합 해제</span>하면 다시 나뉩니다. 글은 왼쪽 위 칸에 남습니다.</li>
<li>글 칸 하나를 클릭한 뒤 <b>위·아래·왼쪽 테두리</b>를 잡아 다른 글 칸으로 끌면 내용과 글자 서식이 함께 이동합니다. 오른쪽 경계는 너비 조절용입니다. 대상에 글이 있으면 덮어쓰기를 확인하고, <kbd>Esc</kbd>로 이동을 취소합니다.</li>
</ol>
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합, 내용 이동을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
<p>관리자의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
<p>Pro user 이상의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
</section>
<!-- 21. 주간 회의록 -->
<section class="pjh-sec" id="meetings">
<h2><span class="pjh-num">21</span>주간 회의록</h2>
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 주요 업무와 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 직원은 조회할 수 있고, 생성·입력·삭제는 관리자만 할 수 있습니다.</p>
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 주요 업무와 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 프로젝트 관리 권한이 있는 직원은 <b>누구나 회의록을 만들고 고칠 수 있습니다</b>. Pro user 이상이 <span class="pjh-ui">회의 완료</span>를 누르면 그 회의록은 아무도 고칠 수 없게 잠기고(🔒 회의 완료 표시), Pro user 이상은 <span class="pjh-ui">완료 해제</span>로 다시 열 수 있습니다. 회의록 삭제도 Pro user 이상만 합니다.</p>
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>지난주 리뷰의 <b>결과</b>(글·금액)는 다음 주 회의에서 적는 값이라, 지난주 회의록이 완료돼 있어도 이번 주 회의록이 열려 있으면 적을 수 있습니다. 이번 주 회의록까지 완료하면 함께 잠깁니다. 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있는 동안만 결과를 고칠 수 있습니다.</div></div>
<h3 id="meetings-week">회의록 열기와 주차 기준</h3>
<p>왼쪽 연도 앞 화살표를 누르면 해당 연도의 하위 월 전체를 접거나 펼칠 수 있습니다. 연도 글자를 누르면 연간 목표를 엽니다. 연도와 월의 접기·펼치기 선택은 이 브라우저에 기억됩니다.</p>
@@ -588,7 +623,7 @@
</ol>
<h3 id="meetings-create">회의록 만들기와 이어받는 항목</h3>
<p>선택한 주에 회의록이 없으면 관리자에게 <span class="pjh-ui">해당 주차 회의록 만들기</span>가 보입니다. 화면을 열기만 해서는 회의록이 만들어지지 않습니다.</p>
<p>선택한 주에 회의록이 없으면 <span class="pjh-ui">해당 주차 회의록 만들기</span>가 보입니다(누구나 만들 수 있습니다). 화면을 열기만 해서는 회의록이 만들어지지 않습니다.</p>
<ul>
<li>줄이 있는 가장 가까운 앞선 회의록에서 <b>구역·항목 이름·색·순서</b>를 이어받습니다. 앞선 회의록이 없으면 가장 가까운 다음 회의록의 구성을 가져옵니다.</li>
<li>어느 쪽에도 회의록이 없으면 해당 연도 목표 표의 업무 영역과 기본 양식으로 시작합니다.</li>
@@ -598,8 +633,14 @@
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 굵게·기울임·밑줄·글자 색상과 줄바꿈·들여쓰기를 유지하고, 글자 크기는 월 계획의 기본 크기로 표시합니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
<h3 id="meetings-kpis">위쪽 숫자(월 목표·누적 목표·누적 실적·달성)와 결정 사항</h3>
<p>위쪽 영역은 화면을 스크롤해도 고정됩니다. 왼쪽 절반은 숫자 4칸, 오른쪽 절반은 <b>결정 사항 · 메모</b>입니다.</p>
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 작업 등록</h3>
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>작업 등록</b> 표입니다.</p>
<ol class="pjh-steps">
<li><b>작업 등록</b> — 제목 칸에 작업 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다.</li>
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 작업이 만들어지고, 줄에 <b>등록됨</b> 링크가 생깁니다. 줄은 이 브라우저에 남아 있어 새로고침해도 사라지지 않습니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 작업도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 작업 삭제는 만든 사람만 할 수 있습니다.</li>
</ol>
<table class="pjh-table">
<tr><th>지표</th><th>뜻과 출처</th></tr>
<tr><td>월 목표 매출</td><td>연간 목표 표의 해당 월 매출 목표(= 주차별 목표 합계)입니다. 매출 단위가 원·천원·만원·십만원·백만원·천만원·억원이면 원으로 환산해 함께 보여 줍니다.</td></tr>
@@ -615,7 +656,7 @@
<li>각 항목의 <b>주요 업무</b>에 실행할 일과 일정을 적습니다.</li>
<li><span class="pjh-ui">참석자</span>를 눌러 프로젝트 관리 권한이 있는 등록 직원 중 선택합니다. 찾기·전원 선택·모두 해제를 사용할 수 있으며, 칩의 <span class="pjh-ui">×</span>로 참석자를 뺍니다.</li>
<li>참석자 오른쪽 <span class="pjh-ui">회의록 보드</span>를 누르면 그 주차의 Google 슬라이드가 새 창으로 열립니다. 처음 누르면 회의록 보드 공유 드라이브에 빈 슬라이드(제목 틀 없음)를 <b>"10월 2주차 (10/5~10/11)"</b> 같은 이름으로 만들고, 다음부터는 같은 파일을 엽니다. 직원 누구나 열 수 있으며, 슬라이드 편집 권한은 공유 드라이브 권한을 따릅니다. 창이 안 뜨면 브라우저의 팝업 허용을 확인하세요.</li>
<li>위쪽 오른쪽 <b>결정 사항 · 메모</b>에 회의 결론과 다음주까지 확인할 일을 적습니다.</li>
<li>위쪽 가운데 <b>결정사항</b>에 회의 결론과 진행상황을 수시로 공유하고 완료되어야 할 일을 적습니다.</li>
</ol>
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 숫자로 읽히지 않는 값(예: <code>20개</code>)은 적은 글 그대로 저장됩니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자는 바꾸는 즉시 저장됩니다.</p>
@@ -634,9 +675,9 @@
<p>지난주 리뷰는 <b>바로 앞 주차의 같은 항목</b>에서 가져옵니다(앞 주차가 앞 달 마지막 주차일 수 있습니다). 이름 변경·순서 이동·회의록 생성 순서와 관계없이 이어진 같은 줄을 찾습니다. 그 주차 회의록이 없으면 “회의록 없음”, 회의록은 있지만 항목이 없으면 “지난주 회의록에 없는 줄”로 표시합니다. 몇 주 전 기록을 지난주로 대신 보여 주지 않습니다.</p>
<ul>
<li><b>전주 업무</b> — 지난 주차에 적은 주요 업무를 그대로 보여 줍니다(읽기 전용).</li>
<li><b>결과</b>(글) — 지난 주차 업무를 어떻게 했는지 관리자가 적습니다.</li>
<li><b>결과</b>(글) — 지난 주차 업무를 어떻게 했는지 적습니다(누구나).</li>
<li><b>전주 목표</b> — 지난 주차 회의록에서 그 줄에 적은 정량 목표입니다.</li>
<li><b>결과</b>(오른쪽 끝) — 관리자가 지난 주차 결과를 직접 입력합니다. 금액도, <code>18개</code> 같은 글도 됩니다(실적 모듈에서 자동 입력되지 않습니다).</li>
<li><b>결과</b>(오른쪽 끝) — 지난 주차 결과를 직접 입력합니다(누구나, 다음 주 회의록이 열려 있는 동안). 금액도, <code>18개</code> 같은 글도 됩니다(실적 모듈에서 자동 입력되지 않습니다).</li>
<li><b>저장 위치</b> — 이번 화면에서 입력한 지난주 결과(글·금액)는 <b>지난 주차 회의록의 줄</b>에 저장됩니다. 주요 업무·정량 목표는 이번 주차 회의록에 저장됩니다.</li>
<li><span class="pjh-ui">순서 바꾸기</span>는 이번주와 지난주 리뷰의 좌우 배치만 바꿉니다. 선택은 로그인한 사람별로 내 브라우저에 기억됩니다.</li>
</ul>
@@ -662,7 +703,7 @@
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 작업에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
<p>관리자의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
<p>Pro user 이상의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
</section>
<!-- 22. 단축키와 FAQ -->
@@ -673,17 +714,17 @@
<tr><th>키</th><th>하는 일</th></tr>
<tr><td><kbd>/</kbd></td><td>작업 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
<tr><td><kbd>Esc</kbd></td><td>작업 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
<tr><td><kbd>Enter</kbd></td><td>하위 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
<tr><td><kbd>Enter</kbd></td><td>세부 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 하위 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 세부 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
</table>
<h3>자주 묻는 질문</h3>
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 관리자에게 멤버 배정을 부탁하세요.</p>
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>작업·섹션·프로젝트는 만든 사람만 지울 수 있습니다. 만든 사람이나 최고 관리자에게 부탁하세요.</p>
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 관리자가 휴지통에서 복구할 수 있습니다.</p>
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 작업은 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
<p><b>Q. 하위 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>하위 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
<p><b>Q. 세부 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>세부 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
<p><b>Q. 작업을 두 프로젝트에 같이 두고 싶어요.</b><br>작업 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 바로 앞 주차 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -18,15 +18,18 @@
<div class="pj-section-head">
<h2>수신함</h2>
<div style="display:flex; gap:8px;">
{# PC 알림 프로그램(023) — 연결·내려받기 화면은 수신함 안에서 들어간다 #}
<a class="pj-btn pj-inbox-notifier" href="/project/notifier" title="브라우저가 뒤에 있어도 PC 화면에 알림 띄우기">
<span class="material-symbols-outlined">desktop_windows</span>PC 알림</a>
<button type="button" class="pj-btn" id="pj-mentions-readall">태그 모두 확인</button>
<button type="button" class="pj-btn pj-btn-primary" id="pj-readall">알림 모두 읽음</button>
</div>
</div>
<div class="pj-view pj-inbox-pane">
<!-- 아사나 Inbox 처럼 "나를 태그(@)한 업무"를 맨 위에 리스트로 보여준다.
"확인"을 누르면 수신함에 머문 채 오른쪽에 그 작업 창이 열린다
(프로젝트 화면을 ?task=&embed=1 로 iframe 에 — project.js initInboxTaskPanel). -->
<!-- 아사나 Inbox 처럼 "나를 태그(@)한 업무"를 맨 위에 리스트로 보여준다. 확인 안 한 태그·읽지 않은 알림만.
줄을 누르면 수신함에 머문 채 오른쪽에 그 작업 창이 열리고(project.js initInboxTaskPanel),
확인한 줄은 다른 줄을 고르거나 창을 닫으면 목록에서 빠진다. -->
<div class="pj-inbox-section">
<h3 class="pj-inbox-h3">
나를 태그한 작업
@@ -38,8 +41,9 @@
{% else %}
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
{% for t in mentioned_tasks %}
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}"
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}">
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 작업 창">
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
<div class="pj-inbox-body">
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
@@ -50,8 +54,6 @@
{% if t.mention_actor %} · {% set nm = t.mention_actor.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }}님이 태그{% endif %}
</div>
</div>
<a class="pj-btn pj-inbox-go" href="/project/p/{{ t.project_id }}?task={{ t.id }}"
data-task-id="{{ t.id }}">확인</a>
</li>
{% endfor %}
</ul>
@@ -65,9 +67,10 @@
{% else %}
<ul class="pj-inbox" id="pj-inbox">
{% for n in notifications %}
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}"
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}" tabindex="0" role="button"
data-id="{{ n.id }}"
{% if n.task_id %}data-project="{{ n.project_id }}"{% endif %}>
{% if n.task_id %}data-project="{{ n.project_id }}" data-task-id="{{ n.task_id }}"{% endif %}
{% if n.task_id %}data-href="/project/t/{{ n.task_id }}"{% elif n.project_id %}data-href="/project/p/{{ n.project_id }}"{% endif %}>
<span class="material-symbols-outlined pj-inbox-icon">
{% if n.type == 'assigned' %}assignment_ind
{% elif n.type == 'completed' %}task_alt
@@ -85,12 +88,6 @@
{% if n.actor_email %}{% set nm = n.actor_email.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }} · {% endif %}{{ n.created_at[:16].replace('T',' ') }}
</div>
</div>
{% if n.project_id %}
{# 작업 알림은 "확인" → 수신함에 머문 채 오른쪽에 작업 창(project.js initInboxTaskPanel) #}
<a class="pj-btn pj-inbox-go"
href="/project/p/{{ n.project_id }}{% if n.task_id %}?task={{ n.task_id }}{% endif %}"
{% if n.task_id %}data-task-id="{{ n.task_id }}"{% endif %}>확인</a>
{% endif %}
</li>
{% endfor %}
</ul>
@@ -104,5 +101,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261007d" defer></script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -17,7 +17,7 @@
{% block content %}
{# 프로젝트 모듈의 첫 화면 = 내 업무. 예전 프로젝트 홈(카드 그리드)은 없앴다. #}
<div class="pj-wrap pj-mytasks-view" data-me="{{ user.email }}"
data-is-admin="{{ 'true' if is_admin else 'false' }}"
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}">
<div class="pj-layout">
{% with current_pid = 0, side_active = "mytasks" %}{% include "project/_side.html" %}{% endwith %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20261007d" defer></script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
@@ -0,0 +1,112 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
{% block content %}
{# PC 알림 프로그램(023) — 트레이 프로그램(desktop/notifier) 내려받기, 연결 승인(?code=), 연결된 PC 해제.
토큰은 프로그램이 받아 PC 에 암호화 저장(Windows DPAPI). 이 화면은 토큰 원문을 보지 않는다. #}
<div class="pj-wrap pj-inbox-view pj-notifier-view">
<div class="pj-layout">
{% with current_pid = 0, side_active = "inbox" %}{% include "project/_side.html" %}{% endwith %}
<section class="pj-main">
<div class="pj-section-head"><h2><a class="pj-notifier-back" href="/project/inbox">수신함</a> › PC 알림 프로그램</h2></div>
<div class="pj-view pj-inbox-pane pj-notifier-pane">
{% if not notifier_enabled %}
<div class="pj-empty">PC 알림 연결이 아직 준비되지 않았습니다(DB 마이그레이션 023 필요).</div>
{% else %}
{% if code %}
<div class="pj-notifier-card is-link" id="pj-notifier-link" data-code="{{ code }}">
{% if link and not link.approved_at %}
<h3>이 PC 를 내 알림에 연결할까요?</h3>
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
<b>{{ user.name or user.email }}</b> 님의 태그·작업 배정 알림이 뜹니다.</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
{% elif link %}
<h3>이미 연결을 승인했습니다</h3>
<p class="pj-notifier-note">알림 프로그램이 곧 연결을 마칩니다. 이 창은 닫아도 됩니다.</p>
{% else %}
<h3>연결 코드가 없거나 만료되었습니다</h3>
<p class="pj-notifier-note">연결 코드는 10분 동안만 쓸 수 있습니다. 알림 프로그램에서 [연결]을 다시 누르세요.</p>
{% endif %}
</div>
{% endif %}
<div class="pj-notifier-card">
<h3>설치</h3>
<ol class="pj-notifier-steps">
<li>{% if download_ready %}<a class="pj-btn pj-btn-primary pj-btn-sm" href="/project/notifier/download">DBXNotifier.exe 내려받기</a>
{% else %}관리자에게 <b>DBXNotifier.exe</b> 파일을 받으세요.{% endif %}
설치 없이 파일 하나로 실행됩니다(Windows 10·11).</li>
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
</ol>
<p class="pj-notifier-note">나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
[열기]를 누르면 브라우저에서 그 작업이 열립니다.</p>
</div>
<div class="pj-notifier-card">
<h3>연결된 PC</h3>
{% if devices %}
<table class="pj-table pj-notifier-table">
<thead><tr><th>PC 이름</th><th>연결한 때</th><th>마지막 확인</th><th></th></tr></thead>
<tbody>
{% for d in devices %}
<tr>
<td>{{ d.device_name or '-' }}</td>
<td>{{ (d.created_at or '')[:16] | replace('T', ' ') }}</td>
<td>{{ (d.last_seen_at or '-')[:16] | replace('T', ' ') }}</td>
<td class="pj-trash-act"><button type="button" class="pj-btn pj-btn-sm pj-notifier-revoke"
data-id="{{ d.id }}" data-name="{{ d.device_name }}">연결 해제</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="pj-notifier-note">연결된 PC 가 없습니다.</p>
{% endif %}
</div>
{% endif %}
</div>
</section>
</div>
</div>
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script>
(function () {
async function post(url, body) {
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) });
const data = await res.json().catch(function () { return {}; });
if (!res.ok) throw new Error(data.detail || ("HTTP " + res.status));
return data;
}
const approve = document.getElementById("pj-notifier-approve");
if (approve) approve.addEventListener("click", async function () {
approve.disabled = true;
try {
await post("/project/api/notifier/link/approve", { code: document.getElementById("pj-notifier-link").dataset.code });
location.replace("/project/notifier?code=" + encodeURIComponent(document.getElementById("pj-notifier-link").dataset.code));
} catch (e) { approve.disabled = false; alert("연결 실패: " + e.message); }
});
document.querySelectorAll(".pj-notifier-revoke").forEach(function (b) {
b.addEventListener("click", async function () {
if (!confirm((b.dataset.name || "이 PC") + " 의 알림 연결을 해제할까요?")) return;
b.disabled = true;
try { await post("/project/api/notifier/devices/" + b.dataset.id + "/revoke"); location.reload(); }
catch (e) { b.disabled = false; alert("해제 실패: " + e.message); }
});
});
})();
</script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261004a" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -27,7 +27,7 @@
<div class="pj-wrap pj-project-view"
data-project-id="{{ project.id }}"
data-can-manage="{{ 'true' if can_manage else 'false' }}"
data-is-admin="{{ 'true' if is_admin else 'false' }}"
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
data-me="{{ user.email }}">
@@ -43,13 +43,13 @@
<div class="pj-head-left">
<!-- 프로젝트 제목 + 이 프로젝트의 멤버 아이콘.
마우스를 올리면 이름(data-tip → initHoverTips), 클릭하면 그 사람이
이 프로젝트에서 맡은 업무 팝업, 우클릭(관리자)하면 제외. 목록은
이 프로젝트에서 맡은 업무 팝업, 우클릭(Pro user 이상)하면 제외. 목록은
renderMemberList 가 같은 마크업으로 다시 그린다.
"전체 프로젝트" 스코프에선 제목이 "전체 프로젝트"로 바뀌고 멤버는 숨긴다
(.pj-title-wrap.is-all-scope). -->
<div class="pj-title-wrap" id="pj-title-wrap">
<h1 class="pj-project-title">
<span class="pj-project-title-pill" style="--pj-color: {{ project.color or '#4573d2' }}"><span class="material-symbols-outlined pj-pill-ic">{{ project.icon or 'folder' }}</span><span class="pj-pill-name">{{ project.name }}</span></span>
<span class="pj-project-title-pill" style="--pj-color: {{ project.color or '#4573d2' }}">{% set _pic = project.icon or 'folder' %}{% set _a = _pic.startswith('asana:') %}<span class="material-symbols-outlined pj-pill-ic{% if _a %} pj-ic-asana{% endif %}">{{ _pic[6:] if _a else _pic }}</span><span class="pj-pill-name">{{ project.name }}</span></span>
</h1>
<h1 class="pj-project-title pj-all-title">
<span class="pj-project-title-all"><span class="material-symbols-outlined pj-pill-ic">apps</span><span class="pj-pill-name">전체 프로젝트</span></span>
@@ -66,8 +66,8 @@
</span>
{% endfor %}
</div>
{% if is_admin %}
<button type="button" class="pj-title-addmember" id="pj-add-member" title="멤버 배정">+</button>
{% if pj_pro %}
<button type="button" class="pj-title-addmember" id="pj-add-member" title="멤버 배정·제외">+</button>
{% endif %}
</div>
<div class="pj-view-tabs pj-view-tabs-line" id="pj-view-tabs">
@@ -80,7 +80,8 @@
</div>
<!-- 아사나처럼 기본은 "이 프로젝트"만 보여준다. 전체 프로젝트 보기는
예전처럼 접근 가능한 모든 프로젝트를 합쳐서 보여주는 모드. -->
<div class="pj-view-tabs" id="pj-scope-toggle">
{# 2026-10-08 — 토글은 숨기고 왼쪽 메뉴 "전체 보기"(Pro user 이상, ?scope=all)로 바꿈. 상태 보관용으로만 남김 #}
<div class="pj-view-tabs" id="pj-scope-toggle" style="display:none">
<button type="button" class="pj-tab is-active" data-scope="project">이 프로젝트</button>
<button type="button" class="pj-tab" data-scope="all">전체 프로젝트</button>
</div>
@@ -213,9 +214,6 @@
<h3 id="pj-stage-modal-title">새 섹션</h3>
<input type="hidden" id="pj-stg-id" />
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
<label>색상
<span class="pj-color-palette" id="pj-stg-colors"></span>
</label>
<div class="pj-field-label">기본 담당자
<div class="pj-member-picker" id="pj-stg-assignee"></div>
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 작업을 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 작업만 이 사람에게 자동 배정됩니다.</span>
@@ -259,7 +257,7 @@
<!-- 아사나처럼 큰 제목은 이 무테 입력칸 하나뿐이다(위의 작은 안내줄은
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
<input type="hidden" id="pj-t-id" />
<!-- 하위 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
<!-- 세부 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 작업 열기">
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
@@ -358,6 +356,9 @@
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
<span class="pj-desc-fmtsep"></span>
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
@@ -374,15 +375,15 @@
</div>
</div>
<!-- 하위 업무 — 설명 바로 아래 줄에서 팝업 너비 전체를 쓴다.
<!-- 세부 업무 — 설명 바로 아래 줄에서 팝업 너비 전체를 쓴다.
기존 업무 편집 시에만. -->
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
<div class="pj-extra-head">
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 하위 작업
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 작업
</div>
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
<div class="pj-subtask-form">
<input type="text" id="pj-subtask-input" placeholder="하위 작업 제목…" autocomplete="off" />
<input type="text" id="pj-subtask-input" placeholder="세부 작업 제목…" autocomplete="off" />
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
<input type="date" id="pj-subtask-add-due" />
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
@@ -424,25 +425,20 @@
</div>
</div>
{% if is_admin %}
{% if pj_pro %}
<!-- 멤버 배정 모달 — 등록된 사용자(프로젝트 권한 보유)를 자동 목록화 -->
<div class="pj-modal" id="pj-modal-member" hidden>
<div class="pj-modal-card">
<h3>멤버 배정</h3>
<p class="pj-modal-hint">관리자 페이지에서 <b>프로젝트 관리</b> 권한을 켠 직원이 후보로 나옵니다. 여러 명을 한 번에 선택할 수 있습니다.</p>
<h3>멤버 배정 · 제외</h3>
<p class="pj-modal-hint">체크하면 배정, 체크를 풀면 제외됩니다(지금 멤버는 체크된 채로 나옵니다). 후보는 관리자 페이지에서
<b>프로젝트 관리</b> 권한을 켠 직원입니다. 배정된 멤버는 모두 이 프로젝트를 보고 수정할 수 있고, 소유자는 뺄 수 없습니다.</p>
<div class="pj-field-label">직원
<div class="pj-member-picker" id="pj-m-users">불러오는 중…</div>
</div>
<label>역할
<select id="pj-m-role">
<option value="member" selected>멤버</option>
<option value="manager">관리(서브·작업 관리)</option>
</select>
</label>
<div class="pj-modal-actions">
<span style="flex:1"></span>
<button type="button" class="pj-btn" data-close>취소</button>
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-member">배정</button>
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-member">저장</button>
</div>
</div>
</div>
@@ -492,5 +488,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261007d" defer></script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
@@ -1,14 +1,14 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
{% block content %}
{# 휴지통 — 관리자 전용. 지운 업무(하위 업무·댓글·팔로워·첨부 포함)를 3개월
{# 휴지통 — Pro user 이상. 지운 업무(세부 업무·댓글·팔로워·첨부 포함)를 3개월
보관하고, [복구] 로 원래 id 그대로 되살린다(project_db 010). #}
<div class="pj-wrap pj-inbox-view pj-trash-view">
<div class="pj-layout">
@@ -17,7 +17,7 @@
<section class="pj-main">
<div class="pj-section-head">
<h2>휴지통</h2>
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 관리자만 할 수 있습니다.</span>
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
</div>
<div class="pj-view pj-inbox-pane">
{% if not trash_enabled %}
@@ -45,7 +45,7 @@
<td class="pj-trash-title">{{ it.title }}</td>
<td>{{ it.project_name or '-' }}</td>
<td class="pj-trash-meta">
{% if it.task_count > 1 %}하위 작업 {{ it.task_count - 1 }}{% endif %}
{% if it.task_count > 1 %}세부 작업 {{ it.task_count - 1 }}{% endif %}
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261007d" defer></script>
<script src="/static/project.js?v=20261012b" defer></script>
{% endblock %}
+1 -1
View File
@@ -387,7 +387,7 @@
return `<section class="am-monitor-summary"><h3>모니터 / MONITOR <span class="am-badge">${monitors.length}개</span></h3><div class="am-monitor-grid">${monitors
.map((m) => {
const a = m.asset;
return `<article class="am-monitor-card"><strong>${esc(m.name)}</strong><small>${esc(m.model)}${m.serial ? " · 시리얼 " + esc(m.serial) : " · 시리얼 미기록"}</small>${a ? `<div class="am-linked-overview"><span class="am-badge">등록된 자산</span><h4>${esc(a.name)}</h4><p>${esc(a.tag)} · ${esc(a.location || "위치 미지정")}<br>${esc(userName(a.assignee_email))} · ${esc(statuses[a.status])}<br>구매 ${money(a.purchase_cost)} · 보증 ${esc(a.warranty_until || "미입력")}</p><button class="am-text-btn" data-monitor-open="${esc(a.id)}">자산 개요 보기 ↗</button></div>` : `<p class="am-muted">${m.candidates?.length ? "같은 시리얼 또는 모델의 자산이 있습니다. 실제 장비를 확인하세요." : "연결된 자산이 없습니다."}</p>${current ? (m.candidates || []).map((c) => `<div class="am-monitor-candidate"><span>${esc(c.tag)} · ${esc(c.name)}<small>${esc(c.serial || "시리얼 미기록")} · ${esc(c.location || "위치 미지정")}</small></span><button class="am-text-btn" data-monitor-link="${m.index}" data-target="${esc(c.id)}">이 자산 연결</button></div>`).join("") + `<button class="erp-btn erp-btn-outline" data-monitor-create="${m.index}">+ 모니터 자산으로 등록</button>` : '<p class="am-muted">모니터 등록·연결은 최신 보고서에서 진행하세요.</p>'}`}</article>`;
return `<article class="am-monitor-card"><strong>${esc(m.name)}</strong><small>${esc(m.model)}${m.serial ? " · 시리얼 " + esc(m.serial) : " · 시리얼 미기록"}</small>${a ? `<div class="am-linked-overview"><span class="am-badge">등록된 자산</span><h4>${esc(a.name)}</h4><p>${esc(a.tag)} · ${esc(a.location || "위치 미지정")}<br>${esc(userName(a.assignee_email))} · ${esc(statuses[a.status])}<br>구매 ${money(a.purchase_cost)} · 보증 ${esc(a.warranty_until || "미입력")}</p><button class="am-text-btn" data-monitor-open="${esc(a.id)}">자산 개요 보기 ↗</button></div>` : `<p class="am-muted">${m.candidate_by === "serial" ? "같은 시리얼의 모니터 자산이 이미 있습니다. 같은 장비이므로 아래 자산에 연결하세요." : m.candidates?.length ? "같은 모델의 다른 자산이 있습니다. 같은 장비면 연결하고, 다른 장비(예: 듀얼 모니터)면 새로 등록하세요." : "연결된 자산이 없습니다."}</p>${current ? (m.candidates || []).map((c) => `<div class="am-monitor-candidate"><span>${esc(c.tag)} · ${esc(c.name)}<small>${esc(c.serial || "시리얼 미기록")} · ${esc(c.location || "위치 미지정")}</small></span><button class="am-text-btn" data-monitor-link="${m.index}" data-target="${esc(c.id)}">이 자산 연결</button></div>`).join("") + (m.candidate_by === "serial" ? "" : `<button class="erp-btn erp-btn-outline" data-monitor-create="${m.index}">+ 모니터 자산으로 등록</button>`) : '<p class="am-muted">모니터 등록·연결은 최신 보고서에서 진행하세요.</p>'}`}</article>`;
})
.join("")}</div></section>`;
}
+244 -11
View File
@@ -315,7 +315,8 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
border-bottom: 1px solid #e2e4ea;
}
/* 세션 제목 — 아사나 보드의 16px/20px, 굵기 500 */
.pj-col-name { font-size: var(--pj-section-size); font-weight: 500; line-height: var(--pj-section-leading); }
/* 섹션 이름은 굵게(2026-10-08) */
.pj-col-name { font-size: var(--pj-section-size); font-weight: 700; line-height: var(--pj-section-leading); }
/* 세션 기본 담당자 아이콘 — 이름 옆에 작게 */
.pj-col-assignee { display: inline-flex; align-items: center; flex: 0 0 auto; }
.pj-col-assignee .pj-avatar { width: 20px; height: 20px; box-shadow: 0 0 0 1.5px #fff; }
@@ -331,7 +332,7 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
.pj-col-name.pj-col-name-editable:hover { background: rgba(0,0,0,.06); }
.pj-col-head-colored .pj-col-name.pj-col-name-editable:hover { background: rgba(255,255,255,.22); }
.pj-col-name-input {
font: inherit; font-size: var(--pj-section-size); font-weight: 500; color: var(--pj-ink);
font: inherit; font-size: var(--pj-section-size); font-weight: 700; color: var(--pj-ink);
min-width: 0; flex: 1 1 auto; max-width: 70%; padding: 2px 6px;
border: 1px solid var(--pj-accent); border-radius: 6px; background: #fff; outline: none; line-height: var(--pj-section-leading);
}
@@ -499,6 +500,7 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
border-bottom: 1px solid var(--pj-border) !important; white-space: nowrap; line-height: var(--pj-section-leading);
}
.pj-list-group-caret { font-size: 18px; color: var(--pj-ink-soft); }
.pj-list-group-name { font-weight: 700; }
.pj-list-group-count {
color: var(--pj-ink-soft); font-weight: 700; font-size: 11px; background: #eef0f2;
border-radius: 999px; min-width: 20px; height: 20px; padding: 0 6px;
@@ -899,7 +901,8 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
.pj-btn-complete.is-done { background: #f2f2f4; color: #6b6f76; border-color: var(--pj-border); }
/* 색상표(아사나) — 8칸씩 둥근 네모, 고른 색엔 체크 */
.pj-color-palette, #pj-f-colors { display: grid; grid-template-columns: repeat(8, 26px); gap: 8px; margin-top: 6px; }
/* 12칸씩(2026-10-08) — 32색이 3줄 */
.pj-color-palette, #pj-f-colors { display: grid; grid-template-columns: repeat(12, 26px); gap: 8px; margin-top: 6px; }
.pj-color-swatch {
position: relative; width: 26px; height: 26px; padding: 0; border: none; border-radius: 6px; cursor: pointer;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .06);
@@ -912,10 +915,22 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
}
.pj-color-swatch.is-dark.is-active::after { color: #fff; }
/* 프로젝트 아이콘 고르기(아사나) — 회색 아이콘 격자, 고른 것은 보라 강조. 길면 칸 안에서 스크롤 */
.pj-icon-palette {
.pj-icon-palette { margin-top: 6px; }
.pj-icon-grid {
/* 높이 제한 없음 — 아이콘 전부가 스크롤 없이 보이고 팝업이 그만큼 길어진다 */
display: grid; grid-template-columns: repeat(auto-fill, 38px); gap: 6px; margin-top: 6px; padding: 2px;
display: grid; grid-template-columns: repeat(auto-fill, 38px); gap: 6px; padding: 2px;
}
/* [기본 아이콘] [아사나 아이콘] 탭 — "아이콘" 글자 오른쪽 */
.pj-icon-tabs { display: inline-flex; gap: 2px; margin-left: 10px; padding: 2px; border-radius: 8px; background: #f1f2f4; vertical-align: middle; }
.pj-icon-tab { border: none; background: transparent; padding: 3px 10px; border-radius: 6px; font: inherit; font-size: 12.5px; color: var(--pj-ink-soft); cursor: pointer; }
.pj-icon-tab:hover { color: var(--pj-ink); }
.pj-icon-tab.is-active { background: #fff; color: var(--pj-ink); font-weight: 600; box-shadow: 0 1px 2px rgba(16, 24, 40, .12); }
/* 아사나 아이콘 — 채워진 모양(Material Symbols FILL 1, 쓰는 33개만 담은 글꼴). 값은 "asana:이름" */
@font-face {
font-family: "Material Symbols Asana"; font-style: normal; font-weight: 400; font-display: block;
src: url(/static/vendor/material-symbols/material-symbols-asana.woff2) format("woff2");
}
.material-symbols-outlined.pj-ic-asana { font-family: "Material Symbols Asana"; }
.pj-icon-pick {
width: 38px; height: 38px; padding: 0; border: none; border-radius: 8px; background: transparent;
color: #6d6e6f; cursor: pointer; display: inline-flex; align-items: center; justify-content: center;
@@ -997,6 +1012,8 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
/* ── 새 프로젝트 모달 — 멤버 선택 ── */
.pj-modal-card .pj-field-label { display: block; font-size: var(--pj-small-size); font-weight: 400; color: var(--pj-ink); margin-bottom: 12px; line-height: var(--pj-small-leading); }
.pj-member-picker { display: flex; flex-wrap: wrap; gap: 4px 12px; margin-top: 5px; max-height: 140px; overflow-y: auto; padding: 6px 2px; border: 1px solid #eef0f2; border-radius: 8px; }
/* 멤버 배정·제외 창은 목록에 스크롤 없이 사람 수만큼 늘어난다(창 전체가 화면보다 길면 창이 스크롤) */
#pj-modal-member .pj-member-picker { max-height: none; overflow: visible; }
.pj-member-pick { display: inline-flex !important; align-items: center; gap: 5px; font-size: 12.5px; font-weight: 500 !important; color: #333; width: auto !important; margin: 0 !important; }
.pj-member-pick input { width: auto !important; margin: 0 !important; }
@@ -1011,6 +1028,12 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
.pj-member-pick-avatar .pj-member-pick-icon.material-symbols-outlined { font-size: 40px; }
.pj-member-pick-avatar img.pj-member-pick-icon { width: 36px; height: 36px; }
.pj-member-pick-stacked .pj-member-pick-name { font-size: 12.5px; }
/* 새 프로젝트 — 만든 뒤 배정에 실패한 멤버(다시 배정 대상)와 안내줄 */
.pj-member-pick-stacked.is-failed { background: #fdecec; box-shadow: inset 0 0 0 1px #f1a8a8; }
.pj-member-pick-stacked.is-failed .pj-member-pick-name { color: #b42318; }
.pj-modal-msg { margin: 8px 0 0; padding: 8px 10px; border-radius: 6px; font-size: 12.5px; line-height: 1.5;
background: #f5f6f8; color: #333; }
.pj-modal-msg.is-error { background: #fdecec; color: #b42318; }
/* ── 좌측 사이드바 "전체 멤버" — 메뉴의 실제 내부 폭에 따라 4열↔3열, 아이콘 아래 이름(새 프로젝트
모달의 pj-member-pick-stacked 와 같은 아이콘 크기 재사용). ── */
@@ -1143,7 +1166,7 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
/* ── 보드 단계 컨트롤 ── */
.pj-col-head { position: relative; }
.pj-col-name { font-weight: 500; font-size: var(--pj-section-size); line-height: var(--pj-section-leading); }
.pj-col-name { font-weight: 700; font-size: var(--pj-section-size); line-height: var(--pj-section-leading); }
.pj-icon-btn[disabled] { opacity: .3; cursor: default; }
.pj-add-stage { width: 100%; padding: 10px; border: 1px dashed #c9cdd3; border-radius: 12px; background: #fff; color: #6b7280; font-size: 13px; font-weight: 600; cursor: pointer; }
.pj-add-stage:hover { border-color: #1e1f21; color: #1e1f21; }
@@ -1467,6 +1490,10 @@ label.pj-desc-fmtbtn {
.pj-inbox-sub { font-size: var(--pj-text-size); color: #525860; margin-top: 2px; line-height: var(--pj-text-leading); font-weight: 400; }
.pj-inbox-meta { font-size: var(--pj-small-size); color: #9aa1a9; margin-top: 4px; line-height: var(--pj-small-leading); font-weight: 400; }
.pj-inbox-go { align-self: center; padding: 4px 12px; font-size: 12px; }
/* 확인한 줄이 목록에서 빠질 때(2026-10-08) */
.pj-inbox-item { transition: opacity .2s, transform .2s; }
.pj-inbox-item.is-leaving { opacity: 0; transform: translateX(-12px); }
.pj-inbox-item:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
/* ── 우클릭 컨텍스트 메뉴 — 클릭 좌표 기준 고정 위치(.pj-daypop 은 앵커
엘리먼트 기준이라 좌표 배치가 다름). z-index 는 .pj-daypop(2100) 보다
@@ -1544,6 +1571,62 @@ img.pj-person-ic { width: 22px; height: 22px; }
box-shadow: var(--pj-card-shadow); padding: 18px 20px 20px; min-width: 0;
}
.pj-dash-card-wide { grid-column: 1 / -1; }
/* 담당자별 작업 합계 — 사람마다 메인·하위 세로 막대. 막대 = 그 작업 전체(100%), 초록 채움 = 완료율. 누르면 오른쪽 업무 목록 패널 */
.pj-wl-legend { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin: -6px 0 14px; font-size: 12px; color: var(--pj-ink-soft); }
.pj-wl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 5px; vertical-align: -1px; }
.pj-wl-legend i.is-done { background: var(--color-success-green, #2e9e5b); }
.pj-wl-legend i.is-open { background: var(--pj-accent-tint); border: 1px solid #cfc6fb; }
.pj-wl-legend .pj-wl-sum { color: var(--pj-ink); }
.pj-wl-legend .pj-wl-hint { margin-left: auto; }
.pj-wl-bars { display: flex; align-items: flex-end; gap: 26px; overflow-x: auto; padding-bottom: 2px; min-height: 220px; }
.pj-wl-group { display: flex; flex-direction: column; align-items: center; flex: 0 0 auto; }
.pj-wl-pair { display: flex; align-items: flex-end; gap: 6px; }
.pj-wl-col {
display: flex; flex-direction: column; align-items: center; gap: 0; padding: 2px 2px 0; border: none; background: none;
border-radius: 8px; font: inherit; cursor: pointer;
}
.pj-wl-col:disabled { cursor: default; opacity: .55; }
.pj-wl-col:not(:disabled):hover .pj-wl-track, .pj-wl-col:focus-visible .pj-wl-track { box-shadow: 0 0 0 2px var(--pj-accent); }
.pj-wl-val { display: flex; flex-direction: column; align-items: center; font-size: 12px; font-weight: 700; color: var(--pj-ink); margin-bottom: 6px; font-variant-numeric: tabular-nums; line-height: 1.25; }
.pj-wl-val small { font-size: 10.5px; font-weight: 600; color: var(--pj-ink-soft); }
.pj-wl-track { position: relative; display: block; width: 30px; height: 150px; border-radius: 6px 6px 4px 4px; background: #f1f2f4; overflow: hidden; }
.pj-wl-track.has-tasks { background: var(--pj-accent-tint); box-shadow: inset 0 0 0 1px #d9d2fb; } /* 미완료 몫 */
.pj-wl-done {
position: absolute; left: 0; right: 0; bottom: 0; height: 0; background: var(--color-success-green, #2e9e5b);
transition: height .7s cubic-bezier(.22,.9,.3,1);
}
.pj-wl-col.is-sub .pj-wl-done { background: #5fbf86; }
.pj-wl-kind { margin-top: 6px; font-size: 11px; color: var(--pj-ink-soft); white-space: nowrap; } /* "메인 작업"·"세부 작업" 한 줄 */
.pj-wl-name { display: flex; flex-direction: column; align-items: center; margin-top: 4px; max-width: 110px; text-align: center; }
.pj-wl-name b { font-size: 12.5px; font-weight: 600; color: var(--pj-ink); max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-wl-name small { font-size: 11px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
/* 오른쪽 업무 목록 패널(body 에 붙음, 작업 편집 창(z 1000) 아래) */
.pj-wl-drawer { position: fixed; inset: 0; z-index: 950; }
.pj-wl-drawer-dim { position: absolute; inset: 0; background: rgba(20, 22, 26, .18); opacity: 0; transition: opacity .25s; }
.pj-wl-panel {
position: absolute; top: 0; right: 0; bottom: 0; width: min(420px, 92vw); display: flex; flex-direction: column;
background: #fff; box-shadow: -12px 0 40px rgba(16, 24, 40, .16); transform: translateX(100%);
transition: transform .26s cubic-bezier(.22,.9,.3,1);
}
.pj-wl-drawer.is-open .pj-wl-drawer-dim { opacity: 1; }
.pj-wl-drawer.is-open .pj-wl-panel { transform: none; }
.pj-wl-panel header { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; padding: 18px 18px 12px; border-bottom: 1px solid var(--pj-border); }
.pj-wl-panel header b { display: block; font-size: 15px; }
.pj-wl-panel header small { color: var(--pj-ink-soft); font-size: 12px; }
.pj-wl-panel-body { flex: 1 1 auto; overflow-y: auto; padding: 8px 10px 16px; }
.pj-wl-panel-group { margin: 12px 8px 4px; font-size: 11.5px; font-weight: 700; color: var(--pj-ink-soft); }
.pj-wl-item {
display: flex; align-items: center; gap: 10px; width: 100%; padding: 9px 8px; border: none; border-radius: 8px;
background: none; font: inherit; text-align: left; cursor: pointer; color: var(--pj-ink);
}
.pj-wl-item:hover { background: #f5f6f8; }
.pj-wl-item .material-symbols-outlined { font-size: 19px; color: #9aa1ab; flex: none; }
.pj-wl-item.is-done .material-symbols-outlined { color: var(--color-success-green, #2e9e5b); }
.pj-wl-item.is-done .pj-wl-item-title { color: var(--pj-ink-soft); text-decoration: line-through; }
.pj-wl-item-main { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
.pj-wl-item-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13.5px; }
.pj-wl-item-main small { color: var(--pj-ink-soft); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-wl-item em { flex: none; font-style: normal; font-size: 12px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
.pj-dash-card-title { font-size: 13.5px; font-weight: 700; color: var(--pj-ink); margin-bottom: 18px; }
/* 세로 막대(섹션별/담당자별 공용) */
@@ -2426,7 +2509,76 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
/* 머리 — 왼쪽: 제목·인쇄·삭제 … 주차 탭(달력 쪽 끝) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력(폭 174px, 글자 10.5px) */
.pj-meet-headgrid { display: flex; align-items: flex-start; gap: 10px; margin: 8px 0 12px; }
.pj-meet-headleft { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
.pj-meet-headleft > .pj-meet-plan { margin: 0; }
/* 머리 영역 3칸(2026-10-07) — ① 월 계획 + 숫자 한 줄 ② 결정 사항·메모 ③ 작업 등록. 머리는 스크롤되지 않아 늘 보인다 */
.pj-meet-board { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, .9fr) minmax(0, 1.35fr); gap: 10px; }
@media (max-width: 1500px) { .pj-meet-board { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } .pj-meet-quick { grid-column: 1 / -1; } }
.pj-meet-area {
display: flex; flex-direction: column; min-width: 0; height: 230px; margin: 0; padding: 8px 10px;
border: 1px solid var(--pj-border); border-radius: 10px; background: #fff;
}
.pj-meet-area h3, .pj-meet-area.pj-meet-notes h3 { margin: 0 0 6px; font-size: 13px; font-weight: 600; }
.pj-meet-area.pj-meet-notes { margin: 0; } /* 예전 .pj-meet-notes 여백(16px) 덮기 */
.pj-meet-area h3 small { margin-left: 6px; font-size: 11px; font-weight: 400; color: var(--pj-ink-soft); }
.pj-meet-area-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
.pj-meet-area.pj-meet-notes textarea, .pj-meet-area.pj-meet-notes .pj-meet-ro {
flex: 1 1 auto; min-height: 0; max-height: none; height: auto !important; overflow-y: auto; padding: 8px 10px;
border: 1px solid #dfe2e6; border-radius: 8px; background: #fff;
}
/* ① 머리 줄 — 제목 + 숫자 4개(작게 한 줄) */
.pj-meet-plan-title { display: inline-flex; align-items: center; gap: 6px; flex: none; }
.pj-meet-kpiline {
display: flex; align-items: baseline; gap: 10px; flex: 1 1 0; flex-wrap: nowrap; min-width: 0; margin-left: 10px;
font-size: 11px; overflow: hidden; white-space: nowrap; /* 늘 1행 — 좁으면 끝이 가려지고 말풍선으로 */
}
.pj-meet-kpiline .pj-meet-kpi { display: inline-flex; flex-direction: row; align-items: baseline; gap: 4px; padding: 0; border: none; background: none; white-space: nowrap; }
.pj-meet-kpiline .pj-meet-kpi + .pj-meet-kpi::before { content: "·"; margin-right: 6px; color: #c4c8cf; }
.pj-meet-kpiline .pj-meet-kpi { flex: none; }
.pj-meet-kpiline .pj-meet-kpi-label { font-size: 11px; font-weight: 500; overflow: visible; }
.pj-meet-kpiline .pj-meet-kpi-val { font-size: 12px; font-weight: 700; }
.pj-meet-kpiline .pj-meet-kpi-val small { font-size: 10px; }
.pj-meet-kpiline .pj-meet-kpi-rate { color: inherit; font-weight: 700; }
/* ③ 작업 등록 표 — 빈 칸을 누르면 목록(body 에 붙는 메뉴) */
.pj-meet-quick-table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: 12.5px; }
.pj-meet-quick-table th { position: sticky; top: 0; z-index: 1; background: #f7f8f9; padding: 4px 6px; font-size: 12px; font-weight: 700; color: var(--pj-ink); text-align: center; border-bottom: 1px solid var(--pj-border); }
.pj-meet-pick-cell.is-person { display: flex; align-items: center; gap: 6px; }
.pj-meet-pick-cell.is-person > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.pj-meet-quick-face { width: 18px; height: 18px; flex: none; border-radius: 50%; object-fit: cover; }
.pj-meet-quick-face.is-ini {
display: inline-flex; align-items: center; justify-content: center; background: var(--pj-accent-tint); color: var(--pj-accent-dark);
font-size: 10.5px; font-weight: 700;
}
.pj-ctxmenu-ic .pj-meet-quick-face { width: 20px; height: 20px; }
.pj-member-pick.is-owner { opacity: .75; }
.pj-meet-quick-table th:nth-child(1) { width: 30%; }
.pj-meet-quick-table th:nth-child(2) { width: 17%; }
.pj-meet-quick-table th:nth-child(3) { width: 19%; }
.pj-meet-quick-table th:nth-child(4) { width: 15%; }
.pj-meet-quick-table th:nth-child(5) { width: 19%; }
.pj-meet-quick-acts { white-space: nowrap; text-align: right; }
.pj-meet-quick-del {
display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-left: 4px; vertical-align: middle;
border: none; border-radius: 6px; background: none; color: #9aa1ab; cursor: pointer;
}
.pj-meet-quick-del .material-symbols-outlined { font-size: 17px; }
.pj-meet-quick-del:hover { background: #fdecec; color: #c22b10; }
.pj-meet-quick-del:disabled { opacity: .4; cursor: default; }
.pj-meet-quick-table td { padding: 2px 3px; border-bottom: 1px solid #eef0f2; vertical-align: middle; }
.pj-meet-quick-table input { width: 100%; box-sizing: border-box; height: 26px; padding: 0 6px; border: 1px solid transparent; border-radius: 6px; background: transparent; font: inherit; }
.pj-meet-quick-table input:hover, .pj-meet-quick-table input:focus { border-color: #dfe2e6; background: #fff; outline: none; }
.pj-meet-pick-cell {
display: block; width: 100%; height: 26px; padding: 0 6px; border: 1px dashed transparent; border-radius: 6px; background: none;
font: inherit; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; color: var(--pj-ink);
}
.pj-meet-pick-cell.is-empty { color: #a7adb6; }
.pj-meet-pick-cell:hover { border-color: #cfd4da; background: #fafbfc; }
.pj-meet-quick-apply { height: 26px; padding: 0 10px; border: none; border-radius: 6px; background: var(--pj-accent); color: #fff; font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; }
.pj-meet-quick-apply:disabled { opacity: .5; cursor: default; }
.pj-meet-quick-done { display: inline-flex; align-items: center; gap: 4px; font-size: 11.5px; color: #1f8a4c; white-space: nowrap; }
.pj-meet-quick-done a { color: inherit; }
.pj-meet-quick-table tr.is-done input, .pj-meet-quick-table tr.is-done .pj-meet-pick-cell { color: var(--pj-ink-soft); pointer-events: none; }
.pj-meet-quick-table tr.is-done .pj-meet-pick-cell.is-person { color: var(--pj-ink-soft); }
.pj-meet-quick-add { margin-top: 4px; padding: 2px 6px; border: none; background: none; color: var(--pj-accent-dark); font: inherit; font-size: 12px; cursor: pointer; }
@media print { .pj-meet-quick { display: none !important; } .pj-meet-area { height: auto; } }
.pj-meet-title { flex-wrap: wrap; }
.pj-meet-title-acts { display: inline-flex; align-items: center; gap: 6px; margin-left: 4px; }
.pj-meet-title-acts .material-symbols-outlined { font-size: 16px; margin-right: 3px; }
@@ -2537,8 +2689,7 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
@media (max-width: 1300px) { .pj-meet-kpibar { grid-template-columns: repeat(2, minmax(0, 1fr)); } .pj-meet-kpi:nth-child(2) { border-right: none; } .pj-meet-kpi:nth-child(-n+2) { border-bottom: 1px solid var(--pj-border); } }
/* 이 달 계획 — 연간 목표 표의 그 달 열(업무 영역별 작은 카드) */
.pj-meet-plan { margin: 0 0 10px; padding: 8px 10px; border: 1px solid var(--pj-border); border-radius: 10px; background: #fff; }
.pj-meet-plan-head { display: flex; align-items: center; gap: 6px; font-size: var(--pj-text-size); font-weight: 500; margin-bottom: 6px; line-height: 20px; color: var(--pj-ink); }
.pj-meet-plan-head { display: flex; align-items: center; flex-wrap: nowrap; gap: 6px; min-width: 0; font-size: var(--pj-text-size); font-weight: 500; margin-bottom: 6px; line-height: 20px; color: var(--pj-ink); }
.pj-meet-plan-head .material-symbols-outlined { font-size: 18px; color: var(--pj-accent); }
.pj-meet-plan-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 6px; }
.pj-meet-plan-area { padding: 6px 8px; border-radius: 8px; background: var(--goal-bg, #f4f5f7); font-size: 12px; line-height: 1.45; min-width: 0; }
@@ -2554,8 +2705,27 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
/* 참석자 — 멤버 칩 + [참석자] 고르기 창(body 에 붙음) */
.pj-meet-attend { display: flex; align-items: flex-start; gap: 8px; margin: 0 0 10px; font-size: 12.5px; }
.pj-meet-attend-label { font-weight: 600; color: var(--pj-ink-soft); line-height: 30px; flex: none; }
.pj-meet-board-btn { flex: none; align-self: center; gap: 4px; }
.pj-meet-board-btn .material-symbols-outlined { font-size: 17px; }
/* 회의 완료(잠금) — 관리자 버튼 · 완료 표시 */
.pj-meet-complete-btn { gap: 4px; background: #e7f6ec; border-color: #b9e3c8; color: #1f7a44; }
.pj-meet-complete-btn:hover { background: #d6f0df; }
.pj-meet-complete-btn .material-symbols-outlined, .pj-meet-done-badge .material-symbols-outlined { font-size: 16px; }
.pj-meet-done-badge {
display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 0 10px; border-radius: 999px;
background: #eef0f3; color: #4b5563; font-size: 12.5px; font-weight: 700;
}
/* 회의록 보드 — 파워포인트 색(#D24726)의 파스텔톤 */
.pj-meet-board-btn {
flex: none; align-self: center; gap: 4px;
background: #fde8e1; border-color: #f5c3b3; color: #b7472a;
}
.pj-meet-board-btn:hover { background: #fbd8cc; border-color: #eea78f; color: #a33d22; }
.pj-meet-board-btn:disabled { opacity: .6; }
/* 회의록 보드 링크 복사(아이콘) — 보드 버튼 바로 오른쪽 */
.pj-meet-board-copy { flex: none; align-self: center; margin-left: -4px; width: 30px; height: 30px; border-radius: 8px; color: #b7472a; }
.pj-meet-board-copy:hover { background: #fde8e1; }
.pj-meet-board-copy .material-symbols-outlined { font-size: 19px; }
@media print { .pj-meet-board-copy { display: none !important; } }
.pj-meet-board-btn .material-symbols-outlined { font-size: 17px; color: #d24726; }
@media print { .pj-meet-board-btn { display: none !important; } }
.pj-meet-attend-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-height: 30px; padding: 2px; border-radius: 8px; }
.pj-meet-chip {
@@ -2713,8 +2883,43 @@ input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
.pj-goal-wkpop-row input[readonly] { background: #f7f8f9; }
.pj-goal-wkpop-sum { display: flex; justify-content: space-between; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--pj-border); }
.pj-goal-wkpop-sum b { font-variant-numeric: tabular-nums; }
/* 월 전체 목표(직접 입력) — 주차 줄과 구분선 */
.pj-goal-wkpop-month { padding-bottom: 8px; margin-bottom: 8px; border-bottom: 1px solid var(--pj-border); font-weight: 700; }
/* 차이 = 월 목표 − 주차 합계 — 남음(+) 주황, 넘음(−) 빨강, 딱 맞음 초록 */
.pj-goal-wkpop-diff { margin-top: 4px; padding-top: 0; border-top: 0; }
.pj-goal-wkpop-diff small { font-size: 11px; color: var(--pj-ink-soft); }
.pj-goal-wkpop-diff b.is-left { color: #c2410c; }
.pj-goal-wkpop-diff b.is-over { color: #dc2626; }
.pj-goal-wkpop-diff b.is-even { color: #16a34a; }
.pj-goal-wkpop-acts { display: flex; justify-content: flex-end; gap: 6px; margin-top: 10px; }
/* 나를 태그·작업 배정 알림 — 화면 가운데 아래 큰 팝업(body 에 붙음), 닫기 전까지 깜박인다(2026-10-07) */
.pj-alert-pop {
position: fixed; left: 50%; bottom: 28px; z-index: 1100; transform: translateX(-50%); width: min(560px, calc(100vw - 32px));
max-height: 46vh; display: flex; flex-direction: column; background: #fff; border: 2px solid var(--pj-accent);
border-radius: 16px; box-shadow: 0 18px 50px rgba(16, 24, 40, .28); overflow: hidden;
animation: pj-alert-blink 1s ease-in-out infinite;
}
@keyframes pj-alert-blink {
0%, 100% { border-color: var(--pj-accent); box-shadow: 0 18px 50px rgba(16, 24, 40, .28), 0 0 0 0 rgba(124, 92, 255, .55); }
50% { border-color: #ff6b4a; box-shadow: 0 18px 50px rgba(16, 24, 40, .28), 0 0 0 10px rgba(255, 107, 74, .18); }
}
@media (prefers-reduced-motion: reduce) { .pj-alert-pop { animation: none; border-color: #ff6b4a; } }
.pj-alert-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; background: #fff4f0; border-bottom: 1px solid #f6d6cc; }
.pj-alert-head .material-symbols-outlined { color: #e5532f; font-size: 22px; }
.pj-alert-head b { flex: 1 1 auto; font-size: 15px; }
.pj-alert-list { overflow-y: auto; padding: 6px; }
.pj-alert-item { display: flex; align-items: center; gap: 10px; padding: 10px 10px; border-radius: 10px; color: var(--pj-ink); text-decoration: none; }
.pj-alert-item:hover { background: #f5f6f8; }
.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; }
.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; }
.pj-alert-go { flex: none; font-size: 12.5px; font-weight: 600; color: var(--pj-accent-dark); }
@media print { .pj-alert-pop { display: none !important; } }
/* 영역 색 고르기 팝업(body 에 붙음) */
.pj-goal-colorpop {
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
@@ -2819,3 +3024,31 @@ html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--p
.pj-goal-text-swatch[aria-pressed="true"] { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
.pj-goal-text-swatch:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
.pj-goal-format :disabled { opacity: .45; cursor: default; }
/* PC 알림 프로그램 화면(/project/notifier, 023) */
.pj-notifier-pane { display: flex; flex-direction: column; gap: 14px; max-width: 760px; padding: 16px; }
.pj-notifier-card { padding: 14px 16px; border: 1px solid var(--pj-border); border-radius: 12px; background: #fff; }
.pj-notifier-card.is-link { border: 2px solid var(--pj-accent); background: #faf8ff; }
.pj-notifier-card h3 { margin: 0 0 8px; font-size: 15px; }
.pj-notifier-card p { margin: 6px 0; }
.pj-notifier-code { font-family: ui-monospace, Consolas, monospace; font-size: 16px; letter-spacing: 1px; color: var(--pj-accent-dark); }
.pj-notifier-note { color: var(--pj-ink-soft); font-size: 13px; }
.pj-notifier-steps { margin: 4px 0 8px; padding-left: 20px; line-height: 1.9; }
.pj-notifier-table { width: 100%; }
.pj-notifier-back { color: var(--pj-ink-soft); text-decoration: none; }
.pj-notifier-back:hover { color: var(--pj-accent-dark); text-decoration: underline; }
.pj-inbox-notifier { display: inline-flex; align-items: center; gap: 4px; text-decoration: none; }
.pj-inbox-notifier .material-symbols-outlined { font-size: 18px; }
/* 설명란 글자 색·크기 고르기(2026-10-08) — body 에 붙는 작은 창 */
.pj-desc-stylepop {
position: fixed; z-index: 1200; display: flex; gap: 4px; padding: 6px; background: #fff;
border: 1px solid var(--pj-border); border-radius: 10px; box-shadow: 0 8px 24px rgba(16, 24, 40, .16);
}
.pj-desc-stylepop.is-size { flex-direction: column; min-width: 120px; }
.pj-desc-stylepop button {
border: none; background: transparent; border-radius: 6px; cursor: pointer; font: inherit; color: var(--pj-ink);
padding: 4px 8px; text-align: left; line-height: 1.3;
}
.pj-desc-stylepop button:hover { background: #f1f2f4; }
.pj-desc-colorchip { display: inline-block; width: 22px; text-align: center; font-weight: 700; font-size: 15px; }
+1205 -428
View File
File diff suppressed because it is too large Load Diff
+34 -3
View File
@@ -87,8 +87,9 @@ a { color: inherit; text-decoration: none; }
.brand-logo-mark svg { color: #fff; }
/* 로그인 왼쪽 위 로고 — 가로 100px, 세로는 비율대로 */
.brand-logo-img {
width: auto;
width: 100px;
height: auto;
}
@@ -705,13 +706,43 @@ a { color: inherit; text-decoration: none; }
color: rgba(255, 255, 255, .9);
letter-spacing: 4px;
text-transform: none;
top: 28%;
right: 7%;
top: 30%;
right: 26%;
z-index: 2;
animation: kingFloat 13s ease-in-out infinite, kingSparkle 2.4s ease-in-out infinite;
white-space: nowrap;
user-select: none;
}
/* King 주위를 도는 사용자 아이디 — 위치·크기·투명도는 login.html 스크립트가 매 프레임 정한다 */
.shape-orbit {
top: 0;
left: 0;
font-size: 24px; /* King(30px)의 80% — 앞쪽에서 이 크기, 뒤쪽은 스크립트가 75%까지 줄인다 */
font-weight: 700;
letter-spacing: 2px;
color: rgba(255, 255, 255, .88);
white-space: nowrap;
user-select: none;
will-change: transform, opacity;
/* King 과 같은 반짝임(빛 번짐만 — 투명도는 앞뒤 깊이로 스크립트가 정함). 시작 시점은 사람마다 무작위 */
animation: orbitSparkle 2.4s ease-in-out infinite;
}
@keyframes orbitSparkle {
0%, 100% {
text-shadow:
0 0 8px rgba(255, 255, 255, .6),
0 0 18px rgba(99, 179, 237, .5);
}
50% {
text-shadow:
0 0 16px rgba(255, 255, 255, 1),
0 0 36px rgba(99, 179, 237, 1),
0 0 56px rgba(147, 197, 253, .9),
0 0 80px rgba(59, 130, 246, .6);
}
}
@keyframes shapeFloat1 {
0%, 100% { transform: translate(0, 0); }
25% { transform: translate(-22px, 32px); }
Binary file not shown.
+9 -2
View File
@@ -41,6 +41,13 @@ MODULE_KEYS: tuple[str, ...] = (
# 승인자 권한 키 — 결재 워크플로에서 별도 검사할 때 사용
APPROVER_KEYS: tuple[str, ...] = ("expense_approver", "vacation_approver")
# 관리자 등급(2026-10-12) — 수퍼관리자(SUPER_ADMIN_EMAIL 한 명, 고정·추가 불가) > admin > pro > user.
# 저장하는 role 값은 admin / pro / user 셋뿐 — 수퍼관리자는 role 이 아니라 이메일로 정해진다.
# pro 는 프로젝트 모듈(프로젝트·목표·주간 회의록)에서만 admin 에 가까운 권한을 받고
# (app/modules/project/access.py), 다른 모듈과 관리자 페이지에서는 user 와 같다(is_admin False).
ROLES: tuple[str, ...] = ("admin", "pro", "user")
ROLE_LABELS: dict[str, str] = {"admin": "Admin", "pro": "Pro user", "user": "User"}
def _now_iso() -> str:
return now_kst_iso()
@@ -121,7 +128,7 @@ class UserStore:
email = email.lower().strip()
if not email or "@" not in email:
raise ValueError("올바른 이메일 형식이 아닙니다.")
if role not in ("admin", "user"):
if role not in ROLES:
raise ValueError(f"role 값이 잘못되었습니다: {role}")
is_super = email == SUPER_ADMIN_EMAIL
with self._lock:
@@ -187,7 +194,7 @@ class UserStore:
email = email.lower().strip()
if email == SUPER_ADMIN_EMAIL:
raise PermissionError("슈퍼 관리자 계정은 수정할 수 없습니다.")
if role is not None and role not in ("admin", "user"):
if role is not None and role not in ROLES:
raise ValueError(f"role 값이 잘못되었습니다: {role}")
with self._lock:
data = self._read()
+19 -9
View File
@@ -97,8 +97,9 @@
<input type="email" name="email" required placeholder="email@dbxcorp.co.kr" style="width: 220px;" />
<input type="text" name="name" placeholder="이름(선택)" style="width: 120px;" />
<select name="role">
<option value="user">user</option>
<option value="admin">admin</option>
{% for r in roles | reverse %}
<option value="{{ r }}">{{ role_labels[r] }}</option>
{% endfor %}
</select>
<button type="submit" class="erp-btn erp-btn-primary">사용자 추가</button>
</form>
@@ -109,7 +110,7 @@
<thead>
<tr>
<th style="width: 200px;">사용자</th>
<th style="width: 80px;">역할</th>
<th style="width: 110px;">등급</th>
<th>접근 권한 <span class="erp-mod-group">클릭하여 토글</span></th>
<th style="width: 110px;">최근 로그인</th>
<th style="width: 130px; text-align: right;">동작</th>
@@ -138,11 +139,18 @@
</div>
</td>
<td>
<select class="erp-select" data-field="role"
{% if u.is_super_admin %}disabled{% endif %}>
<option value="user" {% if u.role == 'user' %}selected{% endif %}>user</option>
<option value="admin" {% if u.role == 'admin' %}selected{% endif %}>admin</option>
{# 수퍼관리자는 한 명으로 고정 — 등급을 바꾸거나 다른 사람을 수퍼관리자로 만들 수 없다. #}
{% if u.is_super_admin %}
<select class="erp-select" data-field="role" disabled>
<option value="admin" selected>수퍼관리자</option>
</select>
{% else %}
<select class="erp-select" data-field="role">
{% for r in roles %}
<option value="{{ r }}" {% if u.role == r %}selected{% endif %}>{{ role_labels[r] }}</option>
{% endfor %}
</select>
{% endif %}
</td>
<td class="erp-perm-cell">
{% for key in module_keys %}
@@ -175,8 +183,10 @@
</div>
<p class="erp-section-meta" style="margin-top: var(--sp-16);">
※ <strong>{{ super_admin_email }}</strong> 은(는) 슈퍼 관리자, 권한 변경/삭제 불가(항상 전체 접근).
admin 역할은 기본 전체 ON 이지만 슈퍼관리자가 개별 프로그램 접근을 끌 수 있다.
※ 등급: <strong>수퍼관리자</strong>(<strong>{{ super_admin_email }}</strong> 한 명 고정 — 권한 변경/삭제 불가, 항상 전체 접근, 더 추가할 수 없음)
&gt; <strong>Admin</strong> &gt; <strong>Pro user</strong> &gt; <strong>User</strong>.
Admin 은 기본 전체 ON 이지만 슈퍼관리자가 개별 프로그램 접근을 끌 수 있다.
Pro user 는 Project 모듈(프로젝트·목표·주간 회의록)에서 프로젝트 만들기·수정·멤버 배정·휴지통·목표 입력·회의 완료 등을 할 수 있고, 다른 모듈에서는 User 와 같다.
<code>expense_approver</code> / <code>vacation_approver</code> 는 결재 승인 권한.
</p>
-37
View File
@@ -7,43 +7,6 @@
<h2 class="erp-hero-title">안녕하세요, {{ user.name }}님</h2>
<p class="erp-hero-sub" id="erp-hero-sub"></p>
</div>
<div class="erp-home-grid">
<article class="erp-tile">
<div class="erp-tile-head">
<span class="erp-tile-label">바로가기</span>
<span class="erp-badge erp-badge-neutral">개인업무</span>
</div>
<h3 class="erp-tile-title">개인경비</h3>
<p class="erp-tile-desc">법인카드/개인지출 등록과 정산 신청.</p>
<a class="erp-btn erp-btn-primary" href="/expense/">개인경비 열기</a>
</article>
<article class="erp-tile">
<div class="erp-tile-head">
<span class="erp-tile-label">바로가기</span>
<span class="erp-badge erp-badge-outline">준비중</span>
</div>
<h3 class="erp-tile-title">휴가</h3>
<p class="erp-tile-desc">연차/반차 신청과 잔여일수 확인.</p>
<button class="erp-btn erp-btn-outline" disabled>오픈 예정</button>
</article>
<article class="erp-tile">
<div class="erp-tile-head">
<span class="erp-tile-label">알림</span>
<span class="erp-badge erp-badge-outline">공지</span>
</div>
<h3 class="erp-tile-title">시스템 안내</h3>
<ul class="erp-tile-list">
<li>좌측 메뉴에서 사용 가능한 업무 모듈을 확인하세요.</li>
<li>외부 모듈(주문/CORM)은 새 창에서 열립니다.</li>
<li>권한이 필요한 모듈은 관리자에게 요청하세요.</li>
</ul>
</article>
</div>
</section>
<script>
+46 -1
View File
@@ -19,7 +19,9 @@
<div class="shape shape-4"></div>
<div class="shape shape-5"></div>
<div class="shape shape-6"></div>
<div class="shape shape-king">King</div>
<div class="shape shape-king" id="orbit-king">King</div>
{# 등록 사용자 아이디 — King 주위를 사람마다 다른 무작위 곡선으로 돈다(아래 스크립트) #}
{% for n in orbit_names or [] %}<div class="shape shape-orbit">{{ n }}</div>{% endfor %}
</div>
<div class="brand-logo">
@@ -74,5 +76,48 @@
</main>
</div>
<script>
// King 을 중심으로 사용자 아이디가 돈다 — 사람마다 반지름·속도·방향·기울기·흔들림이 무작위인 타원 곡선.
// King 자체도 CSS(kingFloat)로 떠다니므로 매 프레임 King 의 지금 위치를 중심으로 삼는다. 뒤쪽(위)은 작고 흐리게.
(function () {
var box = document.querySelector(".brand-shapes");
var king = document.getElementById("orbit-king");
var els = Array.prototype.slice.call(document.querySelectorAll(".shape-orbit"));
if (!box || !king || !els.length) return;
var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function rnd(a, b) { return a + Math.random() * (b - a); }
var n = els.length;
var orbs = els.map(function (el, i) {
el.style.animationDelay = (-Math.random() * 2.4).toFixed(2) + "s"; // 반짝임이 한꺼번에 맞지 않게
return {
el: el,
base: (i / n) * Math.PI * 2 + rnd(-0.4, 0.4),
rx: rnd(80, 200), ry: rnd(50, 140),
speed: rnd(0.018, 0.045) * (Math.random() < 0.5 ? -1 : 1), // 초당 바퀴 수
tilt: rnd(-0.6, 0.6),
wa: rnd(10, 30), wf: rnd(0.15, 0.5), wp: rnd(0, 6.28),
wb: rnd(8, 30), wg: rnd(0.12, 0.45), wq: rnd(0, 6.28)
};
});
function place(t) {
var b = box.getBoundingClientRect(), k = king.getBoundingClientRect();
var cx = k.left - b.left + k.width / 2, cy = k.top - b.top + k.height / 2;
orbs.forEach(function (o) {
var a = o.base + t * o.speed * Math.PI * 2;
var x0 = Math.cos(a) * (o.rx + Math.sin(t * o.wf + o.wp) * o.wa);
var y0 = Math.sin(a) * (o.ry + Math.sin(t * o.wg + o.wq) * o.wb);
var x = x0 * Math.cos(o.tilt) - y0 * Math.sin(o.tilt);
var y = x0 * Math.sin(o.tilt) + y0 * Math.cos(o.tilt);
var depth = (Math.sin(a) + 1) / 2; // 0 = 뒤(위), 1 = 앞(아래)
o.el.style.transform = "translate(" + (cx + x).toFixed(1) + "px," + (cy + y).toFixed(1) + "px) translate(-50%,-50%) scale(" + (0.75 + depth * 0.25).toFixed(3) + ")";
o.el.style.opacity = (0.4 + depth * 0.5).toFixed(2);
o.el.style.zIndex = depth > 0.5 ? 3 : 1;
});
}
if (reduce) { place(0); return; }
function frame(ms) { place(ms / 1000); requestAnimationFrame(frame); }
requestAnimationFrame(frame);
})();
</script>
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
bin/
obj/
dist/
+355
View File
@@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace DbxNotifier
{
/// <summary>
/// 큰 알림 창 — 웹 프로젝트 화면의 큰 팝업(.pj-alert-pop)과 같은 모양: 흰 카드·둥근 모서리 16·연분홍 머리(종 + "새 알림 N건" + 닫기)·
/// 줄마다 배지(작업 배정/나를 태그)·굵은 제목·회색 둘째 줄·"열기 ›", 보라↔주황으로 1초마다 깜박이는 테두리와 빛.
/// 다른 프로그램 위(맨 위)에 뜨지만 포커스는 빼앗지 않는다(입력 중이던 창 그대로). 둥근 모서리·그림자를 위해
/// 픽셀 단위 투명 창(UpdateLayeredWindow)으로 직접 그린다.
/// </summary>
internal sealed class AlertForm : Form
{
public event Action<Alert> OpenClicked;
public event Action CloseClicked;
public event Action MoreClicked;
private const int MaxRows = 6;
private const float CardW = 560, HeadH = 54, RowH = 62, Pad = 6, MoreH = 38, ShadowM = 40, BottomGap = 28, Radius = 16;
private static readonly Color Accent = Gfx.Hex("#7b68ee");
private static readonly Color AccentDark = Gfx.Hex("#6453d6");
private static readonly Color Orange = Gfx.Hex("#ff6b4a");
private static readonly Color Ink = Gfx.Hex("#050505");
private static readonly Color InkSoft = Gfx.Hex("#636363");
private const string FontName = "Malgun Gothic";
private readonly List<Alert> _items = new List<Alert>();
private readonly List<RectangleF> _rows = new List<RectangleF>();
private readonly Timer _blink = new Timer { Interval = 70 };
private readonly DateTime _t0 = DateTime.Now;
private int _total;
private float _s = 1f, _fontScale = -1f;
private RectangleF _card, _close, _more;
private int _hoverRow = -1;
private bool _hoverClose, _hoverMore;
private Font _fHead, _fTitle, _fSmall, _fBadge, _fGo, _fBtn;
public AlertForm()
{
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
TopMost = true;
Text = "DBX 알림";
_blink.Tick += (s, e) => Render();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE;
return cp;
}
}
protected override bool ShowWithoutActivation => true;
/// <summary>알림 목록을 보여 준다(처음이면 띄우고, 이미 떠 있으면 내용만 바꾼다).</summary>
public void SetAlerts(IList<Alert> all)
{
_items.Clear();
for (int i = 0; i < all.Count && i < MaxRows; i++) _items.Add(all[i]);
_total = all.Count;
_hoverRow = -1;
_hoverClose = _hoverMore = false;
if (!IsHandleCreated) CreateHandle();
LayoutCard();
Render();
if (!Visible) Show();
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
_blink.Start();
}
public void HidePopup()
{
_blink.Stop();
Hide();
}
private void EnsureFonts()
{
if (Math.Abs(_fontScale - _s) < 0.01f) return;
DisposeFonts();
_fontScale = _s;
_fHead = new Font(FontName, 15f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fTitle = new Font(FontName, 14.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fSmall = new Font(FontName, 12f * _s, FontStyle.Regular, GraphicsUnit.Pixel);
_fBadge = new Font(FontName, 11.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fGo = new Font(FontName, 12.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fBtn = new Font(FontName, 13f * _s, FontStyle.Regular, GraphicsUnit.Pixel);
}
private void DisposeFonts()
{
foreach (Font f in new[] { _fHead, _fTitle, _fSmall, _fBadge, _fGo, _fBtn }) f?.Dispose();
}
/// <summary>카드 크기·위치 — 마우스가 있는 화면의 작업 영역 아래 가운데(웹 팝업처럼 아래에서 28px 위).</summary>
private void LayoutCard()
{
_s = Gfx.SystemScale();
EnsureFonts();
int extra = _total - _items.Count;
float cardH = HeadH + Pad * 2 + _items.Count * RowH + (extra > 0 ? MoreH : 0);
float m = ShadowM * _s;
_card = new RectangleF(m, m, CardW * _s, cardH * _s);
_close = new RectangleF(_card.Right - 72 * _s, _card.Y + (HeadH - 32) / 2 * _s, 58 * _s, 32 * _s);
_rows.Clear();
float y = _card.Y + (HeadH + Pad) * _s;
foreach (Alert _ in _items)
{
_rows.Add(new RectangleF(_card.X + Pad * _s, y, _card.Width - 2 * Pad * _s, RowH * _s));
y += RowH * _s;
}
_more = extra > 0 ? new RectangleF(_card.X + Pad * _s, y, _card.Width - 2 * Pad * _s, MoreH * _s) : RectangleF.Empty;
int bw = (int)Math.Ceiling(_card.Width + 2 * m), bh = (int)Math.Ceiling(_card.Height + 2 * m);
Rectangle wa = Screen.FromPoint(Cursor.Position).WorkingArea;
int x = wa.Left + (wa.Width - bw) / 2;
int top = (int)(wa.Bottom - BottomGap * _s - _card.Height - m);
Bounds = new Rectangle(x, Math.Max(wa.Top, top), bw, bh);
}
private static void DrawText(Graphics g, string t, Font f, Color c, RectangleF r,
StringAlignment h = StringAlignment.Near, StringAlignment v = StringAlignment.Center)
{
// GenericTypographic — 한글 글자 사이가 벌어지지 않게(기본 StringFormat 은 글자마다 여백을 둔다)
using (var sf = (StringFormat)StringFormat.GenericTypographic.Clone())
using (var b = new SolidBrush(c))
{
sf.FormatFlags |= StringFormatFlags.NoWrap;
sf.Trimming = StringTrimming.EllipsisCharacter;
sf.Alignment = h;
sf.LineAlignment = v;
g.DrawString(t ?? "", f, b, r, sf);
}
}
private static void Fill(Graphics g, RectangleF r, float radius, Color c)
{
using (GraphicsPath p = Gfx.Round(r, radius))
using (var b = new SolidBrush(c))
g.FillPath(b, p);
}
private void Render()
{
if (!IsHandleCreated || Width <= 0 || Height <= 0) return;
double phase = (DateTime.Now - _t0).TotalSeconds % 1.0;
double k = (1 - Math.Cos(phase * 2 * Math.PI)) / 2; // 0 → 1 → 0 (보라 → 주황 → 보라)
float s = _s, rad = Radius * s;
RectangleF c = _card;
using (var bmp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.Clear(Color.Transparent);
// 그림자(0 18px 50px rgba(16,24,40,.28) 비슷하게 — 겹겹이 옅게)
for (int i = 12; i >= 1; i--)
{
RectangleF r = c;
r.Offset(0, 12 * s);
r.Inflate(i * 2.2f * s, i * 2.2f * s);
Fill(g, r, rad + i * 2.2f * s, Color.FromArgb(6, 16, 24, 40));
}
// 깜박이는 주황 빛(0 0 0 10px rgba(255,107,74,.18))
if (k > 0.02)
{
RectangleF r = c;
float sp = (float)(k * 10 * s);
r.Inflate(sp, sp);
Fill(g, r, rad + sp, Color.FromArgb((int)(k * 0.18 * 255), Orange));
}
using (GraphicsPath cardPath = Gfx.Round(c, rad))
{
using (var b = new SolidBrush(Color.White)) g.FillPath(b, cardPath);
GraphicsState gs = g.Save();
g.SetClip(cardPath, CombineMode.Intersect);
var head = new RectangleF(c.X, c.Y, c.Width, HeadH * s);
using (var b = new SolidBrush(Gfx.Hex("#fff4f0"))) g.FillRectangle(b, head);
using (var p = new Pen(Gfx.Hex("#f6d6cc"), Math.Max(1f, s))) g.DrawLine(p, c.X, head.Bottom, c.Right, head.Bottom);
Gfx.Bell(g, new RectangleF(c.X + 16 * s, head.Y + (HeadH - 24) / 2 * s, 24 * s, 24 * s), Gfx.Hex("#e5532f"));
DrawText(g, "새 알림 " + _total + "건", _fHead, Ink, new RectangleF(c.X + 50 * s, head.Y, _close.X - c.X - 60 * s, head.Height));
Fill(g, _close, 8 * s, _hoverClose ? Gfx.Hex("#f2f4f7") : Color.White);
using (GraphicsPath bp = Gfx.Round(_close, 8 * s))
using (var p = new Pen(Gfx.Hex("#d0d5dd"), Math.Max(1f, s)))
g.DrawPath(p, bp);
DrawText(g, "닫기", _fBtn, Gfx.Hex("#344054"), _close, StringAlignment.Center);
for (int i = 0; i < _items.Count; i++) DrawRow(g, _items[i], _rows[i], i == _hoverRow);
if (!_more.IsEmpty)
{
if (_hoverMore) Fill(g, _more, 10 * s, Gfx.Hex("#f5f6f8"));
DrawText(g, "외 " + (_total - _items.Count) + "건 더 — 수신함에서 보기 ›", _fGo, AccentDark, _more, StringAlignment.Center);
}
g.Restore(gs);
RectangleF br = c;
br.Inflate(-s, -s);
using (GraphicsPath bp = Gfx.Round(br, rad - s))
using (var pen = new Pen(Gfx.Mix(Accent, Orange, k), 2 * s))
g.DrawPath(pen, bp);
}
Push(bmp);
}
}
private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover)
{
float s = _s;
if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
string kind = 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);
const string go = "열기 ›";
SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic);
float goX = r.Right - 12 * s - gsz.Width;
DrawText(g, go, _fGo, AccentDark, new RectangleF(goX - 2 * s, r.Y, gsz.Width + 8 * s, r.Height));
float tx = kr.Right + 12 * s, tw = Math.Max(10, goX - 14 * s - tx);
DrawText(g, a.CleanTitle, _fTitle, Ink, new RectangleF(tx, r.Y + 8 * s, tw, 24 * s));
DrawText(g, a.SubLine, _fSmall, InkSoft, new RectangleF(tx, r.Y + 33 * s, tw, 20 * s));
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
int row = -1;
for (int i = 0; i < _rows.Count; i++) if (_rows[i].Contains(e.Location)) row = i;
bool close = _close.Contains(e.Location);
bool more = !_more.IsEmpty && _more.Contains(e.Location);
if (row != _hoverRow || close != _hoverClose || more != _hoverMore)
{
_hoverRow = row;
_hoverClose = close;
_hoverMore = more;
Render();
}
Cursor = row >= 0 || close || more ? Cursors.Hand : Cursors.Default;
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hoverRow = -1;
_hoverClose = _hoverMore = false;
Render();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left) return;
if (_close.Contains(e.Location)) { CloseClicked?.Invoke(); return; }
if (!_more.IsEmpty && _more.Contains(e.Location)) { MoreClicked?.Invoke(); return; }
for (int i = 0; i < _rows.Count; i++)
if (_rows[i].Contains(e.Location)) { OpenClicked?.Invoke(_items[i]); return; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_blink.Dispose();
DisposeFonts();
}
base.Dispose(disposing);
}
// ── Win32: 픽셀 단위 투명 창 ──
private void Push(Bitmap bmp)
{
IntPtr screenDc = GetDC(IntPtr.Zero);
IntPtr memDc = CreateCompatibleDC(screenDc);
IntPtr hBmp = IntPtr.Zero, old = IntPtr.Zero;
try
{
hBmp = bmp.GetHbitmap(Color.FromArgb(0));
old = SelectObject(memDc, hBmp);
var size = new SIZE { cx = bmp.Width, cy = bmp.Height };
var src = new POINT();
var dst = new POINT { x = Left, y = Top };
var blend = new BLENDFUNCTION { BlendOp = 0, BlendFlags = 0, SourceConstantAlpha = 255, AlphaFormat = 1 };
UpdateLayeredWindow(Handle, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, ULW_ALPHA);
}
finally
{
if (old != IntPtr.Zero) SelectObject(memDc, old);
if (hBmp != IntPtr.Zero) DeleteObject(hBmp);
DeleteDC(memDc);
ReleaseDC(IntPtr.Zero, screenDc);
}
}
private const int WS_EX_LAYERED = 0x80000, WS_EX_TOOLWINDOW = 0x80, WS_EX_TOPMOST = 0x8, WS_EX_NOACTIVATE = 0x08000000;
private const int ULW_ALPHA = 2;
private const uint SWP_NOSIZE = 0x1, SWP_NOMOVE = 0x2, SWP_NOACTIVATE = 0x10, SWP_SHOWWINDOW = 0x40;
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int x, y; }
[StructLayout(LayoutKind.Sequential)]
private struct SIZE { public int cx, cy; }
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct BLENDFUNCTION { public byte BlendOp, BlendFlags, SourceConstantAlpha, AlphaFormat; }
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize,
IntPtr hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
private static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
}
}
+166
View File
@@ -0,0 +1,166 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace DbxNotifier
{
internal sealed class Alert
{
public long Id;
public string Type = "";
public string Title = "";
public string Body = "";
public string Actor = "";
public long TaskId;
public long ProjectId;
public bool IsMention => Type == "mention";
/// <summary>제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
public string CleanTitle
{
get
{
foreach (string p in new[] { "나를 태그함:", "작업 배정:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title;
}
}
/// <summary>둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게).</summary>
public string SubLine
{
get
{
string who = Actor;
int at = who.IndexOf('@');
if (at > 0) who = who.Substring(0, at);
if (who.Length > 0) who = char.ToUpperInvariant(who[0]) + who.Substring(1);
if (Body.Length > 0 && who.Length > 0) return Body + " · " + who;
return Body.Length > 0 ? Body : who;
}
}
// 작업 알림은 공유 링크(/project/t/{id}) — 서버가 지금 권한으로 열 수 있는 프로젝트(연결된 프로젝트 포함)로
// 보낸다. 원 소속 주소로 열면 연결된 프로젝트에서만 읽을 수 있는 사람에게 403 이 났다.
public string Path => TaskId > 0
? "/project/t/" + TaskId
: ProjectId > 0 ? "/project/p/" + ProjectId : "/project/inbox";
}
internal sealed class AlertResult
{
public string Name = "";
public long LatestId;
public List<Alert> Alerts = new List<Alert>();
}
internal sealed class ApiException : Exception
{
public readonly int Status;
public ApiException(int status, string message) : base(message) { Status = status; }
}
/// <summary>ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다.</summary>
internal sealed class Api : IDisposable
{
private readonly HttpClient _http;
private static readonly JavaScriptSerializer Json = new JavaScriptSerializer();
public Api()
{
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("DBXNotifier/" + typeof(Api).Assembly.GetName().Version.ToString(3));
}
public void Dispose() => _http.Dispose();
/// <summary>서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외).</summary>
public static string NormalizeServer(string raw)
{
string s = (raw ?? "").Trim().TrimEnd('/');
if (!Uri.TryCreate(s, UriKind.Absolute, out Uri u) || (u.AbsolutePath != "/" && u.AbsolutePath.Length > 0))
throw new ArgumentException("ERP 주소가 올바르지 않습니다. 예: " + Settings.DefaultServer);
bool local = u.Host == "localhost" || u.Host == "127.0.0.1";
if (u.Scheme != Uri.UriSchemeHttps && !(local && u.Scheme == Uri.UriSchemeHttp))
throw new ArgumentException("ERP 주소는 https:// 로 시작해야 합니다.");
return u.GetLeftPart(UriPartial.Authority);
}
private async Task<Dictionary<string, object>> Send(HttpMethod method, string url, string token, object body)
{
using (var req = new HttpRequestMessage(method, url))
{
if (!string.IsNullOrEmpty(token)) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body != null) req.Content = new StringContent(Json.Serialize(body), Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await _http.SendAsync(req).ConfigureAwait(false))
{
string text = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
Dictionary<string, object> d = null;
try { d = Json.Deserialize<Dictionary<string, object>>(text); } catch { /* HTML 오류 화면 등 */ }
if (!res.IsSuccessStatusCode)
{
string detail = d != null && d.TryGetValue("detail", out var x) ? x as string : null;
throw new ApiException((int)res.StatusCode, detail ?? ("서버 오류 HTTP " + (int)res.StatusCode));
}
return d ?? new Dictionary<string, object>();
}
}
}
private static string Str(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : "";
private static long Num(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToInt64(v) : 0;
public async Task<(string Code, string Poll, string ApprovePath, int ExpiresIn)> StartLink(string server, string device)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/start", null, new { device }).ConfigureAwait(false);
return (Str(d, "code"), Str(d, "poll"), Str(d, "approve_path"), (int)Num(d, "expires_in"));
}
/// <summary>연결 확인 — status: pending | expired | ok(token, email).</summary>
public async Task<(string Status, string Token, string Email)> PollLink(string server, string poll)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/poll", null, new { poll }).ConfigureAwait(false);
return (Str(d, "status"), Str(d, "token"), Str(d, "email"));
}
public async Task<AlertResult> Alerts(string server, string token, long after)
{
var d = await Send(HttpMethod.Get, server + "/project/api/notifier/alerts?after=" + after, token, null).ConfigureAwait(false);
var r = new AlertResult { Name = Str(d, "name"), LatestId = Num(d, "latest_id") };
if (d.TryGetValue("alerts", out var list) && list is IEnumerable items)
{
foreach (object o in items)
{
if (!(o is Dictionary<string, object> a)) continue;
r.Alerts.Add(new Alert
{
Id = Num(a, "id"),
Type = Str(a, "type"),
Title = Str(a, "title"),
Body = Str(a, "body"),
Actor = Str(a, "actor_email"),
TaskId = Num(a, "task_id"),
ProjectId = Num(a, "project_id"),
});
}
}
return r;
}
public Task MarkRead(string server, string token, long id) =>
Send(HttpMethod.Post, server + "/project/api/notifier/alerts/" + id + "/read", token, new { });
public Task Logout(string server, string token) =>
Send(HttpMethod.Post, server + "/project/api/notifier/logout", token, new { });
}
}
+195
View File
@@ -0,0 +1,195 @@
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace DbxNotifier
{
internal static class Browser
{
/// <summary>기본 브라우저로 연다. 실패하면 주소를 클립보드에 복사하고 false.</summary>
public static bool Open(string url)
{
try
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
return true;
}
catch
{
try { Clipboard.SetText(url); } catch { /* 클립보드 사용 중 */ }
return false;
}
}
}
/// <summary>
/// PC 연결 창 — [브라우저에서 연결] → 서버가 준 코드를 크게 보여 주고 브라우저로 승인 화면(/project/notifier?code=)을 연다.
/// 사용자가 브라우저(이미 로그인)에서 [연결]을 누르면 2초마다 확인하던 이 창이 토큰을 받아 닫힌다.
/// </summary>
internal sealed class ConnectForm : Form
{
public string Server { get; private set; } = "";
public string Token { get; private set; } = "";
public string Email { get; private set; } = "";
public bool AutoStartChecked => _auto.Checked;
private readonly Api _api;
private readonly TextBox _server;
private readonly CheckBox _auto;
private readonly Button _go;
private readonly Label _code, _status;
private readonly Timer _poll = new Timer { Interval = 2000 };
private string _pollSecret = "", _approveUrl = "";
private DateTime _expires;
private bool _busy;
public ConnectForm(Api api, string server, bool autoStart)
{
_api = api;
Text = "DBX 알림 — PC 연결";
Icon = Gfx.AppIcon(new Size(32, 32));
Font = new Font("Malgun Gothic", 9.75f);
AutoScaleDimensions = new SizeF(96f, 96f);
AutoScaleMode = AutoScaleMode.Dpi;
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = MinimizeBox = false;
StartPosition = FormStartPosition.CenterScreen;
ClientSize = new Size(440, 344);
BackColor = Color.White;
Controls.Add(new Label
{
Text = "이 PC 에 ERP 알림(나를 태그·작업 배정)을 띄우려면\n내 ERP 계정에 연결하세요.",
Location = new Point(20, 18), AutoSize = true, MaximumSize = new Size(400, 0),
});
Controls.Add(new Label { Text = "ERP 주소", Location = new Point(20, 84), AutoSize = true });
_server = new TextBox { Text = server, Location = new Point(20, 106), Width = 400 };
Controls.Add(_server);
_auto = new CheckBox { Text = "Windows 시작 시 자동 실행", Checked = autoStart, Location = new Point(20, 140), AutoSize = true };
Controls.Add(_auto);
_go = new Button
{
Text = "브라우저에서 연결", Location = new Point(20, 174), Size = new Size(170, 34),
BackColor = Gfx.Hex("#7b68ee"), ForeColor = Color.White, FlatStyle = FlatStyle.Flat,
};
_go.FlatAppearance.BorderSize = 0;
_go.Click += (s, e) => OnGo();
Controls.Add(_go);
_code = new Label
{
Location = new Point(200, 172), Size = new Size(220, 38), Visible = false,
Font = new Font("Consolas", 18f, FontStyle.Bold), ForeColor = Gfx.Hex("#6453d6"), TextAlign = ContentAlignment.MiddleCenter,
BackColor = Gfx.Hex("#f4f1ff"),
};
Controls.Add(_code);
_status = new Label { Location = new Point(20, 222), Size = new Size(400, 66), ForeColor = Gfx.Hex("#636363") };
Controls.Add(_status);
var close = new Button { Text = "닫기", Location = new Point(340, 298), Size = new Size(80, 30), DialogResult = DialogResult.Cancel };
Controls.Add(close);
CancelButton = close;
AcceptButton = _go;
_poll.Tick += (s, e) => OnPoll();
}
private async void OnGo()
{
if (_approveUrl.Length > 0) // 이미 코드를 받았으면 브라우저만 다시
{
OpenApprove();
return;
}
string server;
try { server = Api.NormalizeServer(_server.Text); }
catch (ArgumentException ex)
{
_status.Text = ex.Message;
return;
}
_go.Enabled = false;
_server.Enabled = false;
_status.Text = "연결 요청 중…";
try
{
var r = await _api.StartLink(server, Environment.MachineName);
Server = server;
_pollSecret = r.Poll;
_approveUrl = server + r.ApprovePath;
_expires = DateTime.Now.AddSeconds(r.ExpiresIn > 0 ? r.ExpiresIn : 600);
_code.Text = r.Code;
_code.Visible = true;
_go.Text = "브라우저 다시 열기";
OpenApprove();
_poll.Start();
}
catch (Exception ex)
{
_status.Text = "연결 요청 실패: " + ex.Message;
_server.Enabled = true;
}
finally
{
_go.Enabled = true;
}
}
private void OpenApprove()
{
_status.Text = Browser.Open(_approveUrl)
? "브라우저 화면의 연결 코드가 오른쪽 코드와 같은지 확인하고 [연결]을 누르세요.\n(10분 안에 — 연결되면 이 창은 저절로 닫힙니다.)"
: "브라우저를 열지 못해 주소를 복사했습니다. 브라우저 주소창에 붙여 넣으세요.\n" + _approveUrl;
}
private void Reset(string message)
{
_poll.Stop();
_approveUrl = _pollSecret = "";
_code.Visible = false;
_go.Text = "브라우저에서 연결";
_server.Enabled = true;
_status.Text = message;
}
private async void OnPoll()
{
if (_busy) return;
if (DateTime.Now > _expires)
{
Reset("연결 코드가 만료됐습니다. [브라우저에서 연결]을 다시 누르세요.");
return;
}
_busy = true;
try
{
var r = await _api.PollLink(Server, _pollSecret);
if (r.Status == "ok" && r.Token.Length > 0)
{
_poll.Stop();
Token = r.Token;
Email = r.Email;
DialogResult = DialogResult.OK;
Close();
}
else if (r.Status == "expired")
{
Reset("연결 코드가 만료됐습니다. [브라우저에서 연결]을 다시 누르세요.");
}
}
catch
{
// 네트워크 잠깐 끊김 — 다음 확인 때 다시
}
finally
{
_busy = false;
}
}
protected override void Dispose(bool disposing)
{
if (disposing) _poll.Dispose();
base.Dispose(disposing);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- DBX 알림(PC 트레이 프로그램). .NET Framework 4.8 — Windows 10(1903+)·11 에 기본 설치돼 있어 런타임 설치 없이
exe 하나로 실행된다. 압축·난독화·자체 압축 해제(백신 오탐 주원인)를 쓰지 않는 평범한 관리 코드 exe. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net48</TargetFramework>
<LangVersion>latest</LangVersion>
<AssemblyName>DBXNotifier</AssemblyName>
<RootNamespace>DbxNotifier</RootNamespace>
<ApplicationIcon>app.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<Deterministic>true</Deterministic>
<DebugType>none</DebugType>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<!-- 파일 속성(자세히) — 회사·제품·설명·버전이 채워진 exe 가 백신·SmartScreen 평판에 유리 -->
<Version>1.0.0</Version>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<Company>DBX</Company>
<Product>DBX 알림</Product>
<AssemblyTitle>DBX 알림</AssemblyTitle>
<Description>DBX ERP 프로젝트 알림(태그·작업 배정)을 화면에 띄우는 트레이 프로그램</Description>
<Copyright>© 2026 DBX</Copyright>
<NeutralLanguage>ko-KR</NeutralLanguage>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Security" />
<Reference Include="System.Web.Extensions" />
<EmbeddedResource Include="app.ico" LogicalName="DbxNotifier.app.ico" />
</ItemGroup>
<ItemGroup>
<Compile Remove="tools\**" />
<None Remove="tools\**" />
</ItemGroup>
</Project>
+83
View File
@@ -0,0 +1,83 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace DbxNotifier
{
/// <summary>그리기 도우미 — 둥근 사각형, 종 아이콘, 색 섞기, 내장 아이콘.</summary>
internal static class Gfx
{
public static GraphicsPath Round(RectangleF r, float radius)
{
var p = new GraphicsPath();
float d = Math.Min(radius * 2, Math.Min(r.Width, r.Height));
if (d <= 0.5f)
{
p.AddRectangle(r);
return p;
}
p.AddArc(r.X, r.Y, d, d, 180, 90);
p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
p.CloseFigure();
return p;
}
public static Color Mix(Color a, Color b, double t) => Color.FromArgb(
(int)(a.A + (b.A - a.A) * t), (int)(a.R + (b.R - a.R) * t),
(int)(a.G + (b.G - a.G) * t), (int)(a.B + (b.B - a.B) * t));
public static Color Hex(string hex, int alpha = 255)
{
int v = Convert.ToInt32(hex.TrimStart('#'), 16);
return Color.FromArgb(alpha, (v >> 16) & 255, (v >> 8) & 255, v & 255);
}
/// <summary>울리는 종(웹 팝업 머리의 notifications_active 와 같은 느낌) — 24 격자를 r 에 맞춰 그린다.</summary>
public static void Bell(Graphics g, RectangleF r, Color color)
{
GraphicsState st = g.Save();
g.TranslateTransform(r.X, r.Y);
g.ScaleTransform(r.Width / 24f, r.Height / 24f);
using (var b = new SolidBrush(color))
using (var body = new GraphicsPath())
{
body.AddLine(5f, 17f, 6.6f, 15.2f);
body.AddLine(6.6f, 15.2f, 6.6f, 10.6f);
body.AddBezier(6.6f, 10.6f, 6.6f, 7.2f, 9.0f, 4.9f, 12f, 4.9f);
body.AddBezier(12f, 4.9f, 15.0f, 4.9f, 17.4f, 7.2f, 17.4f, 10.6f);
body.AddLine(17.4f, 10.6f, 17.4f, 15.2f);
body.AddLine(17.4f, 15.2f, 19f, 17f);
body.CloseFigure();
g.FillPath(b, body);
g.FillEllipse(b, 10.1f, 16.7f, 3.8f, 3.8f);
g.FillEllipse(b, 10.9f, 3.3f, 2.2f, 2.2f);
}
using (var pen = new Pen(color, 1.7f) { StartCap = LineCap.Round, EndCap = LineCap.Round })
{
g.DrawArc(pen, 2.4f, 1.0f, 19.2f, 19.2f, 198, 40);
g.DrawArc(pen, 2.4f, 1.0f, 19.2f, 19.2f, 302, 40);
}
g.Restore(st);
}
/// <summary>exe 에 넣은 app.ico 에서 원하는 크기 아이콘(트레이 = 작은 아이콘 크기).</summary>
public static Icon AppIcon(Size size)
{
using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("DbxNotifier.app.ico"))
return s == null ? SystemIcons.Information : new Icon(s, size);
}
public static Icon TrayIcon() => AppIcon(SystemInformation.SmallIconSize);
public static float SystemScale()
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
return Math.Max(1f, g.DpiX / 96f);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
using System;
using System.Threading;
using System.Windows.Forms;
namespace DbxNotifier
{
internal static class Program
{
[STAThread]
private static void Main(string[] args)
{
// 한 사용자 세션에 하나만 — 두 번 실행하면 안내만 하고 끝낸다.
using (var mutex = new Mutex(true, @"Local\DBXNotifier.SingleInstance", out bool created))
{
if (!created)
{
MessageBox.Show("DBX 알림이 이미 실행 중입니다.\n화면 오른쪽 아래 트레이의 종 아이콘을 확인하세요.",
"DBX 알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
bool autostart = Array.IndexOf(args, "--autostart") >= 0;
Application.Run(new TrayApp(autostart));
GC.KeepAlive(mutex);
}
}
}
}
+40
View File
@@ -0,0 +1,40 @@
# DBX 알림 (PC 트레이 프로그램)
ERP 프로젝트에서 **나를 태그**하거나 **작업이 배정**되면, 브라우저가 뒤에 있어도 PC 화면 아래 가운데에
웹 팝업과 같은 모양의 큰 알림 창을 띄운다. 서버 쪽 설명은 `docs/PROJECT_MODULE.md` 6-11.
- 실행 파일 하나(`DBXNotifier.exe`, 약 110KB), 설치 없음, 관리자 권한 불필요
- 실행하면 트레이(오른쪽 아래)에 종 아이콘만 남는다 — 메모리 약 25~30MB(전용), 20초마다 서버 확인
- 대상: Windows 10(1903 이후)·11 — 기본으로 들어 있는 .NET Framework 4.8 로 동작(런타임 설치 없음)
## 사용
1. `DBXNotifier.exe` 실행 → 연결 창에서 [브라우저에서 연결]
2. 브라우저(ERP 로그인 상태)의 `/project/notifier` 화면에서 코드가 같은지 보고 [연결] → 연결 창이 저절로 닫힘
3. 트레이 아이콘 메뉴: 지금 알림 확인 · ERP 수신함 열기 · 알림 소리 · Windows 시작 시 실행 · 연결 해제 · 종료
(왼쪽 클릭 = 알림이 있으면 알림 창, 없으면 수신함)
설정: `%APPDATA%\DBXNotifier\settings.json` — 토큰은 Windows DPAPI(현재 사용자)로 암호화. 다른 PC·사용자로 복사해도 못 쓴다.
연결 해제는 트레이 메뉴 또는 ERP `/project/notifier` 의 [연결 해제](분실 PC 등).
## 빌드
```powershell
powershell -ExecutionPolicy Bypass -File desktop\notifier\build.ps1 # → desktop\notifier\dist\DBXNotifier.exe
```
.NET SDK(6 이상)가 있으면 된다. `net48` 참조 어셈블리는 빌드 때 NuGet 에서 자동으로 받는다.
아이콘을 바꾸려면 `tools/make_icon.py`(Pillow) 수정 후 실행 → `app.ico`.
서버 내려받기 버튼에 올리기: `docs/DEPLOYMENT.md` "PC 알림 프로그램 마이그레이션 (023)".
## 백신·SmartScreen
오탐을 부르는 방식은 쓰지 않는다: 실행 파일 압축(UPX)·난독화·자체 압축 해제·다른 프로세스 주입·관리자 권한·숨은 다운로드 없음.
평범한 관리 코드 exe 에 회사·제품·버전 정보가 채워져 있고, 통신은 설정한 ERP 주소(HTTPS)로만 한다.
"Windows 시작 시 실행"은 사용자가 고른 경우에만 현재 사용자 Run 키에 등록한다.
그래도 **서명하지 않은 새 exe** 는 인터넷에서 받으면 Windows SmartScreen 이 "알 수 없는 게시자" 경고를 띄울 수 있다
(백신의 바이러스 판정과는 다르다 — [추가 정보] → [실행]). 경고를 없애는 확실한 방법은 **코드 서명 인증서**(OV/EV)로 서명하는 것:
`build.ps1` 이 `DBX_SIGN_PFX`·`DBX_SIGN_PASSWORD` 환경변수가 있으면 서명한다. 회사 백신 관리 콘솔이 있으면 `build.ps1` 이
출력하는 SHA-256 을 허용 목록에 넣어도 된다.
+134
View File
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using Microsoft.Win32;
using System.Windows.Forms;
namespace DbxNotifier
{
/// <summary>
/// 설정 — %APPDATA%\DBXNotifier\settings.json. 연결 토큰은 Windows DPAPI(현재 사용자)로 암호화해 저장하므로
/// 파일을 다른 PC·다른 사용자로 복사해도 쓸 수 없다.
/// </summary>
internal sealed class Settings
{
public const string DefaultServer = "https://dbx.no1king.freeddns.org";
public string Server = DefaultServer;
public string Token = ""; // 원문은 메모리에서만
public long LastSeen = -1; // 이 번호까지는 본 알림(닫기 누른 것). -1 = 처음(지금 최신을 기준으로)
public bool Sound = true;
public string UserName = "";
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("DBXNotifier.v1");
// DBX_NOTIFIER_DIR — 테스트용 설정 폴더(없으면 %APPDATA%\DBXNotifier)
private static string Dir =>
Environment.GetEnvironmentVariable("DBX_NOTIFIER_DIR") is string d && d.Length > 0
? d
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DBXNotifier");
private static string FilePath => Path.Combine(Dir, "settings.json");
public bool Connected => Token.Length > 0;
public static Settings Load()
{
var s = new Settings();
try
{
if (!File.Exists(FilePath)) return s;
var d = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(File.ReadAllText(FilePath, Encoding.UTF8));
if (d == null) return s;
if (d.TryGetValue("server", out var v) && v is string server && server.Length > 0) s.Server = server;
if (d.TryGetValue("last_seen", out v) && v != null) s.LastSeen = Convert.ToInt64(v);
if (d.TryGetValue("sound", out v) && v is bool sound) s.Sound = sound;
if (d.TryGetValue("user_name", out v) && v is string name) s.UserName = name;
if (d.TryGetValue("token", out v) && v is string enc && enc.Length > 0)
{
byte[] raw = ProtectedData.Unprotect(Convert.FromBase64String(enc), Entropy, DataProtectionScope.CurrentUser);
s.Token = Encoding.UTF8.GetString(raw);
}
}
catch
{
// 깨진 설정은 처음 상태로 — 다시 연결하면 된다.
}
return s;
}
public void Save()
{
try
{
Directory.CreateDirectory(Dir);
string enc = Token.Length == 0
? ""
: Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(Token), Entropy, DataProtectionScope.CurrentUser));
var d = new Dictionary<string, object>
{
["server"] = Server,
["last_seen"] = LastSeen,
["sound"] = Sound,
["user_name"] = UserName,
["token"] = enc,
};
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, new JavaScriptSerializer().Serialize(d), new UTF8Encoding(false));
if (File.Exists(FilePath)) File.Replace(tmp, FilePath, null);
else File.Move(tmp, FilePath);
}
catch
{
// 저장 실패는 다음 저장 때 다시
}
}
}
/// <summary>Windows 시작 시 실행 — 현재 사용자 Run 키(관리자 권한 불필요). 사용자가 켜고 끈다.</summary>
internal static class AutoStart
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string Name = "DBXNotifier";
private static string Command => "\"" + Application.ExecutablePath + "\" --autostart";
public static bool Enabled
{
get
{
using (var k = Registry.CurrentUser.OpenSubKey(RunKey))
return k?.GetValue(Name) is string;
}
}
public static void Set(bool on)
{
try
{
using (var k = Registry.CurrentUser.CreateSubKey(RunKey))
{
if (on) k.SetValue(Name, Command);
else k.DeleteValue(Name, false);
}
}
catch
{
// 정책으로 막힌 PC — 메뉴 체크 표시만 그대로
}
}
/// <summary>exe 를 다른 폴더로 옮겼으면 등록된 경로를 지금 위치로.</summary>
public static void RefreshPath()
{
using (var k = Registry.CurrentUser.OpenSubKey(RunKey))
{
if (k?.GetValue(Name) is string cur && !string.Equals(cur, Command, StringComparison.OrdinalIgnoreCase))
Set(true);
}
}
}
}
+300
View File
@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
namespace DbxNotifier
{
/// <summary>
/// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·작업 배정 알림이 있으면 큰 알림 창.
/// 웹 화면과 같은 규칙: 처음 연결하면 지금 최신 알림을 기준으로(옛 알림을 한꺼번에 띄우지 않음), [닫기] = 본 것으로,
/// [열기] = 브라우저로 그 작업 + 읽음 처리. 다른 곳(웹)에서 읽으면 다음 확인 때 창에서도 빠진다.
/// </summary>
internal sealed class TrayApp : ApplicationContext
{
private const int PollMs = 20000;
private readonly Settings _cfg = Settings.Load();
private readonly Api _api = new Api();
private readonly Icon _icon;
private readonly NotifyIcon _tray;
private readonly ContextMenuStrip _menu;
private readonly Timer _timer = new Timer { Interval = PollMs };
private readonly ToolStripMenuItem _miStatus, _miCheck, _miOpen, _miSound, _miAuto, _miConnect;
private readonly List<Alert> _pending = new List<Alert>();
private readonly HashSet<long> _opened = new HashSet<long>();
private AlertForm _popup;
private ConnectForm _connect;
private bool _busy;
private string _problem = "";
public TrayApp(bool autostart)
{
_icon = Gfx.TrayIcon();
_menu = new ContextMenuStrip { Font = new Font("Malgun Gothic", 9f) };
_miStatus = new ToolStripMenuItem("DBX 알림") { Enabled = false };
_miCheck = new ToolStripMenuItem("지금 알림 확인", null, async (s, e) => await Poll(true));
_miOpen = new ToolStripMenuItem("ERP 수신함 열기", null, (s, e) => OpenPath("/project/inbox"));
_miSound = new ToolStripMenuItem("알림 소리", null, (s, e) => { _cfg.Sound = !_cfg.Sound; _cfg.Save(); Sync(); });
_miAuto = new ToolStripMenuItem("Windows 시작 시 실행", null, (s, e) => { AutoStart.Set(!AutoStart.Enabled); Sync(); });
_miConnect = new ToolStripMenuItem("연결…", null, async (s, e) => { if (_cfg.Connected) await Disconnect(); else ShowConnect(); });
var miExit = new ToolStripMenuItem("종료", null, (s, e) => ExitThread());
_menu.Items.AddRange(new ToolStripItem[]
{
_miStatus, new ToolStripSeparator(), _miCheck, _miOpen, new ToolStripSeparator(),
_miSound, _miAuto, _miConnect, new ToolStripSeparator(), miExit,
});
_menu.Opening += (s, e) => Sync();
_tray = new NotifyIcon { Icon = _icon, Text = "DBX 알림", ContextMenuStrip = _menu, Visible = true };
_tray.MouseClick += (s, e) => { if (e.Button == MouseButtons.Left) OnTrayClick(); };
_timer.Tick += async (s, e) => await Poll(false);
SystemEvents.PowerModeChanged += OnPowerModeChanged;
AutoStart.RefreshPath();
Sync();
// 메시지 루프가 돈 뒤에 시작(창·풍선 도움말이 제대로 뜨게)
var boot = new Timer { Interval = 300 };
boot.Tick += async (s, e) =>
{
boot.Stop();
boot.Dispose();
if (_cfg.Connected)
{
_timer.Start();
await Poll(false);
}
else if (autostart)
{
Balloon("DBX 알림 연결이 필요합니다", "트레이의 종 아이콘을 오른쪽 클릭해 [연결…]을 누르세요.");
}
else
{
ShowConnect();
}
};
boot.Start();
}
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume) _ = Poll(false); // 절전에서 깨면 바로 확인
}
private async Task Poll(bool manual)
{
if (!_cfg.Connected)
{
if (manual) ShowConnect();
return;
}
if (_busy) return;
_busy = true;
try
{
AlertResult r = await _api.Alerts(_cfg.Server, _cfg.Token, _cfg.LastSeen < 0 ? -1 : _cfg.LastSeen);
_problem = "";
if (r.Name.Length > 0 && r.Name != _cfg.UserName)
{
_cfg.UserName = r.Name;
_cfg.Save();
}
if (_cfg.LastSeen < 0)
{
_cfg.LastSeen = r.LatestId; // 처음 — 지금까지 온 알림은 띄우지 않는다
_cfg.Save();
}
else
{
Apply(r.Alerts);
}
if (manual && _pending.Count == 0) Balloon("새 알림 없음", "확인하지 않은 태그·작업 배정 알림이 없습니다.");
}
catch (ApiException ex) when (ex.Status == 401)
{
ClearConnection();
Balloon("DBX 알림 연결이 해제되었습니다", ex.Message + "\n트레이 아이콘 메뉴의 [연결…]로 다시 연결하세요.");
}
catch (Exception ex)
{
_problem = "서버에 연결할 수 없음 — 다시 시도 중";
if (manual) Balloon("서버에 연결할 수 없습니다", ex.Message);
}
finally
{
_busy = false;
Sync();
}
}
/// <summary>서버의 지금 목록으로 바꾼다 — 새 번호가 있으면 창을 띄우고 소리, 다른 곳에서 읽은 것은 빠진다.</summary>
private void Apply(List<Alert> fresh)
{
fresh = fresh.Where(a => !_opened.Contains(a.Id)).ToList();
var known = new HashSet<long>(_pending.Select(a => a.Id));
bool added = fresh.Any(a => !known.Contains(a.Id));
_pending.Clear();
_pending.AddRange(fresh);
if (_pending.Count == 0)
{
_popup?.HidePopup();
return;
}
if (added)
{
ShowPopup();
if (_cfg.Sound) SystemSounds.Exclamation.Play();
}
else if (_popup != null && _popup.Visible)
{
_popup.SetAlerts(_pending);
}
}
private void ShowPopup()
{
if (_popup == null)
{
_popup = new AlertForm();
_popup.OpenClicked += OpenAlert;
_popup.CloseClicked += CloseAll;
_popup.MoreClicked += () =>
{
OpenPath("/project/inbox");
CloseAll();
};
}
_popup.SetAlerts(_pending);
Sync();
}
private void OpenAlert(Alert a)
{
OpenPath(a.Path);
_opened.Add(a.Id);
_ = MarkRead(a.Id);
_pending.RemoveAll(x => x.Id == a.Id);
if (_pending.Count == 0) CloseAll();
else _popup.SetAlerts(_pending);
Sync();
}
private async Task MarkRead(long id)
{
try { await _api.MarkRead(_cfg.Server, _cfg.Token, id); }
catch { /* 다음에 웹에서 읽어도 된다 */ }
}
/// <summary>[닫기] — 지금 보이는 알림까지 본 것으로(다시 뜨지 않음).</summary>
private void CloseAll()
{
long max = _cfg.LastSeen;
foreach (Alert a in _pending) max = Math.Max(max, a.Id);
foreach (long id in _opened) max = Math.Max(max, id);
if (max != _cfg.LastSeen)
{
_cfg.LastSeen = max;
_cfg.Save();
}
_pending.Clear();
_opened.Clear();
_popup?.HidePopup();
Sync();
}
private void OnTrayClick()
{
if (_pending.Count > 0) ShowPopup();
else if (!_cfg.Connected) ShowConnect();
else OpenPath("/project/inbox");
}
private void OpenPath(string path) => Browser.Open(_cfg.Server + path);
private void ShowConnect()
{
if (_connect != null)
{
_connect.Activate();
return;
}
_connect = new ConnectForm(_api, _cfg.Server, true);
_connect.FormClosed += (s, e) =>
{
ConnectForm c = _connect;
_connect = null;
if (c.DialogResult != DialogResult.OK || c.Token.Length == 0) return;
_cfg.Server = c.Server;
_cfg.Token = c.Token;
_cfg.LastSeen = -1;
_cfg.Save();
AutoStart.Set(c.AutoStartChecked);
_timer.Start();
Balloon("DBX 알림이 연결되었습니다", c.Email + " 님의 태그·작업 배정 알림을 이 PC 화면에 띄웁니다.");
_ = Poll(false);
};
_connect.Show();
_connect.Activate();
}
private async Task Disconnect()
{
if (MessageBox.Show("이 PC 의 DBX 알림 연결을 해제할까요?\n해제하면 알림이 오지 않습니다.", "DBX 알림",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return;
try { await _api.Logout(_cfg.Server, _cfg.Token); }
catch { /* 서버에서도 해제할 수 있다(ERP > Project > 수신함 > PC 알림) */ }
ClearConnection();
}
private void ClearConnection()
{
_timer.Stop();
_cfg.Token = "";
_cfg.LastSeen = -1;
_cfg.UserName = "";
_cfg.Save();
_pending.Clear();
_opened.Clear();
_popup?.HidePopup();
Sync();
}
private void Balloon(string title, string text) => _tray.ShowBalloonTip(6000, title, text, ToolTipIcon.Info);
private void Sync()
{
bool on = _cfg.Connected;
string who = _cfg.UserName.Length > 0 ? _cfg.UserName : "연결됨";
_miStatus.Text = on ? "DBX 알림 — " + who : "DBX 알림 — 연결 안 됨";
if (_problem.Length > 0) _miStatus.Text += " (" + _problem + ")";
_miCheck.Enabled = _miOpen.Enabled = on;
_miSound.Checked = _cfg.Sound;
_miAuto.Checked = AutoStart.Enabled;
_miConnect.Text = on ? "연결 해제" : "연결…";
string tip = !on ? "DBX 알림 — 연결 안 됨"
: _pending.Count > 0 ? "DBX 알림 — 새 알림 " + _pending.Count + "건"
: _problem.Length > 0 ? "DBX 알림 — " + _problem
: "DBX 알림 — 클릭하면 수신함";
_tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
}
protected override void ExitThreadCore()
{
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
_timer.Stop();
_timer.Dispose();
_tray.Visible = false;
_tray.Dispose();
_menu.Dispose();
_popup?.Dispose();
_connect?.Dispose();
_api.Dispose();
_icon.Dispose();
base.ExitThreadCore();
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="DBX.Notifier" type="win32" />
<description>DBX 알림</description>
<!-- 관리자 권한을 요구하지 않는다(현재 사용자 권한으로만 실행). -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /><!-- Windows 10 / 11 -->
</application>
</compatibility>
<!-- 화면 배율(125%·150%·200%)에서 글자가 흐리지 않게 — 시스템 DPI 기준으로 직접 그린다. -->
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0"
processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
</assembly>
+27
View File
@@ -0,0 +1,27 @@
# DBX 알림 빌드 — dist\DBXNotifier.exe 하나를 만든다(.NET SDK 필요, 실행 PC 에는 .NET Framework 4.8 만 있으면 됨).
# powershell -ExecutionPolicy Bypass -File desktop\notifier\build.ps1
# 코드 서명(선택, 백신·SmartScreen 경고를 줄이는 가장 확실한 방법):
# $env:DBX_SIGN_PFX = 'C:\cert\dbx-codesign.pfx'; $env:DBX_SIGN_PASSWORD = '...' (비밀번호는 저장소에 남기지 않는다)
$ErrorActionPreference = 'Stop'
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Push-Location $here
try {
dotnet build -c Release
if ($LASTEXITCODE -ne 0) { throw "빌드 실패" }
New-Item -ItemType Directory -Force (Join-Path $here 'dist') | Out-Null
$exe = Join-Path $here 'dist\DBXNotifier.exe'
Copy-Item (Join-Path $here 'bin\Release\net48\DBXNotifier.exe') $exe -Force
if ($env:DBX_SIGN_PFX) {
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" -ErrorAction SilentlyContinue |
Sort-Object FullName -Descending | Select-Object -First 1
if (-not $signtool) { throw "signtool.exe 를 찾을 수 없습니다(Windows SDK 설치 필요)." }
& $signtool.FullName sign /fd SHA256 /f $env:DBX_SIGN_PFX /p $env:DBX_SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $exe
if ($LASTEXITCODE -ne 0) { throw "서명 실패" }
}
$f = Get-Item $exe
"{0} {1:N0} KB SHA256 {2}" -f $f.FullName, ($f.Length / 1KB), (Get-FileHash $exe -Algorithm SHA256).Hash
}
finally {
Pop-Location
}
+68
View File
@@ -0,0 +1,68 @@
"""app.ico 생성 — 보라(#7b68ee) 둥근 사각형 위 흰 종(울리는 표시). 크기별로 따로 그려 작은 트레이 크기도 또렷하게.
사용: python desktop/notifier/tools/make_icon.py (Pillow 필요) → desktop/notifier/app.ico
"""
from pathlib import Path
from PIL import Image, ImageDraw
SIZES = [16, 20, 24, 32, 40, 48, 64, 128, 256]
SS = 8 # 슈퍼샘플링 배율
def bezier(p0, p1, p2, p3, n=24):
out = []
for i in range(n + 1):
t = i / n
a = (1 - t) ** 3
b = 3 * (1 - t) ** 2 * t
c = 3 * (1 - t) * t ** 2
d = t ** 3
out.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]))
return out
def draw(size: int) -> Image.Image:
big = size * SS
k = big / 24.0 # 24 단위 격자
img = Image.new("RGBA", (big, big), (0, 0, 0, 0))
g = ImageDraw.Draw(img)
g.rounded_rectangle([0, 0, big - 1, big - 1], radius=int(5.5 * k), fill=(123, 104, 238, 255))
white = (255, 255, 255, 255)
small = size <= 20 # 아주 작은 크기는 종을 크게, 울림 표시는 생략
def P(x, y):
# 종 중심을 (12, 12.5) 기준으로 확대
s = 1.12 if small else 0.92
return ((12 + (x - 12) * s) * k, (12.6 + (y - 12) * s) * k)
body = [P(5, 17), P(6.6, 15.2), P(6.6, 10.6)]
body += [P(*q) for q in bezier((6.6, 10.6), (6.6, 7.2), (9.0, 4.9), (12, 4.9))[1:]]
body += [P(*q) for q in bezier((12, 4.9), (15.0, 4.9), (17.4, 7.2), (17.4, 10.6))[1:]]
body += [P(17.4, 15.2), P(19, 17)]
g.polygon(body, fill=white)
cx, cy = P(12, 18.6)
r = 1.9 * k * (1.12 if small else 0.92)
g.ellipse([cx - r, cy - r, cx + r, cy + r], fill=white)
kx, ky = P(12, 4.4)
r2 = 1.1 * k * (1.12 if small else 0.92)
g.ellipse([kx - r2, ky - r2, kx + r2, ky + r2], fill=white)
if not small:
w = max(1, int(1.5 * k))
c = P(12, 10.6)
rr = 9.6 * 0.92 * k
box = [c[0] - rr, c[1] - rr, c[0] + rr, c[1] + rr]
g.arc(box, 198, 238, fill=white, width=w)
g.arc(box, 302, 342, fill=white, width=w)
return img.resize((size, size), Image.LANCZOS)
def main() -> None:
out = Path(__file__).resolve().parents[1] / "app.ico"
imgs = [draw(s) for s in SIZES]
imgs[-1].save(out, format="ICO", sizes=[(s, s) for s in SIZES], append_images=imgs[:-1])
print(out)
if __name__ == "__main__":
main()
+3
View File
@@ -18,6 +18,9 @@
시리얼이 없거나 중복·제조사/모델 불일치인 경우 자동 확정하지 않고 후보를 직접 연결한다.
- 미등록 모니터는 보고서의 이름/제조사/모델/시리얼과 컴퓨터의 위치/부서를 채운 등록 창을 연다.
생성과 컴퓨터 연결은 한 트랜잭션으로 저장한다. 동시 등록은 컴퓨터 행 잠금과 시리얼 잠금으로 보호한다.
- 새 등록을 막는 것은 **같은 시리얼의 모니터 자산이 이미 있을 때뿐**이다(같은 실물 — 기존 자산에 연결).
같은 모델·이름의 자산은 참고 후보로만 보여 주고(`candidate_by = "model"`), 시리얼이 다르거나 없으면 새 자산으로 등록된다
(듀얼 모니터처럼 같은 모델 여러 대 — 2026-10-07 수정, 예전엔 같은 모델 후보만 있어도 막혔다).
- 등록·연결은 최신 보고서에서만 가능하다. 이전 보고서도 모니터와 자산 개요를 조회할 수 있다.
기존에 업로드한 보고서도 재업로드 없이 지원한다.
+29
View File
@@ -125,6 +125,35 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
## PC 알림 프로그램 마이그레이션 (023)
023은 `notifier_links`·`notifier_tokens` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 `/project/notifier` 화면은
"마이그레이션 필요" 안내만, PC 알림 API 는 503.
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_023_$(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_023_notifier.sql
```
내려받기 파일(선택): 개발 PC 에서 `desktop/notifier/build.ps1` 로 만든 `dist/DBXNotifier.exe` 를 서버로 옮긴 뒤 컨테이너 데이터 볼륨에 둔다.
없으면 화면에 "관리자에게 받으세요"만 나온다(공유 드라이브로 나눠 줘도 된다).
```bash
cd /opt/www/main && docker compose exec web mkdir -p /data/notifier && docker compose cp ~/DBXNotifier.exe web:/data/notifier/DBXNotifier.exe
```
## 주간 회의록 회의 완료 마이그레이션 (022)
022는 `goal_meetings` 에 `completed_at`·`completed_by` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 [회의 완료] 버튼이 나오지 않고
회의록은 누구나 계속 고칠 수 있다.
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_022_$(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_022_meeting_complete.sql
```
## 주간 회의록 정량 목표·결과 글 마이그레이션 (021)
021은 `goal_meeting_items` 에 `target_text`·`result_text` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 정량 목표·결과는 예전처럼 숫자만 받는다.
+215 -24
View File
@@ -46,14 +46,14 @@
| 연결 env | `PROJECT_DB_URL` (미설정 시 "설정 필요" 안내, 앱은 죽지 않음) |
| 진입 권한 | 권한키 `project` (관리자 페이지 토글로 직원별 부여, admin 자동) |
| 멤버 배정 후보 | `project` 권한 보유 등록 사용자 자동 목록 (`GET /project/api/assignable-users`) |
| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 건 관리자만(비관리자가 `owner_email` 을 남으로 보내면 403) |
| 소유자 변경 | **관리자만**(2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) |
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) |
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) |
| 생성 권한 | **새 최상위 프로젝트는 Pro user 이상(2026-10-12, 6-14). 섹션·작업·서브프로젝트는 그 프로젝트 멤버 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 것도 Pro user 이상 |
| 소유자 변경 | **Pro user 이상**(2026-10-12, 예전 관리자만 2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) |
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 슈퍼관리자(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) |
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner 만(`_require_manage`). 비멤버는 403. **관리자(is_admin)도 멤버가 아니면 못 본다 — 예외는 슈퍼관리자(`app.store.SUPER_ADMIN_EMAIL`) 한 명**(2026-10-07, `access.sees_all_projects`·`visible_project_ids`). 왼쪽 사이드바 프로젝트 목록·`GET /api/projects`·검색·수신함·알림·마감 알림·휴지통(목록·복구)도 같은 기준. 멤버 배정은 여전히 관리자만이라, 관리자는 자기가 멤버인 프로젝트에서만 배정할 수 있다(직원이 만든 프로젝트는 슈퍼관리자가 배정). `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) |
| 지금 권한 기준 | 모든 판단은 **지금** 권한(`app/modules/project/access.py`) — 멤버에서 빠진 사람은 예전 담당자·멘션·협업자 기록이 있어도 내 작업·수신함·알림·검색·상세·공유 링크·댓글·첨부에서 그 작업이 보이지 않고, 새 알림·메일도 받지 않는다(기록은 이력으로 남김) |
| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다. 새 담당자는 그 프로젝트를 볼 수 있는 사람만(400). 날짜 범위(시작 ≤ 마감, 같은 날이면 시작 시각 ≤ 마감 시각)는 부분 수정도 기존 값과 합친 최종 상태로 검사(400) |
| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일. **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) |
| 멤버 배정 | 여전히 관리자(`is_admin`) 전용. 비관리자가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) |
| 삭제 권한 | **프로젝트·섹션은 Admin 이상이면 누구 것이든, 그 밖은 "만든 사람만"**(생성자 정보 없는 과거 데이터는 Admin 이상) — `_can_delete`. **작업은 멤버 누구나**(2026-10-12). **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) |
| 멤버 배정 | Pro user 이상, 자기가 멤버인 프로젝트만(2026-10-12). User 가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) |
| 메일 알림 | `app/mail.py` (stdlib smtplib). 작업 배정/완료 시 관리자에게 발송 |
## 1-1. 프로젝트 → 섹션 → 작업 (하위 작업 포함) 3단계 구조
@@ -184,7 +184,8 @@
## 2. 데이터 모델 (`scripts/sql/project_db_init.sql` + `..._002_*` ~ `..._006_*`)
- `projects` — `parent_id`(self-FK, NULL=최상위 / NOT NULL=서브프로젝트, `ON DELETE CASCADE`), name, description, color, owner_email, start/due_date, status(active|archived).
- `project_members` — 프로젝트↔사용자 배정. role(manager|member), `UNIQUE(project_id, user_email)`.
- `project_members` — 프로젝트↔사용자 배정. `UNIQUE(project_id, user_email)`. role 열(manager|member)은 남아 있지만
2026-10-07 부터 화면·권한에서 쓰지 않는다 — 배정 창의 역할 선택을 없앴고 새 배정은 늘 member, 배정된 멤버는 모두 보기·수정.
- `project_stages`(="섹션") — 진행단계(칸반 컬럼). **프로젝트 생성 시 자동으로
만들지 않는다**(아사나처럼 직접 "+ 섹션 추가"로 만든다 — `create_project`
의 `seed_stages` 기본값은 `False`). `is_done_stage`=TRUE 단계로 옮기면 작업
@@ -238,8 +239,8 @@
좌측 사이드바는 프로젝트·수신함 화면과 공용(`project/_side.html`, `side_active` 로
활성 메뉴 표시) — 수신함 · 내 작업 ·
프로젝트 트리(+ 새 프로젝트) · "전체 멤버". 프로젝트 트리는 **수신함·내 작업·휴지통·프로젝트
네 화면 모두 같다** — 관리자에게 드래그 순서 변경(⣿)·✎ 수정·× 삭제·우클릭 메뉴(공용
`initSideTree`, 모달은 `project/_side_modals.html` 을 각 화면이 include). "전체 멤버"는 **관리자(`is_admin`)에게만**
네 화면 모두 같다** — Pro user 이상에게 드래그 순서 변경(⣿)·✎ 수정·× 삭제·우클릭 메뉴(공용
`initSideTree`, 모달은 `project/_side_modals.html` 을 각 화면이 include). "전체 멤버"는 **Pro user 이상(`pj_pro`)에게만**
그리고 수신함·내 작업·프로젝트 화면 모두에서 나온다. 아이콘 클릭 = 그 사람의 담당 작업
팝업(`_member_tasks_modal.html`, `initMemberTasks`) — 프로젝트 화면에선 더블클릭 시 그 자리에서
편집 팝업, 다른 화면에선 그 작업의 프로젝트 화면(`?task=`)으로 이동.
@@ -247,7 +248,9 @@
좌측 "내 작업"는 접이식 패널이 아니라 `/project/` 로 가는 링크다.
**이 프로젝트의 멤버는 화면 위 제목 오른쪽**에 겹친 아바타로 둔다(`.pj-title-members`) —
마우스를 올리면 이름(`data-tip`, `initHoverTips` 가 위임 방식이라 동적 요소에도 붙는다),
클릭하면 그 사람이 이 프로젝트에서 맡은 작업 팝업, 우클릭(관리자)하면 제외, 옆 `+` 는 멤버 배정.
클릭하면 그 사람이 이 프로젝트에서 맡은 작업 팝업, 우클릭(Pro user 이상)하면 제외, 옆 `+` 는 **멤버 배정·제외 창**(2026-10-07 —
후보 전원 + 지금 멤버는 체크된 채, 체크 = 배정 `POST …/members`, 해제 = 제외 `DELETE …/members/{email}`(확인 뒤), 소유자는 잠금.
두 API 모두 Pro user 이상 + 그 프로젝트 관리 권한(`_require_manage`)).
좌측 트리의 작업 클릭도 페이지 이동 없이 바로 팝업(이미 로드된 전체 작업 데이터 사용).
좌측 맨 위 **수신함**(미확인 @태그 배지)과 **내 작업**(접이식, 기본 접힘 — 작업을 고르면
팝업이 열리며 다시 접힌다)가 있다. 예전 화면 오른쪽에 항상 떠 있던 "내 작업" 패널은 없앴고
@@ -280,9 +283,16 @@
CSS 의 크기는 전부 `calc(Npx * var(--tz))`(배율 모드 `--tz: .75`), vis 옵션 높이·간격도
`uiZoom()` 을 곱한다. 배율을 토글하면(resize) 다시 그린다. **타임라인 CSS 에 px 크기를 새로 넣을
때도 `var(--tz)` 를 곱한다.**
- **대시보드** — 합계 타일 4개 + 미완료 작업(섹션별)·작업 합계(완료 상태별) 차트. **"예정된 작업 합계
(담당자별)" 차트는 관리자(`is_admin`)에게만** 보인다(사람별 업무량이 드러나서). 화면 표시만 막는 것 —
작업 데이터 자체는 멤버가 원래 볼 수 있는 범위 그대로다.
- **대시보드** — 합계 타일 4개 + 미완료 작업(섹션별)·작업 합계(완료 상태별) 차트. **"담당자별 작업 합계(메인·하위
작업, 완료)" 표는 Pro user 이상에게만** 보인다(사람별 업무량이 드러나서, 세부 작업 API `subtasks-summary` 도 Pro user 이상) —
작업 데이터 자체는 멤버가 원래 볼 수 있는 범위 그대로다. (2026-10-07, 예전 "예정된 작업 합계(담당자별)" 막대 대신)
그 범위(이 프로젝트 = 여기 연결된 작업 포함 / 전체 프로젝트)에서 사람별로 배정된 작업 **전부**(마감일·필터와 무관) —
메인 작업(`scopeTasks()` 최상위, 중복 없이)과 하위 작업(화면 목록엔 없어 `GET /api/projects/{id}/subtasks-summary?scope=`
— `db.list_subtasks_of`, 그 범위 메인 작업의 하위만, 하위 작업 자신의 담당자 기준)을 나눠 세고, 메인·하위·전체 완료 수와
전체 완료율. 하위 요약은 15초 캐시(`paintWorkload`). **세로 막대**(같은 날 변경 — 사람마다 메인·하위 막대, 막대 = 그 작업 전체(100%),
초록 채움 높이 = 완료율, 위 = 완료/전체·%. 처음엔 높이를 작업 수로 그려 많은 사람 기준에 다른 막대가 눌려 보였다 → 완료율로 수정). 막대를 누르면 오른쪽 슬라이드 패널(`openWorkloadDrawer`, body 에 붙음, z 950 — 편집 창 아래)에
그 업무 목록(미완료·완료, 하위는 상위 작업 이름), 항목 → `openTaskById`(하위는 서버에서 받아) 편집 창. 편집 창이 닫히면
요약을 다시 받아 대시보드·패널을 다시 그린다. 하위 요약 API 는 id·제목·마감일·완료 시각도 준다.
- **보드** — 섹션별 칸반. `renderBoard` 는 캔버스를 통째로 다시 그리므로 **섹션 세로 스크롤(`.pj-col-body`,
섹션 id/이름 기준)·보드 가로 스크롤을 저장했다가 되돌린다**(작업 창 닫기·완료 체크·8초 갱신 후에도 보던 자리).
작업 창을 닫으면 펼친 카드의 하위 작업을 먼저 다 받은 뒤 한 번에 다시 그린다(짧아진 채 그리면 스크롤이 밀림). 섹션은 아사나처럼 **가로로 계속 늘어난다** — 화면을 넘치면
@@ -362,6 +372,9 @@ docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
# 020 = 새 주차(월요일 아닌 시작일)·지난주 결과 글·주차별 매출 목표 + 흡수된 월요일 회의록 이동 — 적용 전 project_db 백업(6-9-4)
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
< scripts/sql/project_db_020_meeting_periods.sql
# 022 = 회의 완료(goal_meetings.completed_at·completed_by) — 열 추가만(6-9-4)
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
< scripts/sql/project_db_022_meeting_complete.sql
# 021 = 회의록 정량 목표·결과에 글(target_text·result_text, 예: 20개) — 열 추가만(6-9-4)
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
< scripts/sql/project_db_021_meeting_amount_text.sql
@@ -511,7 +524,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
모든 조회 쿼리에 "삭제됨" 필터를 넣는 소프트 삭제 대신 이 방식 — 기존 화면·쿼리를 안 건드린다.
- 첨부 실물은 지우지 않고 `DATA_DIR/project/_trash/<trash_id>/<task_id>/` 로 옮긴다(복구 시 되돌림).
- **보관 3개월**(`expires_at`). 휴지통 화면을 열거나 작업을 지울 때 만료분을 영구 삭제(`_purge_trash`).
- **관리자 전용**: 좌측 "휴지통" 메뉴·`/project/trash` 화면·`POST /project/api/trash/{id}/restore` 모두 `is_admin`.
- **Pro user 이상**(2026-10-12, 예전 관리자 전용): 좌측 "휴지통" 메뉴·`/project/trash` 화면·`POST /project/api/trash/{id}/restore` 모두 `access.is_pro`.
복구는 원래 id 그대로(`restore_trash`): 같은 id 가 이미 있으면 거부, 프로젝트가 지워졌으면 거부, 하위 작업만
지웠는데 상위가 없으면 거부(상위 먼저 복구). 지워진 섹션은 섹션 없이, 지워진 프로젝트를 가리키는 연결/이력은 뺀다.
복구하면 휴지통 행은 지운다.
@@ -582,11 +595,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 관리자만**(`_require_admin`, 화면도 관리자에게만 입력칸·도구).
- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 Pro user 이상**(`_require_pro`, 화면도 `pj_pro` 에게만 입력칸·도구 — 6-14).
- 연도 추가(`POST /api/goals/years {year}`)는 가장 가까운 이전 연도(없으면 다음 연도)의 영역·줄 구조를 글 없이 복사,
목표가 하나도 없으면 `store.DEFAULT_GOAL_AREAS`(상품·마케팅·컨텐츠·유통[콜라보·인플·쿠팡·기타]). 없는 연도 화면은
관리자에게 "목표 만들기" 버튼(GET 에서 자동 생성하지 않는다). 연도 삭제는 연도를 직접 입력해야 진행(CASCADE 전부 삭제).
- API(전부 관리자): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
- API(전부 Pro user 이상): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
`{metric,kind,month,value}`(빈값 = 지움, 응답 `label` 은 쉼표 표기) · `POST /api/goals/{y}/areas` `{name,color}` ·
`PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` `{label, ref_row_id?, place?: above|below}`(기준 줄 위/아래, 없으면 맨 끝) ·
`PUT|DELETE /api/goals/rows/{id}` · `POST /api/goals/rows/{id}/move` · `PUT /api/goals/rows/{id}/cells/{month}` `{body}`.
@@ -713,7 +726,9 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
- **우클릭 너비 자동 맞춤**(2026-10-03) — 목표 표의 이름·글·숫자·머리 칸 모두 "현재 열 너비 자동 맞춤" / "전체 열 너비 자동 맞춤"을 표시한다.
보기 전용 사용자도 사용 가능하며 너비는 브라우저에 저장한다. 현재 열은 경계 더블클릭과 같고, 병합 칸은 오른쪽 끝 열을 맞춘다.
전체 맞춤은 접힌 월 열도 포함해 각 열의 가장 긴 문단에 맞추고, 병합 글에 부족한 폭은 그 병합의 마지막 열에 더한다.
- **셀 테두리로 내용 이동**(관리자, 2026-10-03) — 업무 영역의 연간·월·분기 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 잡아
- **셀 테두리로 내용 이동 — 연간 목표 표에서는 2026-10-07 요청으로 화면에서 없앴다**(테두리 손잡이·드래그 코드 삭제, 누른 칸 표시
`is-goal-active` 만 남김. `POST /api/goals/cells/move` API 는 남아 있음. 주간 회의록 표의 이동은 그대로). 아래는 예전 설명 —
(관리자, 2026-10-03) 업무 영역의 연간·월·분기 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 잡아
다른 글 칸에 놓으면 내용과 색·크기·굵게·기울임·밑줄을 옮긴다. 오른쪽 경계는 열 너비 조절용이다. 끄는 동안 대상 칸을 표시하고
표 가장자리에서는 자동 스크롤한다. Esc·창 포커스 해제·원본에 놓기는 취소한다. 대상에 글이 있으면 덮어쓰기를 확인한다.
병합 시작 칸의 글도 이동 가능하며 병합 배치·영역 색·열 너비는 유지한다. 연간·분기의 기본 글자 서식도 명시해 원본의 표시를 보존한다.
@@ -849,7 +864,16 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
회의록 `week_start` = 주차 시작일(월요일이 아닐 수 있음). 화면 `?week=` 에 아무 날짜(예전 월요일 주소)를 주면 그 날짜가 든 주차로.
작은 달력은 월요일 시작 줄 그대로, 줄을 누르면 그 줄의 이 달 날짜가 든 주차(한 주차가 두 줄일 수 있음).
- **지난주** = 바로 앞 주차(`db.get_meeting` 이 `store.prev_week_period` 로 찾음) 회의록의 같은 연결키 줄.
- **위쪽 고정 영역**(`#pj-meet-top`, `.pj-meet-pane` 안 sticky): 왼쪽 절반 숫자 4칸 — **월 목표 매출**(목표 표, = 주차 목표 합) ·
- **머리 영역 3칸**(2026-10-07 개편, 아래 "위쪽 고정 영역" 설명을 대신함): 제목 줄 아래 `.pj-meet-board`(머리 `.pj-meet-headgrid` 안 —
`.pj-meet-pane` 밖이라 표를 스크롤해도 늘 보임, 칸 높이 230px·안에서 스크롤) = ① 월 계획(`router._month_plan`) + 머리 줄 오른쪽에
숫자 4개를 작게 1행(`.pj-meet-kpiline` — 월 목표 · 누적 목표 · 누적 실적 · 목표 대비, 클래스는 `.pj-meet-kpi` 그대로라 `meetRepaint` 가 갱신)
② 결정 사항·메모(`#pj-meet-notes`, 회의록이 있을 때) ③ **작업 등록 표**(`#pj-meet-quick`, `initMeetQuickTasks`): 제목 | 담당자 | 프로젝트 | 섹션 |
[적용]. 빈 칸을 누르면 `showContextMenu`(body) 목록 — 프로젝트 = `GET /api/projects` 의 최상위(내가 멤버인 것), 고르면 첫 섹션 자동,
담당자 = 그 프로젝트 멤버+소유자(`GET /api/projects/{id}/members`, 프로젝트 전이면 `PJ_MEET_MEMBERS`; 프로젝트를 바꿔 멤버가 아니면 비움),
섹션 = `GET /api/projects/{id}/stages`. [적용] = `POST /api/projects/{id}/tasks {title, stage_id, assignee_email}`(서버가 멤버·담당자 권한 검사)
→ 줄에 "등록됨" 링크(`/project/p/{id}?task=`) + 삭제(확인 뒤 `DELETE /api/tasks/{id}` — 그 프로젝트 작업도 삭제, 휴지통, 이미 없으면 줄만 지움),
적용 전 줄의 × = 줄만 지움. 줄(등록된 줄 포함)은 localStorage `pj_meet_quick:{이메일}`. 예전 `#pj-meet-top`(pane 안 sticky)은 없앴다.
- (예전) **위쪽 고정 영역**(`#pj-meet-top`, `.pj-meet-pane` 안 sticky): 왼쪽 절반 숫자 4칸 — **월 목표 매출**(목표 표, = 주차 목표 합) ·
**월 누적 목표 매출**(주차별 목표 1주차~이 주차 합, 원) · **월 누적 실적**(1일 ~ 오늘, 지난 주차면 그 주차 끝날 — 실적 모듈) ·
**누적 목표 대비 달성**(실적 − 누적 목표 차액 + 실적 ÷ 누적 목표 %) / 오른쪽 절반 **결정 사항·메모**(예전엔 표 아래).
표 머리 줄 sticky top = 이 영역 높이(`--pj-meet-top-h`, `initMeetTop` 의 ResizeObserver). 예전 9칸(주당 필요·목표 ROAS·전주 목표·
@@ -859,9 +883,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
`result_note` — 020, `.pj-meet-rnote` textarea, 0.8초 멈춤·칸 떠남 저장, 초안 `pj_draft:meet:item:{지난 줄}:result_note`) |
**전주 목표**(지난 주차 `target_amount`) | **결과**(금액, 지난 주차 `result_amount`). 020 미적용이면 결과 글 칸은 보기만, API 503.
- **주차별 매출 목표**(`goal_week_targets(week_start PK, year FK goal_years CASCADE, month, value NUMERIC)` — 목표 표 매출 단위 그대로):
연간 목표 표 매출 **목표** 월 칸(`data-weekly`, readonly)을 누르면 그 달 주차 입력 창(`.pj-goal-wkpop`, body 에 붙음, 보기만 하는 사람은 값만).
`PUT /project/api/goals/{연도}/week-targets/{월} {weeks: {주차 시작일: 값|""}}`(관리자) → 저장 후 그 달 주차 합계를
`goal_metrics(sales, target)` 에 쓴다(모두 비면 월 목표도 지움). 020 미적용이면 예전처럼 월 칸 직접 입력.
연간 목표 표 매출 **목표** 월 칸(`data-weekly`, readonly)을 누르면 그 달 입력 창(`.pj-goal-wkpop`, body 에 붙음, 보기만 하는 사람은 값만).
맨 위 **월 전체 목표**(직접 입력) → 주차별 목표 → 맨 아래 **주차 합계**·**차이(월 목표 − 주차 합계**, + 주황 = 덜 나눔,
− 빨강 = 넘침, 0 초록). `PUT /project/api/goals/{연도}/week-targets/{월} {month: 월 목표|"", weeks: {주차 시작일: 값|""}}`
(관리자) → 주차 저장 + `goal_metrics(sales, target)` 에 `month` 그대로(빈값 = 지움, 주차 합계와 무관). `month` 가 없는 요청(예전
화면 캐시)만 주차 합계를 월 목표로. 020 미적용이면 예전처럼 월 칸 직접 입력.
- **020 마이그레이션**(`scripts/sql/project_db_020_meeting_periods.sql`, 멱등): ① `goal_meeting_items.result_note` ② `goal_meetings`
월요일 CHECK 제거 ③ `goal_week_targets` ④ 새 주차에 흡수된 월요일 회의록(1일이 토·일인 달의 2·3일 월요일 → 1일, 말일이 월·화인 달의
마지막 월요일 → 7일 전 월요일)을 옮김 — 옮길 자리에 회의록이 있으면 옮기지 않고 NOTICE. 이미 쓰던 9/28(월) 회의록은 9월 마지막 주차
@@ -874,6 +900,18 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
이름 `{월}월 {n}주차 ({기간})`(`router.meeting_board_title`), 첫 장의 제목·부제목 틀(TITLE 레이아웃)을 지우고 틀 없는 BLANK 한 장만.
파일 이름을 바꿔도 같은 보드, 휴지통에 버리면 다음에 새로 만든다. 인증은 Google 시트 설정 재사용 + Drive·Slides 범위
(`GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` 없으면 시트 토큰 — Drive·Slides 권한으로 재발급 필요, docs/DEPLOYMENT.md). DB 변경 없음.
- **회의록 누구나 수정 · 회의 완료 잠금**(마이그레이션 022, 2026-10-07): 회의록 만들기·머리 칸·줄 추가/삭제/이동·셀 이동/병합·줄 칸 API 가
`_require_admin` → `_require_user`(프로젝트 권한자 누구나). 회의록 삭제와 `POST /api/goals/meetings/{주차}/complete {done}`(회의 완료·완료 해제)만
Pro user 이상(2026-10-12, 예전 관리자). `goal_meetings.completed_at`·`completed_by` 가 있으면 잠금 — `db._check_meeting_open`(머리 칸·줄 추가·`_locked_meeting_items`)이
`store.MeetingLocked` → 409. 예외: 줄 칸 변경이 결과(`result_note`·`result_amount`·`status`)뿐이면 그 줄의 회의록이 아니라 **바로 다음 주차
회의록**(그 결과를 적는 회의)의 잠금을 본다. 화면은 `data-edit`(완료 전이면 누구나) 로 편집 도구를 켜고, Pro user 이상에게 [회의 완료]/[완료 해제],
완료면 "🔒 회의 완료" 표시. 022 전이면 완료 버튼 없음(`meeting.can_complete`).
- **알림 팝업**(2026-10-07): 나를 태그(mention)하거나 작업을 배정(assigned)받으면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(`initTaskAlerts`,
`.pj-alert-pop`, body 에 붙음) — [닫기] 전까지 남는다. 20초마다(창을 다시 볼 때 바로) `GET /api/notifications/alerts?after=본 것`(읽지 않은
mention·assigned 중 after 보다 새 것, 지금 볼 수 있는 작업만, 오래된 것부터 10). 본 것 = localStorage `pj_alert_seen:{이메일}`, 처음 쓰는 브라우저는
latest_id 를 기준으로 삼아 옛 알림을 한꺼번에 띄우지 않는다. 다른 탭에서 닫으면 storage 이벤트로 함께 닫힌다. 수신함 iframe 안에선 돌지 않는다.
- **섹션 색 없앰**(2026-10-07): 보드 섹션 머리는 모두 `#f3f3f3`(`STAGE_HEAD_BG`), 섹션 편집 창의 색 고르기 삭제(저장 때 color 를 보내지 않는다),
타임라인 줄 색은 프로젝트 색. DB 의 `project_stages.color` 값은 남아 있지만 화면에서 쓰지 않는다.
- **정량 목표·결과(금액)에 글**(마이그레이션 021, 2026-10-07): 입력이 숫자로 읽히면(`store.validate_meeting_amount` — 1,200,000 · 120만 ·
1.5억) 지금처럼 `target_amount`/`result_amount`(원 정수), 아니면(예: "20개", 100자까지) `target_text`/`result_text` 에 — 둘 중 하나만
채운다(숫자로 바꾸면 글은 비움). 화면·전주 목표는 글이 있으면 글, 없으면 쉼표 숫자. 021 전이면 글은 예전처럼 400(숫자 오류).
@@ -973,7 +1011,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
`client_token`) 한 요청으로, 댓글+첨부를 한 트랜잭션(`add_comment_with_attachments`)에 만든다. 빈 파일·20MB 초과가 하나라도
있으면 아무것도 만들지 않고 400 `detail.failed=[{index,name,reason}]` → 화면은 그 파일만 빨갛게 표시하고 입력·파일을 유지.
DB 실패면 방금 쓴 파일도 지운다. 글 댓글(`POST /comments`)은 본문 필수 — 예전 `has_attachment` 플래그는 받지 않는다.
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리, 단일 워커 기준).
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리 — 보장 범위는 6-15).
작업 창 댓글 목록도 댓글별 첨부(이미지 미리보기·파일명 다운로드, 이스케이프)를 보여 주고, 첨부 파일 목록엔 "댓글" 표시.
**마감 알림** — `add_reminder_notification`: 발송 기록(`task_reminders`)과 수신함 알림을 한 트랜잭션에. 알림 생성이 실패하면
@@ -1003,7 +1041,160 @@ SELECT t.id, t.title FROM tasks t JOIN project_stages s ON s.id = t.stage_id
교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다.
권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다).
## 6-11. PC 알림 프로그램 (마이그레이션 023, 2026-10-08)
웹 큰 팝업(`initTaskAlerts`)은 브라우저 탭이 보일 때만 뜬다. 브라우저가 뒤에 있어도 같은 알림을 PC 화면 위에 크게 띄우는
Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Framework 4.8 WinForms, exe 하나). 빌드·배포·백신 주의는
`desktop/notifier/README.md`.
- **연결(토큰)**: 브라우저 쿠키를 쓸 수 없어 PC마다 토큰. ① 프로그램 `POST /project/api/notifier/link/start {device}`(로그인
없음 → 화면 코드 `XXXX-XXXX` + poll 비밀값, 10분, 대기 200건 상한 429) → ② 브라우저 `/project/notifier?code=`(로그인 필요,
없으면 `/login?next=`)에서 PC 이름·코드 확인 후 [연결] = `POST .../link/approve {code}` → ③ 프로그램 `POST .../link/poll {poll}`
→ `pending`/`expired`/`ok`(토큰 **한 번만**). `notifier_links`·`notifier_tokens` 에는 poll·토큰 **SHA-256 만** 저장.
PC 쪽 토큰은 Windows DPAPI(현재 사용자)로 암호화해 `%APPDATA%\DBXNotifier\settings.json`.
- **알림**: `GET /project/api/notifier/alerts?after=` (`Authorization: Bearer`) — 웹 `/api/notifications/alerts` 와 같은
`_alerts_payload`(태그·배정, 읽지 않은 것, 지금 볼 수 있는 작업만) + `name`. 토큰마다 **지금** 사용자 레코드·`project` 권한을
다시 확인(해제·권한 회수 = 401 → 프로그램이 연결 끊김 안내). `POST .../alerts/{id}/read`, `POST .../logout`(토큰 해제).
- **프로그램 동작**: 20초마다 확인(절전 해제 시 바로). 처음 연결하면 최신 번호를 기준으로(옛 알림 몰아 띄우지 않음),
새 번호가 오면 마우스가 있는 화면 아래 가운데에 웹과 같은 모양의 큰 창(맨 위, 포커스 안 뺏음, 보라↔주황 깜박임, 최대 6줄 +
"외 N건 더") + 알림 소리. [열기] = 기본 브라우저로 작업 + 읽음, [닫기] = 그 번호까지 본 것으로(PC 설정 `last_seen`).
웹에서 읽은 알림은 다음 확인 때 창에서 빠진다. 웹 팝업의 "본 것"(localStorage)과는 따로다.
- **화면** `/project/notifier`(수신함 머리의 [PC 알림] 버튼으로 들어감, 사이드바는 수신함 활성): 연결 승인 카드, 설치 안내, 내 연결된 PC 목록·[연결 해제]
(`POST /project/api/notifier/devices/{id}/revoke`). 내려받기 `GET /project/notifier/download` = 서버
`DATA_DIR/notifier/DBXNotifier.exe`(컨테이너 `/data/notifier/`) — 파일이 없으면 버튼 대신 "관리자에게 받으세요".
- **웹 팝업 쉬기**: 그 사용자의 PC 알림 프로그램이 돌고 있으면(해제 안 된 토큰 중 `last_seen_at` 3분 안 — `st.notifier_active`)
웹 `/api/notifications/alerts` 는 알림 없이 `latest_id` + `desktop: true` 만 준다. 웹은 그 번호까지 본 것으로 두므로, 프로그램을 끄면
3분쯤 뒤 그 뒤에 온 알림부터 웹 팝업이 다시 뜬다. 사용자 단위(어느 PC 에서 켰든 모든 브라우저 팝업이 쉼). 확인 실패면 웹 팝업 그대로.
- 023 미적용이면 화면은 안내만, notifier API 는 503.
## 6-12. 아사나 아이콘 · 색 12열 · 섹션 굵게 · 전체 보기 메뉴 · 설명란 글자 색/크기 (2026-10-08, 마이그레이션 없음)
- **프로젝트 색상표** 12칸씩(32색 = 3줄). **아이콘** 머리 "아이콘" 오른쪽 탭 [기본 아이콘](`PROJECT_ICONS`, 외곽선) /
[아사나 아이콘](`PROJECT_ASANA_ICONS` 33개, 채워진 모양). 아사나 아이콘 값은 `"asana:" + 이름`(`projects.icon` TEXT 그대로),
`validate_project_icon` 이 두 목록만 허용. 채워진 모양은 그 33개만 담은 글꼴
`static/vendor/material-symbols/material-symbols-asana.woff2`(Google Fonts `FILL 1` + `icon_names=` 부분 글꼴, 약 6KB) —
`.material-symbols-outlined.pj-ic-asana`. 목록을 늘리면 글꼴도 그 이름들로 다시 받는다. 그리는 곳: `projIconSpan`(JS)·
`_side.html`·`project.html` 제목 알약.
- **섹션 이름 굵게**(보드 `.pj-col-name`, 목록 묶음 `.pj-list-group-name`, 이름 바꾸기 칸).
- **전체 보기**: 프로젝트 화면 오른쪽 위 범위 토글(`#pj-scope-toggle`)은 숨기고, 왼쪽 메뉴 수신함 아래 **전체 보기**(Pro user 이상,
`#pj-side-allview`) — 지금 프로젝트(없으면 목록 첫 활성 프로젝트) `/project/p/{id}?scope=all`. 프로젝트 화면에서는 새로고침 없이
`applyAllScope(true)`. `?scope=all` 은 `data-is-pro` 일 때만 따른다. 이 프로젝트로 돌아가기 = 왼쪽 목록에서 프로젝트.
- **수신함 작업 창**: [확인]으로 연 오른쪽 작업 창은 왼쪽 수신함 영역(`.pj-inbox-view`)을 누르면 닫힌다(메뉴·모달·알림 팝업 제외).
- **설명란 글자 색·크기**: 서식 도구 [글자 색](10색, 기본)·[글자 크기](작게 12px·보통·크게 18px·더 크게 22px·제목 28px).
`execCommand` 가 만든 `<font>` 를 바로 `<span style>` 로 바꾸고, 서버 `sanitize_description_html` 은 평범한 span 의 style 에서
`color`(#hex·rgb()) 와 `font-size`(`DESC_FONT_SIZES`)만 다시 조립해 남긴다(`desc_inline_style`). 멘션 칩·다른 태그의 style 은 버림.
## 6-13. 수신함 줄 클릭 · 용어 · 회의록 보드 링크 복사 (2026-10-08, 마이그레이션 없음)
- **수신함**: `inbox_page` 는 읽지 않은 알림(`unread_only`)·확인 안 한 태그(`unread_mentions`)만. [확인] 버튼 없음 — 줄(`data-href`,
`data-task-id`)을 누르면 `initInboxTaskPanel` 이 같은 작업의 줄(태그·알림)을 모두 확인(`POST /api/mentions/read {task_id}`,
`POST /api/notifications/{id}/read`)하고 오른쪽 iframe 작업 창을 연다. 다른 줄을 고르거나 창을 닫으면 앞서 확인한 줄은 목록에서
빠진다(빈 목록이면 "없습니다"). 오른쪽 클릭 = 열지 않고 확인. [태그 모두 확인]·[알림 모두 읽음] = 그 목록을 비운다.
- **용어**: 프로젝트 모듈 화면 글자 "하위 작업" → **"세부 작업"**, "작업 추가" → **"메인 작업 추가"**(세부 작업 추가는 그대로).
대시보드 담당자별 막대 이름 "메인 작업"·"세부 작업".
- **담당자별 작업 합계 — 세부 작업의 세부 작업까지**: `list_subtasks_of` 가 재귀 CTE 로 모든 단계(깊이 20 까지)를 돌려주고
`root_task_id`(맨 위 메인 작업)·`parent_title`(바로 위 작업) 을 붙인다. 화면은 `root_task_id` 가 이 범위 메인 작업이면 센다.
- **회의록 보드 링크 복사**: [회의록 보드] 오른쪽 🔗(`#pj-meet-board-copy`) — 같은 `POST …/board`(없으면 만든다)로 주소를 받아
클립보드에(실패하면 주소 창). 한 번 받은 주소는 그 화면에서 다시 쓴다.
## 6-14. 관리자 등급 4단계 — 수퍼관리자 · Admin · Pro user · User (2026-10-12, 마이그레이션 없음)
- **등급**: 사용자 레코드 `role` 이 `admin` / `pro` / `user`(`app.store.ROLES`, 관리자 페이지 등급 선택 — 표시 Admin · Pro user · User).
수퍼관리자는 role 이 아니라 `SUPER_ADMIN_EMAIL` 한 명(고정, 등급 변경·삭제·추가 불가). `pro` 는 **프로젝트 모듈에서만** 권한이
늘고, 그 밖(관리자 페이지·다른 모듈·`is_admin`)에서는 `user` 와 같다. 모듈 칩 기본값도 user 처럼 전부 꺼짐.
- **판단 함수**(`access.py`): `role_of` · `is_pro`(수퍼관리자·Admin·Pro user) · `is_project_admin`(수퍼관리자·Admin).
라우터 `_require_pro`(예전 `_require_admin` 자리 전부), 화면 값 `_role_ctx(user)` → `is_admin`(ERP 상단 관리자 메뉴용, 그대로) ·
`pj_pro` · `pj_admin`. 템플릿의 프로젝트 기능 버튼은 `pj_pro`, 마크업은 `data-is-pro`·`data-is-padmin`(사이드바·프로젝트·내 작업),
목표 표·회의록은 `data-pro`.
- **프로젝트 보기는 여전히 멤버·owner 만**(관리자도 마찬가지, 수퍼관리자만 전체 — 6-10). 아래 Pro user 권한도 멤버인 프로젝트 안에서만.
| 프로젝트 | Admin | Pro user | User | 서버 |
| --- | --- | --- | --- | --- |
| 프로젝트 보기, 작업·섹션 만들기·고치기·옮기기 | O | O | O | `_require_manage` |
| 작업 삭제(휴지통) | O | O | O | 멤버면 누구나 — 생성자 검사 없앰 |
| 섹션 삭제 | O | 만든 사람만 | 만든 사람만 | `_can_delete` (기록 없는 옛 섹션 = Admin 이상) |
| 서브프로젝트 만들기 | O | O | O | `_require_manage` |
| 새 프로젝트 만들기 | O | O | X | `POST /api/projects` → `_require_pro` |
| 프로젝트 이름·색·아이콘·날짜·완료 수정, 소유자 바꾸기 | O | O | X | `PUT /api/projects/{id}` → `_require_pro` + 멤버 |
| 프로젝트 삭제 | O | 만든 사람만 | 만든 사람만 | `_can_delete` + 멤버 |
| 멤버 배정·제외(+ 배정 후보 목록) | O | O(멤버인 프로젝트) | X | `_require_pro` + `_require_manage` |
| 사이드바 프로젝트 순서 | O | O | X | `PUT /api/projects/order` |
| 댓글 수정·삭제 / 댓글에 파일 붙이기 | O | 남의 것도 | 본인만 | `update_comment`·`delete_comment(is_admin=is_pro)` |
| 휴지통 보기·복구 | O | O | X | `/trash`·`/api/trash/{id}/restore` |
| 전체 보기 | O | O(멤버 범위) | X | 화면 `isPro` (`?scope=all` 도 isPro 일 때만) |
| 대시보드 담당자별 작업 합계 | O | O | X(안 보임) | `GET …/subtasks-summary` → `_require_pro` |
| 사이드바 전체 멤버 | O | O | X | 화면 `pj_pro` |
| 수신함·내 작업·PC 알림 | O | O | O(자기 것) | 변화 없음 |
| 목표·주간 회의록 | Admin | Pro user | User |
| --- | --- | --- | --- |
| 연간 목표 표 보기 | O | O | O |
| 목표 표 입력·구조 변경(매출·로아스, 영역·줄, 칸 병합·이동), 주차별·월 매출 목표, 연도 추가·삭제 | O | O | X |
| 회의록 만들기·글 수정·줄 추가·삭제·칸 병합(완료 전까지), 지난주 결과(다음 주 회의록이 열려 있는 동안) | O | O | O |
| 회의 완료·완료 해제, 회의록 삭제 | O | O | X |
| 회의록 보드 열기·링크 복사 | O | O | O |
| 회의록 작업 등록 표로 작업 만들기 | 멤버인 프로젝트만 | 멤버인 프로젝트만 | 멤버인 프로젝트만 |
- 회의록 표 첫 열 머리 글자 "구역" → **"구분"**(화면 글자만, 데이터·코드의 section 이름은 그대로).
- 테스트: `tests/test_project_roles.py`(DB 없이 등급별 API), `tests/test_project_module.py` 의 소유자·삭제 테스트를 새 규칙으로.
## 6-15. 검토 반영 — 권한·열기 경로·저장·동시성 (2026-10-12, 마이그레이션 없음)
권한 정책(6-14 표)은 그대로 두고, 그 정책이 새던 곳을 막았다. 테스트 `tests/test_project_review_fixes.py`(DB 없이),
`tests/test_project_meeting_lock.py`·`test_project_alerts_api.py`, `tests/js/project_ui.test.js` 의 [검토 *] 항목.
- **서브프로젝트 작업**: `GET /api/projects/{id}/tasks`(하위 프로젝트까지 재귀)는 작업마다 지금 권한으로 다시 거른다
(`access.filter_visible_tasks`) — 부모 멤버라고 멤버가 아닌 자식 프로젝트 작업이 보이지 않는다. 연결된 작업의 READ 는 그대로.
(이 API·`POST /subprojects` 는 지금 화면에서 부르지 않는다 — 외부 호출 호환 때문에 남겨 둠.)
- **사이드바 순서** `PUT /api/projects/order`: Pro user 이상 + 보낸 id **전부** 지금 관리할 수 있는 프로젝트여야(없는 id 도 같은 403,
하나라도 아니면 아무것도 안 바뀜). 빈 목록·정수 아님(참/거짓·소수·글자)·0 이하·중복 = 400. 순서는 예전처럼 모두가 같이 보는 순서.
- **작업 열기 경로 하나로**: 수신함 줄·웹 큰 팝업·PC 알림 [열기] = `/project/t/{task_id}`(공유 링크). 서버(`_task_open_project`)가
지금 권한으로 열 프로젝트를 고른다 — FULL 이면 원 소속, READ 면 내가 볼 수 있는 연결된 프로젝트. `?embed=1` 은 옮긴 주소에도
붙는다(수신함 iframe). 알림 응답에 `href` 가 붙는다. 예전 주소 `/p/{원 소속}?task=` 로 READ 사용자가 오면 403 대신 연결된
프로젝트로 보낸다(옛 PC 알림 프로그램·북마크). 작업 없는 프로젝트 알림은 예전처럼 `/p/{id}`.
- **보관·서브프로젝트 화면**: `project_page`·스냅샷(scope=all)·담당자별 합계(scope=all)는 같은 범위(`_view_scope`) — 활성 최상위
멤버 프로젝트 + **지금 연 프로젝트 하나**(보관됐거나 서브프로젝트여서 목록에 없을 때만). 다른 보관 프로젝트는 읽지 않는다. 그
프로젝트 메타는 `view_only: true` 로 와서 사이드바 목록엔 그리지 않는다(작업 권한 판단·타임라인 그룹용).
- **전체 보기**: 작업마다 한 행 — 원 소속 행이 있으면 그것, 원 소속을 볼 수 없어 연결된 프로젝트 행(READ)만 있으면 그중 첫 행
(`scopeTasks`). 예전엔 원 소속 행만 남겨 이런 작업이 빠졌다. 사용자별 작업 팝업(`/api/users/tasks`, 전체 대상)도 같은 기준(READ 포함).
- **큰 팝업 알림**(`_alerts_payload`, 웹·PC 공용): 수신자·읽지 않음·종류(태그·배정)·`id > after` 를 DB 에서 먼저 걸고
(`list_unread_after`) **오래된 것부터** 200건씩 넘기며 지금 볼 수 있는 것 10건을 모은다(한 번에 최대 25쪽 = 5,000행).
예전엔 최신 50건을 자른 뒤 걸러 — 배정 뒤 댓글 알림 50건, 배정 60건 이상, 볼 수 없는 알림이 앞을 채우면 팝업이 빠졌다.
기준점(`latest_id`)·처음 연결 때 옛 알림 안 띄움·PC 프로그램이 돌면 웹 팝업 쉼은 그대로.
- **수신함 오른쪽 작업 창**: 다른 줄로 바꾸거나 닫기(Esc·바깥 클릭·모두 확인·프로젝트 알림 이동) 전에 iframe 안 작업 창의
`window.__pjEmbedSettle()` 을 기다린다 — 작업 창 닫기와 같은 절차(업로드·만들기·저장 대기 → 실패 칸 재시도 → "버리고 넘어가기 /
계속 편집"). 계속 편집이면 창·입력·선택 그대로, 새 줄은 확인하지 않는다. 바꾸기는 한 번에 하나, 마지막 요청만(A→B→A·저장 중
Esc 연타). beforeunload 경고에 기대지 않는다. 읽음/확인은 **서버가 받았을 때만** 확인으로 두고(실패면 굵게 남기고 알림), 확인된
줄만 목록에서 뺀다. `POST /api/mentions/read` 는 006 미적용(표 없음)만 0건 성공, 그 밖의 DB 오류는 실패로 돌려준다.
- **일반 첨부**(`POST /api/tasks/{id}/attachments`): DB 저장이 실패하면 이 요청이 쓴 파일(새 uuid 이름)만 지운다. 크기·빈 파일·
권한·inline 정책은 그대로.
- **새 프로젝트 창**: ① 생성(한 번만) ② 멤버 배정(사람마다)을 나눠 안내 — 배정 실패면 창을 닫지 않고 실패한 멤버를 빨갛게,
[실패한 멤버 다시 배정]은 그 멤버만(프로젝트를 또 만들지 않음). 진행 중 연타 무시, 진행 중 닫아도 요청은 끝까지 가고 결과는 알림.
만든 프로젝트를 되돌리려고 지우지 않는다.
- **배지 개수**: 내 작업(`list_my_open_refs`)·수신함 태그(`list_unread_mention_refs`)·읽지 않은 알림(`list_unread_refs`)은 가벼운 열만
제한 없이 읽어 지금 권한으로 센다(예전 1000·1000·500건 상한). 내 작업 목록은 **미완료 전부** + 최근 완료 1000건
(`list_my_tasks(completed_limit=)`) — 오래된 완료가 새 미완료를 밀어내지 않는다.
- **동시성**: `update_task` 는 기존 값 읽기·섹션 확인·기본 담당자·완료 섹션 여부·최종 날짜 검사·변경·이력을 한 트랜잭션에서 그
작업 행을 잠그고(`FOR UPDATE`) 같은 연결로 한다 — 시작일·마감일을 동시에 바꿔도 역전되지 않고, 동시 완료의 완료 이력·알림은 실제로
바뀐 한 요청에서만. `update_project` 날짜 검사도 행 잠금 뒤. (한 창 저장 직렬화와 별개 — 여러 사람 사이의 충돌 방지.)
- **회의록**: 머리(메모·참석자·금주 목표) 수정은 그 회의록 행을 잠그고 완료 여부를 본다([회의 완료]도 같은 행을 잠근다). 결과 칸만
고칠 때(`_check_result_open`): 다음 주차 회의록이 **있으면** 그 회의록이 열려 있을 때만, **없으면** 그 주 회의록이 열려 있을 때만
(예전엔 다음 회의록이 없으면 완료된 주의 결과도 고칠 수 있었다). 다음 주차 = `week_period` 끝 + 1일(달이 바뀌어도, 월요일이 아닌
시작일도). 다음 회의록 행은 `FOR SHARE` — 잠금 순서는 늘 주차 오름차순(교착 없음).
- **소유자를 남으로 정해 만들기**: 만든 사람을 같은 트랜잭션에서 **일반 멤버 행**으로 넣는다(`create_project(member_emails=)`) —
`created_by` 로 권한을 주지 않으니 나중에 멤버에서 빼면 권한도 없어진다. 소유자 변경 뒤 옛 소유자 권한 회수도 그대로.
- **중복 방지 키**(`_once`, 댓글 `client_token`): 키별 잠금을 쓰는 요청 수로 관리해 0 이 되면 바로 뺀다(실패한 키도) — 결과를 먼저
저장한 뒤 잠금을 풀어 기다리던 요청은 결과로 답한다. 실패하면 다음 요청이 새로 만든다(재시도). **보장 범위: 웹 프로세스 하나**
— 지금 운영은 web 컨테이너 1개·uvicorn 워커 1개(Dockerfile). 워커·컨테이너를 늘리면 다른 워커로 간 재전송은 막지 못하고 재시작하면
기록도 사라진다(그때는 DB UNIQUE 키가 필요).
- **섹션 기본 담당자**: 자동 배정 전에 그 사람이 지금 등록된 project 권한 사용자인지도 본다(`_registered_project_user`, 사용자 목록만 —
잠근 트랜잭션 안에서 DB 연결을 더 빌리지 않음). 기본 담당자 지정도 같은 기준. 협업자 추가는 담당자 후보와 같은 `access.can_assign`
(예전엔 관리자는 멤버가 아니어도 넣을 수 있었다).
정책 결정이 필요한 것(바꾸지 않음): 배정·완료 **메일**은 `PROJECT_NOTIFY_EMAIL`(없으면 Admin 전원)에게 프로젝트·작업 제목·담당자가
간다 — 화면에선 비멤버 Admin 이 그 프로젝트를 못 보지만 메일로는 제목을 받는다(4장 관리자 보고 정책).
## 7. 추후 단계
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩,
아사나도 UI상 1단계만 허용해 현재 의도적으로 안 함).
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성.
(세부 작업의 세부 작업은 2026-10-08 부터 지원 — 6-13 담당자별 합계 참고.)
+4
View File
@@ -39,6 +39,10 @@
`admin` 역할은 모든 권한 자동 부여. 신규 사용자는 관리자 페이지(`/admin`)에서 이메일만으로 등록 가능.
관리자 등급(2026-10-12): **수퍼관리자**(`SUPER_ADMIN_EMAIL` 한 명 고정 — 변경·삭제·추가 불가) > **Admin**(`role=admin`) >
**Pro user**(`role=pro`) > **User**(`role=user`). Pro user 는 Project 모듈(프로젝트·목표·주간 회의록)에서만 권한이 늘고
(`app/modules/project/access.py`, 표는 `docs/PROJECT_MODULE.md` 6-14), 다른 모듈·관리자 페이지에서는 User 와 같다.
---
## 모듈 디렉토리 규약
+9 -1
View File
@@ -18,6 +18,13 @@
마지막에 출력되는 refresh token 을 서버 `.env` 의
`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 에 넣는다(시트·회의록 보드가 같이 쓴다).
400 redirect_uri_mismatch 가 나오면
- 쓰는 OAuth 클라이언트가 "웹 애플리케이션" 유형이면 승인된 리디렉션 URI 에 **http://localhost:18765/** 를 추가하고
(끝 / 포함, 반영까지 몇 분) 다시 실행한다. 포트를 바꾸면(--port N) 그 주소(http://localhost:N/)를 등록해야 한다.
- "데스크톱 앱" 유형 클라이언트는 등록 없이 된다.
- refresh token 은 발급한 클라이언트 ID 에 묶인다 — 서버 .env 의 GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET
(없으면 GOOGLE_CLIENT_ID/SECRET)이 여기서 쓴 클라이언트와 같아야 한다.
주의
- 출력된 refresh token 은 비밀값이다. Git·메신저에 남기지 말 것.
- 토큰은 발급한 사용자 권한으로 동작한다. 그 사용자가 대상 문서를 편집할 수
@@ -45,7 +52,8 @@ def main() -> int:
"--client-secret", default=os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET", "")
)
parser.add_argument(
"--port", type=int, default=0, help="로컬 콜백 포트(기본: 임의 포트)"
"--port", type=int, default=18765,
help="로컬 콜백 포트(기본 18765 — 웹 애플리케이션 클라이언트면 http://localhost:18765/ 를 리디렉션 URI 로 등록)"
)
args = parser.parse_args()
@@ -0,0 +1,18 @@
-- =====================================================================
-- project_db 마이그레이션 022 — 주간 회의록 "회의 완료"(수정 잠금)
-- =====================================================================
-- 멱등(idempotent). 열만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
--
-- 왜(2026-10-07 사용자 요청): 주간 회의록은 프로젝트 권한이 있는 누구나 고칠 수 있고, 관리자가 [회의 완료]를 누르면
-- 그 회의록은 더 고칠 수 없다(관리자는 [완료 해제]로 다시 열 수 있다).
-- completed_at 이 있으면 완료. 지난주 결과(글·금액)는 다음 주 회의록이 열려 있는 동안만 고칠 수 있다.
-- =====================================================================
BEGIN;
ALTER TABLE goal_meetings ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ NULL;
ALTER TABLE goal_meetings ADD COLUMN IF NOT EXISTS completed_by TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN goal_meetings.completed_at IS '회의 완료 시각 — 있으면 이 회의록은 수정 잠금(관리자만 완료·해제)';
COMMENT ON COLUMN goal_meetings.completed_by IS '회의 완료를 누른 관리자 이메일';
COMMIT;
SELECT 'project_db 022 meeting complete ready' AS status;
+44
View File
@@ -0,0 +1,44 @@
-- =====================================================================
-- project_db 마이그레이션 023 — PC 알림 프로그램(DBX 알림) 연결
-- =====================================================================
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
--
-- 왜(2026-10-08 사용자 요청): 웹브라우저가 뒤에 있어도 태그·작업 배정 알림을 PC 화면 위에 크게 띄우는
-- 트레이 프로그램(desktop/notifier). 브라우저 세션(쿠키)을 쓸 수 없으므로 PC마다 연결 토큰을 발급한다.
-- ① 프로그램이 연결 요청(notifier_links: 화면 코드 + 확인용 poll 비밀값) → ② 사용자가 브라우저(로그인 상태)에서
-- 코드를 확인하고 [연결] → ③ 프로그램이 poll 로 토큰을 한 번 받는다(notifier_tokens). 토큰·poll 값은 원문을
-- 저장하지 않고 SHA-256 해시만 저장한다. 연결 해제 = revoked_at.
-- =====================================================================
BEGIN;
CREATE TABLE IF NOT EXISTS notifier_links (
id BIGSERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE, -- 화면에 보이는 짧은 코드(예: K7QM-4XPA)
poll_hash TEXT NOT NULL UNIQUE, -- 프로그램만 아는 poll 비밀값의 SHA-256
device_name TEXT NOT NULL DEFAULT '',
email TEXT NULL, -- [연결]을 누른 사용자(승인 전 NULL)
approved_at TIMESTAMPTZ NULL,
consumed_at TIMESTAMPTZ NULL, -- 토큰을 내준 시각(한 번만)
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_notifier_links_expires ON notifier_links (expires_at);
COMMENT ON TABLE notifier_links IS 'PC 알림 프로그램 연결 요청 — 10분 유효, 승인 후 토큰 1회 발급';
CREATE TABLE IF NOT EXISTS notifier_tokens (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE, -- 토큰 원문의 SHA-256
device_name TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_seen_at TIMESTAMPTZ NULL,
revoked_at TIMESTAMPTZ NULL
);
CREATE INDEX IF NOT EXISTS idx_notifier_tokens_email ON notifier_tokens (email);
COMMENT ON TABLE notifier_tokens IS 'PC 알림 프로그램 토큰 — 사용자·PC 단위, revoked_at 이면 해제';
GRANT SELECT, INSERT, UPDATE, DELETE ON notifier_links, notifier_tokens TO project_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
COMMIT;
SELECT 'project_db 023 notifier ready' AS status;
+13
View File
@@ -60,3 +60,16 @@ python -m unittest discover -s tests -p test_project_meeting_cells.py
`PROJECT_TEST_DB_URL`에 기존 로컬 테스트 DB를 지정해야 하며, 미설정 또는 로컬 주소가 아니면 건너뛴다.
회의록 셀 테스트는 DB 연결을 대신하는 트랜잭션 모형으로 실제 저장소 메서드·API 권한/충돌·이동/병합 롤백·
019 미적용·병합 행 작업 보호·서식 보존·안전한 템플릿 출력을 검증한다. 실제 PostgreSQL 잠금 동작 검증은 별도다.
# 프로젝트 화면·수신함 UI 테스트 (jsdom + 실제 Chrome)
`project.html`·`inbox.html` + `static/project.js` — 작업 창 저장/실패/동기화, 전체 보기의 연결된(읽기 전용) 작업,
수신함 오른쪽 작업 창(저장 대기 뒤 바꾸기·계속 편집·A→B→A·저장 중 Esc·읽음 실패), 새 프로젝트 창(생성/멤버 배정 결과 분리·
실패한 멤버만 다시 배정·연타)을 가짜 서버로 검증한다.
```powershell
python tests/js/render_project.py # → tests/js/.out/project_*.html · inbox_render.html
node tests/js/project_ui.test.js # jsdom
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉트 뒤 embed·저장 실패 확인창·A→B→A·iframe 안 Esc·읽음 실패
```
+6 -33
View File
@@ -463,47 +463,20 @@ const server = http.createServer(function (req, res) {
console.log("PASS merged meeting rowspan, independent numeric cells and both column orders");
const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
let releaseMove, startedMove;
const moveGate = new Promise(function (resolve) { releaseMove = resolve; });
const moveStarted = new Promise(function (resolve) { startedMove = resolve; });
const moveRequests = [];
await interactive.route("**/project/api/**", async function (route) {
const request = route.request();
if (request.url().endsWith("/goals/cells/move")) {
const payload = request.postDataJSON(); moveRequests.push(payload); startedMove();
await moveGate;
await route.fulfill({ json: { ok: true, body: payload.body } });
} else await route.fulfill({ json: { ok: true } });
});
await interactive.route("**/project/api/**", function (route) { return route.fulfill({ json: { ok: true } }); });
await interactive.addInitScript(function () {
localStorage.setItem("pj_goal_col_w", JSON.stringify({ y: 240, m1: 240, m2: 240 }));
});
await interactive.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026");
const sourceCell = interactive.locator('tr[data-row-id="10"] td[data-month="1"]');
const targetCell = interactive.locator('tr[data-row-id="11"] td[data-month="2"]');
await sourceCell.locator(".pj-goal-text").evaluate(function (editor) {
// 연간 목표 셀 끌어서 이동은 2026-10-07 요청으로 없앴다 — 이동 테두리가 없어야 한다
await sourceCell.locator(".pj-goal-text").click();
assert.equal(await interactive.locator("#pj-goal-table .pj-goal-move-edge").count(), 0);
await targetCell.locator(".pj-goal-text").evaluate(function (editor) {
editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "드래그 이동", bold: true, italic: true, underline: true, size: 24, color: "#ff0000" }]);
});
await sourceCell.locator(".pj-goal-text").click();
const edge = await sourceCell.locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox();
const dest = await targetCell.boundingBox();
await interactive.mouse.move(edge.x + edge.width / 2, edge.y + edge.height / 2);
await interactive.mouse.down();
await interactive.mouse.move(dest.x + dest.width / 2, dest.y + dest.height / 2, { steps: 6 });
assert(await targetCell.evaluate(function (td) { return td.classList.contains("is-goal-move-target"); }));
await interactive.mouse.up(); await moveStarted;
assert.equal(moveRequests.length, 1);
assert.equal(await sourceCell.locator(".pj-goal-text").textContent(), "드래그 이동");
assert.equal(await targetCell.locator(".pj-goal-text").textContent(), "");
releaseMove();
await interactive.waitForFunction(function () {
return document.querySelector('tr[data-row-id="10"] .pj-goal-text[data-month="1"]').textContent === "";
});
const moved = await targetCell.locator(".pj-goal-text").evaluate(function (editor) { return JSON.parse(editor.value.slice(11))[0]; });
assert.equal(moved.text, "드래그 이동"); assert.equal(moved.color, "#ff0000"); assert.equal(moved.size, 24);
assert(moved.bold && moved.italic && moved.underline);
assert.deepEqual(await targetCell.evaluate(function (td) { return [td.colSpan, td.rowSpan]; }), [1, 1]);
console.log("PASS actual mouse border drag, delayed atomic response, all text formats, unchanged cell geometry");
console.log("PASS goal cells have no drag-move borders");
await targetCell.click({ button: "right" });
await interactive.getByRole("menuitem", { name: "현재 열 너비 자동 맞춤" }).click();
+101 -63
View File
@@ -15,7 +15,7 @@ const ROOT = path.join(__dirname, "..", "..");
const OUT = path.join(__dirname, ".out");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
const PAGE = {};
["goals_admin", "goals_ro", "goals_weekly_admin", "meeting_admin", "meeting_err", "meeting_ro"].forEach(function (n) {
["goals_admin", "goals_ro", "goals_weekly_admin", "meeting_admin", "meeting_err", "meeting_ro", "meeting_member"].forEach(function (n) {
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
});
const GOALS_URL = "http://localhost/project/goals/2026";
@@ -427,10 +427,11 @@ function meetServer(env, st) {
rin.focus(); rin.value = "1200"; rin.blur();
await settle(); await wait(10); await settle();
check("[2d] 결과 숫자는 쉼표 표기(1,200)", st.items[902].result_amount === 1200 && rin.value === "1,200", rin.value);
check("[2d] 금주 목표 입력칸 없음(위쪽 숫자 4칸)", !env.d.getElementById("pj-meet-target") && env.d.querySelectorAll(".pj-meet-top .pj-meet-kpi").length === 4);
check("[2d] 금주 목표 입력칸 없음 · 숫자 4개는 월 계획 머리 줄에", !env.d.getElementById("pj-meet-target") &&
env.d.querySelectorAll(".pj-meet-plan-head .pj-meet-kpiline .pj-meet-kpi").length === 4 && !env.d.querySelector(".pj-meet-top"));
});
// ════════════════════ [2e] 주차별 매출 목표(020) — 매출 목표 칸 → 주차 입력 창(body), 저장하면 합계가 월 목표 ════════════════════
// ════════════════════ [2e] 주차별 매출 목표(020) — 매출 목표 칸 → 입력 창(body): 월 전체 목표 직접 입력 + 주차별 + 차이 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.goals_weekly_admin, GOALS_URL);
const st = goalsServer(env);
@@ -439,23 +440,32 @@ function meetServer(env, st) {
sent = body;
const weeks = {};
Object.keys(body.weeks).forEach(function (k) { weeks[k] = body.weeks[k]; });
return { body: { ok: true, value: 600, label: "600", weeks: weeks } };
return { body: { ok: true, value: Number(body.month), label: body.month, week_total: 600, weeks: weeks } };
});
await boot(env);
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
check("[2e] 매출 목표 칸은 직접 입력 아님(readonly)", inp.readOnly && inp.dataset.weekly === "1");
const before = inp.value;
inp.click();
const pop = env.d.body.querySelector(".pj-goal-wkpop");
const ins = pop ? Array.from(pop.querySelectorAll("input")) : [];
check("[2e] 창은 body 에, 1월 주차 수만큼 입력칸", !!pop && pop.parentElement === env.d.body && ins.length === 5, ins.length);
const month = pop && pop.querySelector("input[data-month-total]");
const ins = pop ? Array.from(pop.querySelectorAll("input[data-start]")) : [];
check("[2e] 창은 body 에, 월 전체 목표 칸 + 1월 주차 수만큼 입력칸", !!pop && pop.parentElement === env.d.body && !!month && ins.length === 5, ins.length);
check("[2e] 월 전체 목표 칸 = 지금 월 목표", month && month.value === before, { month: month && month.value, before: before });
check("[2e] 주차 날 수 표시(1월 1주차 1/1~1/4 = 4일)", pop.querySelector(".pj-goal-wkpop-days").textContent === "4일", pop.querySelector(".pj-goal-wkpop-days").textContent);
check("[2e] 저장된 주차 값·합계", ins[0].value === "100" && ins[1].value === "200" && pop.querySelector(".pj-goal-wkpop-sum b").textContent === "300");
const sumEl = pop.querySelector('[data-sum="weeks"]'), diffEl = pop.querySelector('[data-sum="diff"]');
check("[2e] 저장된 주차 값·주차 합계", ins[0].value === "100" && ins[1].value === "200" && sumEl.textContent === "300", sumEl.textContent);
type(env, ins[2], "300");
check("[2e] 입력하면 합계 다시 계산", pop.querySelector(".pj-goal-wkpop-sum b").textContent === "600");
check("[2e] 입력하면 주차 합계 다시 계산", sumEl.textContent === "600", sumEl.textContent);
type(env, month, "700");
check("[2e] 차이 = 월 목표 − 주차 합계(+ 남음)", diffEl.textContent === "+100" && diffEl.classList.contains("is-left"), diffEl.textContent);
type(env, month, "500");
check("[2e] 주차 합계가 넘으면 −", diffEl.textContent === "-100" && diffEl.classList.contains("is-over"), diffEl.textContent);
type(env, month, "700");
pop.querySelector('[data-act="save"]').click();
await settle(); await wait(10); await settle();
check("[2e] 주차별 값 전송(주차 시작일 키)", sent && sent.weeks["2026-01-12"] === "300" && Object.keys(sent.weeks).length === 5, sent);
check("[2e] 월 목표 칸 = 합계, 창 닫힘", inp.value === "600" && !env.d.body.querySelector(".pj-goal-wkpop"));
check("[2e] 월 목표·주차별 값 전송(주차 시작일 키)", sent && sent.month === "700" && sent.weeks["2026-01-12"] === "300" && Object.keys(sent.weeks).length === 5, sent);
check("[2e] 월 목표 칸 = 입력한 월 목표(주차 합계 아님), 창 닫힘", inp.value === "700" && !env.d.body.querySelector(".pj-goal-wkpop"), inp.value);
check("[2e] 월 목표 직접 저장 요청 없음", !st.metric);
});
@@ -482,6 +492,80 @@ function meetServer(env, st) {
check("[2f] 창을 슬라이드 주소로", popup.location.href === "https://docs.google.com/presentation/d/abc/edit" && popup.focused);
});
// ════════════════════ [2g] 머리 영역 3칸 — 결정 사항은 ②, 작업 등록 표(③): 칸 → 목록 → [적용] = 그 프로젝트에 작업 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
meetServer(env);
let posted = null;
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [
{ id: 7, name: "브랜드", parent_id: null, owner_email: "owner@test.local" }, { id: 8, name: "하위", parent_id: 7 }] } }; });
env.route("GET", /\/project\/api\/projects\/7\/members$/, function () { return { body: { members: [{ user_email: "kim@test.local" }] } }; });
env.route("GET", /\/project\/api\/projects\/7\/stages$/, function () { return { body: { stages: [{ id: 72, name: "진행", sort_order: 2 }, { id: 71, name: "할 일", sort_order: 1 }] } }; });
env.route("POST", /\/project\/api\/projects\/7\/tasks$/, function (u, body) { posted = body; return { status: 201, body: { ok: true, task: { id: 555 } } }; });
await boot(env);
const d = env.d, board = d.querySelector(".pj-meet-board");
check("[2g] 머리 영역: 월 계획 · 결정 사항 · 작업 등록", !!board && board.children.length === 3 &&
!!board.querySelector(".pj-meet-notes #pj-meet-notes") && !!board.querySelector("#pj-meet-quick"));
const tr = d.querySelector("#pj-meet-quick tbody tr");
const title = tr.querySelector("input[data-field=title]");
title.value = "상세페이지 수정"; title.dispatchEvent(new env.w.Event("input", { bubbles: true }));
const pickItem = async function (kind, label) {
d.querySelector('#pj-meet-quick tbody tr [data-pick="' + kind + '"]').click(); await settle(); await wait(5); await settle();
const items = Array.from(d.querySelectorAll(".pj-ctxmenu-item"));
const it = items.find(function (n) { return itemLabel(n) === label; });
if (it) it.click();
await settle(); await wait(5); await settle();
return items.map(itemLabel);
};
const projLabels = await pickItem("project", "브랜드");
check("[2g] 프로젝트 목록 = 최상위 프로젝트", JSON.stringify(projLabels) === JSON.stringify(["브랜드"]), projLabels);
const row = d.querySelector("#pj-meet-quick tbody tr");
check("[2g] 프로젝트 고르면 첫 섹션 자동", row.querySelector('[data-pick="stage"]').textContent === "할 일", row.querySelector('[data-pick="stage"]').textContent);
const people = await pickItem("assignee", "Kim");
check("[2g] 담당자 목록 = 그 프로젝트 소유자·멤버", people.indexOf("Owner") >= 0 && people.indexOf("Kim") >= 0, people);
d.querySelector('#pj-meet-quick tbody tr [data-quick="apply"]').click(); await settle(); await wait(5); await settle();
check("[2g] 적용 → 그 프로젝트에 작업 생성", posted && posted.title === "상세페이지 수정" && posted.stage_id === 71 && posted.assignee_email === "kim@test.local", posted);
check("[2g] 등록된 줄은 '등록됨' 링크", /등록됨/.test(d.querySelector("#pj-meet-quick tbody tr").textContent) &&
d.querySelector("#pj-meet-quick tbody tr a").getAttribute("href") === "/project/p/7?task=555");
// 등록된 줄 삭제 → 확인 → 그 프로젝트의 작업도 삭제(DELETE), 줄 사라짐
let deleted = null;
env.route("DELETE", /\/project\/api\/tasks\/555$/, function (u) { deleted = u; return { body: { ok: true } }; });
env.w.erpConfirm = function () { return Promise.resolve(true); };
const before = d.querySelectorAll("#pj-meet-quick tbody tr").length;
d.querySelector('#pj-meet-quick tbody tr [data-quick="delete"]').click(); await settle(); await wait(5); await settle();
check("[2g] 등록된 작업 삭제 → 프로젝트 작업 DELETE·줄 제거", !!deleted && d.querySelectorAll("#pj-meet-quick tbody tr").length === before - 1 &&
!d.querySelector("#pj-meet-quick tbody tr.is-done"), [deleted, before]);
// 적용 전 줄의 × = 줄만 지움(요청 없음)
const calls = env.calls.length, n = d.querySelectorAll("#pj-meet-quick tbody tr").length;
d.querySelector('#pj-meet-quick tbody tr [data-quick="remove"]').click(); await settle();
check("[2g] 적용 전 줄 × → 줄만 지움", d.querySelectorAll("#pj-meet-quick tbody tr").length === n - 1 && env.calls.length === calls);
}, { notifyOnFail: true });
// ════════════════════ [2h] 회의록은 누구나 수정 · [회의 완료](관리자)면 잠금 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_member, MEET_URL);
const st = meetServer(env);
await boot(env);
const d = env.d;
check("[2h] 직원도 회의록 입력칸·메모 편집", !!d.querySelector(".pj-meet-text") && !!d.getElementById("pj-meet-notes"));
check("[2h] 직원에겐 삭제·회의 완료 버튼 없음", !d.getElementById("pj-meet-del") && !d.getElementById("pj-meet-complete"));
const ta = d.querySelector('tr[data-item="1"] .pj-meet-text');
ta.focus(); type(env, ta, "직원이 적은 업무"); ta.blur(); await settle(); await wait(10); await settle();
check("[2h] 직원 입력 저장", st.items[1] && st.items[1].content === "직원이 적은 업무", st.items[1]);
});
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
meetServer(env);
let posted = null;
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/complete$/, function (u, body) { posted = body; return { body: { ok: true, completed: true } }; });
env.w.erpConfirm = function () { return Promise.resolve(true); };
await boot(env);
env.d.getElementById("pj-meet-complete").click(); await settle(); await wait(10); await settle();
check("[2h] 관리자 [회의 완료] → 완료 요청·새로고침", posted && posted.done === true && env.navigations === 1, [posted, env.navigations]);
const ro = makeEnv(PAGE.meeting_ro, MEET_URL); meetServer(ro); await boot(ro);
check("[2h] 완료된 회의록 — 입력칸 없음·완료 표시", !ro.d.querySelector(".pj-meet-text, #pj-meet-notes") && /회의 완료/.test(ro.d.querySelector(".pj-meet-done-badge").textContent));
});
// ════════════════════ [3] 목표 표 — 글 저장 실패면 구조 변경·표 교체 중단 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
@@ -565,9 +649,9 @@ function meetServer(env, st) {
meetServer(env, { page: PAGE.meeting_err });
await boot(env);
const kpi = Array.from(env.d.querySelectorAll(".pj-meet-kpi")).map(function (k) { return k.textContent.replace(/\s+/g, " ").trim(); });
const mtd = kpi.find(function (t) { return /월 누적 실적/.test(t); });
const mtd = kpi.find(function (t) { return /누적 실적/.test(t); });
check("[6] 월 누적 = 미확인(0원 아님)", /미확인/.test(mtd) && !/0원|0 원/.test(mtd), mtd);
check("[6] 누적 목표 대비 달성 = 미확인(차액·% 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /누적 목표 대비/.test(t); })));
check("[6] 누적 목표 대비 달성 = 미확인(차액·% 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /목표 대비/.test(t); })));
const row = env.d.querySelector('tr[data-item="1"]');
check("[6] 쇼핑몰 줄도 결과 = 직접 입력 칸(자동 결과 폐지)", !!row.querySelector(".pj-meet-c-result input") && !/미확인/.test(row.querySelector(".pj-meet-c-result").textContent));
check("[6] 줄별 이번주 실적 표시 없음 · 달성률 열 없음", !row.querySelector(".pj-meet-week-slot") && !row.querySelector("[data-rate]"));
@@ -752,58 +836,12 @@ function meetServer(env, st) {
menu(table.querySelector("th.pj-goal-area-name"));
check("[너비 메뉴] 구역 이름 편집 메뉴에도 맞춤 제공", !!action("색 바꾸기") && !!action("현재 열 너비 자동 맞춤"));
});
await section(async function () {
const gate = deferred(), env = makeEnv(PAGE.goals_admin, GOALS_URL);
const st = goalsServer(env, { moveHook: async function (body) { await gate.promise; return { body: { ok: true, body: body.body } }; } });
await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
type(env, source, "pj-rich:v1:" + JSON.stringify([{ text: "이동할 글", color: "#ff0000", size: 24, bold: true, italic: true, underline: true }]));
const original = source.value;
const drop = beginGoalMove(env, source, target);
check("[셀 이동] 대상 미리보기·일반 범위 선택과 분리", target.closest("td").classList.contains("is-goal-move-target") && env.d.documentElement.classList.contains("pj-goal-moving"));
drop(); await settle();
check("[셀 이동] 먼저 초안 저장·이동은 한 번·응답 전 원본 유지", st.moves === 1 && source.value === original && target.value === "" && source.getAttribute("contenteditable") === "false" && target.getAttribute("contenteditable") === "false");
const moveIndex = env.calls.findIndex(function (c) { return /cells\/move$/.test(c.url); });
check("[셀 이동] 글 PUT 뒤 원자적 이동 API", moveIndex > env.calls.findIndex(function (c) { return c.method === "PUT" && /rows\/10\/cells\/1$/.test(c.url); }));
gate.resolve(); await settle();
const run = JSON.parse(target.value.slice(11))[0];
check("[셀 이동] 성공 뒤 원본 비우기·대상 글과 모든 서식 보존", source.value === "" && run.text === "이동할 글" && run.color === "#ff0000" && run.size === 24 && run.bold && run.italic && run.underline);
const count = env.calls.length; fire(env, source, "blur"); fire(env, target, "blur"); await settle();
check("[셀 이동] 저장 기준값·초안 정리·후속 blur 중복 저장 없음", env.calls.length === count && !env.w.localStorage.getItem("pj_draft:goal:10:1") && source.getAttribute("contenteditable") === "true" && target.closest("td").classList.contains("is-goal-active"));
});
for (const failure of ["network", "conflict", "save"]) await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
const st = goalsServer(env, { moveHook: function () { return failure === "network" ? "NETWORK" : { status: 409, body: { detail: "다른 창에서 수정" } }; },
cellHook: failure === "save" ? function () { return { status: 503, body: { detail: "저장 장애" } }; } : null });
await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
if (failure === "save") type(env, source, "미저장 초안");
const before = source.value; beginGoalMove(env, source, target)(); await settle();
check("[셀 이동 " + failure + "] 실패해도 양쪽 내용·편집 가능 상태 유지", source.value === before && target.value === "" && source.getAttribute("contenteditable") === "true" && !env.d.documentElement.classList.contains("pj-goal-moving"));
check("[셀 이동 " + failure + "] 저장 실패면 이동 API 생략", failure !== "save" || !st.moves);
});
await section(async function () {
await section(async function () { // 연간 목표 셀 끌어서 이동 — 2026-10-07 요청으로 없앰(회의록 표 이동은 그대로)
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
target.value = "대상 기존 글"; let confirmations = 0;
env.w.erpConfirm = function () { confirmations++; return Promise.resolve(false); };
beginGoalMove(env, source, target)(); await settle();
check("[셀 이동] 덮어쓰기 취소는 두 내용 유지·이동 없음", confirmations === 1 && !st.moves && source.value === "original" && target.value === "대상 기존 글");
env.w.erpConfirm = function () { return Promise.resolve(true); };
beginGoalMove(env, source, target)(); await settle();
check("[셀 이동] 확인 뒤 덮어쓰기·원본 비우기", st.moves === 1 && source.value === "" && target.textContent === "original");
});
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
beginGoalMove(env, source, target); key(env, env.d, "Escape"); await settle();
check("[셀 이동] Esc 취소는 원본 유지·이동 요청 없음", !st.moves && source.value === "original" && !env.d.documentElement.classList.contains("pj-goal-moving"));
beginGoalMove(env, source, target); env.w.dispatchEvent(new env.w.Event("blur")); await settle();
check("[셀 이동] 창 포커스 이탈도 이동 취소·드래그 정리", !st.moves && !env.d.querySelector(".is-goal-move-target"));
beginGoalMove(env, source, source)(); await settle();
check("[셀 이동] 자기 셀에 놓기 = 변경 없음", !st.moves && source.value === "original");
const ro = makeEnv(PAGE.goals_ro, GOALS_URL); goalsServer(ro); await boot(ro);
check("[셀 이동] 보기 전용에는 이동 테두리 없음", !ro.d.querySelector(".pj-goal-move-edge"));
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
check("[셀 이동 없음] 연간 목표 글 칸에 이동 테두리 없음", !env.d.querySelector("#pj-goal-table .pj-goal-move-edge"));
source.closest("td").dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
check("[셀 이동 없음] 누르면 칸 표시만", source.closest("td").classList.contains("is-goal-active") && !st.moves);
});
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════
+134
View File
@@ -0,0 +1,134 @@
// 실제 브라우저 — 수신함 오른쪽 작업 창(iframe)이 다른 줄로 바뀌거나 닫히기 전에 작업 창의 저장을 기다리는지,
// 저장 실패면 작업 창과 같은 "버리고 넘어가기 / 계속 편집"을 묻는지, 공유 링크 리다이렉트 뒤에도 embed 인지,
// iframe 안 Esc·빠른 A→B→A·읽음 실패를 확인한다. 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
// python tests/js/render_project.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/inbox_panel.browser.test.js
const assert = require("node:assert/strict");
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
const { chromium } = require("playwright");
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
const detail = (id, title) => ({ id, title, project_id: 1, stage_id: 11, description: "", priority: "normal",
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null });
let putStatus = 200, holdPut = false, releasePut = null, failNotiRead = false;
const puts = [], reads = [];
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
if (url.pathname === "/project/inbox") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "inbox_render.html"))); return; }
const tm = /^\/project\/t\/(\d+)$/.exec(url.pathname);
if (tm) { // 공유 링크 — 서버(router.task_permalink)처럼 embed 를 이어서 보낸다
res.statusCode = 303;
res.setHeader("Location", `/project/p/1?task=${tm[1]}${url.searchParams.get("embed") === "1" ? "&embed=1" : ""}`);
res.end(); return;
}
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "project_render.html"))); return; }
if (url.pathname.startsWith("/project/api/")) {
let raw = ""; for await (const c of req) raw += c;
const body = raw ? JSON.parse(raw) : null;
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
if (task && req.method === "GET") return json(200, { task: detail(+task[1], "작업 " + task[1]) });
if (task && req.method === "PUT") {
puts.push({ id: +task[1], body });
if (holdPut) await new Promise(r => { releasePut = r; });
return putStatus >= 400 ? json(putStatus, { detail: "서버 오류" }) : json(200, { task: Object.assign(detail(+task[1], "작업"), body) });
}
if (url.pathname === "/project/api/mentions/read") { reads.push("m" + (body && body.task_id)); return json(200, { ok: true, marked: 1 }); }
const nr = /^\/project\/api\/notifications\/(\d+)\/read$/.exec(url.pathname);
if (nr) { reads.push("n" + nr[1]); return failNotiRead ? json(500, { detail: "db" }) : json(200, { ok: true }); }
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
return json(200, {});
}
if (url.pathname.startsWith("/static/")) {
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
if (file.startsWith(STATIC) && fs.existsSync(file)) {
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
res.end(fs.readFileSync(file)); return;
}
}
res.statusCode = 404; res.end("");
});
(async function () {
await new Promise(r => server.listen(0, "127.0.0.1", r));
const base = "http://127.0.0.1:" + server.address().port;
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } }); // 작업 창이 왼쪽 목록을 가리지 않는 보통 PC 화면
const dialogs = [];
let dialogAnswer = false;
page.on("dialog", async d => { dialogs.push(d.type() + ":" + d.message().slice(0, 20)); if (dialogAnswer) await d.accept(); else await d.dismiss(); });
const pass = [];
const ok = (name, cond, extra) => { assert.ok(cond, name + (extra === undefined ? "" : " → " + JSON.stringify(extra))); pass.push(name); console.log("PASS " + name); };
try {
await page.goto(base + "/project/inbox");
const frameOf = () => page.frames().find(f => f !== page.mainFrame());
const frameUrl = () => (frameOf() ? frameOf().url() : "");
const waitModal = async () => {
await page.waitForFunction(() => { const f = document.querySelector(".pj-inbox-panel iframe"); const d = f && f.contentDocument;
const m = d && d.getElementById("pj-modal-task"); return !!(m && !m.hidden && d.getElementById("pj-t-id").value); });
};
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
await waitModal();
ok("공유 링크 리다이렉트 뒤에도 embed 화면(작업 창만)", /\/project\/p\/1\?/.test(frameUrl()) && /embed=1/.test(frameUrl()) &&
await frameOf().evaluate(() => document.documentElement.classList.contains("pj-embed")), frameUrl());
ok("같은 작업의 태그·알림을 함께 확인", reads.includes("m101") && reads.includes("n901"), reads);
// ① 저장 실패 → 다른 줄 → 묻기 → 계속 편집: 창·입력 그대로
putStatus = 500;
const fr = frameOf();
await fr.fill("#pj-t-title", "작업 101 고침");
await fr.evaluate(() => document.getElementById("pj-t-title").blur());
await page.waitForTimeout(150);
dialogAnswer = false;
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
await page.waitForTimeout(400);
ok("저장 실패면 바꾸기 전에 묻고(작업 창과 같은 확인), 계속 편집이면 그대로", dialogs.length === 1 && /\?task=|\/p\/1/.test(frameUrl()) &&
await fr.evaluate(() => document.getElementById("pj-t-title").value) === "작업 101 고침" &&
!reads.includes("m102"), { dialogs, url: frameUrl(), reads });
// ② 저장 대기 중 A→B→A — 확인 뒤 A 그대로, 새 줄 안 열림
putStatus = 200; holdPut = true;
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
await page.waitForTimeout(150);
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
await page.waitForTimeout(100);
ok("저장이 끝나기 전엔 창을 바꾸지 않는다", frameOf() === fr && releasePut !== null);
holdPut = false; releasePut(); releasePut = null;
await page.waitForTimeout(500);
ok("A→B→A 빨리 — 저장 성공 뒤 A 작업 창 그대로(다시 읽지 않음)", frameOf() === fr &&
await fr.evaluate(() => document.getElementById("pj-t-id").value) === "101" && puts[puts.length - 1].body.title === "작업 101 고침" &&
!reads.includes("m102"), { puts: puts.length, reads });
// ③ 저장 성공 상태에서 B → 바로 바뀌고 이탈 경고 없음
const before = dialogs.length;
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
await waitModal();
await page.waitForFunction(() => document.querySelector(".pj-inbox-panel iframe").contentDocument.getElementById("pj-t-id").value === "102");
ok("저장된 상태면 묻지 않고 B 로(beforeunload 경고도 없음)", dialogs.length === before && reads.includes("m102"), dialogs);
// ④ iframe 안 포커스에서 Esc — 작업 창이 닫히며 패널도 닫힘, 확인한 줄은 목록에서 빠짐
const fr2 = frameOf();
await fr2.focus("#pj-t-title");
await page.keyboard.press("Escape");
await page.waitForFunction(() => !document.querySelector(".pj-inbox-panel").classList.contains("is-open"));
await page.waitForTimeout(400);
ok("iframe 안에서 Esc → 패널 닫힘, 확인한 태그 줄은 빠짐", await page.evaluate(() =>
!document.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]')));
// ⑤ 읽음 실패한 알림 줄은 남는다
failNotiRead = true;
await page.click('#pj-inbox .pj-inbox-item[data-id="903"]', { button: "right" });
await page.click(".pj-ctxmenu button, .pj-ctxmenu [role=menuitem], .pj-ctxmenu li");
await page.waitForTimeout(400);
ok("읽음 처리 실패 — 줄이 남고 굵게(읽지 않음)", await page.evaluate(() => {
const li = document.querySelector('#pj-inbox .pj-inbox-item[data-id="903"]'); return !!li && li.classList.contains("is-unread"); }));
console.log("\nALL PASS (" + pass.length + ")");
} finally {
await browser.close();
server.close();
}
})().catch(e => { console.error(e); process.exit(1); });
+216 -2
View File
@@ -15,6 +15,8 @@ const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에
const ROOT = path.join(__dirname, "..", "..");
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
const fails = [];
@@ -29,8 +31,8 @@ function deferred() {
return { promise: p, resolve: resolve, reject: reject };
}
function makeEnv() {
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
function makeEnv(page) {
const dom = new JSDOM(page || html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
const w = dom.window, d = w.document;
w.__PJ_TEST__ = true;
w.HTMLDialogElement.prototype.showModal = function () { this.open = true; };
@@ -684,6 +686,218 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
const d = env.d;
check("[프로젝트 줄] 읽기 전용은 연결 목록만 표시", d.getElementById("pj-link-form").hidden && d.getElementById("pj-links-block").classList.contains("is-readonly") && !!d.querySelector(".pj-link-chip") && !d.querySelector(".pj-link-del"));
}
// ── 대시보드 담당자별 작업 합계 — 사람마다 메인·하위 세로 막대(완료/전체), 막대 → 오른쪽 업무 목록, 항목 → 편집 창 ──
{
const env = makeEnv(); baseRoutes(env);
env.d.querySelector(".pj-project-view").dataset.isPro = "true";
let asked = null;
env.route("GET", /\/project\/api\/projects\/1\/subtasks-summary\?scope=project$/, function (u) {
asked = u;
return { body: { subtasks: [
{ id: 501, parent_task_id: 101, title: "하위 1", assignee_email: "me@test.local", assignee_name: "Me", done: true, completed_at: "2026-09-29T10:00:00+09:00" },
{ id: 502, parent_task_id: 101, title: "하위 2", assignee_email: "bob@test.local", assignee_name: "Bob", done: false },
{ id: 503, parent_task_id: 103, title: "다른 프로젝트 하위", assignee_email: "bob@test.local", assignee_name: "Bob", done: true },
// 세부 작업의 세부 작업(2026-10-08) — root_task_id 로 맨 위 메인 작업을 따져 센다
{ id: 504, parent_task_id: 501, root_task_id: 101, depth: 2, parent_title: "하위 1", title: "하위 1-1", assignee_email: "me@test.local", assignee_name: "Me", done: false },
{ id: 505, parent_task_id: 503, root_task_id: 103, depth: 2, parent_title: "다른 프로젝트 하위", title: "다른 1-1", assignee_email: "bob@test.local", assignee_name: "Bob", done: true },
] } };
});
env.route("GET", /\/project\/api\/tasks\/502$/, function () { return { body: { task: detail(502, "하위 2", { parent_task_id: 101 }) } }; });
const P = await boot(env);
P.state().tasks.forEach(function (t) {
if (t.id === 101) Object.assign(t, { assignee_email: "me@test.local", assignee_name: "Me", completed_at: "2026-09-29T10:00:00+09:00" });
if (t.id === 102) Object.assign(t, { assignee_email: "me@test.local", assignee_name: "Me" });
if (t.id === 301) Object.assign(t, { assignee_email: "bob@test.local", assignee_name: "Bob" });
});
env.d.querySelector('.pj-tab[data-view="dashboard"]').click(); await settle();
const groups = Array.from(env.d.querySelectorAll(".pj-wl-group")).map(function (g) {
return [g.querySelector(".pj-wl-name b").textContent].concat(Array.from(g.querySelectorAll(".pj-wl-val")).map(function (v) { return v.firstChild.textContent; })).join("|");
});
check("[대시보드 담당자별] 하위 작업 요청(이 프로젝트 범위)", !!asked);
check("[대시보드 담당자별] 세로 막대: 사람별 메인·세부 완료/전체(세부의 세부 포함, 다른 프로젝트 제외)",
JSON.stringify(groups) === JSON.stringify(["Me|1/2|1/2", "Bob|0/1|0/1"]), groups);
// 막대 = 그 작업 전체, 채움 = 완료율(작업 수가 아니라) — Me 메인 1/2 → 50%, 하위 1/1 → 100%, Bob 0/1 → 0%
const pcts = Array.from(env.d.querySelectorAll(".pj-wl-done")).map(function (f) { return f.dataset.pct; });
check("[대시보드 담당자별] 채움 높이 = 완료율", JSON.stringify(pcts) === JSON.stringify(["50", "50", "0", "0"]), pcts);
const sum = env.d.querySelector(".pj-wl-sum").textContent.replace(/\s+/g, " ");
check("[대시보드 담당자별] 전체 완료 2/6 (33%)", /2 \/ 6 \(33%\)/.test(sum), sum);
// 막대 → 오른쪽 패널(body 에) → 항목 → 편집 창
env.d.querySelectorAll(".pj-wl-group")[1].querySelector(".pj-wl-col.is-sub").click(); await settle();
const drawer = env.d.body.querySelector(".pj-wl-drawer");
const items = drawer ? Array.from(drawer.querySelectorAll(".pj-wl-item-title")).map(function (n) { return n.textContent; }) : [];
check("[대시보드 담당자별] 하위 막대 → 오른쪽 패널에 업무 목록(상위 작업 표시)", !!drawer && drawer.parentElement === env.d.body &&
JSON.stringify(items) === JSON.stringify(["하위 2"]) && /상위: 작업 A/.test(drawer.textContent), [items, drawer && drawer.textContent]);
drawer.querySelector(".pj-wl-item").click(); await settle();
check("[대시보드 담당자별] 항목 → 작업 편집 창(하위 작업은 서버에서 받아)", !env.d.getElementById("pj-modal-task").hidden &&
env.d.getElementById("pj-t-title").value === "하위 2", env.d.getElementById("pj-t-title").value);
}
// ── 나를 태그·작업 배정 알림 팝업 — 본 것 이후 새 알림만, 깜박이는 팝업, 닫기 전까지 유지 ──
{
const env = makeEnv(); baseRoutes(env);
const asked = [];
env.route("GET", /\/project\/api\/notifications\/alerts/, function (u) {
asked.push(u);
const after = /after=(\d+)/.exec(u);
if (!after) return { body: { me: "me@test.local", latest_id: 5, alerts: [] } };
return { body: { me: "me@test.local", latest_id: 5, alerts: [
{ id: 4, type: "assigned", title: "작업 배정: 촬영 준비", body: "P1 · 마감 -", task_id: 101, project_id: 1, actor_email: "bob@test.local" },
{ id: 5, type: "mention", title: "나를 태그함: 작업 A", body: "P1 · 댓글", task_id: 101, project_id: 1, actor_email: "bob@test.local" }] } };
});
env.w.localStorage.setItem("pj_alert_seen:me@test.local", "3");
await boot(env); await settle(); await wait(10); await settle();
const pop = env.d.body.querySelector(".pj-alert-pop");
check("[알림 팝업] 본 것(3) 이후 새 알림 2건을 body 에 팝업", !!pop && pop.querySelectorAll(".pj-alert-item").length === 2 &&
/촬영 준비/.test(pop.textContent) && /나를 태그/.test(pop.textContent) && asked.some(function (u) { return /after=3/.test(u); }), asked);
pop.querySelector("[data-alert-close]").click();
check("[알림 팝업] 닫기 → 사라지고 본 것 = 5", !env.d.body.querySelector(".pj-alert-pop") && env.w.localStorage.getItem("pj_alert_seen:me@test.local") === "5");
}
{
const env = makeEnv(); baseRoutes(env);
env.route("GET", /\/project\/api\/notifications\/alerts/, function () { return { body: { me: "me@test.local", latest_id: 9, alerts: [] } }; });
await boot(env); await settle();
check("[알림 팝업] 처음 쓰는 브라우저 — 옛 알림 안 띄우고 기준점만", !env.d.body.querySelector(".pj-alert-pop") && env.w.localStorage.getItem("pj_alert_seen:me@test.local") === "9");
}
// ── 멤버 배정·제외 — 지금 멤버는 체크된 채로, 체크 = 배정 · 해제 = 제외(확인 뒤) ──
{
const env = makeEnv(adminHtml); baseRoutes(env);
env.route("GET", /\/project\/api\/assignable-users$/, function () { return { body: { users: [
{ email: "me@test.local", id: "me", name: "Me", avatar: "" },
{ email: "bob@test.local", id: "bob", name: "Bob", avatar: "" },
{ email: "carol@test.local", id: "carol", name: "Carol", avatar: "" }] } }; });
const added = [], removed = [];
env.route("POST", /\/project\/api\/projects\/1\/members$/, function (u, body) { added.push(body.user_email); return { body: { member: { user_email: body.user_email } } }; });
env.route("DELETE", /\/project\/api\/projects\/1\/members\/.+$/, function (u) { removed.push(decodeURIComponent(u.split("/").pop())); return { body: { ok: true } }; });
await boot(env);
const d = env.d;
d.getElementById("pj-add-member").click(); await settle();
const box = function (e) { return d.querySelector('#pj-m-users input[value="' + e + '"]'); };
check("[멤버 배정·제외] 지금 멤버 체크·나머지 해제", box("bob@test.local").checked && box("me@test.local").checked && !box("carol@test.local").checked);
box("bob@test.local").checked = false; box("carol@test.local").checked = true;
env.setConfirm(true);
d.getElementById("pj-save-member").click(); await settle(); await wait(10); await settle();
check("[멤버 배정·제외] 체크 = 배정, 해제 = 제외(확인 뒤)", JSON.stringify(added) === '["carol@test.local"]' &&
JSON.stringify(removed) === '["bob@test.local"]' && env.confirms === 1, [added, removed, env.confirms]);
const shown = Array.from(d.querySelectorAll(".pj-tmember")).map(function (n) { return n.dataset.email; });
check("[멤버 배정·제외] 머리 멤버 아이콘 갱신", shown.indexOf("bob@test.local") < 0 && shown.indexOf("carol@test.local") >= 0, shown);
}
// ── [검토 A] 전체 보기 — 원 소속을 볼 수 없는 연결된 작업(301, 읽기 전용)도 한 번 나온다 ──
{
const env = makeEnv(adminHtml); baseRoutes(env);
await boot(env);
const d = env.d;
d.getElementById("pj-side-allview").click(); await settle();
const cards = function (id) { return d.querySelectorAll('.pj-card[data-task-id="' + id + '"]').length; };
check("[전체 보기] 연결된 작업(원 소속 못 봄)도 한 장, 원 소속 작업은 그대로 한 장", cards(301) === 1 && cards(101) === 1 && cards(103) === 1,
[cards(301), cards(101), cards(103)]);
}
// ── [검토 7] 수신함 iframe 안쪽 — __pjEmbedSettle 이 작업 창 닫기와 같은 저장 절차를 탄다 ──
{
const env = makeEnv(); baseRoutes(env);
env.d.documentElement.classList.add("pj-embed");
let putStatus = 500; const puts = [];
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) {
puts.push(b);
return putStatus >= 400 ? { status: putStatus, body: { detail: "서버 오류" } } : { body: { task: Object.assign(detail(101, "작업 A"), b) } };
});
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
await P.openTaskModal(taskOf(P, 101)); await settle();
const ta = d.getElementById("pj-t-title");
ta.value = "작업 A3"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
env.setConfirm(false); // 계속 편집
const ok1 = await env.w.__pjEmbedSettle(); await settle();
check("[수신함 iframe] 저장 실패 → 다시 시도 후 묻고, 계속 편집이면 false·입력 유지",
ok1 === false && !modal.hidden && titleVal(d) === "작업 A3" && env.confirms === 1 && puts.length >= 2, [ok1, env.confirms, puts.length]);
putStatus = 200;
const ok2 = await env.w.__pjEmbedSettle(); await settle();
check("[수신함 iframe] 다시 — 재시도 성공이면 true(묻지 않음)", ok2 === true && env.confirms === 1 && puts[puts.length - 1].title === "작업 A3",
[ok2, env.confirms]);
}
// ── [검토 7] 수신함 작업 창 — 바꾸기·닫기 전 저장 대기, 계속 편집이면 그대로, A→B→A, 저장 중 Esc, 읽음 실패 ──
{
const env = makeEnv(inboxHtml); baseRoutes(env);
const reads = [];
env.route("POST", /\/project\/api\/mentions\/read$/, function (u, b) { reads.push("m" + (b && b.task_id)); return { body: { ok: true, marked: 1 } }; });
let failNoti = true;
env.route("POST", /\/project\/api\/notifications\/\d+\/read$/, function (u) {
reads.push("n" + u.split("/")[4]);
return failNoti ? { status: 500, body: { detail: "db" } } : { body: { ok: true } };
});
await boot(env);
const d = env.d;
const A = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
const B = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
const N901 = d.querySelector('#pj-inbox .pj-inbox-item[data-id="901"]');
const frame = function () { const p = d.body.querySelector(".pj-inbox-panel"); return p && p.querySelector("iframe"); };
const src = function () { return frame() ? frame().getAttribute("src") : ""; };
A.click(); await settle();
check("[수신함] 줄 → 오른쪽 작업 창 = 공유 링크 + embed", src() === "/project/t/101?embed=1", src());
check("[수신함] 같은 작업의 태그·알림을 함께 확인", reads.indexOf("m101") >= 0 && reads.indexOf("n901") >= 0, reads);
await settle();
check("[수신함] 알림 읽음 실패 — 굵게(읽지 않음) 그대로", N901.classList.contains("is-unread"));
let gate = deferred(), settles = 0;
frame().contentWindow.__pjEmbedSettle = function () { settles++; return gate.promise; };
B.click(); await settle();
check("[수신함] 작업 창 저장 확인 중엔 바꾸지 않음", src() === "/project/t/101?embed=1" && settles === 1, [src(), settles]);
A.click(); await settle(); // A→B→A 빨리
gate.resolve(true); await settle();
check("[수신함] A→B→A — 확인 뒤 A 그대로, B 는 열거나 확인하지 않음",
src() === "/project/t/101?embed=1" && reads.indexOf("m102") < 0 && B.classList.contains("is-unread") && settles === 1, [src(), reads, settles]);
gate = deferred();
B.click(); await settle(); gate.resolve(false); await settle();
check("[수신함] 계속 편집 — 창·선택 그대로, 새 줄 확인 안 함",
src() === "/project/t/101?embed=1" && A.classList.contains("is-selected") && !B.classList.contains("is-selected") && reads.indexOf("m102") < 0);
gate = deferred(); settles = 0;
const esc = function () { d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); };
esc(); await settle(); esc(); await settle();
const panelEl = d.body.querySelector(".pj-inbox-panel");
check("[수신함] 저장 중 Esc(두 번) — 확인 하나만, 끝나기 전엔 열린 채", panelEl.classList.contains("is-open") && settles === 1, settles);
gate.resolve(true); await settle();
check("[수신함] 저장이 끝나면 닫힘", !panelEl.classList.contains("is-open"));
await wait(260); await settle();
check("[수신함] 확인된 태그 줄은 빠지고, 읽음 실패한 알림 줄은 남는다", !A.isConnected && N901.isConnected, [A.isConnected, N901.isConnected]);
failNoti = false;
B.click(); await settle(); await settle();
check("[수신함] 닫힌 뒤 다른 줄 — 바로 열림", src() === "/project/t/102?embed=1", src());
}
// ── [검토 9] 새 프로젝트 — 생성과 멤버 배정 결과를 따로, 실패한 멤버만 다시, 연타해도 한 번 생성 ──
{
const env = makeEnv(adminHtml); baseRoutes(env);
env.route("GET", /\/project\/api\/assignable-users$/, function () { return { body: { users: [
{ email: "bob@test.local", id: "bob", name: "Bob", avatar: "" },
{ email: "carol@test.local", id: "carol", name: "Carol", avatar: "" }] } }; });
let creates = 0, failCarol = true;
const memberCalls = [];
const createGate = deferred();
env.route("POST", /\/project\/api\/projects$/, async function () {
creates++;
await createGate.promise;
return { status: 201, body: { project: { id: 9, name: "새 프로젝트" } } };
});
env.route("POST", /\/project\/api\/projects\/9\/members$/, function (u, b) {
memberCalls.push(b.user_email);
return failCarol && b.user_email === "carol@test.local" ? { status: 400, body: { detail: "배정 불가" } } : { status: 201, body: { member: {} } };
});
await boot(env);
const d = env.d;
d.getElementById("pj-new-project-side").click(); await settle();
d.getElementById("pj-f-name").value = "새 프로젝트";
d.querySelectorAll("#pj-f-members input[type=checkbox]").forEach(function (c) { c.checked = true; });
const save = d.getElementById("pj-save-project");
save.click(); save.click(); await settle(); // 연타
createGate.resolve(); await settle(); await settle();
const modal = d.getElementById("pj-modal-project");
const msg = d.getElementById("pj-f-project-msg");
const carol = d.querySelector('#pj-f-members input[value="carol@test.local"]').closest(".pj-member-pick");
check("[새 프로젝트] 연타해도 한 번만 생성", creates === 1, creates);
check("[새 프로젝트] 배정 실패 — 창 유지, 생성됨·실패 멤버 안내, 실패 표시",
!modal.hidden && !msg.hidden && /만들어졌습니다/.test(msg.textContent) && /배정 불가/.test(msg.textContent) &&
carol.classList.contains("is-failed") && /다시 배정/.test(save.textContent), [modal.hidden, msg.textContent, save.textContent]);
failCarol = false;
save.click(); await settle(); await settle();
check("[새 프로젝트] 다시 배정 — 실패한 멤버만, 프로젝트는 다시 만들지 않음, 끝나면 닫힘",
creates === 1 && JSON.stringify(memberCalls) === JSON.stringify(["bob@test.local", "carol@test.local", "carol@test.local"]) && modal.hidden,
[creates, memberCalls, modal.hidden]);
}
clearTimeout(WATCHDOG);
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
+15 -3
View File
@@ -46,7 +46,7 @@ def board() -> dict:
def goals_ctx(admin: bool) -> dict:
return {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "nav_projects": [], "goal_years": [2026],
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
"project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(),
"months": list(range(1, 13)),
@@ -103,8 +103,8 @@ def meeting_view(err: bool) -> dict:
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
view = meeting_view(err)
return {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
ctx = {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "nav_projects": [], "goal_years": [2026],
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
"project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True,
"weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False,
@@ -114,6 +114,16 @@ def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
"can_sync": can_sync, "meeting_status": store.MEETING_STATUS, "meet_members": [], "month_plan": None,
"attendee_list": [], **copy.deepcopy(view),
}
# 회의록은 누구나 고친다(2026-10-07) — 보기 전용은 "회의 완료"된 회의록뿐. 관리자 아닌 화면 = 완료된 회의록으로 시험
ctx["meeting"].update(can_complete=True, completed=not admin, completed_at="2026-10-02 18:00" if not admin else "",
completed_by="admin@test.local" if not admin else "")
return ctx
def member_ctx() -> dict:
ctx = meeting_ctx(False, False, can_sync=False)
ctx["meeting"].update(completed=False, completed_at="", completed_by="")
return ctx
def meeting_layout_ctx(admin: bool) -> dict:
@@ -156,6 +166,8 @@ def main() -> None:
"meeting_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False)),
"meeting_err.html": ("project/goal_meeting.html", meeting_ctx(True, True)),
"meeting_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False)),
# 관리자 아닌 직원 + 아직 완료 전 회의록 — 누구나 고친다(2026-10-07)
"meeting_member.html": ("project/goal_meeting.html", member_ctx()),
"meeting_layout_admin.html": ("project/goal_meeting.html", meeting_layout_ctx(True)),
"meeting_layout_ro.html": ("project/goal_meeting.html", meeting_layout_ctx(False)),
"meeting_merged.html": ("project/goal_meeting.html", meeting_merged_ctx()),
+32 -2
View File
@@ -50,8 +50,38 @@ def main() -> None:
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
]))
env.globals["pj_kr_holidays"] = {}
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)):
render_one(env, name, admin)
render_inbox(env)
def render_inbox(env) -> None:
"""수신함(project/inbox.html) — 태그한 작업 101·102, 알림(작업 101·102·프로젝트만)."""
def mt(tid: int, title: str) -> dict:
return {"id": tid, "title": title, "project_id": 1, "project_name": "P1", "project_color": "#4573d2",
"unread_mentions": 1, "stage_name": "할 일", "due_label": "", "mention_actor": "bob@test.local",
"completed_at": None}
def nt(nid: int, ntype: str, title: str, task_id: int | None) -> dict:
return {"id": nid, "type": ntype, "title": title, "body": "P1", "task_id": task_id, "project_id": 1,
"is_read": False, "actor_email": "bob@test.local", "created_at": "2026-10-12T09:00:00+09:00"}
html = env.get_template("project/inbox.html").render(
user={"email": ME, "is_super_admin": False}, is_admin=False, pj_pro=False, pj_admin=False,
nav_projects=PROJECTS, goal_years=[2026], my_open_total=0, mention_unread=2,
color_palette=["#4573d2"], project_icons=["folder"], project_asana_icons=[],
mentioned_tasks=[mt(101, "작업 A"), mt(102, "작업 B")],
notifications=[nt(901, "assigned", "작업 배정: 작업 A", 101), nt(902, "comment", "새 댓글: 작업 B", 102),
nt(903, "completed", "프로젝트 알림", None)],
)
path = os.path.join(OUT_DIR, "inbox_render.html")
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
print("rendered:", path)
def render_one(env, name: str, admin: bool) -> None:
html = env.get_template("project/project.html").render(
user={"email": ME, "is_super_admin": False}, is_admin=False, can_manage=True,
user={"email": ME, "is_super_admin": False}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True,
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
@@ -62,7 +92,7 @@ def main() -> None:
my_open_total=0, mention_unread=0,
)
os.makedirs(OUT_DIR, exist_ok=True)
path = os.path.join(OUT_DIR, "project_render.html")
path = os.path.join(OUT_DIR, name)
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
print("rendered:", path)
+15
View File
@@ -104,6 +104,21 @@ class FeatureStoreTests(unittest.TestCase):
match=self.store._monitor_matches(self.conn,"other-computer",unknown)[0]
self.assertIsNone(match["asset"]);self.assertEqual(len(match["candidates"]),2)
def test_same_model_different_serial_can_be_registered(self):
# 같은 모델(듀얼 모니터 등)이 이미 있어도 시리얼이 다르면 새 자산으로 등록된다(2026-10-07)
other = self.store.create(AssetInput(name="Display", category="monitor", model="Display 24", serial="SN-OTHER"), "actor")
match = self.store._monitor_matches(self.conn, self.computer, self.parsed)[0]
self.assertIsNone(match["asset"]); self.assertEqual(match["candidate_by"], "model")
self.assertEqual([c["id"] for c in match["candidates"]], [other])
target = self.store.register_monitor(self.computer, 0, self.monitor_payload(asset=AssetInput(name="Second", category="monitor", model="Display 24")), "actor")
self.assertNotEqual(target, other); self.assertEqual(self.conn.assets[target]["serial"], "SN-1")
def test_same_serial_still_blocks_new_registration(self):
self.store.create(AssetInput(name="Other", category="monitor", serial="SN-1", model="Different Model", manufacturer="Another"), "actor")
self.assertEqual(self.store._monitor_matches(self.conn, self.computer, self.parsed)[0]["candidate_by"], "serial")
with self.assertRaises(AssetConflict):
self.store.register_monitor(self.computer, 0, self.monitor_payload(asset=AssetInput(name="Dup", category="monitor")), "actor")
def test_existing_unique_serial_matches_automatically(self):
target=self.store.create(AssetInput(name="Existing",category="monitor",serial="sn-1"),"actor")
match=self.store._monitor_matches(self.conn,self.computer,self.parsed)[0]
+80
View File
@@ -0,0 +1,80 @@
"""프로젝트는 멤버(owner 포함)만 — 관리자도 멤버가 아니면 안 보인다, 예외는 슈퍼관리자(2026-10-07). DB 없이."""
import importlib
import sys
import unittest
from types import SimpleNamespace
from unittest.mock import Mock, patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.project import access
from app.store import SUPER_ADMIN_EMAIL
api = importlib.import_module("app.modules.project.router")
ADMIN = {"email": "admin@test.local", "role": "admin"}
SUPER = {"email": SUPER_ADMIN_EMAIL, "role": "admin"}
MEMBER = {"email": "bob@test.local", "role": "user"}
class FakeStore:
"""프로젝트 1 = bob 멤버, 2 = admin 멤버. list_projects(member_email) 는 그 사람이 owner·멤버인 것만."""
members = {1: {"bob@test.local"}, 2: {"admin@test.local"}}
def __init__(self):
self.member_email_asked = "unset"
def is_member(self, project_id, user_email):
return user_email in self.members.get(project_id, set())
def list_projects(self, include_archived=False, member_email=None):
self.member_email_asked = member_email
return [{"id": pid, "parent_id": None, "name": f"P{pid}"} for pid, ms in self.members.items()
if member_email is None or member_email in ms]
class MembersOnlyTests(unittest.TestCase):
def setUp(self):
self.st = FakeStore()
p = patch.object(access, "can_use_module", side_effect=lambda u: bool(u))
p.start()
self.addCleanup(p.stop)
def test_admin_sees_only_member_projects(self):
self.assertFalse(access.can_manage_project(self.st, ADMIN, 1))
self.assertTrue(access.can_manage_project(self.st, ADMIN, 2))
self.assertEqual(access.visible_project_ids(self.st, ADMIN), {2})
self.assertFalse(access.sees_all_projects(ADMIN))
def test_member_and_super_admin(self):
self.assertTrue(access.can_manage_project(self.st, MEMBER, 1))
self.assertFalse(access.can_manage_project(self.st, MEMBER, 2))
self.assertTrue(access.can_manage_project(self.st, SUPER, 1))
self.assertIsNone(access.visible_project_ids(self.st, SUPER)) # 전체
self.assertTrue(access.sees_all_projects(SUPER))
def test_sidebar_list_is_member_only_for_admin(self):
self.assertEqual([p["id"] for p in api._nav_projects(self.st, ADMIN, True)], [2])
self.assertEqual(self.st.member_email_asked, "admin@test.local")
self.assertEqual(sorted(p["id"] for p in api._nav_projects(self.st, SUPER, True)), [1, 2])
self.assertIsNone(self.st.member_email_asked)
def test_project_list_api_is_member_only_for_admin(self):
app = FastAPI()
app.include_router(api.router)
client = TestClient(app)
with patch.object(api, "_require_user", return_value=ADMIN), patch.object(api, "_db_or_503", return_value=self.st):
r = client.get("/project/api/projects")
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual([p["id"] for p in r.json()["projects"]], [2])
def test_trash_is_filtered_to_member_projects(self):
st = SimpleNamespace(list_trash=lambda: [{"id": 7, "project_id": 1}, {"id": 8, "project_id": 2}],
**{k: getattr(self.st, k) for k in ("is_member", "list_projects")})
self.assertEqual([t["id"] for t in api._visible_trash(st, ADMIN)], [8])
self.assertEqual([t["id"] for t in api._visible_trash(st, SUPER)], [7, 8])
if __name__ == "__main__":
unittest.main()
+117
View File
@@ -0,0 +1,117 @@
"""알림 팝업 API — 기준점·태그/배정만·읽지 않은 것·after 이후·오래된 것부터. DB 없이 가짜 저장소로."""
import importlib
import unittest
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
api = importlib.import_module("app.modules.project.router")
ROWS = [ # 최신순(list_notifications 와 같게)
{"id": 9, "type": "completed", "title": "완료", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 8, "type": "mention", "title": "나를 태그함: A", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 7, "type": "assigned", "title": "작업 배정: B", "is_read": True, "task_id": 2, "project_id": 1},
{"id": 6, "type": "assigned", "title": "작업 배정: C", "is_read": False, "task_id": 3, "project_id": 1},
{"id": 2, "type": "assigned", "title": "작업 배정: 옛것", "is_read": False, "task_id": 4, "project_id": 1},
]
class FakeStore:
"""list_notifications(최신순) + list_unread_after(DB 쪽 조건·오래된 것부터) — db.py 와 같은 의미."""
desktop = False
def __init__(self, rows=None):
self.rows = list(ROWS if rows is None else rows)
self.pages = 0
def notifier_active(self, email):
return self.desktop
def list_notifications(self, recipient_email, unread_only=False, limit=100):
rows = sorted((r for r in self.rows if not unread_only or not r["is_read"]), key=lambda r: -r["id"])
return rows[:limit]
def list_unread_after(self, recipient_email, after_id, types, limit=200):
self.pages += 1
rows = sorted((r for r in self.rows if not r["is_read"] and r["id"] > after_id and r["type"] in types),
key=lambda r: r["id"])
return rows[:limit]
class AlertsApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
def get(self, qs="", desktop=False, st=None, visible=None):
st = st or FakeStore()
st.desktop = desktop
vis = visible or (lambda st, user, items: items)
with patch.object(api, "_require_user", return_value={"email": "Me@Test.local"}), \
patch.object(api, "_db_or_503", return_value=st), \
patch.object(api, "_visible_notifications", side_effect=vis):
return self.client.get("/project/api/notifications/alerts" + qs).json()
def test_without_after_returns_only_baseline(self):
out = self.get()
self.assertEqual((out["me"], out["latest_id"], out["alerts"]), ("me@test.local", 9, []))
def test_after_returns_unread_mentions_and_assignments_oldest_first(self):
out = self.get("?after=5")
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8]) # 완료 알림(9)·읽은 것(7)·옛것(2) 제외
self.assertEqual(out["alerts"][1]["type"], "mention")
self.assertNotIn("desktop", out)
def test_alert_links_use_task_permalink(self):
# 작업 알림은 /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 사람도 403 없이 열린다
out = self.get("?after=5")
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
st = FakeStore([{"id": 3, "type": "mention", "is_read": False, "task_id": None, "project_id": 4}])
self.assertEqual(self.get("?after=0", st=st)["alerts"][0]["href"], "/project/p/4")
def test_pc_notifier_running_silences_web_popup(self):
out = self.get("?after=5", desktop=True)
self.assertEqual((out["alerts"], out["latest_id"], out["desktop"]), ([], 9, True))
def test_notifier_check_failure_keeps_web_popup(self):
class Broken(FakeStore):
def notifier_active(self, email):
raise RuntimeError("db down")
out = self.get("?after=5", st=Broken())
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
# ── 예전엔 최신 50건을 자른 뒤 걸러서 빠지던 경우들 ──
def test_assignment_behind_fifty_comment_alerts_is_not_lost(self):
rows = [{"id": 1, "type": "assigned", "title": "배정", "is_read": False, "task_id": 1, "project_id": 1}]
rows += [{"id": 100 + i, "type": "comment", "title": "댓글", "is_read": False, "task_id": 1, "project_id": 1}
for i in range(50)]
out = self.get("?after=0", st=FakeStore(rows))
self.assertEqual([a["id"] for a in out["alerts"]], [1])
def test_more_than_sixty_assignments_page_oldest_first(self):
rows = [{"id": i, "type": "assigned", "title": f"배정{i}", "is_read": False, "task_id": i, "project_id": 1}
for i in range(1, 66)]
st = FakeStore(rows)
out = self.get("?after=0", st=st)
self.assertEqual([a["id"] for a in out["alerts"]], list(range(1, 11))) # 오래된 것부터 10건
out = self.get("?after=10", st=st) # 닫으면 그 뒤 것(화면이 본 것=10 으로 다시 묻는다)
self.assertEqual([a["id"] for a in out["alerts"]], list(range(11, 21)))
out = self.get("?after=60", st=st)
self.assertEqual([a["id"] for a in out["alerts"]], [61, 62, 63, 64, 65])
def test_invisible_alerts_ahead_do_not_hide_visible_ones(self):
# 앞쪽 450건은 지금 볼 수 없는 작업(권한 회수) — 페이지를 넘겨 그 뒤의 볼 수 있는 알림을 찾는다
rows = [{"id": i, "type": "mention", "title": "x", "is_read": False, "task_id": 9, "project_id": 9}
for i in range(1, 451)]
rows.append({"id": 500, "type": "mention", "title": "보임", "is_read": False, "task_id": 1, "project_id": 1})
st = FakeStore(rows)
out = self.get("?after=0", st=st,
visible=lambda st, user, items: [n for n in items if n["project_id"] == 1])
self.assertEqual([a["id"] for a in out["alerts"]], [500])
self.assertEqual(st.pages, 3) # 200·200·51 — 끝까지 읽고 멈춘다
if __name__ == "__main__":
unittest.main()
+75
View File
@@ -0,0 +1,75 @@
"""대시보드 담당자별 작업 합계 — 하위 작업 요약 API(subtasks-summary) 범위·권한. DB 없이 가짜 저장소로."""
import importlib
import unittest
from types import SimpleNamespace
from unittest.mock import patch
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
api = importlib.import_module("app.modules.project.router")
class FakeStore:
def __init__(self):
self.asked_projects, self.asked_parents = None, None
def list_projects(self, include_archived, member_email):
return [{"id": 1, "parent_id": None}, {"id": 2, "parent_id": None}, {"id": 5, "parent_id": 1}]
def get_project(self, project_id):
# 7 = 보관된 프로젝트(활성 목록에 없음), 5 = 서브프로젝트
return {"id": project_id, "parent_id": 1 if project_id == 5 else None,
"status": "archived" if project_id == 7 else "active"}
def list_tasks_for_projects(self, project_ids):
self.asked_projects = project_ids
return [{"id": 10 * pid} for pid in project_ids]
def list_subtasks_of(self, parent_ids):
self.asked_parents = parent_ids
return [{"parent_task_id": parent_ids[0], "assignee_email": "a@test", "assignee_name": "A", "done": True}]
class SubtaskSummaryTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
self.st = FakeStore()
def call(self, scope, pid=1):
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
patch.object(api, "_db_or_503", return_value=self.st), \
patch.object(api, "_require_manage", return_value=None), \
patch.object(api, "_accessible_project_ids", return_value=None):
return self.client.get(f"/project/api/projects/{pid}/subtasks-summary?scope={scope}")
def test_project_scope_uses_only_this_project(self):
r = self.call("project")
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.st.asked_projects, [1])
self.assertEqual(self.st.asked_parents, [10])
self.assertEqual(r.json()["subtasks"][0]["done"], True)
def test_all_scope_uses_top_level_projects(self):
self.call("all")
self.assertEqual(self.st.asked_projects, [1, 2]) # 서브프로젝트(5) 제외 — 스냅샷과 같은 범위
def test_all_scope_adds_open_archived_or_subproject_only(self):
# 지금 연 프로젝트가 보관(7)·서브프로젝트(5)면 그 하나만 더한다(다른 보관 프로젝트는 읽지 않는다)
self.call("all", pid=7)
self.assertEqual(self.st.asked_projects, [1, 2, 7])
self.call("all", pid=5)
self.assertEqual(self.st.asked_projects, [1, 2, 5])
def test_no_access_is_rejected(self):
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
patch.object(api, "_db_or_503", return_value=self.st), \
patch.object(api, "_require_manage", side_effect=HTTPException(403)):
self.assertEqual(self.client.get("/project/api/projects/1/subtasks-summary").status_code, 403)
self.assertIsNone(self.st.asked_parents)
if __name__ == "__main__":
unittest.main()
+44
View File
@@ -0,0 +1,44 @@
"""아사나 아이콘 값 검증 · 설명란 글자 색/크기 sanitize (2026-10-08)."""
import importlib
import unittest
store = importlib.import_module("app.modules.project.store")
class ProjectIconTests(unittest.TestCase):
def test_basic_and_asana_icons_accepted(self):
self.assertEqual(store.validate_project_icon("rocket_launch"), "rocket_launch")
self.assertEqual(store.validate_project_icon("asana:rocket_launch"), "asana:rocket_launch")
def test_unknown_or_malformed_rejected(self):
for v in ("asana:", "asana:nope", "asana:asana:rocket_launch", "nope", "Asana:rocket_launch", ""):
self.assertIsNone(store.validate_project_icon(v), v)
class DescStyleTests(unittest.TestCase):
def clean(self, html):
return store.sanitize_description_html(html)
def test_color_and_allowed_size_kept(self):
out = self.clean('<span style="color: rgb(224, 62, 62); font-size: 22px">a</span><span style="color:#ABC">b</span>')
self.assertEqual(out, '<span style="color: rgb(224, 62, 62); font-size: 22px">a</span><span style="color: #abc">b</span>')
def test_other_declarations_and_sizes_dropped(self):
out = self.clean('<span style="background:url(javascript:x); font-size: 99px; color: red; position:fixed">a</span>')
self.assertEqual(out, "<span>a</span>")
def test_style_injection_attempts_dropped(self):
out = self.clean('<span style="color: #fff;}body{display:none">a</span>'
'<span style="color: expression(alert(1))">b</span>')
# 선언을 다시 조립하므로 "}body{…" 같은 나머지는 사라지고 검증된 색만 남는다
self.assertEqual(out, '<span style="color: #fff">a</span><span>b</span>')
def test_style_only_on_plain_span(self):
self.assertEqual(self.clean('<p style="color:#fff">a</p>'), "<p>a</p>")
self.assertEqual(self.clean('<span class="pj-mention" data-email="a@b.c" style="color:#fff">@a</span>'),
'<span class="pj-mention" data-email="a@b.c">@a</span>')
self.assertEqual(self.clean('<font color="#ff0000">a</font>'), "a")
if __name__ == "__main__":
unittest.main()
+2
View File
@@ -90,6 +90,8 @@ class MeetingBoardTests(unittest.TestCase):
with self.assertRaises(gs.GoogleSlidesError):
off.open_week_board(folder_id="F", week_key="2026-10-05", title="t")
self.assertIn("토큰을 다시 발급", gs._friendly(RuntimeError("invalid_scope: Bad Request")))
self.assertIn("OAuth 클라이언트", gs._friendly(RuntimeError("('unauthorized_client: Unauthorized', {'error': 'unauthorized_client'})")))
self.assertIn("만료·폐기", gs._friendly(RuntimeError("('invalid_grant: Bad Request', {})")))
def test_title_uses_month_week_and_period(self):
self.assertEqual(api.meeting_board_title(date(2026, 10, 5)), "10월 2주차 (10/5~10/11)")
+5 -4
View File
@@ -196,9 +196,6 @@ class MeetingCellTests(unittest.TestCase):
endpoints = [("POST", "/meeting-cells/move", self.payload),
("POST", "/meeting-cells/merge", dict(item_from=1, item_to=2)),
("DELETE", "/meeting-items/1/cell-merge", None)]
with patch.object(api, "_require_user", return_value=dict(role="user", email="user@test.local")):
for method, endpoint, body in endpoints:
self.assertEqual(client.request(method, "/project/api/goals" + endpoint, json=body).status_code, 403)
with patch.object(api, "_require_user", return_value=dict(role="admin", email="admin@test.local")):
url = "/project/api/goals/meeting-cells/move"
self.assertEqual(client.post(url, json={}).status_code, 400)
@@ -207,6 +204,10 @@ class MeetingCellTests(unittest.TestCase):
self.st._meeting_cells = lambda conn: False
self.assertEqual(client.post("/project/api/goals/meeting-cells/merge", json=dict(item_from=1, item_to=2)).status_code, 503)
self.assertEqual(client.post(url, json=self.payload).status_code, 200, "Move/formatting work without 019")
# 회의록은 누구나 고친다(2026-10-07) — 관리자가 아니어도 셀 이동·병합·해제를 막지 않는다(잠금은 회의 완료로)
with patch.object(api, "_require_user", return_value=dict(role="user", email="user@test.local")):
for method, endpoint, body in endpoints:
self.assertNotEqual(client.request(method, "/project/api/goals" + endpoint, json=body).status_code, 403)
def test_amount_cells_accept_text_after_021_and_result_note_reaches_store(self):
"""정량 목표·결과 — 숫자면 원 정수 칸, 글(예: 20개)이면 글 칸(021). 지난주 결과 글(result_note, 020)은 API 를 거쳐 저장된다."""
@@ -260,7 +261,7 @@ class MeetingCellTests(unittest.TestCase):
DictLoader({"erp_base.html": "{% block head_extra %}{% endblock %}{% block content %}{% endblock %}"}),
FileSystemLoader(root / "app/modules/project/templates")]), autoescape=True)
html = env.get_template("project/goal_meeting.html").render(
user=dict(email="test@local"), is_admin=True, goal_year=2026, goal_month=9,
user=dict(email="test@local"), is_admin=True, pj_pro=True, goal_year=2026, goal_month=9,
meetings_enabled=True, week="2026-09-28", week_end="2026-10-04", prev_week="2026-09-21",
prev_week_end="2026-09-27", meeting_status=store.MEETING_STATUS, pj_kr_holidays={},
nav_projects=[], goal_years=[2026], color_palette=[], project_icons=[], meet_members=[], month_plan=None, **view)
+115
View File
@@ -0,0 +1,115 @@
"""주간 회의록 — 누구나 수정, 회의 완료(022)면 잠금. 지난주 결과는 다음 주 회의록이 열려 있는 동안만. DB 없이."""
import importlib
import unittest
from contextlib import contextmanager
from datetime import date
from types import SimpleNamespace
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.project import store
from app.modules.project.db import ProjectStore
from tests.test_project_meeting_cells import Connection, Result
api = importlib.import_module("app.modules.project.router")
class LockConnection(Connection):
def __init__(self):
super().__init__()
self.completed = set() # 완료된 주차 시작일
# 있는 회의록 — 9/28 주차(9/28~9/30)와 바로 다음 주차(10/1, 목요일 시작 — 달이 바뀐다)
self.meetings = {date(2026, 9, 28), date(2026, 10, 1)}
self.shared = [] # FOR SHARE 로 잠근 주차(다음 회의록)
def execute(self, sql, params=()):
if sql.startswith("SELECT completed_at FROM goal_meetings WHERE week_start = %s"):
if sql.endswith("FOR SHARE"):
assert self.depth > 0, "다음 회의록 잠금은 트랜잭션 안에서"
self.shared.append(params[0])
if params[0] not in self.meetings:
return Result([])
return Result([{"completed_at": "done" if params[0] in self.completed else None}])
if sql.startswith("UPDATE goal_meetings SET"):
assert self.locked and self.depth > 0, "머리 변경은 회의록 행을 잠근 트랜잭션 안에서"
self.calls.append((sql, params))
return Result([{"week_start": params[-1]}])
return super().execute(sql, params)
class MeetingLockTests(unittest.TestCase):
def setUp(self):
self.conn = LockConnection()
@contextmanager
def connection():
yield self.conn
self.st = ProjectStore.__new__(ProjectStore)
self.st._pool = SimpleNamespace(connection=connection)
self.st._table_exists = lambda conn, name: True
self.st._column_exists = lambda conn, table, col: col in {"content_row_span", "completed_at", "result_note"}
for r in self.conn.rows.values():
r["result_note"] = ""
def test_completed_meeting_rejects_edits(self):
self.conn.completed.add(date(2026, 9, 28))
with self.assertRaises(store.MeetingLocked):
self.st.update_meeting_item(item_id=1, fields={"content": "x"})
with self.assertRaises(store.MeetingLocked):
self.st.move_meeting_item(item_id=2, direction=1)
def test_last_week_result_follows_next_meeting(self):
# 9/28 주차(9/28~9/30)가 완료돼도 다음 주차(10/1) 회의록이 열려 있으면 결과는 적을 수 있다
self.conn.completed.add(date(2026, 9, 28))
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "잘 됨", "result_amount": "100"})
self.assertEqual((out["result_note"], out["result_amount"]), ("잘 됨", 100))
self.assertEqual(self.conn.shared, [date(2026, 10, 1)]) # 달이 바뀐 다음 주차(목요일 시작)를 잠그고 확인
self.conn.completed.add(date(2026, 10, 1))
with self.assertRaises(store.MeetingLocked):
self.st.update_meeting_item(item_id=1, fields={"result_note": "늦게"})
def test_completed_week_without_next_meeting_is_locked(self):
# 예전엔 다음 주차 회의록이 없으면 완료된 회의록의 결과도 고칠 수 있었다
self.conn.meetings.discard(date(2026, 10, 1))
self.conn.completed.add(date(2026, 9, 28))
with self.assertRaises(store.MeetingLocked):
self.st.update_meeting_item(item_id=1, fields={"result_note": "다음 회의 전"})
self.assertEqual(self.conn.rows[1]["result_note"], "")
def test_open_week_without_next_meeting_accepts_result(self):
self.conn.meetings.discard(date(2026, 10, 1))
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "이번 주 결과"})
self.assertEqual(out["result_note"], "이번 주 결과")
def test_header_update_checks_lock_inside_row_lock(self):
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "메모"})
sqls = [s for s, _ in self.conn.calls]
lock = next(i for i, s in enumerate(sqls) if s.startswith("SELECT week_start FROM goal_meetings") and "FOR UPDATE" in s)
upd = next(i for i, s in enumerate(sqls) if s.startswith("UPDATE goal_meetings SET"))
self.assertLess(lock, upd)
self.conn.completed.add(date(2026, 9, 28))
with self.assertRaises(store.MeetingLocked):
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "잠김"})
self.assertEqual(sum(1 for s, _ in self.conn.calls if s.startswith("UPDATE goal_meetings SET")), 1)
def test_anyone_edits_but_only_admin_completes(self):
app = FastAPI()
app.include_router(api.router)
app.state.project_store = self.st
client = TestClient(app)
member = dict(role="user", email="member@test.local")
with patch.object(api, "_require_user", return_value=member):
r = client.put("/project/api/goals/meeting-items/1", json={"content": "누구나"})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(client.post("/project/api/goals/meetings/2026-09-28/complete", json={"done": True}).status_code, 403)
self.conn.completed.add(date(2026, 9, 28))
r = client.put("/project/api/goals/meeting-items/1", json={"content": "잠김"})
self.assertEqual(r.status_code, 409, r.text)
self.assertIn("회의가 완료", r.json()["detail"])
if __name__ == "__main__":
unittest.main()
+167 -18
View File
@@ -89,6 +89,7 @@ if ENABLED:
RUN = uuid.uuid4().hex[:6]
ADMIN = USERS.add(f"admin-{RUN}@test.local", role="admin")
PRO = USERS.add(f"pro-{RUN}@test.local", role="pro") # Pro user(2026-10-12)
SUPER = USERS.add("king@dbxcorp.co.kr", role="admin", super_=True)
ALICE = USERS.add(f"alice-{RUN}@test.local")
BOB = USERS.add(f"bob-{RUN}@test.local")
@@ -118,17 +119,19 @@ def _count(sql: str, *args) -> int:
# ════════════════════════════════════════════════════════════
# [07] 소유자 변경은 관리자만
# [07] 프로젝트 수정·소유자 변경은 Pro user 이상(2026-10-12)
# ════════════════════════════════════════════════════════════
def test_owner_change_admin_only():
p = _project("P-owner", ADMIN, (BOB,))
# 관리자도 멤버가 아닌 프로젝트는 못 다룬다(2026-10-07) — 소유자를 남에게 넘긴 뒤에도 바꿀 수 있게 멤버로 둔다
p = _project("P-owner", ADMIN, (BOB, ADMIN, PRO))
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": BOB})
assert r.status_code == 403, r.text
assert ST.get_project(project_id=p["id"])["owner_email"] == ADMIN
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": CAROL, "name": "x"})
assert r.status_code == 403 and ST.get_project(project_id=p["id"])["name"] != "x"
# 같은 값을 같이 보내는 건(화면 저장) 통과
assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200
# User 는 이름만 바꾸는 것도 안 된다, Pro user 멤버는 된다(같은 소유자 값을 같이 보내는 화면 저장 포함)
assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"name": "no"}).status_code == 403
assert req("PUT", f"/project/api/projects/{p['id']}", PRO, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200
# 관리자: 모듈 권한 없는 사람은 소유자 불가, 정상 사용자는 가능
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": EVE}).status_code == 400
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": CAROL}).status_code == 200
@@ -136,10 +139,10 @@ def test_owner_change_admin_only():
# 소유자에서 빠지면(관리자가 다시 바꿈) 멤버가 아닌 CAROL 은 관리 권한을 잃는다
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": ADMIN}).status_code == 200
assert req("GET", f"/project/api/projects/{p['id']}/snapshot", CAROL).status_code == 403
# 생성: 비관리자가 남을 소유자로 지정 → 거절, 본인·미지정 → 본인이 소유자
assert req("POST", "/project/api/projects", BOB, json={"name": "n1", "owner_email": CAROL}).status_code == 403
r = req("POST", "/project/api/projects", BOB, json={"name": "n2"})
assert r.status_code == 201 and r.json()["project"]["owner_email"] == BOB
# 생성: User 는 새 프로젝트 불가, Pro user 는 본인·미지정 → 본인이 소유자
assert req("POST", "/project/api/projects", BOB, json={"name": "n1"}).status_code == 403
r = req("POST", "/project/api/projects", PRO, json={"name": "n2"})
assert r.status_code == 201 and r.json()["project"]["owner_email"] == PRO
# ════════════════════════════════════════════════════════════
@@ -151,8 +154,10 @@ def test_delete_requires_current_access():
t = req("POST", f"/project/api/projects/{p['id']}/tasks", ALICE, json={"title": "alice task", "stage_id": s["id"]}).json()["task"]
ST.add_comment(task_id=t["id"], author_email=ALICE, author_name="a", body="hi")
trash_before = _count("SELECT COUNT(*) AS n FROM project_trash")
# 현재 멤버인 타인 → 생성자 규칙으로 거절
assert req("DELETE", f"/project/api/tasks/{t['id']}", BOB).status_code == 403
# 작업 삭제는 멤버 누구나(2026-10-12) — 남(BOB)이 만든 작업도 ALICE 가 지울 수 있다
t_bob = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "bob task", "stage_id": s["id"]}).json()["task"]
assert req("DELETE", f"/project/api/tasks/{t_bob['id']}", ALICE).status_code == 200
trash_before = _count("SELECT COUNT(*) AS n FROM project_trash")
# 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음
ST.remove_member(project_id=p["id"], user_email=ALICE)
assert req("DELETE", f"/project/api/tasks/{t['id']}", ALICE).status_code == 403
@@ -341,7 +346,7 @@ def test_file_comment_atomic_and_idempotent():
# [04] 날짜 범위
# ════════════════════════════════════════════════════════════
def test_date_range_validation():
p = _project("P-date", ADMIN, (BOB,))
p = _project("P-date", ADMIN, (BOB, PRO))
s = _stage(p["id"], by=ADMIN)
base = f"/project/api/projects/{p['id']}/tasks"
assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400
@@ -354,12 +359,12 @@ def test_date_range_validation():
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200
# 프로젝트도 같은 규칙(부분 수정 포함)
# 프로젝트도 같은 규칙(부분 수정 포함) — 프로젝트 수정은 Pro user 이상 멤버(2026-10-12)
pu = f"/project/api/projects/{p['id']}"
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400
assert req("POST", "/project/api/projects", BOB, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
assert req("PUT", pu, PRO, json={"due_date": "2026-10-01"}).status_code == 200
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01"}).status_code == 400
assert req("POST", "/project/api/projects", PRO, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
# ════════════════════════════════════════════════════════════
@@ -746,7 +751,8 @@ def test_goal_meetings():
except KeyError:
pass
try:
assert req("POST", f"/project/api/goals/meetings/{w1}", BOB, json={"year": w1.year}).status_code == 403
# 회의 완료(잠금)는 관리자만 — 회의록 만들기·고치기는 누구나(2026-10-07)
assert req("POST", f"/project/api/goals/meetings/{w1}/complete", BOB, json={"done": True}).status_code == 403
assert req("POST", f"/project/api/goals/meetings/{w1 + timedelta(days=1)}", ADMIN, json={}).status_code == 400
r = req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year})
assert r.status_code == 201 and r.json()["created"] is True, r.text
@@ -770,7 +776,7 @@ def test_goal_meetings():
assert r.status_code == 400
assert put(coupang["id"], {"target_amount": "1,200만"}).json()["item"]["target_amount"] == 12_000_000
assert put(coupang["id"], {"status": "bogus"}).status_code == 400
assert put(coupang["id"], {"content": "x"}, BOB).status_code == 403
assert put(coupang["id"], {"content": "추석 타임딜"}, BOB).status_code == 200 # 누구나 수정
assert req("PUT", f"/project/api/goals/meetings/{w1}", ADMIN,
json={"week_target": "3천만", "attendees": "대표", "notes": "메모"}).status_code == 200
# 다음 주 — 줄을 이어받고 전주 칸(prev)에 지난주 할 일·목표
@@ -780,6 +786,14 @@ def test_goal_meetings():
c2 = next(it for it in m2["items"] if it["carry_from"] == coupang["id"])
assert c2["prev"]["content"] == "추석 타임딜" and c2["prev"]["target_amount"] == 12_000_000
assert m2["prev_meeting"] == {"week_start": w1.isoformat(), "week_target": 30_000_000}
# 회의 완료(022) — w1 을 잠그면 w1 의 주요 업무는 못 고치지만, 지난주 결과는 다음 주(w2)가 열려 있으니 적을 수 있다
r = req("POST", f"/project/api/goals/meetings/{w1}/complete", ADMIN, json={"done": True})
if r.status_code == 200:
assert put(coupang["id"], {"content": "잠김"}, BOB).status_code == 409
assert put(coupang["id"], {"result_amount": "100"}, BOB).status_code == 200
assert req("POST", f"/project/api/goals/meetings/{w1}/complete", ADMIN, json={"done": False}).json()["completed"] is False
else:
assert r.status_code == 503, r.text # 022 미적용
# 지난주 결과·평가는 지난 회의록 줄에 저장
assert put(coupang["id"], {"result_amount": "1.5억", "status": "done"}).json()["item"]["result_amount"] == 150_000_000
# 줄 추가(기준 줄 아래)·이동(같은 구역 안)·삭제, 새 구역
@@ -1017,6 +1031,141 @@ def test_meeting_perf_unknown_vs_zero():
_drop_meetings([w, w - timedelta(days=7)])
# ════════════════════════════════════════════════════════════
# [검토 2026-10-12] 실제 DB — 동시성·조회 범위·알림 페이지·배지·회의록 결과 잠금
# ════════════════════════════════════════════════════════════
def _race(fns):
"""함수들을 최대한 같은 순간에 돌리고 (결과 또는 예외) 목록."""
gate = threading.Barrier(len(fns))
out: list = [None] * len(fns)
def run(i, fn):
gate.wait()
try:
out[i] = fn()
except Exception as exc: # noqa: BLE001
out[i] = exc
ths = [threading.Thread(target=run, args=(i, f)) for i, f in enumerate(fns)]
[t.start() for t in ths]
[t.join() for t in ths]
return out
def test_review_task_dates_never_invert_under_race():
p = _project("P-race", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
for _ in range(10):
t = ST.create_task(project_id=p["id"], title="race", stage_id=s["id"],
start_date="2026-10-10", due_date="2026-10-20", created_by=BOB)
_race([lambda: ST.update_task(task_id=t["id"], fields={"start_date": "2026-10-18"}),
lambda: ST.update_task(task_id=t["id"], fields={"due_date": "2026-10-12"})])
got = ST.get_task(task_id=t["id"])
assert got["start_date"] <= got["due_date"], got # 한쪽은 지금 값으로 검사돼 거절된다
# 프로젝트도 같은 규칙
for _ in range(5):
q = ST.create_project(name=f"race-{uuid.uuid4().hex[:4]}", owner_email=ADMIN, created_by=ADMIN,
start_date="2026-10-10", due_date="2026-10-20")
_race([lambda: ST.update_project(project_id=q["id"], fields={"start_date": "2026-10-18"}),
lambda: ST.update_project(project_id=q["id"], fields={"due_date": "2026-10-12"})])
got = ST.get_project(project_id=q["id"])
assert got["start_date"] <= got["due_date"], got
def test_review_concurrent_completion_logs_once():
p = _project("P-done-race", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
t = ST.create_task(project_id=p["id"], title="once", stage_id=s["id"], created_by=BOB)
outs = _race([lambda: ST.update_task(task_id=t["id"], fields={"completed": True}, actor=BOB) for _ in range(4)])
assert sum(1 for o in outs if isinstance(o, dict) and o["_newly_completed"]) == 1, outs
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id = %s AND action = 'completed'", t["id"]) == 1
def test_review_subproject_tasks_and_archived_scope():
parent = _project("P-parent", ADMIN, (BOB, CAROL))
child = ST.create_project(name=f"child-{uuid.uuid4().hex[:4]}", parent_id=parent["id"], owner_email=ADMIN, created_by=ADMIN)
ST.add_member(project_id=child["id"], user_email=CAROL)
tp = ST.create_task(project_id=parent["id"], title="부모", created_by=ADMIN)
tc = ST.create_task(project_id=child["id"], title="자식", created_by=ADMIN)
ids = lambda who: sorted(t["id"] for t in req("GET", f"/project/api/projects/{parent['id']}/tasks", who).json()["tasks"])
assert ids(BOB) == [tp["id"]] # 부모 멤버·자식 비멤버 — 자식 작업 안 보임
assert ids(CAROL) == sorted([tp["id"], tc["id"]])
assert req("GET", f"/project/api/projects/{parent['id']}/tasks", ADMIN).status_code == 200 # ADMIN = owner
# 보관된 프로젝트를 열어도 자기 작업은 받는다(스냅샷)
arch = _project("P-arch", BOB)
ta = ST.create_task(project_id=arch["id"], title="보관 작업", created_by=BOB)
ST.update_project(project_id=arch["id"], fields={"status": "archived"})
snap = req("GET", f"/project/api/projects/{arch['id']}/snapshot?scope=all", BOB).json()
assert ta["id"] in [t["id"] for t in snap["tasks"]]
assert [x["id"] for x in snap["projects"] if x.get("view_only")] == [arch["id"]]
def test_review_alert_paging_and_badges():
me = USERS.add(f"alert-{uuid.uuid4().hex[:6]}@test.local")
p = _project("P-alert", ADMIN, (me,))
t = ST.create_task(project_id=p["id"], title="x", created_by=ADMIN)
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="assigned", title="배정")
for _ in range(55):
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="comment", title="댓글")
out = req("GET", "/project/api/notifications/alerts?after=0", me).json()
assert [a["type"] for a in out["alerts"]] == ["assigned"] and out["alerts"][0]["href"] == f"/project/t/{t['id']}"
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 56
# 권한을 잃은 프로젝트의 알림은 배지에서 빠진다(기록은 그대로)
ST.remove_member(project_id=p["id"], user_email=me)
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 0
# 내 작업 배지·목록 — 미완료는 전부, 완료는 최근 것만
q = _project("P-my", ADMIN, (me,))
open_ids = [ST.create_task(project_id=q["id"], title=f"o{i}", assignee_email=me, created_by=ADMIN)["id"] for i in range(3)]
done_ids = []
for i in range(3):
d = ST.create_task(project_id=q["id"], title=f"d{i}", assignee_email=me, created_by=ADMIN)
ST.update_task(task_id=d["id"], fields={"completed": True})
done_ids.append(d["id"])
rows = ST.list_my_tasks(assignee_email=me, completed_limit=1)
assert sorted(r["id"] for r in rows if not r["completed_at"]) == sorted(open_ids)
assert [r["id"] for r in rows if r["completed_at"]] == [done_ids[-1]]
assert req("GET", "/project/api/my-tasks/open-count", me).json()["open"] == 3
ST.add_mentions(task_id=open_ids[0], emails=[me], actor_email=ADMIN)
assert req("GET", "/project/api/mentions/unread-count", me).json()["unread"] == 1
def test_review_reorder_and_creator_membership():
mine = _project("P-ord", PRO)
other = _project("P-ord-other", ADMIN)
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], other["id"]]}).status_code == 403
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], mine["id"]]}).status_code == 400
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"]]}).status_code == 200
r = req("POST", "/project/api/projects", PRO, json={"name": f"own-{RUN}", "owner_email": ALICE})
assert r.status_code == 201, r.text
pid = r.json()["project"]["id"]
assert ST.get_project(project_id=pid)["owner_email"] == ALICE
assert req("GET", f"/project/p/{pid}", PRO).status_code == 200 # 만든 직후 자기 프로젝트를 연다(멤버 행)
ST.remove_member(project_id=pid, user_email=PRO)
assert req("GET", f"/project/p/{pid}", PRO).status_code == 403 # created_by 로는 권한이 남지 않는다
def test_review_meeting_result_lock_rules():
from app.modules.project import store
w2 = date(2031, 10, 1) # 수요일 시작 1주차(달 경계)
w1 = store.prev_week_period(w2)[0] # 9월 마지막 주차
_drop_meetings([w1, w2])
try:
_create_meeting(w1)
item = ST.get_meeting(week_start=w1)["items"][0]["id"]
put = lambda body: req("PUT", f"/project/api/goals/meeting-items/{item}", BOB, json=body).status_code
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
assert put({"result_note": "다음 회의 전"}) == 409 # 다음 주차 회의록이 없으면 그 주가 완료되면 잠김
_create_meeting(w2)
assert put({"result_note": "다음 회의에서"}) == 200 # 다음 주차 회의록이 열려 있으면 결과는 적을 수 있다
assert put({"content": "내용"}) == 409 # 주요 업무는 그 주 완료로 잠김(잠금 차이 보존)
ST.set_meeting_completed(week_start=w2, done=True, by=ADMIN)
assert put({"result_note": "늦게"}) == 409
r = req("PUT", f"/project/api/goals/meetings/{w2}", BOB, json={"notes": "잠김"})
assert r.status_code == 409, r.text # 완료된 회의록 머리도
finally:
_drop_meetings([w1, w2])
if __name__ == "__main__":
if not ENABLED:
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
+134
View File
@@ -0,0 +1,134 @@
"""PC 알림 프로그램 API(023) — 토큰 인증·연결 요청/승인/발급·마이그레이션 미적용 503. DB 없이 가짜 저장소로."""
import importlib
import unittest
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from psycopg.errors import UndefinedTable
api = importlib.import_module("app.modules.project.router")
ROWS = [
{"id": 8, "type": "mention", "title": "나를 태그함: A", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 6, "type": "assigned", "title": "작업 배정: C", "is_read": False, "task_id": 3, "project_id": 1},
]
class FakeStore:
def __init__(self):
self.links = {} # poll → {"code", "email"}
self.tokens = {"good-token": "me@test.local"}
self.read = []
def list_notifications(self, recipient_email, unread_only=False, limit=100):
return ROWS[:limit]
def list_unread_after(self, recipient_email, after_id, types, limit=200):
return sorted((r for r in ROWS if not r["is_read"] and r["id"] > after_id and r["type"] in types),
key=lambda r: r["id"])[:limit]
def mark_read(self, notification_id, recipient_email):
self.read.append((notification_id, recipient_email))
def notifier_token_email(self, token):
return self.tokens.get(token)
def notifier_start_link(self, device_name):
self.links["poll-1"] = {"code": "ABCD-EFGH", "email": None, "device": device_name, "used": False}
return {"code": "ABCD-EFGH", "poll": "poll-1", "expires_in": 600}
def notifier_approve_link(self, code, email):
for link in self.links.values():
if link["code"] == code.upper() and link["email"] is None:
link["email"] = email
return True
return False
def notifier_poll_link(self, poll):
link = self.links.get(poll)
if not link or link["used"]:
return {"status": "expired"}
if not link["email"]:
return {"status": "pending"}
link["used"] = True
self.tokens["new-token"] = link["email"]
return {"status": "ok", "token": "new-token", "email": link["email"]}
def notifier_revoke_token(self, token):
self.tokens.pop(token, None)
USER = {"email": "me@test.local", "name": "나"}
class NotifierApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
self.st = FakeStore()
self.patches = [
patch.object(api, "_db_or_503", return_value=self.st),
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items),
patch.object(api, "_user_by_email", side_effect=lambda e: dict(USER) if e == USER["email"] else None),
patch("app.store.has_module", return_value=True),
]
for p in self.patches:
p.start()
def tearDown(self):
for p in self.patches:
p.stop()
def alerts(self, token, qs="?after=0"):
return self.client.get("/project/api/notifier/alerts" + qs, headers={"Authorization": "Bearer " + token})
def test_alerts_with_token_returns_same_payload_as_web_plus_name(self):
res = self.alerts("good-token")
self.assertEqual(res.status_code, 200)
out = res.json()
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
self.assertEqual((out["me"], out["latest_id"], out["name"]), ("me@test.local", 8, "나"))
# PC 알림 [열기] 도 웹과 같은 주소(작업 공유 링크) — 서버가 지금 권한으로 열 프로젝트를 고른다
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
def test_alerts_rejects_missing_or_unknown_token(self):
self.assertEqual(self.client.get("/project/api/notifier/alerts").status_code, 401)
self.assertEqual(self.alerts("bad").status_code, 401)
def test_alerts_rejects_user_without_project_module(self):
with patch("app.store.has_module", return_value=False):
self.assertEqual(self.alerts("good-token").status_code, 401)
def test_read_marks_only_for_token_owner(self):
res = self.client.post("/project/api/notifier/alerts/8/read", headers={"Authorization": "Bearer good-token"})
self.assertEqual(res.status_code, 200)
self.assertEqual(self.st.read, [(8, "me@test.local")])
def test_link_flow_pending_then_token_once(self):
start = self.client.post("/project/api/notifier/link/start", json={"device": "KING-PC"}).json()
self.assertEqual(start["approve_path"], "/project/notifier?code=ABCD-EFGH")
self.assertEqual(self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()["status"], "pending")
with patch.object(api, "_require_user", return_value=dict(USER)):
self.assertEqual(self.client.post("/project/api/notifier/link/approve", json={"code": "abcd-efgh"}).status_code, 200)
self.assertEqual(self.client.post("/project/api/notifier/link/approve", json={"code": "ABCD-EFGH"}).status_code, 404)
got = self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()
self.assertEqual((got["status"], got["token"]), ("ok", "new-token"))
self.assertEqual(self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()["status"], "expired")
self.assertEqual(self.alerts("new-token").status_code, 200)
def test_logout_revokes_token(self):
self.client.post("/project/api/notifier/logout", headers={"Authorization": "Bearer good-token"})
self.assertEqual(self.alerts("good-token").status_code, 401)
def test_missing_migration_is_503(self):
def boom(**_):
raise UndefinedTable("notifier_links")
self.st.notifier_start_link = boom
res = self.client.post("/project/api/notifier/link/start", json={"device": "X"})
self.assertEqual(res.status_code, 503)
if __name__ == "__main__":
unittest.main()
+478
View File
@@ -0,0 +1,478 @@
"""2026-10-12 검토 반영 회귀 테스트 — 권한·링크·조회 범위·저장 실패·동시성·중복 방지. DB 없이 가짜 저장소로.
실제 PostgreSQL 이 있어야 확인되는 동시성(두 요청이 정말 동시에 행을 잠그는 경우)은
tests/test_project_module.py 의 test_review_* 가 맡는다(로컬 테스트 DB 전용).
"""
import importlib
import sys
import tempfile
import threading
import time
import types
import unittest
from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.testclient import TestClient
from app.modules.project import access, store
from app.modules.project.db import ProjectStore
from app.store import SUPER_ADMIN_EMAIL
api = importlib.import_module("app.modules.project.router")
PM = {"email": "pm@test.local", "role": "pro"} # 부모(1)·보관(4) 멤버, 자식(2) 비멤버
BOTH = {"email": "both@test.local", "role": "user"} # 부모·자식 멤버
CHILD = {"email": "child@test.local", "role": "user"} # 자식만
ADMIN = {"email": "admin@test.local", "role": "admin"} # 어디에도 멤버 아님
SUPER = {"email": SUPER_ADMIN_EMAIL, "role": "admin"}
READER = {"email": "reader@test.local", "role": "pro"} # 부모(1)·연결 대상(3) 멤버 — 자식 작업 20 은 3 에 연결돼 READ
class Store(MagicMock):
"""프로젝트 1(부모) ─ 2(서브), 3(다른 프로젝트), 4(보관). 작업 10∈1, 20∈2(3 에 연결), 21∈2."""
PROJECTS = {
1: {"id": 1, "parent_id": None, "name": "부모", "owner_email": "", "status": "active", "created_by": ""},
2: {"id": 2, "parent_id": 1, "name": "자식", "owner_email": "", "status": "active", "created_by": ""},
3: {"id": 3, "parent_id": None, "name": "연결", "owner_email": "", "status": "active", "created_by": ""},
4: {"id": 4, "parent_id": None, "name": "보관", "owner_email": "", "status": "archived", "created_by": ""},
}
MEMBERS = {1: {"pm@test.local", "both@test.local", "reader@test.local"},
2: {"both@test.local", "child@test.local"},
3: {"reader@test.local"},
4: {"pm@test.local"}}
TASKS = {10: {"id": 10, "project_id": 1, "title": "부모 작업", "parent_task_id": None},
20: {"id": 20, "project_id": 2, "title": "자식 작업(연결)", "parent_task_id": None},
21: {"id": 21, "project_id": 2, "title": "자식 작업", "parent_task_id": None},
40: {"id": 40, "project_id": 4, "title": "보관 작업", "parent_task_id": None}}
LINKS = {20: {3}}
def is_member(self, project_id, user_email):
return user_email in self.MEMBERS.get(int(project_id), set())
def list_projects(self, include_archived=False, member_email=None):
return [dict(p) for pid, p in self.PROJECTS.items()
if (include_archived or p["status"] != "archived")
and (member_email is None or member_email in self.MEMBERS.get(pid, set()))]
def get_project(self, project_id):
p = self.PROJECTS.get(int(project_id))
return dict(p) if p else None
def get_task(self, task_id):
t = self.TASKS.get(int(task_id))
return dict(t) if t else None
def task_link_scope(self, task_ids):
return {int(t): set(self.LINKS[int(t)]) for t in task_ids if int(t) in self.LINKS}
def list_tasks(self, project_id=None, include_subprojects=False, limit=1000, **kw):
tree = {int(project_id)}
if include_subprojects:
tree |= {pid for pid, p in self.PROJECTS.items() if p["parent_id"] in tree}
return [dict(t) for t in self.TASKS.values() if t["project_id"] in tree]
def list_tasks_for_projects(self, project_ids, **kw):
self.asked_task_projects = list(project_ids)
out = []
for pid in project_ids:
out += [{**t, "context_project_id": pid} for t in self.TASKS.values() if t["project_id"] == pid]
out += [{**self.TASKS[tid], "context_project_id": pid} for tid, ps in self.LINKS.items() if pid in ps]
return out
def list_stages_for_projects(self, project_ids):
return {int(i): [] for i in project_ids}
def list_stages(self, project_id):
return []
def list_members(self, project_id):
return [{"user_email": e} for e in sorted(self.MEMBERS.get(int(project_id), set()))]
def client_for(st, data_dir=None):
app = FastAPI()
app.include_router(api.router)
app.state.project_store = st
app.state.data_dir = data_dir or tempfile.mkdtemp(prefix="pj-review-")
return TestClient(app, raise_server_exceptions=False)
class Base(unittest.TestCase):
def setUp(self):
self.st = Store()
for p in (patch.object(access, "can_use_module", side_effect=lambda u: bool(u)),):
p.start()
self.addCleanup(p.stop)
self.client = client_for(self.st)
def call(self, who, method, url, **kw):
with patch.object(api, "_require_user", return_value=who), patch.object(api, "_db_or_503", return_value=self.st):
return self.client.request(method, url, **kw)
# ── [1] 부모 프로젝트 조회로 서브프로젝트 작업이 새지 않는다 ─────────────
class SubprojectTasksTests(Base):
def ids(self, who, pid=1):
r = self.call(who, "GET", f"/project/api/projects/{pid}/tasks")
return r.status_code, sorted(t["id"] for t in r.json().get("tasks", [])) if r.status_code == 200 else None
def test_parent_member_without_child_membership(self):
self.assertEqual(self.ids(PM), (200, [10]))
def test_member_of_both_and_child_member(self):
self.assertEqual(self.ids(BOTH), (200, [10, 20, 21]))
self.assertEqual(self.ids(CHILD)[0], 403) # 부모 화면은 못 연다
self.assertEqual(self.ids(CHILD, pid=2), (200, [20, 21]))
def test_non_member_admin_and_super(self):
self.assertEqual(self.ids(ADMIN)[0], 403)
self.assertEqual(self.ids(SUPER), (200, [10, 20, 21]))
def test_linked_read_task_stays_visible(self):
# READER 는 자식(2) 멤버가 아니지만 작업 20 이 자기 프로젝트(3)에 연결돼 읽기 권한(READ)
self.assertEqual(self.ids(READER), (200, [10, 20]))
self.assertEqual(access.task_access(self.st, READER, self.st.get_task(20)), access.READ)
# ── [2] 사이드바 순서 API — 보낸 id 전부 관리 권한, 이상한 값은 400 ──────────
class ReorderTests(Base):
def put(self, who, body):
self.st.reorder_projects.reset_mock()
return self.call(who, "PUT", "/project/api/projects/order", json=body).status_code
def test_only_manageable_projects(self):
self.assertEqual(self.put(PM, {"ordered_ids": [4, 1]}), 200)
self.st.reorder_projects.assert_called_once_with(ordered_ids=[4, 1])
self.assertEqual(self.put(PM, {"ordered_ids": [1, 3]}), 403) # 3 은 멤버 아님
self.st.reorder_projects.assert_not_called() # 일부만 바뀌지 않는다
self.assertEqual(self.put(PM, {"ordered_ids": [999]}), 403) # 없는 id 도 같은 403
self.assertEqual(self.put(ADMIN, {"ordered_ids": [1]}), 403) # 비멤버 Admin
self.assertEqual(self.put(SUPER, {"ordered_ids": [3, 1]}), 200)
self.assertEqual(self.put(SUPER, {"ordered_ids": [999]}), 403)
self.assertEqual(self.put(BOTH, {"ordered_ids": [1]}), 403) # User 는 등급에서 막힘
def test_bad_payloads_are_400(self):
for body in ({}, {"ordered_ids": []}, {"ordered_ids": "1,2"}, {"ordered_ids": [1, 1]},
{"ordered_ids": [True]}, {"ordered_ids": ["a"]}, {"ordered_ids": [1.5]},
{"ordered_ids": [0]}, {"ordered_ids": [None]}):
with self.subTest(body=body):
self.assertEqual(self.put(PM, body), 400)
self.st.reorder_projects.assert_not_called()
# ── [3][4] 작업 열기 경로·보관/서브프로젝트 화면 ─────────────────────────
class FakeMain(types.ModuleType):
def __init__(self, who):
super().__init__("app.main")
self.who = who
self.ctx = None
self.user_store = SimpleNamespace(list_all=lambda: [], get=lambda e: None)
def get_current_user_record(self, request):
return self.who
def build_erp_nav(self, user, active=""):
return []
def render_template(self, request, name, ctx, status_code=200):
self.ctx = ctx
return HTMLResponse(f"{name}|{ctx.get('reason', '')}", status_code=status_code)
class OpenPathTests(Base):
def get(self, who, url):
fake = FakeMain(who)
with patch.dict(sys.modules, {"app.main": fake}), patch("app.store.has_module", return_value=True):
r = self.call(who, "GET", url, follow_redirects=False)
return r, fake
def test_permalink_opens_linked_project_for_read_user_and_keeps_embed(self):
r, _ = self.get(READER, "/project/t/20?embed=1")
self.assertEqual((r.status_code, r.headers["location"]), (303, "/project/p/3?task=20&embed=1"))
r, _ = self.get(PM, "/project/t/10")
self.assertEqual(r.headers["location"], "/project/p/1?task=10")
r, _ = self.get(ADMIN, "/project/t/20")
self.assertEqual(r.status_code, 403)
def test_old_home_project_url_redirects_read_user(self):
# 옛 PC 알림 프로그램·북마크(/p/{원 소속}?task=) — 403 대신 읽을 수 있는 연결된 프로젝트로
r, _ = self.get(READER, "/project/p/2?task=20&embed=1")
self.assertEqual((r.status_code, r.headers["location"]), (303, "/project/p/3?task=20&embed=1"))
r, _ = self.get(ADMIN, "/project/p/2?task=20")
self.assertEqual(r.status_code, 403)
r, _ = self.get(READER, "/project/p/2")
self.assertEqual(r.status_code, 403)
def test_archived_project_page_reads_its_own_tasks_only(self):
r, fake = self.get(PM, "/project/p/4")
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.st.asked_task_projects, [1, 4]) # 활성 최상위(1) + 지금 연 보관 프로젝트(4)만
self.assertIn(40, [t["id"] for t in fake.ctx["tasks"]])
metas = {p["id"]: p for p in fake.ctx["projects_meta"]}
self.assertTrue(metas[4]["view_only"]) # 화면용 — 사이드바 목록에는 없다
self.assertNotIn(4, [p["id"] for p in fake.ctx["nav_projects"]])
def test_snapshot_matches_first_page_scope(self):
r = self.call(PM, "GET", "/project/api/projects/4/snapshot?scope=all")
self.assertEqual(r.status_code, 200, r.text)
out = r.json()
self.assertEqual(self.st.asked_task_projects, [1, 4])
self.assertIn(40, [t["id"] for t in out["tasks"]])
self.assertEqual([p["id"] for p in out["projects"] if p.get("view_only")], [4])
def test_subproject_page_includes_its_tasks(self):
r, fake = self.get(BOTH, "/project/p/2")
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.st.asked_task_projects, [1, 2]) # 최상위 멤버 프로젝트(1) + 지금 연 서브프로젝트(2)
self.assertEqual(sorted(t["id"] for t in fake.ctx["tasks"] if t["context_project_id"] == 2), [20, 21])
# ── [8] 일반 첨부 — DB 저장 실패면 이 요청이 쓴 파일만 지운다 ─────────────
class AttachmentCleanupTests(Base):
def test_db_failure_removes_only_new_file(self):
data_dir = tempfile.mkdtemp(prefix="pj-att-")
self.client = client_for(self.st, data_dir)
old = Path(data_dir) / "project" / "10"
old.mkdir(parents=True)
(old / "existing.bin").write_bytes(b"keep")
self.st.add_attachment.side_effect = RuntimeError("db down")
r = self.call(PM, "POST", "/project/api/tasks/10/attachments", files={"file": ("a.txt", b"hello", "text/plain")})
self.assertEqual(r.status_code, 500)
self.assertEqual(sorted(p.name for p in old.iterdir()), ["existing.bin"])
self.st.add_attachment.side_effect = None
self.st.add_attachment.return_value = {"id": 1}
r = self.call(PM, "POST", "/project/api/tasks/10/attachments", files={"file": ("a.txt", b"hello", "text/plain")})
self.assertEqual(r.status_code, 201)
self.assertEqual(len(list(old.iterdir())), 2)
# 빈 파일·권한은 그대로
self.assertEqual(self.call(PM, "POST", "/project/api/tasks/10/attachments",
files={"file": ("e.txt", b"", "text/plain")}).status_code, 400)
self.assertEqual(self.call(CHILD, "POST", "/project/api/tasks/10/attachments",
files={"file": ("a.txt", b"x", "text/plain")}).status_code, 403)
# ── [10] 배지 개수 — 제한 없이, 지금 권한으로 ─────────────────────────────
class BadgeCountTests(Base):
def test_my_open_count_is_exact_past_old_limit(self):
self.st.list_my_open_refs.return_value = (
[{"id": i, "project_id": 1} for i in range(1, 1501)] + [{"id": 5000 + i, "project_id": 2} for i in range(10)])
self.assertEqual(api._my_open_count(self.st, PM), 1500) # 2(비멤버)의 10건은 빼고
self.assertEqual(api._my_open_count(self.st, BOTH), 1510)
def test_unread_notification_count_is_exact(self):
self.st.list_unread_refs.return_value = (
[{"id": i, "project_id": 1, "task_id": 10} for i in range(700)] + [{"id": 900, "project_id": 2, "task_id": 21}])
self.assertEqual(api._notification_unread(self.st, PM), 700)
self.assertEqual(api._notification_unread(self.st, BOTH), 701)
def test_unread_mentions_count_filters_by_current_access(self):
self.st.list_unread_mention_refs.return_value = [
{"id": 10, "project_id": 1, "unread_mentions": 3}, {"id": 21, "project_id": 2, "unread_mentions": 4}]
self.assertEqual(api._safe_mention_unread(self.st, PM), 3)
self.assertEqual(api._safe_mention_unread(self.st, BOTH), 7)
# ── [13] 남을 소유자로 지정해 만들면 만든 사람은 명시적 멤버로 ───────────────
class CreatorMemberTests(Base):
def test_creator_added_as_member_only_when_owner_is_someone_else(self):
self.st.create_project.return_value = {"id": 9, "name": "n"}
with patch.object(api, "_check_owner_candidate"):
self.call(PM, "POST", "/project/api/projects", json={"name": "n", "owner_email": "other@test.local"})
kw = self.st.create_project.call_args.kwargs
self.assertEqual((kw["owner_email"], kw["member_emails"]), ("other@test.local", ["pm@test.local"]))
self.call(PM, "POST", "/project/api/projects", json={"name": "n"})
kw = self.st.create_project.call_args.kwargs
self.assertEqual((kw["owner_email"], kw["member_emails"]), ("pm@test.local", []))
# ── [14] 중복 방지 키 — 실패·성공·동시 요청에서 잠금이 남지 않는다 ───────────
class OnceTests(unittest.TestCase):
USER = {"email": "me@test.local"}
def setUp(self):
api._once_results.clear()
api._once_key_locks.clear()
def test_failure_releases_lock_and_retry_runs_again(self):
calls = []
def boom():
calls.append(1)
raise RuntimeError("x")
with self.assertRaises(RuntimeError):
api._once(self.USER, 1, "tok", boom)
self.assertEqual(api._once_key_locks, {}) # 실패한 키의 잠금이 남지 않는다
out = api._once(self.USER, 1, "tok", lambda: {"ok": 1})
self.assertEqual((out, len(calls)), ({"ok": 1}, 1))
self.assertEqual(api._once(self.USER, 1, "tok", lambda: {"ok": 2}), {"ok": 1, "duplicate": True}) # 응답 유실 후 재전송
self.assertEqual(api._once_key_locks, {})
def test_concurrent_same_token_runs_once(self):
started, release, runs, outs = threading.Event(), threading.Event(), [], []
def slow():
runs.append(1)
started.set()
release.wait(2)
return {"id": 7}
th = [threading.Thread(target=lambda: outs.append(api._once(self.USER, 1, "same", slow))) for _ in range(5)]
th[0].start()
started.wait(2)
for t in th[1:]:
t.start()
time.sleep(0.05)
self.assertEqual(api._once_key_locks[("me@test.local", 1, "same")][1], 5) # 기다리는 요청이 있는 동안 유지
release.set()
for t in th:
t.join(2)
self.assertEqual(len(runs), 1)
self.assertEqual(sorted(bool(o.get("duplicate")) for o in outs), [False, True, True, True, True])
self.assertEqual(api._once_key_locks, {})
def test_expired_results_are_purged(self):
api._once(self.USER, 1, "old", lambda: {"ok": 1})
with patch.object(api.time, "monotonic", return_value=time.monotonic() + api._ONCE_TTL_SEC + 1):
api._once(self.USER, 1, "new", lambda: {"ok": 2})
self.assertNotIn(("me@test.local", 1, "old"), api._once_results)
# ── [B] 섹션 기본 담당자 — 지금 권한(등록·project 권한)도 통과해야 자동 배정 ──────
class _Res:
def __init__(self, rows):
self.rows = list(rows)
def fetchone(self):
return self.rows[0] if self.rows else None
def fetchall(self):
return self.rows
class StageDefaultAssigneeTests(unittest.TestCase):
def conn(self):
def execute(sql, params=()):
if "to_jsonb(s)" in sql:
return _Res([{"e": "Gone@Test.local"}])
if "FROM project_members" in sql:
return _Res([{"user_name": "Gone"}])
raise AssertionError(sql)
return SimpleNamespace(execute=execute)
def test_revoked_or_deleted_user_is_not_auto_assigned(self):
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1), ("gone@test.local", "Gone"))
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1, allowed=lambda e: False), ("", ""))
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1, allowed=lambda e: True),
("gone@test.local", "Gone"))
def test_router_check_uses_user_registry_and_module(self):
with patch.object(access, "default_user_lookup", return_value=None):
self.assertFalse(api._registered_project_user("x@test.local"))
with patch.object(access, "default_user_lookup", return_value={"email": "x@test.local"}), \
patch.object(access, "can_use_module", return_value=False):
self.assertFalse(api._registered_project_user("x@test.local"))
with patch.object(access, "default_user_lookup", return_value={"email": "x@test.local"}), \
patch.object(access, "can_use_module", return_value=True):
self.assertTrue(api._registered_project_user("x@test.local"))
# ── [11] 작업 수정 — 잠근 행으로 검사, 같은 연결, 실제 전환 기준 알림 힌트 ────────
class TaskConn:
"""tasks 한 행 + 섹션. FOR UPDATE 로 읽힌 '지금 값'이 검사·알림 기준이어야 한다."""
def __init__(self, row):
self.row = dict(row)
self.depth, self.locked, self.updates, self.logs = 0, False, [], []
self.stages = {11: {"project_id": 1, "is_done_stage": False, "dae": "dae@test.local"},
12: {"project_id": 1, "is_done_stage": True, "dae": ""}}
@contextmanager
def transaction(self):
self.depth += 1
try:
yield
finally:
self.depth -= 1
self.locked = False
def execute(self, sql, params=()):
if sql.startswith("SELECT * FROM tasks WHERE id = %s FOR UPDATE"):
assert self.depth > 0
self.locked = True
return _Res([dict(self.row)])
if sql.startswith("SELECT 1 FROM project_stages WHERE id = %s AND project_id = %s"):
s = self.stages.get(params[0])
return _Res([{"?": 1}] if s and s["project_id"] == params[1] else [])
if "to_jsonb(s)" in sql:
return _Res([{"e": self.stages[params[0]]["dae"]}])
if "FROM project_members" in sql:
return _Res([{"user_name": "Dae"}])
if sql.startswith("SELECT is_done_stage FROM project_stages"):
return _Res([{"is_done_stage": self.stages[params[0]]["is_done_stage"]}])
if sql.startswith("UPDATE tasks SET"):
assert self.locked, "변경은 잠근 행에"
self.updates.append((sql, params))
return _Res([])
if sql.startswith("INSERT INTO project_activity"):
self.logs.append(params)
return _Res([])
raise AssertionError(sql)
class UpdateTaskConcurrencyTests(unittest.TestCase):
def make(self, row, stale=None):
self.conn = TaskConn(row)
self.borrows = 0
@contextmanager
def connection():
self.borrows += 1
yield self.conn
st = ProjectStore.__new__(ProjectStore)
st._pool = SimpleNamespace(connection=connection)
# 잠그기 전 다른 연결로 읽은 옛 값(예전 코드가 검사에 쓰던 값) — 이제는 결과 표시에만 쓰인다
st.get_task = lambda task_id: {**(stale or self.conn.row), "id": task_id}
return st
BASE = {"id": 7, "project_id": 1, "stage_id": 11, "title": "t", "assignee_email": "", "completed_at": None,
"start_date": "2026-10-10", "due_date": "2026-10-20", "start_time": None, "due_time": None}
def test_date_check_uses_locked_current_row(self):
# A 가 시작일을 10/18 로 이미 바꿨다(잠근 행) — B 의 마감일 10/12 는 옛 값(10/10)으론 통과했지만 이제 거절
st = self.make({**self.BASE, "start_date": "2026-10-18"}, stale=self.BASE)
with self.assertRaises(ValueError):
st.update_task(task_id=7, fields={"due_date": "2026-10-12"})
self.assertEqual(self.conn.updates, [])
st.update_task(task_id=7, fields={"due_date": "2026-10-25"})
self.assertEqual(len(self.conn.updates), 1)
self.assertEqual(self.borrows, 2) # 요청마다 연결 하나(get_task 대역 제외) — 트랜잭션 안에서 다시 빌리지 않는다
def test_second_completion_is_not_a_new_transition(self):
st = self.make({**self.BASE, "completed_at": "2026-10-11T10:00:00+09:00"})
out = st.update_task(task_id=7, fields={"completed": True}, actor="b@test.local")
self.assertFalse(out["_newly_completed"])
self.assertEqual((self.conn.updates, self.conn.logs), ([], []))
def test_stage_move_default_assignee_and_done_in_same_connection(self):
st = self.make({**self.BASE, "stage_id": 12})
asked = []
out = st.update_task(task_id=7, fields={"stage_id": 11}, actor="a@test.local",
assignee_allowed=lambda e: asked.append(e) or True)
self.assertEqual((asked, out["_newly_assigned"], self.borrows), (["dae@test.local"], "dae@test.local", 1))
st = self.make({**self.BASE, "stage_id": 12})
out = st.update_task(task_id=7, fields={"stage_id": 11}, assignee_allowed=lambda e: False)
self.assertIsNone(out["_newly_assigned"]) # 권한을 잃은 기본 담당자는 자동 배정·배정 알림 없음
st = self.make(self.BASE)
out = st.update_task(task_id=7, fields={"stage_id": 12})
self.assertTrue(out["_newly_completed"])
self.assertEqual(len(self.conn.logs), 1)
if __name__ == "__main__":
unittest.main()
+205
View File
@@ -0,0 +1,205 @@
"""관리자 등급(2026-10-12) — 수퍼관리자 > Admin > Pro user > User 별 프로젝트·목표·회의록 권한. DB 없이."""
import importlib
import tempfile
import unittest
from unittest.mock import MagicMock, patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.project import access
from app.store import SUPER_ADMIN_EMAIL, UserStore, is_admin
api = importlib.import_module("app.modules.project.router")
SUPER = {"email": SUPER_ADMIN_EMAIL, "role": "admin"}
ADMIN = {"email": "admin@test.local", "role": "admin"}
PRO = {"email": "pro@test.local", "role": "pro"}
USER = {"email": "user@test.local", "role": "user"}
OUTSIDER_PRO = {"email": "pro2@test.local", "role": "pro"} # 프로젝트 1 멤버가 아닌 Pro user
class FakeStore(MagicMock):
"""프로젝트 1 = admin·pro·user 멤버(pro2 는 아님). 나머지 메서드는 MagicMock 이 받아 준다."""
MEMBERS = {1: {"admin@test.local", "pro@test.local", "user@test.local"}}
def is_member(self, project_id, user_email):
return user_email in self.MEMBERS.get(int(project_id), set())
def list_projects(self, include_archived=False, member_email=None):
return [{"id": pid, "parent_id": None} for pid, ms in self.MEMBERS.items()
if member_email is None or member_email in ms]
def get_project(self, project_id):
return {"id": project_id, "name": "P1", "owner_email": "admin@test.local", "created_by": "admin@test.local"}
def get_task(self, task_id):
# 남(admin)이 만든 작업
return {"id": task_id, "project_id": 1, "title": "t", "created_by": "admin@test.local"}
def get_stage(self, stage_id):
return {"id": stage_id, "project_id": 1, "created_by": "admin@test.local"}
def task_link_scope(self, task_ids):
return {}
class RoleHelperTests(unittest.TestCase):
def test_role_of(self):
self.assertEqual(access.role_of(SUPER), "super")
self.assertEqual(access.role_of(ADMIN), "admin")
self.assertEqual(access.role_of(PRO), "pro")
self.assertEqual(access.role_of(USER), "user")
self.assertEqual(access.role_of({"email": "x@test.local", "role": "weird"}), "user")
self.assertEqual(access.role_of(None), "user")
def test_pro_and_admin_flags(self):
self.assertEqual([access.is_pro(u) for u in (SUPER, ADMIN, PRO, USER)], [True, True, True, False])
self.assertEqual([access.is_project_admin(u) for u in (SUPER, ADMIN, PRO, USER)], [True, True, False, False])
# pro 는 프로젝트 모듈 밖(관리자 페이지 등)에서는 관리자가 아니다
self.assertFalse(is_admin(PRO))
def test_can_delete_project_or_section(self):
self.assertTrue(api._can_delete(ADMIN, "someone@test.local"))
self.assertTrue(api._can_delete(SUPER, "someone@test.local"))
self.assertFalse(api._can_delete(PRO, "someone@test.local"))
self.assertTrue(api._can_delete(PRO, "pro@test.local"))
self.assertTrue(api._can_delete(USER, "USER@test.local"))
# 만든 사람 기록이 없는 옛 데이터 — Admin 이상만
self.assertTrue(api._can_delete(ADMIN, ""))
self.assertFalse(api._can_delete(PRO, ""))
self.assertFalse(api._can_delete(USER, None))
def test_role_ctx(self):
self.assertEqual(api._role_ctx(PRO), {"is_admin": False, "pj_pro": True, "pj_admin": False})
self.assertEqual(api._role_ctx(ADMIN), {"is_admin": True, "pj_pro": True, "pj_admin": True})
self.assertEqual(api._role_ctx(USER), {"is_admin": False, "pj_pro": False, "pj_admin": False})
class UserStoreRoleTests(unittest.TestCase):
def setUp(self):
d = tempfile.mkdtemp(prefix="users-")
self.us = UserStore(__import__("pathlib").Path(d) / "users.json")
def test_pro_role_saved_and_validated(self):
rec = self.us.create_user(email="p@test.local", role="pro")
self.assertEqual(rec["role"], "pro")
self.assertFalse(any(rec["modules"].values())) # pro 도 모듈은 기본 꺼짐(user 와 같음)
rec = self.us.update_permissions(email="p@test.local", role="user", modules=None)
self.assertEqual(rec["role"], "user")
with self.assertRaises(ValueError):
self.us.create_user(email="x@test.local", role="super")
with self.assertRaises(PermissionError):
self.us.update_permissions(email=SUPER_ADMIN_EMAIL, role="pro", modules=None)
class RoleApiTests(unittest.TestCase):
def setUp(self):
self.st = FakeStore()
p = patch.object(access, "can_use_module", side_effect=lambda u: bool(u))
p.start()
self.addCleanup(p.stop)
app = FastAPI()
app.include_router(api.router)
app.state.data_dir = tempfile.mkdtemp(prefix="pj-roles-")
self.client = TestClient(app)
def call(self, who, method, url, **kw):
with patch.object(api, "_require_user", return_value=who), patch.object(api, "_db_or_503", return_value=self.st):
return self.client.request(method, url, **kw)
def test_create_project_pro_and_up(self):
self.st.create_project.return_value = {"id": 9, "name": "n"}
self.assertEqual(self.call(USER, "POST", "/project/api/projects", json={"name": "n"}).status_code, 403)
for who in (PRO, ADMIN):
self.assertEqual(self.call(who, "POST", "/project/api/projects", json={"name": "n"}).status_code, 201)
def test_subproject_any_member(self):
self.st.create_project.return_value = {"id": 10, "name": "s"}
r = self.call(USER, "POST", "/project/api/projects/1/subprojects", json={"name": "s"})
self.assertEqual(r.status_code, 201, r.text)
def test_edit_project_pro_member_only(self):
self.st.update_project.return_value = {"id": 1, "name": "x"}
self.assertEqual(self.call(USER, "PUT", "/project/api/projects/1", json={"name": "x"}).status_code, 403)
self.assertEqual(self.call(OUTSIDER_PRO, "PUT", "/project/api/projects/1", json={"name": "x"}).status_code, 403)
self.assertEqual(self.call(PRO, "PUT", "/project/api/projects/1", json={"name": "x"}).status_code, 200)
def test_owner_change_by_pro(self):
self.st.update_project.return_value = {"id": 1}
with patch.object(api, "_check_owner_candidate"):
r = self.call(PRO, "PUT", "/project/api/projects/1", json={"owner_email": "user@test.local"})
self.assertEqual(r.status_code, 200, r.text)
def test_delete_project_admin_any_pro_own(self):
self.st.delete_project.return_value = []
self.assertEqual(self.call(PRO, "DELETE", "/project/api/projects/1").status_code, 403) # admin 이 만든 것
self.assertEqual(self.call(ADMIN, "DELETE", "/project/api/projects/1").status_code, 200)
def test_members_pro_in_own_project(self):
self.st.add_member.return_value = {"user_email": "x@test.local"}
body = {"user_email": "x@test.local"}
self.assertEqual(self.call(USER, "POST", "/project/api/projects/1/members", json=body).status_code, 403)
self.assertEqual(self.call(OUTSIDER_PRO, "POST", "/project/api/projects/1/members", json=body).status_code, 403)
self.assertEqual(self.call(PRO, "POST", "/project/api/projects/1/members", json=body).status_code, 201)
self.assertEqual(self.call(PRO, "DELETE", "/project/api/projects/1/members/x@test.local").status_code, 200)
def test_reorder_pro_and_up(self):
body = {"ordered_ids": [1]}
self.assertEqual(self.call(USER, "PUT", "/project/api/projects/order", json=body).status_code, 403)
self.assertEqual(self.call(PRO, "PUT", "/project/api/projects/order", json=body).status_code, 200)
# Pro user 라도 멤버가 아닌 프로젝트는 순서를 못 바꾼다(검토 2026-10-12)
self.assertEqual(self.call(OUTSIDER_PRO, "PUT", "/project/api/projects/order", json=body).status_code, 403)
def test_section_delete_admin_any_others_creator(self):
self.assertEqual(self.call(PRO, "DELETE", "/project/api/projects/1/stages/5").status_code, 403)
self.assertEqual(self.call(USER, "DELETE", "/project/api/projects/1/stages/5").status_code, 403)
self.assertEqual(self.call(ADMIN, "DELETE", "/project/api/projects/1/stages/5").status_code, 200)
def test_task_delete_any_member(self):
self.st.delete_task.return_value = ([7], None)
r = self.call(USER, "DELETE", "/project/api/tasks/7") # 남이 만든 작업도
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.call(OUTSIDER_PRO, "DELETE", "/project/api/tasks/7").status_code, 403)
def test_comment_edit_passes_pro_flag(self):
self.st.get_comment.return_value = {"id": 3, "task_id": 7, "author_email": "admin@test.local"}
self.st.update_comment.return_value = {"id": 3}
for who, flag in ((PRO, True), (USER, False)):
self.st.update_comment.reset_mock()
with patch.object(api, "_comment_task_access"):
self.call(who, "PUT", "/project/api/comments/3", json={"body": "b"})
self.assertEqual(self.st.update_comment.call_args.kwargs["is_admin"], flag)
def test_workload_summary_pro_only(self):
self.st.list_tasks_for_projects.return_value = []
self.st.list_subtasks_of.return_value = []
self.assertEqual(self.call(USER, "GET", "/project/api/projects/1/subtasks-summary").status_code, 403)
self.assertEqual(self.call(PRO, "GET", "/project/api/projects/1/subtasks-summary").status_code, 200)
def test_trash_restore_pro(self):
self.st.list_trash.return_value = [{"id": 4, "project_id": 1}] # 프로젝트 1 = PRO 가 멤버(list_projects)
self.st.restore_trash.return_value = {"restored": 1}
self.assertEqual(self.call(USER, "POST", "/project/api/trash/4/restore").status_code, 403)
self.assertEqual(self.call(PRO, "POST", "/project/api/trash/4/restore").status_code, 200)
def test_goals_input_pro_and_up(self):
body = {"metric": "sales", "kind": "target", "month": 1, "value": "10"}
self.assertEqual(self.call(USER, "PUT", "/project/api/goals/2026/metrics", json=body).status_code, 403)
self.assertEqual(self.call(PRO, "PUT", "/project/api/goals/2026/metrics", json=body).status_code, 200)
self.assertEqual(self.call(USER, "POST", "/project/api/goals/years", json={"year": 2027}).status_code, 403)
self.assertEqual(self.call(PRO, "POST", "/project/api/goals/years", json={"year": 2027}).status_code, 201)
self.assertEqual(self.call(USER, "DELETE", "/project/api/goals/2027").status_code, 403)
self.assertEqual(self.call(PRO, "DELETE", "/project/api/goals/2027").status_code, 200)
def test_meeting_complete_and_delete_pro(self):
self.st.set_meeting_completed.return_value = {"completed": True}
for url, method, kw in (("/project/api/goals/meetings/2026-10-12/complete", "POST", {"json": {"done": True}}),
("/project/api/goals/meetings/2026-10-12", "DELETE", {})):
self.assertEqual(self.call(USER, method, url, **kw).status_code, 403)
self.assertEqual(self.call(PRO, method, url, **kw).status_code, 200)
if __name__ == "__main__":
unittest.main()