diff --git a/CLAUDE.md b/CLAUDE.md index 5a352ee..5cc7dff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia` - 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1상자=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md` - 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력. 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지(`POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A` — NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다. 그래서 "마지막 쓰기가 권위": 상세설명은 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 쓰고(`store.resolve_description`), 스칼라(상품명·가격·이미지·진열/판매)는 PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌운다(`store.overlay_recent_write`). 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분). 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다. 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md` -- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 머리는 모두 `#f3f3f3` — 섹션별 색 지정 없음, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`). 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 3·6·9·12월 오른쪽 1~4분기 칸(글 칸 13=1분기·15=2분기·14=3분기·16=4분기 — 예전 반기 칸 번호 재사용, 15·16 은 마이그레이션 017) + 분기 월 칸 접기 애니메이션(localStorage `pj_goal_fold_q`, 표는 `width:1px`+`table-layout:fixed`), 영역·줄 이름 클릭 바로 수정, **엑셀식 칸 병합**(마우스로 끌어 사각형 선택 → 우클릭 셀 병합/병합 해제, 같은 영역 안 세로 `row_span` + 같은 분기 월 칸 가로, 글은 왼쪽 위 칸 — `goal_cell_merges`, 마이그레이션 014·015·017), 3열 줄 추가는 같은 항목 칸(2열) 안에(`goal_rows.label_cont`, 마이그레이션 016), 구조 변경은 새로고침 없이 제자리 다시 그리기(`refreshTable`)+애니메이션, 로아스는 % 표기. 월 머리 → **주간 회의록**(`/project/goals/{연도}/meetings/{월}`, 프로젝트 권한자 **누구나 수정** — 관리자 [회의 완료](`completed_at`, 마이그레이션 022)면 잠금(지난주 결과는 다음 주 회의록이 열려 있는 동안 허용), 삭제·완료·완료 해제는 관리자, 주차 탭 — **주차는 그 달 안**(`store.month_weeks`: 1일이 월~금이면 1일~일요일이 1주차, 토·일이면 1일~다음 주 일요일, 그 뒤 월~일, 말일이 월·화면 앞 주차에 붙음, 회의록 `week_start` = 주차 시작일, 마이그레이션 020), `goal_meetings`·`goal_meeting_items` 마이그레이션 015 — 지난주 = **바로 앞 주차**(`store.prev_week_period`) 회의록의 같은 연결키 줄(`line_key`, 마이그레이션 018 — 생성 순서·이름 변경과 무관, 이름 추정 연결 금지)로 리뷰(열: 주요 업무·정량 목표 ‖ 전주 업무·결과(글, `result_note` 020)·전주 목표·결과 — 정량 목표·결과는 숫자면 원 정수 칸, 아니면 글 칸 `target_text`·`result_text`(예: 20개, 021)), 실적 조회 장애는 0원이 아니라 "미확인", 위에 목표 표 그 달 열 글을 영역별 "N월 계획" 카드로, 참석자 옆 [회의록 보드] = 그 주차의 빈 Google 슬라이드를 독립 창으로(공유 드라이브 `MEETING_BOARD_FOLDER_ID`, 없으면 만듦, `app/integrations/google_slides.py`, Drive appProperties 로 주차 연결 — Drive·Slides 권한 토큰 필요), 표를 스크롤해도 보이는 머리 영역 3칸 = ① 월 계획 + 머리 줄에 숫자 4개 작게 1행(월 목표 매출·월 누적 목표 매출(목표 표 **주차별 매출 목표** `goal_week_targets` 1주차~이 주차 합 — 목표 표 매출 목표 월 칸을 누르면 입력 창 — 월 전체 목표는 직접 입력(주차 합계와 별개), 맨 아래 차이 = 월 목표 − 주차 합계)·월 누적 실적(1일~오늘)·누적 목표 대비 차액·%) | ② 결정 사항·메모 | ③ 작업 등록 표(제목·담당자·프로젝트·섹션 → [적용] = 그 프로젝트에 작업 생성, `initMeetQuickTasks`), 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력). 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 목표 표·회의록 칸 저장은 공용 `createFieldSaver`(같은 칸 요청 직렬화·보낸 값만 저장됨·실패 시 초안 유지·localStorage 초안 백업, 저장 실패면 구조 변경 중단 — docs/PROJECT_MODULE.md 6-9-3), 구역·항목 메뉴는 우클릭 + ⋮ 버튼(키보드·터치). ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title). 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea), 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md` +- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 머리는 모두 `#f3f3f3` — 섹션별 색 지정 없음, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`). 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 3·6·9·12월 오른쪽 1~4분기 칸(글 칸 13=1분기·15=2분기·14=3분기·16=4분기 — 예전 반기 칸 번호 재사용, 15·16 은 마이그레이션 017) + 분기 월 칸 접기 애니메이션(localStorage `pj_goal_fold_q`, 표는 `width:1px`+`table-layout:fixed`), 영역·줄 이름 클릭 바로 수정, **엑셀식 칸 병합**(마우스로 끌어 사각형 선택 → 우클릭 셀 병합/병합 해제, 같은 영역 안 세로 `row_span` + 같은 분기 월 칸 가로, 글은 왼쪽 위 칸 — `goal_cell_merges`, 마이그레이션 014·015·017), 3열 줄 추가는 같은 항목 칸(2열) 안에(`goal_rows.label_cont`, 마이그레이션 016), 구조 변경은 새로고침 없이 제자리 다시 그리기(`refreshTable`)+애니메이션, 로아스는 % 표기. 월 머리 → **주간 회의록**(`/project/goals/{연도}/meetings/{월}`, 프로젝트 권한자 **누구나 수정** — 관리자 [회의 완료](`completed_at`, 마이그레이션 022)면 잠금(지난주 결과는 다음 주 회의록이 열려 있는 동안 허용), 삭제·완료·완료 해제는 관리자, 주차 탭 — **주차는 그 달 안**(`store.month_weeks`: 1일이 월~금이면 1일~일요일이 1주차, 토·일이면 1일~다음 주 일요일, 그 뒤 월~일, 말일이 월·화면 앞 주차에 붙음, 회의록 `week_start` = 주차 시작일, 마이그레이션 020), `goal_meetings`·`goal_meeting_items` 마이그레이션 015 — 지난주 = **바로 앞 주차**(`store.prev_week_period`) 회의록의 같은 연결키 줄(`line_key`, 마이그레이션 018 — 생성 순서·이름 변경과 무관, 이름 추정 연결 금지)로 리뷰(열: 주요 업무·정량 목표 ‖ 전주 업무·결과(글, `result_note` 020)·전주 목표·결과 — 정량 목표·결과는 숫자면 원 정수 칸, 아니면 글 칸 `target_text`·`result_text`(예: 20개, 021)), 실적 조회 장애는 0원이 아니라 "미확인", 위에 목표 표 그 달 열 글을 영역별 "N월 계획" 카드로, 참석자 옆 [회의록 보드] = 그 주차의 빈 Google 슬라이드를 독립 창으로(공유 드라이브 `MEETING_BOARD_FOLDER_ID`, 없으면 만듦, `app/integrations/google_slides.py`, Drive appProperties 로 주차 연결 — Drive·Slides 권한 토큰 필요), 표를 스크롤해도 보이는 머리 영역 3칸 = ① 월 계획 + 머리 줄에 숫자 4개 작게 1행(월 목표 매출·월 누적 목표 매출(목표 표 **주차별 매출 목표** `goal_week_targets` 1주차~이 주차 합 — 목표 표 매출 목표 월 칸을 누르면 입력 창 — 월 전체 목표는 직접 입력(주차 합계와 별개), 맨 아래 차이 = 월 목표 − 주차 합계)·월 누적 실적(1일~오늘)·누적 목표 대비 차액·%) | ② 결정 사항·메모 | ③ 작업 등록 표(제목·담당자·프로젝트·섹션 → [적용] = 그 프로젝트에 작업 생성, `initMeetQuickTasks`), 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력). 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 목표 표·회의록 칸 저장은 공용 `createFieldSaver`(같은 칸 요청 직렬화·보낸 값만 저장됨·실패 시 초안 유지·localStorage 초안 백업, 저장 실패면 구조 변경 중단 — docs/PROJECT_MODULE.md 6-9-3), 구역·항목 메뉴는 우클릭 + ⋮ 버튼(키보드·터치). ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title). **PC 알림 프로그램**(`desktop/notifier/`, C# .NET Framework 4.8 WinForms exe 하나·트레이 상주, 마이그레이션 023 `notifier_links`·`notifier_tokens`) — 브라우저가 뒤에 있어도 태그·배정 알림을 웹 팝업과 같은 모양으로 화면 위에. 브라우저 `/project/notifier?code=` 승인으로 PC별 토큰(서버는 SHA-256 만, PC 는 DPAPI), `GET /project/api/notifier/alerts`(Bearer)는 웹 알림과 같은 `_alerts_payload`, 토큰마다 지금 사용자·권한 재확인. 압축·난독화 금지(백신 오탐), 빌드 `desktop/notifier/build.ps1`, 상세 docs/PROJECT_MODULE.md 6-11. 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea), 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md` - 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md` @@ -101,6 +101,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 ``` Main-app/ ├─ app/ FastAPI 앱 소스 +├─ desktop/notifier/ PC 알림 트레이 프로그램(C#, Windows exe) ├─ docs/ 운영/설계 문서 (작업 전 필독) ├─ scripts/ 배포·유지보수 스크립트 ├─ skills/ Claude Code 규칙/스킬 diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 19defac..f37772e 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -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 @@ -1560,6 +1562,123 @@ 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_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 # diff --git a/app/modules/project/router.py b/app/modules/project/router.py index ea078ae..1ce9d41 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -2299,19 +2299,180 @@ def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse: 처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게.""" user = _require_user(request) st = _db_or_503(request) + return JSONResponse(_alerts_payload(st, user, after)) + + +def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]: + """큰 팝업 알림 — 웹 화면(initTaskAlerts)과 PC 알림 프로그램이 같이 쓴다.""" newest = st.list_notifications(recipient_email=user["email"], limit=1) latest = int(newest[0]["id"]) if newest else 0 out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []} if after < 0: - return JSONResponse(out) + return out rows = [n for n in st.list_notifications(recipient_email=user["email"], unread_only=True, limit=50) if n.get("type") in ("mention", "assigned") and int(n["id"]) > after] rows = sorted(_visible_notifications(st, user, rows), key=lambda n: int(n["id"]))[:10] out["alerts"] = [{k: n.get(k) for k in ("id", "type", "title", "body", "task_id", "project_id", "actor_email", "created_at")} for n in rows] + return out + + +# ──────────────────────────────────────────────────────────── +# PC 알림 프로그램(desktop/notifier, 023) — 브라우저 쿠키 대신 PC별 연결 토큰(Authorization: Bearer). +# 연결: 프로그램 POST link/start → 사용자가 브라우저 /project/notifier?code= 에서 [연결] → 프로그램 POST link/poll 로 토큰 1회. +# ──────────────────────────────────────────────────────────── +_NOTIFIER_MIGRATION_MSG = "PC 알림 연결이 아직 준비되지 않았습니다(project_db 023 마이그레이션 필요)." + + +def _notifier_call(fn: Any, **kwargs: Any) -> Any: + try: + return fn(**kwargs) + except UndefinedTable: + raise HTTPException(status_code=503, detail=_NOTIFIER_MIGRATION_MSG) + + +def _notifier_token(request: Request) -> str: + auth = request.headers.get("authorization", "") + return auth[7:].strip() if auth.lower().startswith("bearer ") else "" + + +def _user_by_email(email: str) -> dict[str, Any] | None: + from app.main import user_store # noqa: WPS433 + + return user_store.get(email) + + +def _notifier_user(request: Request, st: Any) -> dict[str, Any]: + """토큰 → 지금 사용자 레코드(권한 포함). 토큰 해제·사용자 삭제·프로젝트 권한 회수면 401.""" + from app.store import has_module # noqa: WPS433 + + email = _notifier_call(st.notifier_token_email, token=_notifier_token(request)) + user = _user_by_email(email) if email else None + if user is None or not has_module(user, "project"): + raise HTTPException(status_code=401, detail="연결이 해제되었습니다. 다시 연결하세요.") + return user + + +@router.post("/api/notifier/link/start") +def api_notifier_link_start(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse: + """연결 요청(로그인 없이) — 화면 코드 + poll 비밀값. 사용자는 /project/notifier?code= 에서 승인.""" + st = _db_or_503(request) + device = store.norm_str(payload.get("device") or "")[:80] + try: + link = _notifier_call(st.notifier_start_link, device_name=device) + except OverflowError as exc: + raise HTTPException(status_code=429, detail=str(exc)) + return JSONResponse({**link, "approve_path": "/project/notifier?code=" + link["code"]}) + + +@router.post("/api/notifier/link/poll") +def api_notifier_link_poll(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse: + st = _db_or_503(request) + poll = store.norm_str(payload.get("poll") or "") + if not poll: + raise HTTPException(status_code=400, detail="poll 이 필요합니다.") + return JSONResponse(_notifier_call(st.notifier_poll_link, poll=poll)) + + +@router.post("/api/notifier/link/approve") +def api_notifier_link_approve(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """브라우저(로그인 사용자)가 [연결] — 이 코드의 PC 를 내 알림에 연결.""" + user = _require_user(request) + st = _db_or_503(request) + if not _notifier_call(st.notifier_approve_link, code=str(payload.get("code") or ""), email=user["email"]): + raise HTTPException(status_code=404, detail="연결 코드가 없거나 만료되었습니다. 프로그램에서 다시 연결하세요.") + return JSONResponse({"ok": True}) + + +@router.post("/api/notifier/devices/{device_id}/revoke") +def api_notifier_revoke_device(request: Request, device_id: int) -> JSONResponse: + user = _require_user(request) + st = _db_or_503(request) + if not _notifier_call(st.notifier_revoke_device, device_id=device_id, email=user["email"]): + raise HTTPException(status_code=404, detail="연결된 PC 를 찾을 수 없습니다.") + return JSONResponse({"ok": True}) + + +@router.get("/api/notifier/alerts") +def api_notifier_alerts(request: Request, after: int = -1) -> JSONResponse: + """PC 알림 프로그램 — 웹 큰 팝업과 같은 알림. name = 표시 이름(트레이 메뉴용).""" + st = _db_or_503(request) + user = _notifier_user(request, st) + out = _alerts_payload(st, user, after) + out["name"] = user.get("name") or user["email"] return JSONResponse(out) +@router.post("/api/notifier/alerts/{notification_id}/read") +def api_notifier_alert_read(request: Request, notification_id: int) -> JSONResponse: + st = _db_or_503(request) + user = _notifier_user(request, st) + st.mark_read(notification_id=notification_id, recipient_email=user["email"]) + return JSONResponse({"ok": True}) + + +@router.post("/api/notifier/logout") +def api_notifier_logout(request: Request) -> JSONResponse: + st = _db_or_503(request) + _notifier_call(st.notifier_revoke_token, token=_notifier_token(request)) + return JSONResponse({"ok": True}) + + +@router.get("/notifier/download") +def notifier_download(request: Request) -> Any: + """PC 알림 프로그램 내려받기 — 서버 DATA_DIR/notifier/DBXNotifier.exe 를 그대로(없으면 404).""" + from app.main import DATA_DIR # noqa: WPS433 + + _require_user(request) + exe = Path(DATA_DIR) / "notifier" / "DBXNotifier.exe" + if not exe.is_file(): + raise HTTPException(status_code=404, detail="아직 서버에 프로그램 파일이 없습니다. 관리자에게 문의하세요.") + return FileResponse(exe, filename="DBXNotifier.exe", media_type="application/octet-stream") + + +@router.get("/notifier", response_class=HTMLResponse) +def notifier_page(request: Request) -> Any: + """PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기.""" + from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433 + from app.store import is_admin # noqa: WPS433 + from urllib.parse import quote # noqa: WPS433 + + if get_current_user_record(request) is None: + return RedirectResponse(url="/login?next=" + quote(str(request.url.path) + ( + "?" + request.url.query if request.url.query else ""), safe=""), status_code=303) + user = _require_user(request) + st = _store(request) + if st is None: + return _render_config_needed(request, user) + admin = is_admin(user) + enabled = st.notifier_enabled() + code = store.norm_str(request.query_params.get("code") or "").upper()[:9] + link = st.notifier_get_link(code=code) if enabled and code else None + return render_template( + request, + "project/notifier.html", + { + "user": user, + "is_admin": admin, + "nav_items": build_erp_nav(user, active="project"), + "nav_projects": _nav_projects(st, user, admin), + "goal_years": _goal_years_nav(st), + "my_open_total": _my_open_count(st, user), + "mention_unread": _safe_mention_unread(st, user), + "page_title": "PC 알림 프로그램", + "page_subtitle": "브라우저가 뒤에 있어도 태그·작업 배정 알림을 화면 위에 크게", + "force_sidebar_collapsed": True, + "color_palette": list(store.COLOR_PALETTE), + "project_icons": list(store.PROJECT_ICONS), + "notifier_enabled": enabled, + "code": code, + "link": link, + "devices": st.notifier_list_devices(email=user["email"]) if enabled else [], + "download_ready": (Path(DATA_DIR) / "notifier" / "DBXNotifier.exe").is_file(), + }, + ) + + @router.get("/api/notifications/unread-count") def api_notif_count(request: Request) -> JSONResponse: user = _require_user(request) diff --git a/app/modules/project/templates/project/_side.html b/app/modules/project/templates/project/_side.html index cd29a55..3ff87f0 100644 --- a/app/modules/project/templates/project/_side.html +++ b/app/modules/project/templates/project/_side.html @@ -7,7 +7,7 @@ my_open_total 진행 중인 내 업무 개수 (내 업무 배지) nav_projects 프로젝트 목록(평면) current_pid 지금 보고 있는 프로젝트 id (내 업무/수신함 화면이면 0) - side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시 + side_active 'inbox' | 'mytasks' | 'notifier' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시 goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함) goal_year_active 목표 화면에서 보고 있는 연도 is_admin 프로젝트 생성/수정/삭제 권한 @@ -44,6 +44,11 @@ {{ my_open_total }} + {# PC 알림 — 트레이 프로그램(desktop/notifier) 내려받기·연결 승인·연결된 PC 해제(023) #} + + desktop_windows + PC 알림 + {# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #} {% if is_admin %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html new file mode 100644 index 0000000..7c8ba89 --- /dev/null +++ b/app/modules/project/templates/project/notifier.html @@ -0,0 +1,112 @@ +{% extends "erp_base.html" %} + +{% block head_extra %} + + +{% endblock %} + +{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %} + +{% block content %} +{# PC 알림 프로그램(023) — 트레이 프로그램(desktop/notifier) 내려받기, 연결 승인(?code=), 연결된 PC 해제. + 토큰은 프로그램이 받아 PC 에 암호화 저장(Windows DPAPI). 이 화면은 토큰 원문을 보지 않는다. #} +
+
+ {% with current_pid = 0, side_active = "notifier" %}{% include "project/_side.html" %}{% endwith %} + +
+

PC 알림 프로그램

+
+ {% if not notifier_enabled %} +
PC 알림 연결이 아직 준비되지 않았습니다(DB 마이그레이션 023 필요).
+ {% else %} + + {% if code %} + + {% endif %} + +
+

설치

+
    +
  1. {% if download_ready %}DBXNotifier.exe 내려받기 + {% else %}관리자에게 DBXNotifier.exe 파일을 받으세요.{% endif %} + 설치 없이 파일 하나로 실행됩니다(Windows 10·11).
  2. +
  3. 실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.
  4. +
  5. 열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.
  6. +
+

나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다. + [열기]를 누르면 브라우저에서 그 작업이 열립니다.

+
+ +
+

연결된 PC

+ {% if devices %} + + + + {% for d in devices %} + + + + + + + {% endfor %} + +
PC 이름연결한 때마지막 확인
{{ d.device_name or '-' }}{{ (d.created_at or '')[:16] | replace('T', ' ') }}{{ (d.last_seen_at or '-')[:16] | replace('T', ' ') }}
+ {% else %} +

연결된 PC 가 없습니다.

+ {% endif %} +
+ {% endif %} +
+
+
+
+ +{% include "project/_side_modals.html" %} +{% include "project/_member_tasks_modal.html" %} + + + +{% endblock %} diff --git a/app/static/project.css b/app/static/project.css index ace8a1d..42df728 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2994,3 +2994,14 @@ 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%; } diff --git a/desktop/notifier/.gitignore b/desktop/notifier/.gitignore new file mode 100644 index 0000000..9ba2259 --- /dev/null +++ b/desktop/notifier/.gitignore @@ -0,0 +1,3 @@ +bin/ +obj/ +dist/ diff --git a/desktop/notifier/AlertForm.cs b/desktop/notifier/AlertForm.cs new file mode 100644 index 0000000..287e1ae --- /dev/null +++ b/desktop/notifier/AlertForm.cs @@ -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 +{ + /// + /// 큰 알림 창 — 웹 프로젝트 화면의 큰 팝업(.pj-alert-pop)과 같은 모양: 흰 카드·둥근 모서리 16·연분홍 머리(종 + "새 알림 N건" + 닫기)· + /// 줄마다 배지(작업 배정/나를 태그)·굵은 제목·회색 둘째 줄·"열기 ›", 보라↔주황으로 1초마다 깜박이는 테두리와 빛. + /// 다른 프로그램 위(맨 위)에 뜨지만 포커스는 빼앗지 않는다(입력 중이던 창 그대로). 둥근 모서리·그림자를 위해 + /// 픽셀 단위 투명 창(UpdateLayeredWindow)으로 직접 그린다. + /// + internal sealed class AlertForm : Form + { + public event Action 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 _items = new List(); + private readonly List _rows = new List(); + 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; + + /// 알림 목록을 보여 준다(처음이면 띄우고, 이미 떠 있으면 내용만 바꾼다). + public void SetAlerts(IList 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(); + } + + /// 카드 크기·위치 — 마우스가 있는 화면의 작업 영역 아래 가운데(웹 팝업처럼 아래에서 28px 위). + 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); + } +} diff --git a/desktop/notifier/Api.cs b/desktop/notifier/Api.cs new file mode 100644 index 0000000..494e4f3 --- /dev/null +++ b/desktop/notifier/Api.cs @@ -0,0 +1,164 @@ +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"; + + /// 제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게). + public string CleanTitle + { + get + { + foreach (string p in new[] { "나를 태그함:", "작업 배정:" }) + if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim(); + return Title; + } + } + + /// 둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게). + 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; + } + } + + public string Path => ProjectId > 0 + ? "/project/p/" + ProjectId + (TaskId > 0 ? "?task=" + TaskId : "") + : "/project/inbox"; + } + + internal sealed class AlertResult + { + public string Name = ""; + public long LatestId; + public List Alerts = new List(); + } + + internal sealed class ApiException : Exception + { + public readonly int Status; + + public ApiException(int status, string message) : base(message) { Status = status; } + } + + /// ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다. + 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(); + + /// 서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외). + 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> 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 d = null; + try { d = Json.Deserialize>(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(); + } + } + } + + private static string Str(Dictionary d, string key) => + d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : ""; + + private static long Num(Dictionary 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")); + } + + /// 연결 확인 — status: pending | expired | ok(token, email). + 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 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 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 { }); + } +} diff --git a/desktop/notifier/ConnectForm.cs b/desktop/notifier/ConnectForm.cs new file mode 100644 index 0000000..70bc00a --- /dev/null +++ b/desktop/notifier/ConnectForm.cs @@ -0,0 +1,195 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Windows.Forms; + +namespace DbxNotifier +{ + internal static class Browser + { + /// 기본 브라우저로 연다. 실패하면 주소를 클립보드에 복사하고 false. + public static bool Open(string url) + { + try + { + Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); + return true; + } + catch + { + try { Clipboard.SetText(url); } catch { /* 클립보드 사용 중 */ } + return false; + } + } + } + + /// + /// PC 연결 창 — [브라우저에서 연결] → 서버가 준 코드를 크게 보여 주고 브라우저로 승인 화면(/project/notifier?code=)을 연다. + /// 사용자가 브라우저(이미 로그인)에서 [연결]을 누르면 2초마다 확인하던 이 창이 토큰을 받아 닫힌다. + /// + 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); + } + } +} diff --git a/desktop/notifier/DbxNotifier.csproj b/desktop/notifier/DbxNotifier.csproj new file mode 100644 index 0000000..95e934c --- /dev/null +++ b/desktop/notifier/DbxNotifier.csproj @@ -0,0 +1,40 @@ + + + + WinExe + net48 + latest + DBXNotifier + DbxNotifier + app.ico + app.manifest + AnyCPU + false + true + none + false + + 1.0.0 + 1.0.0.0 + 1.0.0.0 + DBX + DBX 알림 + DBX 알림 + DBX ERP 프로젝트 알림(태그·작업 배정)을 화면에 띄우는 트레이 프로그램 + © 2026 DBX + ko-KR + + + + + + + + + + + + + + diff --git a/desktop/notifier/Gfx.cs b/desktop/notifier/Gfx.cs new file mode 100644 index 0000000..d42775d --- /dev/null +++ b/desktop/notifier/Gfx.cs @@ -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 +{ + /// 그리기 도우미 — 둥근 사각형, 종 아이콘, 색 섞기, 내장 아이콘. + 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); + } + + /// 울리는 종(웹 팝업 머리의 notifications_active 와 같은 느낌) — 24 격자를 r 에 맞춰 그린다. + 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); + } + + /// exe 에 넣은 app.ico 에서 원하는 크기 아이콘(트레이 = 작은 아이콘 크기). + 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); + } + } +} diff --git a/desktop/notifier/Program.cs b/desktop/notifier/Program.cs new file mode 100644 index 0000000..f10d3e8 --- /dev/null +++ b/desktop/notifier/Program.cs @@ -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); + } + } + } +} diff --git a/desktop/notifier/README.md b/desktop/notifier/README.md new file mode 100644 index 0000000..e3ee144 --- /dev/null +++ b/desktop/notifier/README.md @@ -0,0 +1,40 @@ +# DBX 알림 (PC 트레이 프로그램) + +ERP 프로젝트에서 **나를 태그**하거나 **작업이 배정**되면, 브라우저가 뒤에 있어도 PC 화면 아래 가운데에 +웹 팝업과 같은 모양의 큰 알림 창을 띄운다. 서버 쪽 설명은 `docs/PROJECT_MODULE.md` 6-11. + +- 실행 파일 하나(`DBXNotifier.exe`, 약 50KB), 설치 없음, 관리자 권한 불필요 +- 실행하면 트레이(오른쪽 아래)에 종 아이콘만 남는다 — 메모리 약 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 을 허용 목록에 넣어도 된다. diff --git a/desktop/notifier/Settings.cs b/desktop/notifier/Settings.cs new file mode 100644 index 0000000..7a619e4 --- /dev/null +++ b/desktop/notifier/Settings.cs @@ -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 +{ + /// + /// 설정 — %APPDATA%\DBXNotifier\settings.json. 연결 토큰은 Windows DPAPI(현재 사용자)로 암호화해 저장하므로 + /// 파일을 다른 PC·다른 사용자로 복사해도 쓸 수 없다. + /// + 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>(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 + { + ["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 + { + // 저장 실패는 다음 저장 때 다시 + } + } + } + + /// Windows 시작 시 실행 — 현재 사용자 Run 키(관리자 권한 불필요). 사용자가 켜고 끈다. + 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 — 메뉴 체크 표시만 그대로 + } + } + + /// exe 를 다른 폴더로 옮겼으면 등록된 경로를 지금 위치로. + 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); + } + } + } +} diff --git a/desktop/notifier/TrayApp.cs b/desktop/notifier/TrayApp.cs new file mode 100644 index 0000000..78439ea --- /dev/null +++ b/desktop/notifier/TrayApp.cs @@ -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 +{ + /// + /// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·작업 배정 알림이 있으면 큰 알림 창. + /// 웹 화면과 같은 규칙: 처음 연결하면 지금 최신 알림을 기준으로(옛 알림을 한꺼번에 띄우지 않음), [닫기] = 본 것으로, + /// [열기] = 브라우저로 그 작업 + 읽음 처리. 다른 곳(웹)에서 읽으면 다음 확인 때 창에서도 빠진다. + /// + 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 _pending = new List(); + private readonly HashSet _opened = new HashSet(); + 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(); + } + } + + /// 서버의 지금 목록으로 바꾼다 — 새 번호가 있으면 창을 띄우고 소리, 다른 곳에서 읽은 것은 빠진다. + private void Apply(List fresh) + { + fresh = fresh.Where(a => !_opened.Contains(a.Id)).ToList(); + var known = new HashSet(_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 { /* 다음에 웹에서 읽어도 된다 */ } + } + + /// [닫기] — 지금 보이는 알림까지 본 것으로(다시 뜨지 않음). + 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(); + } + } +} diff --git a/desktop/notifier/app.ico b/desktop/notifier/app.ico new file mode 100644 index 0000000..5ac962a Binary files /dev/null and b/desktop/notifier/app.ico differ diff --git a/desktop/notifier/app.manifest b/desktop/notifier/app.manifest new file mode 100644 index 0000000..fe9dfac --- /dev/null +++ b/desktop/notifier/app.manifest @@ -0,0 +1,30 @@ + + + + DBX 알림 + + + + + + + + + + + + + + + + + true + + + + + + + + diff --git a/desktop/notifier/build.ps1 b/desktop/notifier/build.ps1 new file mode 100644 index 0000000..98ccd1c --- /dev/null +++ b/desktop/notifier/build.ps1 @@ -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 +} diff --git a/desktop/notifier/tools/make_icon.py b/desktop/notifier/tools/make_icon.py new file mode 100644 index 0000000..516effb --- /dev/null +++ b/desktop/notifier/tools/make_icon.py @@ -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() diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index d1d97df..141e09b 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -125,6 +125,24 @@ 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` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 [회의 완료] 버튼이 나오지 않고 diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index e7559f1..d626287 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -1041,6 +1041,29 @@ 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/`) — 파일이 없으면 버튼 대신 "관리자에게 받으세요". +- 023 미적용이면 화면은 안내만, notifier API 는 503. + ## 7. 추후 단계 작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩, diff --git a/scripts/sql/project_db_023_notifier.sql b/scripts/sql/project_db_023_notifier.sql new file mode 100644 index 0000000..030fe2b --- /dev/null +++ b/scripts/sql/project_db_023_notifier.sql @@ -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; diff --git a/tests/test_project_notifier_api.py b/tests/test_project_notifier_api.py new file mode 100644 index 0000000..edf3dfc --- /dev/null +++ b/tests/test_project_notifier_api.py @@ -0,0 +1,128 @@ +"""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 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, "나")) + + 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()