diff --git a/CLAUDE.md b/CLAUDE.md index 47133f3..6b120bd 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색, 수정 창 12열)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011 + [아사나 아이콘] 탭 33종 `"asana:"+이름`, 채워진 모양 전용 부분 글꼴 `material-symbols-asana.woff2`)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작 — `create_project(seed_stages=True)` 일 때만 기본 4단계, 섹션 머리는 모두 `#f3f3f3` — 섹션별 색 지정 없음, 섹션 이름 굵게, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`)·내 작업(접이식) 메뉴. 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). **관리자 등급 4단계(2026-10-12) — 수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User** — 판단은 `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`, `is_admin` 은 ERP 상단 관리자 메뉴용 그대로). pro 는 프로젝트 모듈 밖에서는 user 와 같다. 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버 = Pro user 이상, 프로젝트·섹션 삭제 = Admin 이상 또는 만든 사람, 작업 삭제·서브프로젝트 = 멤버 누구나(표는 docs/PROJECT_MODULE.md 6-14). 배정 멤버(또는 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개월 보관, Pro user 이상만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 Pro user 이상, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력(주차별 목표·연도 추가/삭제 포함)은 Pro user 이상. 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/{월}`, 프로젝트 권한자 **누구나 수정** — Pro user 이상 [회의 완료](`completed_at`, 마이그레이션 022)면 잠금(지난주 결과는 다음 주 회의록이 열려 있는 동안 허용), 삭제·완료·완료 해제는 Pro user 이상, 표 첫 열 머리 글자 "구분", 주차 탭 — **주차는 그 달 안**(`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일~오늘)·누적 목표 대비 차액·%) | ② 결정 사항·메모 | ③ "N주차 작업 등록" 표(제목·담당자·프로젝트·섹션 → [적용] = 서버가 그 프로젝트에 작업 생성, `initMeetQuickTasks` — 주차별 서버 표 `goal_meeting_tasks`(마이그레이션 025)라 모두가 같이 보고, 남의 프로젝트 이름은 가림, 완료 프로젝트·섹션은 목록에서 뺌, 세부 작업 줄 `parent_id` 한 단계 — ↳·우클릭·Tab/Shift+Tab, [적용]은 위 줄 작업 밑에, [크게 열기] = 같은 표를 넓은 창으로), 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력). 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제, 구분(구역) 칸 우클릭·⋯ = 구역 통째로 위/아래(`move-section`). 마감 알림(`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`, 토큰마다 지금 사용자·권한 재확인. 프로그램이 돌고 있으면(최근 3분 확인, `notifier_active`) 웹 큰 팝업은 쉰다(`desktop: true`). 압축·난독화 금지(백신 오탐), 빌드 `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 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 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색, 수정 창 12열)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011 + [아사나 아이콘] 탭 33종 `"asana:"+이름`, 채워진 모양 전용 부분 글꼴 `material-symbols-asana.woff2`)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작 — `create_project(seed_stages=True)` 일 때만 기본 4단계, 섹션 머리는 모두 `#f3f3f3` — 섹션별 색 지정 없음, 섹션 이름 굵게, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`)·내 작업(접이식) 메뉴. 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). **관리자 등급 4단계(2026-10-12) — 수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User** — 판단은 `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`, `is_admin` 은 ERP 상단 관리자 메뉴용 그대로). pro 는 프로젝트 모듈 밖에서는 user 와 같다. 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버 = Pro user 이상, 프로젝트·섹션 삭제 = Admin 이상 또는 만든 사람, 작업 삭제·서브프로젝트 = 멤버 누구나(표는 docs/PROJECT_MODULE.md 6-14). 배정 멤버(또는 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개월 보관, Pro user 이상만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 Pro user 이상, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력(주차별 목표·연도 추가/삭제 포함)은 Pro user 이상. 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/{월}`, 프로젝트 권한자 **누구나 수정** — Pro user 이상 [회의 완료](`completed_at`, 마이그레이션 022)면 잠금(지난주 결과는 다음 주 회의록이 열려 있는 동안 허용), 삭제·완료·완료 해제는 Pro user 이상, 표 첫 열 머리 글자 "구분", 주차 탭 — **주차는 그 달 안**(`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일~오늘)·누적 목표 대비 차액·%) | ② 결정 사항·메모 | ③ "N주차 작업 등록" 표(제목·담당자·프로젝트·섹션 → [적용] = 서버가 그 프로젝트에 작업 생성, `initMeetQuickTasks` — 주차별 서버 표 `goal_meeting_tasks`(마이그레이션 025)라 모두가 같이 보고, 남의 프로젝트 이름은 가림, 완료 프로젝트·섹션은 목록에서 뺌, 작업 칸(마이그레이션 026 `parent_task_id`) = 이미 있는 작업을 고르면 그 작업의 세부 작업으로 등록, 등록된 줄 제목 = 오른쪽 작업 창(편집, 저장 대기), [크게 열기] = 같은 표를 넓은 창으로), 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력). 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제, 구분(구역) 칸 우클릭·⋯ = 구역 통째로 위/아래(`move-section`). 마감 알림(`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`, 토큰마다 지금 사용자·권한 재확인. 프로그램이 돌고 있으면(최근 3분 확인, `notifier_active`) 웹 큰 팝업은 쉰다(`desktop: true`). 압축·난독화 금지(백신 오탐), 빌드 `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 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 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` diff --git a/app/modules/notice/templates/notice/admin.html b/app/modules/notice/templates/notice/admin.html index 8980c64..ab9c63c 100644 --- a/app/modules/notice/templates/notice/admin.html +++ b/app/modules/notice/templates/notice/admin.html @@ -2,7 +2,7 @@ {% block head_extra %} {# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + {% endblock %} @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 3d9f0dc..d6cc102 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -3349,9 +3349,26 @@ class ProjectStore: conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x)) # ── 회의록 작업 등록 표(025) — 주차별 한 표, 모두가 같이 본다. [적용] 전 줄은 고치고, [적용]은 한 번만 ── - _MT_COLS = ("id, week_start, parent_id, sort_order, title, assignee_email, project_id, stage_id, task_id, " + # 026 — 작업 칸(parent_task_id): 고르면 [적용] 때 그 작업의 세부 작업으로(비우면 그 섹션에 새 작업). + # 025 의 parent_id(표 안 줄끼리 세부 작업)는 화면에서 쓰지 않는다(열·값은 그대로, 읽기·쓰기 안 함). + _MT_BASE = ("id, week_start, sort_order, title, assignee_email, project_id, stage_id, task_id, " "created_by, updated_by, created_at, updated_at") + def _mt_v26(self, conn: Any) -> bool: + """026(작업 칸 parent_task_id) 적용 여부 — 적용되면 한 번만 확인.""" + if getattr(self, "_mt_v26_ok", False): + return True + ok = self._column_exists(conn, "goal_meeting_tasks", "parent_task_id") + if ok: + self._mt_v26_ok = True + return ok + + def _mt_cols(self, conn: Any, prefix: str = "") -> str: + cols = [prefix + c.strip() for c in self._MT_BASE.split(",")] + if self._mt_v26(conn): + cols.append(prefix + "parent_task_id") + return ", ".join(cols) + def _mt_conn(self) -> Any: return self._pool.connection() @@ -3364,22 +3381,24 @@ class ProjectStore: @staticmethod def _mt_row(r: dict[str, Any]) -> dict[str, Any]: - out = {k: r.get(k) for k in ("id", "parent_id", "sort_order", "title", "assignee_email", "project_id", - "stage_id", "task_id", "created_by", "updated_by")} - for k in ("id", "parent_id", "project_id", "stage_id", "task_id"): + out = {k: r.get(k) for k in ("id", "sort_order", "title", "assignee_email", "project_id", + "stage_id", "task_id", "parent_task_id", "created_by", "updated_by")} + for k in ("id", "project_id", "stage_id", "task_id", "parent_task_id"): out[k] = int(out[k]) if out[k] is not None else None out["week_start"] = r["week_start"].isoformat() out["updated_at"] = r["updated_at"].astimezone(KST).isoformat(timespec="seconds") if r.get("updated_at") else "" - for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id"): + for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id", "parent_task_title"): if k in r: out[k] = r[k] if "task_exists" in r: out["task_exists"] = bool(r["task_exists"]) return out - def _mt_clean(self, conn: Any, fields: dict[str, Any], *, project_id: Any = ...) -> dict[str, Any]: - """고칠 칸 정리 — title(200자)·assignee_email·project_id·stage_id(그 프로젝트 섹션). 프로젝트가 바뀌면 섹션을 비운다.""" + def _mt_clean(self, conn: Any, fields: dict[str, Any], *, project_id: Any = None) -> dict[str, Any]: + """고칠 칸 정리 — title(200자)·assignee_email·project_id·stage_id(그 프로젝트 섹션)·parent_task_id(그 프로젝트 작업, 026). + 프로젝트가 바뀌면 섹션·작업을 비운다.""" clean: dict[str, Any] = {} + v26 = self._mt_v26(conn) if "title" in fields: t = store.norm_str(fields.get("title")) if len(t) > 200: @@ -3397,44 +3416,68 @@ class ProjectStore: clean["project_id"] = pid if "stage_id" not in fields: clean["stage_id"] = None + if v26 and "parent_task_id" not in fields: + clean["parent_task_id"] = None if "stage_id" in fields: sid = fields.get("stage_id") if sid in (None, ""): clean["stage_id"] = None else: - if pid in (None, ...): + if pid is None: raise ValueError("프로젝트를 먼저 고르세요.") clean["stage_id"] = self._check_stage_in_project(conn, sid, int(pid)) + if "parent_task_id" in fields: + if not v26: + raise store.MeetingParentTaskMigrationNeeded() + raw = fields.get("parent_task_id") + if raw in (None, ""): + clean["parent_task_id"] = None + else: + try: + tid = int(raw) + except (TypeError, ValueError): + raise ValueError("작업 값이 올바르지 않습니다.") + if pid is None: + raise ValueError("프로젝트를 먼저 고르세요.") + t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (tid,)).fetchone() + if t is None or int(t["project_id"]) != int(pid): + raise ValueError("이 프로젝트의 작업이 아닙니다.") + clean["parent_task_id"] = tid return clean + def _mt_select(self, conn: Any, where: str, params: tuple[Any, ...]) -> list[dict[str, Any]]: + """줄 + 프로젝트·섹션·고른 작업 이름 + 만든 작업 존재 여부(목록·한 줄 응답 공용).""" + v26 = self._mt_v26(conn) + return conn.execute( + f"SELECT {self._mt_cols(conn, 'm.')}, " + " p.name AS project_name, p.status AS project_status, s.name AS stage_name, " + " t.title AS task_title, t.project_id AS task_project_id, (t.id IS NOT NULL) AS task_exists" + + (", pt.title AS parent_task_title " if v26 else " ") + + "FROM goal_meeting_tasks m " + "LEFT JOIN projects p ON p.id = m.project_id " + "LEFT JOIN project_stages s ON s.id = m.stage_id " + "LEFT JOIN tasks t ON t.id = m.task_id " + + ("LEFT JOIN tasks pt ON pt.id = m.parent_task_id " if v26 else "") + + f"WHERE {where} ORDER BY m.sort_order, m.id", params, + ).fetchall() + def list_meeting_tasks(self, *, week_start: date) -> list[dict[str, Any]]: - """그 주차 표 — 순서대로(세부 작업 줄은 부모 바로 뒤에 화면이 묶는다). 프로젝트·섹션 이름·만든 작업 존재 여부를 붙인다.""" + """그 주차 표 — 순서대로. 프로젝트·섹션·고른 작업 이름, 만든 작업 존재 여부를 붙인다.""" def run() -> list[dict[str, Any]]: with self._mt_conn() as conn: - rows = conn.execute( - "SELECT m.id, m.week_start, m.parent_id, m.sort_order, m.title, m.assignee_email, m.project_id, " - " m.stage_id, m.task_id, m.created_by, m.updated_by, m.created_at, m.updated_at, " - " p.name AS project_name, p.status AS project_status, s.name AS stage_name, " - " t.title AS task_title, t.project_id AS task_project_id, (t.id IS NOT NULL) AS task_exists " - "FROM goal_meeting_tasks m " - "LEFT JOIN projects p ON p.id = m.project_id " - "LEFT JOIN project_stages s ON s.id = m.stage_id " - "LEFT JOIN tasks t ON t.id = m.task_id " - "WHERE m.week_start = %s ORDER BY m.sort_order, m.id", (week_start,), - ).fetchall() - return [self._mt_row(r) for r in rows] + return [self._mt_row(r) for r in self._mt_select(conn, "m.week_start = %s", (week_start,))] return self._mt_call(run) def get_meeting_task(self, *, item_id: int) -> dict[str, Any] | None: def run() -> dict[str, Any] | None: with self._mt_conn() as conn: - r = conn.execute(f"SELECT {self._MT_COLS} FROM goal_meeting_tasks WHERE id = %s", (item_id,)).fetchone() - return self._mt_row(r) if r else None + rows = self._mt_select(conn, "m.id = %s", (item_id,)) + return self._mt_row(rows[0]) if rows else None return self._mt_call(run) def add_meeting_task(self, *, week_start: date, fields: dict[str, Any], by: str = "", - parent_id: int | None = None, task_id: int | None = None) -> dict[str, Any]: - """줄 추가(빈 줄도). parent_id = 세부 작업 줄(같은 주차 줄 밑). task_id = 예전 브라우저 표에서 옮겨 온 이미 등록된 줄.""" + task_id: int | None = None) -> dict[str, Any]: + """줄 추가(빈 줄도). task_id = 예전 브라우저 표에서 옮겨 온 이미 등록된 줄.""" who = store.norm_str(by, lower=True) def run() -> int: @@ -3442,21 +3485,18 @@ class ProjectStore: with conn.transaction(): self._check_meeting_open(conn, week_start) clean = self._mt_clean(conn, fields) - if parent_id is not None: - par = conn.execute("SELECT week_start, parent_id FROM goal_meeting_tasks WHERE id = %s", - (parent_id,)).fetchone() - if par is None or par["week_start"] != week_start: - raise ValueError("위 줄이 이 주차 표에 없습니다.") - if par["parent_id"] is not None: - raise ValueError("세부 작업 줄 밑으로는 넣을 수 없습니다(한 단계만).") nxt = conn.execute("SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM goal_meeting_tasks " "WHERE week_start = %s", (week_start,)).fetchone()["n"] + cols = ["week_start", "sort_order", "title", "assignee_email", "project_id", "stage_id", "task_id", + "created_by", "updated_by"] + vals = [week_start, int(nxt), clean.get("title", ""), clean.get("assignee_email", ""), + clean.get("project_id"), clean.get("stage_id"), task_id, who, who] + if clean.get("parent_task_id") is not None: + cols.append("parent_task_id") + vals.append(clean["parent_task_id"]) return int(conn.execute( - "INSERT INTO goal_meeting_tasks (week_start, parent_id, sort_order, title, assignee_email, " - "project_id, stage_id, task_id, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) " - "RETURNING id", - (week_start, parent_id, int(nxt), clean.get("title", ""), clean.get("assignee_email", ""), - clean.get("project_id"), clean.get("stage_id"), task_id, who, who), + f"INSERT INTO goal_meeting_tasks ({', '.join(cols)}) VALUES ({', '.join(['%s'] * len(cols))}) " + "RETURNING id", vals, ).fetchone()["id"]) return self.get_meeting_task(item_id=self._mt_call(run)) # type: ignore[return-value] @@ -3473,25 +3513,6 @@ class ProjectStore: if row["task_id"] is not None: raise store.GoalCellConflict("이미 [적용]해 작업으로 만든 줄입니다. 새로고침해 주세요.") clean = self._mt_clean(conn, fields, project_id=row["project_id"]) - if "parent_id" in fields: - # 세부 작업 줄로(Tab)·위 단계로(Shift+Tab) — 한 단계만: 위 줄은 같은 주차의 맨 위 단계 줄, - # 자기 밑에 세부 작업 줄이 있는 줄은 세부 작업 줄이 될 수 없다. - raw = fields.get("parent_id") - try: - pid = int(raw) if raw not in (None, "") else None - except (TypeError, ValueError): - raise ValueError("위 줄 값이 올바르지 않습니다.") - if pid is not None: - par = conn.execute("SELECT week_start, parent_id FROM goal_meeting_tasks WHERE id = %s", - (pid,)).fetchone() - if pid == item_id or par is None or par["week_start"] != row["week_start"]: - raise ValueError("위 줄이 이 주차 표에 없습니다.") - if par["parent_id"] is not None: - raise ValueError("세부 작업 줄 밑으로는 넣을 수 없습니다(한 단계만).") - if conn.execute("SELECT 1 FROM goal_meeting_tasks WHERE parent_id = %s LIMIT 1", - (item_id,)).fetchone(): - raise ValueError("세부 작업 줄이 딸린 줄은 세부 작업이 될 수 없습니다.") - clean["parent_id"] = pid if not clean: return sets = ", ".join(f"{k} = %s" for k in clean) @@ -3501,11 +3522,11 @@ class ProjectStore: return self.get_meeting_task(item_id=item_id) # type: ignore[return-value] def delete_meeting_task(self, *, item_id: int) -> dict[str, Any]: - """줄 지우기(세부 작업 줄도 함께). 만든 작업은 라우터·화면이 따로 지운다(휴지통).""" + """줄 지우기. 만든 작업은 라우터·화면이 따로 지운다(휴지통).""" def run() -> dict[str, Any]: with self._mt_conn() as conn: with conn.transaction(): - row = conn.execute(f"SELECT {self._MT_COLS} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", + row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", (item_id,)).fetchone() if row is None: raise KeyError(item_id) @@ -3515,28 +3536,26 @@ class ProjectStore: return self._mt_call(run) def apply_meeting_task(self, *, item_id: int, create: Any) -> tuple[dict[str, Any], bool]: - """[적용] — 줄을 잠그고 아직 작업이 없을 때만 create(줄) 로 작업을 만들어 task_id 를 남긴다. - (줄, 이번에 만들었는가). 두 사람이 동시에 눌러도 작업은 하나. create 가 실패하면 줄은 그대로.""" + """[적용] — 줄을 잠그고 아직 작업이 없을 때만 create(줄, 상위 작업 id) 로 작업을 만들어 task_id 를 남긴다. + 작업 칸(parent_task_id)을 골랐으면 그 작업의 세부 작업으로(섹션 없이). (줄, 이번에 만들었는가). + 두 사람이 동시에 눌러도 작업은 하나. create 가 실패하면 줄은 그대로.""" def run() -> tuple[int, bool]: with self._mt_conn() as conn: with conn.transaction(): - row = conn.execute(f"SELECT {self._MT_COLS} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", + row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", (item_id,)).fetchone() if row is None: raise KeyError(item_id) self._check_meeting_open(conn, row["week_start"]) if row["task_id"] is not None: return item_id, False - parent_task = None use = self._mt_row(row) - if row["parent_id"] is not None: - # 세부 작업 줄 — 위 줄이 만든 작업 밑에, 그 작업의 프로젝트로(줄의 프로젝트 칸은 쓰지 않는다) - par = conn.execute("SELECT m.task_id, t.project_id FROM goal_meeting_tasks m " - "LEFT JOIN tasks t ON t.id = m.task_id WHERE m.id = %s", (row["parent_id"],)).fetchone() - parent_task = par["task_id"] if par else None - if parent_task is None or par["project_id"] is None: - raise ValueError("위 줄(상위 작업)을 먼저 [적용]하세요.") - use = {**use, "project_id": int(par["project_id"]), "stage_id": None} + parent_task = use.get("parent_task_id") + if parent_task is not None: + t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (parent_task,)).fetchone() + if t is None or use["project_id"] is None or int(t["project_id"]) != int(use["project_id"]): + raise ValueError("고른 작업이 없어졌거나 다른 프로젝트로 옮겨졌습니다. 작업 칸을 다시 고르세요.") + use = {**use, "stage_id": None} task = create(use, parent_task) conn.execute("UPDATE goal_meeting_tasks SET task_id = %s, updated_at = now() WHERE id = %s", (int(task["id"]), item_id)) diff --git a/app/modules/project/router.py b/app/modules/project/router.py index f59afbb..e6c9900 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -2956,6 +2956,8 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any: raise HTTPException(status_code=409, detail="회의가 완료되어 수정할 수 없습니다. 관리자가 [완료 해제]하면 다시 고칠 수 있습니다.") except store.MeetingMigration022Needed: raise HTTPException(status_code=503, detail="회의 완료 기능은 project_db 마이그레이션 022 적용 후 사용할 수 있습니다.") + except store.MeetingParentTaskMigrationNeeded: + raise HTTPException(status_code=503, detail="작업 칸(이미 있는 작업의 세부 작업으로 등록)은 project_db 마이그레이션 026 적용 후 사용할 수 있습니다.") except store.MeetingTaskMigrationNeeded: raise HTTPException(status_code=503, detail="작업 등록 표(모두가 같이 보는 주차별 표)는 project_db 마이그레이션 025 적용 후 사용할 수 있습니다.") except store.MeetingMigration020Needed: @@ -3763,13 +3765,13 @@ def _quick_view(st: Any, user: dict[str, Any], rows: list[dict[str, Any]]) -> li r = dict(r, visible=ok, registered=r.get("task_id") is not None) # 등록됨 여부는 누구에게나(작업 내용은 멤버만) if not ok: r.update(project_name="(볼 수 없는 프로젝트)", stage_name="", task_title="", task_id=None, - task_project_id=None) + task_project_id=None, parent_task_id=None, parent_task_title="") out.append(r) return out def _quick_fields(st: Any, user: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]: - fields = {k: payload[k] for k in ("title", "assignee_email", "project_id", "stage_id") if k in payload} + fields = {k: payload[k] for k in ("title", "assignee_email", "project_id", "stage_id", "parent_task_id") if k in payload} pid = fields.get("project_id") if pid not in (None, ""): try: @@ -3792,16 +3794,12 @@ def api_list_quick_tasks(request: Request, week_start: str) -> JSONResponse: @router.post("/api/goals/meetings/{week_start}/quick-tasks") def api_add_quick_task(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse: - """줄 추가 {title?, assignee_email?, project_id?, stage_id?, parent_id?(세부 작업 줄), task_id?(예전 브라우저 표의 등록된 줄)}.""" + """줄 추가 {title?, assignee_email?, project_id?, stage_id?, parent_task_id?(작업 칸 — 그 작업의 세부 작업으로), + task_id?(예전 브라우저 표의 등록된 줄)}.""" user = _require_user(request) st = _db_or_503(request) ws = _goal_call(store.validate_week_start, week_start) fields = _quick_fields(st, user, payload) - parent = payload.get("parent_id") - try: - parent_id = int(parent) if parent not in (None, "") else None - except (TypeError, ValueError): - raise HTTPException(status_code=400, detail="parent_id 가 올바르지 않습니다.") task_id = None if payload.get("task_id") not in (None, ""): # 옮겨 오는 등록된 줄 — 그 작업을 지금 내가 원 소속으로 다룰 수 있을 때만 이어 붙인다(남의 작업 id 를 끌어오지 못하게) @@ -3811,8 +3809,7 @@ def api_add_quick_task(request: Request, week_start: str, payload: dict[str, Any t = None if t is not None and access.task_access(st, user, t) == access.FULL: task_id = int(t["id"]) - row = _goal_call(st.add_meeting_task, week_start=ws, fields=fields, by=user["email"], - parent_id=parent_id, task_id=task_id) + row = _goal_call(st.add_meeting_task, week_start=ws, fields=fields, by=user["email"], task_id=task_id) return JSONResponse({"task": _quick_view(st, user, [row])[0]}, status_code=201) @@ -3821,8 +3818,6 @@ def api_update_quick_task(request: Request, item_id: int, payload: dict[str, Any user = _require_user(request) st = _db_or_503(request) fields = _quick_fields(st, user, payload) - if "parent_id" in payload: # 세부 작업 줄로(Tab)·위 단계로(Shift+Tab) — 한 단계만(저장소가 검사) - fields["parent_id"] = payload["parent_id"] row = _goal_call(st.update_meeting_task, item_id=item_id, fields=fields, by=user["email"]) return JSONResponse({"task": _quick_view(st, user, [row])[0]}) @@ -3848,6 +3843,7 @@ def api_apply_quick_task(request: Request, item_id: int, bg: BackgroundTasks) -> if row["project_id"] is None: raise ValueError("프로젝트를 고르세요.") rec = access.default_user_lookup(row["assignee_email"]) if row["assignee_email"] else None + # 작업 칸을 골랐으면 그 작업의 세부 작업(섹션 없음) — _create_task_for 가 프로젝트 멤버를, create_task 가 같은 프로젝트를 확인 payload = {"title": row["title"].strip(), "stage_id": None if parent_task_id else row["stage_id"], "assignee_email": row["assignee_email"], "assignee_name": (rec or {}).get("name") or (row["assignee_email"].split("@")[0] if row["assignee_email"] else ""), diff --git a/app/modules/project/store.py b/app/modules/project/store.py index 5ffbfc7..79498e2 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -435,6 +435,10 @@ class MeetingTaskMigrationNeeded(RuntimeError): """회의록 작업 등록 표(서버 저장)는 마이그레이션 025 뒤에만 된다.""" +class MeetingParentTaskMigrationNeeded(RuntimeError): + """작업 등록 표의 작업 칸(이미 있는 작업의 세부 작업으로)은 마이그레이션 026 뒤에만 된다.""" + + class MeetingMigration020Needed(RuntimeError): """새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다.""" diff --git a/app/modules/project/templates/project/goal_meeting.html b/app/modules/project/templates/project/goal_meeting.html index 4ade42f..e723bd2 100644 --- a/app/modules/project/templates/project/goal_meeting.html +++ b/app/modules/project/templates/project/goal_meeting.html @@ -1,7 +1,7 @@ {% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -119,11 +119,11 @@ {# 작업 등록 — 주차마다 한 표를 서버에(025, 모두가 같은 표 — project.js initMeetQuickTasks). 제목 = "N주차 작업 등록", 회의 완료면 읽기 전용 #} {% set qw = weeks | selectattr("start", "equalto", week) | first %}
-

{% if week_n %}{{ week_n }}주차 {% endif %}작업 등록 제목 → 담당자·프로젝트·섹션 → [적용] · ↳ 또는 Tab = 세부 작업 +

{% if week_n %}{{ week_n }}주차 {% endif %}작업 등록 제목 → 담당자·프로젝트·섹션·작업 → [적용]

- +
제목담당자프로젝트섹션
제목담당자프로젝트섹션작업
@@ -295,5 +295,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index 6c39002..cde8fff 100644 --- a/app/modules/project/templates/project/goals.html +++ b/app/modules/project/templates/project/goals.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -207,5 +207,5 @@ {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/help.html b/app/modules/project/templates/project/help.html index d85d628..696803b 100644 --- a/app/modules/project/templates/project/help.html +++ b/app/modules/project/templates/project/help.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -637,7 +637,7 @@

제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 월 계획이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 결정사항(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 작업 등록 표입니다.

  1. 작업 등록(제목에 N주차 작업 등록) — 주차마다 한 표를 모두가 같이 봅니다(다른 사람이 적거나 등록한 줄도 보임, 30초마다·창을 다시 볼 때 새로 읽음). 내가 멤버가 아닌 프로젝트를 고른 남의 줄은 프로젝트 이름을 가립니다. 회의 완료면 읽기 전용입니다. - 세부 작업 — 줄에 마우스를 올리면 나오는 ↳(또는 우클릭 → 세부 작업 추가)로 바로 아래에 세부 작업 줄을 만듭니다. 제목 칸에서 Tab = 위 줄의 세부 작업으로, Shift+Tab = 다시 위 단계로(한 단계만). 세부 작업 줄은 위 줄의 프로젝트를 따르고 섹션이 없으며, 위 줄을 [적용]한 뒤 [적용]하면 그 작업의 세부 작업이 됩니다. + 작업 칸 — 비워 두면 고른 섹션에 새 작업으로, 작업을 고르면 그 작업의 세부 작업으로 등록합니다(목록 = 그 섹션의 진행 중인 메인 작업, 고르면 섹션 칸은 —). 등록된 줄의 제목을 누르면 오른쪽에 작업 창이 열려 바로 편집할 수 있습니다(작업 창에서 저장이 끝나야 닫히거나 다른 작업으로 바뀝니다). 크게 열기 — 같은 표를 넓은 창으로 열어 씁니다(줄·저장은 그대로, Esc·×로 닫기). 제목 칸에 작업 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다(완료 프로젝트·완료 섹션은 목록에 나오지 않습니다). 목록 맨 위 새 프로젝트(Pro user 이상)·새 섹션(그 프로젝트 멤버)을 누르면 이름만 적어 바로 만들고 그 칸에 골라집니다. 새 프로젝트는 섹션 없이 시작하니 섹션 칸에서 새 섹션을 만들어 고르세요.
  2. 프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).
  3. 맨 오른쪽 적용을 누르면 그 프로젝트에 작업이 만들어지고, 줄에 등록됨 링크가 생깁니다. 줄은 이 브라우저에 남아 있어 새로고침해도 사라지지 않습니다. + 줄 추가로 줄을 늘립니다.
  4. diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index a7ec16b..33794b8 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -101,5 +101,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index fd26706..81b2782 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html index deb521c..a7c9610 100644 --- a/app/modules/project/templates/project/notifier.html +++ b/app/modules/project/templates/project/notifier.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -108,5 +108,5 @@ }); })(); - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index d029d35..40cc4fc 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -468,5 +468,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index f974887..09ecfeb 100644 --- a/app/modules/project/templates/project/trash.html +++ b/app/modules/project/templates/project/trash.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -70,5 +70,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/static/project.css b/app/static/project.css index 22170e3..61f8953 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2549,11 +2549,13 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important; } .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-table th:nth-child(1) { width: 24%; } +.pj-meet-quick-table th:nth-child(2) { width: 15%; } +.pj-meet-quick-table th:nth-child(3) { width: 15%; } +.pj-meet-quick-table th:nth-child(4) { width: 12%; } +.pj-meet-quick-table th:nth-child(5) { width: 15%; } +.pj-meet-quick-table th:nth-child(6) { 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; @@ -3057,21 +3059,15 @@ html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--p /* 회의록 작업 등록 — 제목 앞 주차(N주차 작업 등록, 주차마다 따로 기억) */ .pj-meet-quick-week { color: var(--pj-accent); } .pj-meet-quick-note { padding: 10px 8px; color: #8a9099; font-size: 12.5px; } -/* 작업 등록 — 세부 작업 줄(↳ 들여쓰기)·줄 위 ↳ 추가 버튼·[크게 열기] 창(같은 표를 옮겨 쓴다) */ +/* 작업 등록 — [크게 열기] 창(같은 표를 옮겨 쓴다)·등록된 제목(누르면 오른쪽 작업 창) */ .pj-meet-quick h3 { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; } .pj-meet-quick-expand { margin-left: auto; order: 2; display: inline-flex; align-items: center; gap: 3px; } .pj-meet-quick h3 small { order: 3; flex-basis: 100%; margin-left: 0; } /* 한 줄: 제목 + [크게 열기], 그 아래 안내 */ .pj-meet-quick-expand .material-symbols-outlined { font-size: 15px; } -.pj-meet-quick-title { position: relative; } -.pj-meet-quick-table tr.is-sub .pj-meet-quick-title { padding-left: 20px; } -.pj-meet-quick-submark { position: absolute; left: 6px; top: 50%; transform: translateY(-50%); color: #9aa1a9; font-size: 13px; pointer-events: none; } -.pj-meet-quick-addsub { - position: absolute; right: 2px; top: 50%; transform: translateY(-50%); width: 22px; height: 22px; padding: 0; - display: inline-flex; align-items: center; justify-content: center; border: 1px solid var(--pj-border, #e3e5e8); border-radius: 5px; - background: #fff; color: var(--pj-ink-soft); cursor: pointer; opacity: 0; transition: opacity .12s; -} -.pj-meet-quick-addsub .material-symbols-outlined { font-size: 15px; } -.pj-meet-quick-table tr:hover .pj-meet-quick-addsub, .pj-meet-quick-addsub:focus { opacity: 1; } +.pj-meet-quick-open { display: block; width: 100%; padding: 2px 6px; border: none; background: none; text-align: left; font: inherit; + color: var(--pj-ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; border-radius: 5px; } +button.pj-meet-quick-open:hover { background: #f1f3f5; color: var(--pj-accent-dark, #2f5bb7); text-decoration: underline; } +.pj-meet-quick-open.is-plain { cursor: default; color: var(--pj-ink-soft); } .pj-meet-quick-inherit { display: block; padding: 0 4px; color: #9aa1a9; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; } .pj-meet-quick-modal { position: fixed; inset: 0; z-index: 2100; /* 고르기 메뉴(.pj-ctxmenu 2200)가 그 위에 */ display: flex; align-items: center; justify-content: center; padding: 16px; box-sizing: border-box; background: rgba(15, 17, 21, .4); } diff --git a/app/static/project.js b/app/static/project.js index 9e9a303..9a95280 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -10667,8 +10667,8 @@ // · 등록된 줄의 [삭제] = 확인 뒤 그 작업도 삭제(휴지통 3개월), 적용 전 줄의 × = 줄만 지움. // · 30초마다·창을 다시 볼 때 다시 읽는다(입력 중·저장 중엔 건너뜀). 회의 완료면 읽기 전용. // · 이 브라우저에 남은 예전 표(pj_meet_quick:…)는 처음 열 때 서버로 한 번 옮기고 지운다. - // · 세부 작업 줄(한 단계, 서버 parent_id) — ↳ 버튼·우클릭으로 추가, 제목 칸 Tab = 위 줄의 세부 작업으로, Shift+Tab = 위 단계로. - // 프로젝트는 위 줄을 따르고 섹션은 없다. [적용]은 위 줄이 먼저(서버가 위 줄 작업 밑에 세부 작업으로 만든다). + // · 작업 칸(026 parent_task_id) — 비우면 그 섹션에 새 작업, 이미 있는 작업을 고르면 [적용] 때 그 작업의 세부 작업으로(섹션 없음). + // · 등록된 줄의 제목을 누르면 오른쪽에 작업 창(편집, 수신함과 같은 iframe·저장 대기). // · [크게 열기] — 같은 표를 넓은 창으로 옮겨 쓴다(줄·저장 그대로), 닫으면 제자리. function initMeetQuickTasks() { const box = el("pj-meet-quick"); @@ -10693,41 +10693,26 @@ return url ? '' : '' + escapeHtml(nameOf(email).slice(0, 1)) + ""; }; - const blank = function (parent) { + const blank = function () { return { id: null, title: "", assignee: "", projectId: null, projectName: "", stageId: null, stageName: "", - taskId: null, registered: false, visible: true, taskExists: true, chain: null, - parentId: parent && parent.id ? parent.id : null, parentRef: parent || null }; + parentTaskId: null, parentTaskTitle: "", taskId: null, registered: false, visible: true, taskExists: true, chain: null }; }; function fromServer(t) { return { id: t.id, title: t.title || "", assignee: t.assignee_email || "", projectId: t.project_id, - projectName: t.project_name || "", stageId: t.stage_id, stageName: t.stage_name || "", taskId: t.task_id, - registered: !!t.registered, visible: t.visible !== false, taskExists: t.task_exists !== false, chain: null, - parentId: t.parent_id || null, parentRef: null }; + projectName: t.project_name || "", stageId: t.stage_id, stageName: t.stage_name || "", + parentTaskId: t.parent_task_id || null, parentTaskTitle: t.parent_task_title || "", taskId: t.task_id, + registered: !!t.registered, visible: t.visible !== false, taskExists: t.task_exists !== false, chain: null }; } let rows = []; let ready = false, unavailable = ""; - // 세부 작업 줄(한 단계) — 위 줄 = parentRef(아직 서버에 없는 줄) 또는 parentId - function parentOf(r) { - if (r.parentRef && rows.indexOf(r.parentRef) >= 0) return r.parentRef; - if (r.parentId) return rows.find(function (x) { return x.id === r.parentId; }) || null; - return null; - } - function childrenOf(p) { return rows.filter(function (x) { return parentOf(x) === p; }); } - // 화면 순서 = 맨 위 단계 줄(지금 순서) 바로 뒤에 그 세부 작업 줄들 - function reorder() { - const tops = rows.filter(function (r) { return !parentOf(r); }); - const out = []; - tops.forEach(function (t) { out.push(t); childrenOf(t).forEach(function (c) { out.push(c); }); }); - rows = out; - } function padBlank() { if (locked) return; - const open = rows.filter(function (r) { return !r.registered && !parentOf(r); }).length; + const open = rows.filter(function (r) { return !r.registered; }).length; for (let i = open; i < 3; i++) rows.push(blank()); } let projects = null; - const memberCache = {}, stageCache = {}; + const memberCache = {}, stageCache = {}, taskCache = {}; async function loadProjects() { if (projects) return projects; const res = await api("GET", "/project/api/projects"); @@ -10750,26 +10735,27 @@ stageCache[pid] = (res.stages || []).slice().sort(function (a, b) { return a.sort_order - b.sort_order; }); return stageCache[pid]; } + // 작업 칸 후보 — 그 프로젝트의 (그 섹션) 미완료 메인 작업. 고르면 [적용] 때 그 작업의 세부 작업으로 만든다. + async function tasksOf(pid) { + if (taskCache[pid]) return taskCache[pid]; + const res = await api("GET", "/project/api/projects/" + pid + "/tasks"); + taskCache[pid] = (res.tasks || []).filter(function (t) { return t.project_id === pid && !t.completed_at && !t.parent_task_id; }); + return taskCache[pid]; + } - // ── 저장 — 줄마다 차례대로. 서버에 없는 줄은 처음 채울 때 만든다(지금 칸 전부 + 위 줄을 보낸다 — 위 줄도 없으면 먼저) ── + // ── 저장 — 줄마다 차례대로. 서버에 없는 줄은 처음 채울 때 만든다(지금 칸 전부를 보낸다) ── let pendingSaves = 0; function persist(r, patch) { pendingSaves++; const run = async function () { - const par = parentOf(r); - if (par && !par.id) await persist(par, {}); - if (par && !par.id) throw new Error("위 줄을 저장하지 못했습니다"); if (!r.id) { const res = await api("POST", listUrl, { - title: r.title, assignee_email: r.assignee, project_id: par ? null : r.projectId, - stage_id: par ? null : r.stageId, parent_id: par ? par.id : null, + title: r.title, assignee_email: r.assignee, project_id: r.projectId, stage_id: r.stageId, + parent_task_id: r.parentTaskId, }); r.id = res.task.id; - r.parentId = par ? par.id : null; r.parentRef = null; } else { - if (patch && Object.prototype.hasOwnProperty.call(patch, "parent_id") && patch.parent_id === undefined) patch.parent_id = par ? par.id : null; await api("PUT", rowUrl(r.id), patch); - if (patch && Object.prototype.hasOwnProperty.call(patch, "parent_id")) { r.parentId = patch.parent_id; r.parentRef = null; } } }; r.chain = (r.chain || Promise.resolve()).then(run).catch(function (e) { @@ -10778,24 +10764,22 @@ }).finally(function () { pendingSaves--; }); return r.chain; } - function cell(kind, text, placeholder, disabled, extra) { - return '"; + function cell(kind, text, placeholder, disabled, title) { + return '"; } function render() { if (unavailable) { - tbody.innerHTML = '' + escapeHtml(unavailable) + ""; + tbody.innerHTML = '' + escapeHtml(unavailable) + ""; return; } - reorder(); tbody.innerHTML = rows.map(function (r, i) { - const par = parentOf(r); const ro = locked || r.registered; let acts; if (r.registered) { const label = !r.taskExists ? "작업 삭제됨" : "등록됨"; const link = r.visible && r.taskId && r.taskExists - ? '' + label + "" : "" + label + ""; + ? '' + label + "" : "" + label + ""; acts = 'check_circle' + link + "" + (!locked && r.visible ? '" + + acts = '' + ''; } - // 세부 작업 줄 — ↳ 들여쓰기, 프로젝트는 위 줄을 따르고 섹션은 없다(작업의 세부 작업) - const projCell = par - ? '' + escapeHtml(par.projectName || "위 줄 따름") + "" - : cell("project", r.projectName, "프로젝트", ro); - const stageCell = par ? '—' : cell("stage", r.stageName, "섹션", ro); - const addSub = !par && !locked && r.visible - ? '' : ""; - return '' + - '' + (par ? '' : "") + - '" + addSub + "" + + // 제목 — 등록된 줄은 누르면 오른쪽에 작업 창(편집), 아니면 입력칸 + const titleCell = r.registered + ? (r.visible && r.taskId && r.taskExists + ? '" + : '' + escapeHtml(r.title || "(제목 없음)") + "") + : '"; + // 작업 칸 — 비우면 그 섹션에 새 작업, 고르면 그 작업의 세부 작업(↳ 표시) + const taskCell = r.parentTaskId + ? cell("task", "↳ " + (r.parentTaskTitle || "작업"), "", ro, "이 작업의 세부 작업으로 등록") + : cell("task", "", r.registered ? "—" : "새 작업", ro || !r.projectId, r.projectId ? "고르면 그 작업의 세부 작업으로 등록(비우면 섹션에 새 작업)" : "프로젝트를 먼저 고르세요"); + return '" + + '' + titleCell + "" + "" + (r.assignee ? '" : cell("assignee", "", "담당자", ro)) + "" + - "" + projCell + "" + - "" + stageCell + "" + + "" + cell("project", r.projectName, "프로젝트", ro) + "" + + "" + (r.parentTaskId ? '—' + : cell("stage", r.stageName, "섹션", ro)) + "" + + "" + taskCell + "" + '' + acts + ""; }).join(""); } - function focusTitle(r) { - const i = rows.indexOf(r); - const inp = i >= 0 ? tbody.querySelector('tr[data-i="' + i + '"] input[data-field="title"]') : null; - if (inp) { inp.focus(); try { inp.setSelectionRange(inp.value.length, inp.value.length); } catch (_) {} } - } function menuAt(btn, items) { const r = btn.getBoundingClientRect(); showContextMenu(r.left, r.bottom + 2, items.length ? items : [{ label: "고를 항목이 없습니다", onClick: function () {} }]); } async function chooseProject(r, p) { - if (r.projectId !== p.id) { r.stageId = null; r.stageName = ""; } + if (r.projectId !== p.id) { r.stageId = null; r.stageName = ""; r.parentTaskId = null; r.parentTaskTitle = ""; } r.projectId = p.id; r.projectName = p.name; try { const [mem, stages] = await Promise.all([membersOf(p.id), stagesOf(p.id)]); @@ -10866,6 +10846,7 @@ if (projects) projects.push(p); memberCache[p.id] = [String(p.owner_email || "").toLowerCase()].filter(Boolean); stageCache[p.id] = []; + taskCache[p.id] = []; showToast("프로젝트 ‘" + p.name + "’를 만들었습니다."); await chooseProject(r, p); } catch (e) { showToast("프로젝트 만들기 실패: " + e.message, "error"); } @@ -10879,9 +10860,8 @@ }))); } async function pickAssignee(r, btn) { - // 프로젝트(세부 작업 줄은 위 줄의 프로젝트)를 골랐으면 그 멤버·소유자만, 아니면 프로젝트 권한이 있는 전체 직원 - const par = parentOf(r), pid = par ? par.projectId : r.projectId; - const emails = pid ? await membersOf(pid) + // 프로젝트를 골랐으면 그 프로젝트 멤버·소유자만(작업을 볼 수 있는 사람), 아니면 프로젝트 권한이 있는 전체 직원 + const emails = r.projectId ? await membersOf(r.projectId) : (window.PJ_MEET_MEMBERS || []).map(function (m) { return String(m.email).toLowerCase(); }); const set = function (e) { r.assignee = e; render(); persist(r, { assignee_email: e }); }; menuAt(btn, [{ label: "담당자 없음", icon: menuIcon("person_off"), checked: !r.assignee, onClick: function () { set(""); } }, null] @@ -10893,7 +10873,12 @@ if (!r.projectId) { showToast("프로젝트를 먼저 고르세요."); return; } const stages = await stagesOf(r.projectId); const pid = r.projectId; - const set = function (st) { r.stageId = st.id; r.stageName = st.name; render(); persist(r, { project_id: pid, stage_id: st.id }); }; + const set = function (st) { + r.stageId = st.id; r.stageName = st.name; + const keepTask = r.parentTaskId && (taskCache[pid] || []).some(function (t) { return t.id === r.parentTaskId && t.stage_id === st.id; }); + if (!keepTask) { r.parentTaskId = null; r.parentTaskTitle = ""; } + render(); persist(r, { project_id: pid, stage_id: st.id, parent_task_id: r.parentTaskId }); + }; // 목록 맨 위 "+ 새 섹션" — 그 프로젝트 멤버 누구나(서버 POST …/stages). 만든 섹션을 바로 고른다. const head = [{ label: "새 섹션", icon: menuIcon("add"), onClick: async function () { const name = await prompt("‘" + r.projectName + "’에 만들 섹션 이름", ""); @@ -10910,58 +10895,43 @@ return { label: st.name, icon: menuIcon("view_column"), checked: r.stageId === st.id, onClick: function () { set(st); } }; }))); } - - // ── 세부 작업 줄 — 추가(↳ 버튼·우클릭), 세부 작업으로(Tab)·위 단계로(Shift+Tab). 한 단계만 ── - function addSub(p) { - if (locked) return; - const kids = childrenOf(p); - const at = rows.indexOf(kids.length ? kids[kids.length - 1] : p); - const c = blank(p); - rows.splice(at + 1, 0, c); - render(); - focusTitle(c); - } - function canIndent(r) { - if (locked || r.registered || parentOf(r) || childrenOf(r).length) return null; - const i = rows.indexOf(r); - for (let k = i - 1; k >= 0; k--) { if (!parentOf(rows[k])) return rows[k].visible ? rows[k] : null; } - return null; - } - function indent(r) { - const p = canIndent(r); - if (!p) return false; - r.parentRef = p; r.parentId = p.id || null; - render(); focusTitle(r); - if (r.id || r.title || r.assignee) persist(r, { parent_id: undefined }); - return true; - } - function outdent(r) { - const p = parentOf(r); - if (locked || r.registered || !p) return false; - const kids = childrenOf(p); - rows.splice(rows.indexOf(r), 1); - r.parentRef = null; r.parentId = null; - rows.splice(rows.indexOf(kids[kids.length - 1] === r ? p : kids[kids.length - 1]) + 1, 0, r); - render(); focusTitle(r); - if (r.id) persist(r, { parent_id: null }); - return true; + // 작업 칸 — 맨 위 "새 작업(섹션에)" + 그 섹션(섹션이 없으면 프로젝트 전체)의 미완료 메인 작업. 고르면 세부 작업으로 등록. + async function pickTask(r, btn) { + if (!r.projectId) { showToast("프로젝트를 먼저 고르세요."); return; } + const pid = r.projectId; + const all = await tasksOf(pid); + const list = r.stageId ? all.filter(function (t) { return t.stage_id === r.stageId; }) : all; + const set = function (t) { + r.parentTaskId = t ? t.id : null; r.parentTaskTitle = t ? t.title : ""; + if (t && t.stage_id) { + const st = (stageCache[pid] || []).find(function (x) { return x.id === t.stage_id; }); + if (st) { r.stageId = st.id; r.stageName = st.name; } + } + render(); persist(r, { parent_task_id: r.parentTaskId, stage_id: r.stageId }); + }; + menuAt(btn, [{ label: "새 작업" + (r.stageName ? " (‘" + r.stageName + "’ 섹션에)" : ""), icon: menuIcon("add_task"), + checked: !r.parentTaskId, onClick: function () { set(null); } }, null] + .concat(list.length ? list.map(function (t) { + return { label: t.title, icon: menuIcon("subdirectory_arrow_right"), checked: r.parentTaskId === t.id, onClick: function () { set(t); } }; + }) : [{ label: r.stageName ? "이 섹션에 진행 중인 작업이 없습니다" : "진행 중인 작업이 없습니다", onClick: function () {} }])); } async function apply(r, btn) { flushTitle(r); - const par = parentOf(r); if (!r.title.trim()) { showToast("작업 제목을 쓰세요."); return; } - if (par && !par.registered) { showToast("위 줄(상위 작업)을 먼저 [적용]하세요."); return; } - if (!par && !r.projectId) { showToast("프로젝트를 고르세요."); return; } + if (!r.projectId) { showToast("프로젝트를 고르세요."); return; } btn.disabled = true; try { await r.chain; if (!r.id) await persist(r, {}); if (!r.id) throw new Error("줄을 저장하지 못했습니다"); const res = await api("POST", rowUrl(r.id) + "/apply", {}); + const sub = !!r.parentTaskId; Object.assign(r, fromServer(res.task)); - showToast(res.created ? "‘" + ((par ? par.projectName : r.projectName) || "프로젝트") + "’에 " + (par ? "세부 작업을" : "작업을") + " 등록했습니다." + if (sub && taskCache[r.projectId]) delete taskCache[r.projectId]; + showToast(res.created ? (sub ? "‘" + r.parentTaskTitle + "’의 세부 작업으로 등록했습니다." : "‘" + r.projectName + "’에 작업을 등록했습니다.") : "이미 등록된 줄입니다(다른 사람이 먼저 [적용]했습니다)."); + delete taskCache[r.projectId]; // 새 작업이 작업 칸 후보에 보이게 padBlank(); render(); } catch (e) { btn.disabled = false; @@ -10977,19 +10947,76 @@ try { await api("DELETE", "/project/api/tasks/" + r.taskId); showToast("작업을 삭제했습니다."); } catch (e) { if (e.status !== 404) { btn.disabled = false; showToast("작업 삭제 실패: " + e.message, "error"); return; } } } - dropRow(r, true); + dropRow(r); } - async function dropRow(r, asked) { - const kids = childrenOf(r); - if (!asked && kids.length && !(await confirm("세부 작업 줄 " + kids.length + "개도 함께 지울까요? (이미 [적용]해 만든 작업은 프로젝트에 남습니다)", - { okText: "지우기", cancelText: "취소" }))) return; + async function dropRow(r) { try { await r.chain; - if (r.id) await api("DELETE", rowUrl(r.id)); // 서버는 세부 작업 줄도 함께 지운다(CASCADE) + if (r.id) await api("DELETE", rowUrl(r.id)); } catch (e) { if (e.status !== 404) { showToast("줄을 지우지 못했습니다: " + e.message, "error"); return; } } - rows = rows.filter(function (x) { return x !== r && kids.indexOf(x) < 0; }); + const i = rows.indexOf(r); + if (i >= 0) rows.splice(i, 1); padBlank(); render(); } + + // ── 오른쪽 작업 창 — 등록된 줄의 제목을 누르면 그 작업 편집 창(프로젝트 화면 ?embed=1 을 iframe 에, 수신함과 같은 방식). + // 다른 작업으로 바꾸거나 닫기 전에 작업 창 안의 저장을 기다린다(__pjEmbedSettle — 실패면 "버리고 넘어가기 / 계속 편집"). + let panel = null, panelTask = null, switching = null, wanted; + function panelOpen() { return !!panel && panel.classList.contains("is-open"); } + async function settleFrame() { + if (!panelOpen()) return true; + let fn = null; + try { fn = panel.querySelector("iframe").contentWindow.__pjEmbedSettle; } catch (_) { fn = null; } + if (typeof fn !== "function") return true; + try { return !!(await fn()); } catch (_) { return false; } + } + function showPanel(taskId) { + if (taskId == null) { + if (!panelOpen()) return; + panel.classList.remove("is-open"); + panelTask = null; + const p = panel; + setTimeout(function () { if (!p.classList.contains("is-open")) p.querySelector("iframe").src = "about:blank"; }, 250); + load(true); // 작업 창에서 제목 등을 바꿨을 수 있다 + return; + } + if (!panel) { + panel = document.createElement("div"); + panel.className = "pj-inbox-panel pj-meet-task-panel"; + panel.innerHTML = ''; + document.body.appendChild(panel); // 화면 배율(.pj-ui-scale) 밖 — body 에 + } + panelTask = taskId; + panel.querySelector("iframe").src = "/project/t/" + taskId + "?embed=1"; + void panel.offsetWidth; + panel.classList.add("is-open"); + } + function requestPanel(taskId) { + wanted = taskId; + if (switching) return switching; + switching = (async function () { + while (wanted !== undefined) { + const t = wanted; + if ((t === null && !panelOpen()) || (t !== null && panelOpen() && panelTask === t)) { wanted = undefined; break; } + const ok = await settleFrame(); + if (!ok) { wanted = undefined; break; } + if (wanted !== t) continue; + wanted = undefined; + showPanel(t); + } + })().finally(function () { switching = null; }); + return switching; + } + window.addEventListener("message", function (e) { + if (e.origin === location.origin && e.data && e.data.type === "pj-embed-close" && panelOpen()) requestPanel(null); + }); + document.addEventListener("keydown", function (e) { if (e.key === "Escape" && panelOpen() && !modal) requestPanel(null); }); + document.addEventListener("mousedown", function (e) { + if (!panelOpen() || panel.contains(e.target)) return; + if (e.target.closest && e.target.closest('[data-quick="open"], .pj-ctxmenu, .pj-modal, .erp-dialog')) return; + requestPanel(null); + }); + // 제목 — 치는 동안 0.6초 멈추면, 칸을 떠나면 저장 const titleTimers = new Map(); function flushTitle(r) { @@ -11013,17 +11040,9 @@ }); tbody.addEventListener("keydown", function (e) { const inp = e.target.closest("input[data-field=title]"); - if (!inp || inp.readOnly || isImeEnter(e)) return; - const r = rowOf(inp); - if (e.key === "Tab") { - // 아사나처럼 — Tab = 위 줄의 세부 작업으로, Shift+Tab = 위 단계로. 할 수 없으면 원래 Tab(다음 칸) - flushTitle(r); - if (e.shiftKey ? outdent(r) : indent(r)) e.preventDefault(); - return; - } - if (e.key === "Enter") { + if (inp && !inp.readOnly && e.key === "Enter" && !isImeEnter(e)) { e.preventDefault(); - flushTitle(r); + flushTitle(rowOf(inp)); inp.closest("tr").querySelector('[data-pick="assignee"]').click(); } }); @@ -11033,31 +11052,22 @@ const r = rows[+tr.dataset.i], pick = e.target.closest("[data-pick]"); const del = e.target.closest('[data-quick="delete"], [data-quick="remove"]'); if (del) { if (del.dataset.quick === "delete") removeTask(r, del); else dropRow(r); return; } - if (e.target.closest('[data-quick="add-sub"]')) { addSub(r); return; } + if (e.target.closest('[data-quick="open"]')) { if (modal) closeBig(); requestPanel(r.taskId); return; } if (r.registered || locked) return; const fail = function (err) { showToast("목록을 읽지 못했습니다: " + err.message, "error"); }; if (pick) { e.stopPropagation(); - ({ project: pickProject, assignee: pickAssignee, stage: pickStage })[pick.dataset.pick](r, pick).catch(fail); + ({ project: pickProject, assignee: pickAssignee, stage: pickStage, task: pickTask })[pick.dataset.pick](r, pick).catch(fail); } else if (e.target.closest('[data-quick="apply"]')) apply(r, e.target.closest('[data-quick="apply"]')); }); - // 우클릭 — 세부 작업 추가 · 세부 작업으로 · 위 단계로 · 줄 지우기 - tbody.addEventListener("contextmenu", function (e) { - const r = rowOf(e.target); - if (!r || locked) return; - e.preventDefault(); - const par = parentOf(r); - const items = []; - if (!par && r.visible) items.push({ label: "세부 작업 추가", icon: menuIcon("subdirectory_arrow_right"), onClick: function () { addSub(r); } }); - if (canIndent(r)) items.push({ label: "위 줄의 세부 작업으로 (Tab)", icon: menuIcon("format_indent_increase"), onClick: function () { indent(r); } }); - if (par && !r.registered) items.push({ label: "위 단계로 (Shift+Tab)", icon: menuIcon("format_indent_decrease"), onClick: function () { outdent(r); } }); - if (!r.registered) { if (items.length) items.push(null); items.push({ label: "줄 지우기", danger: true, icon: menuIcon("close"), onClick: function () { dropRow(r); } }); } - if (items.length) showContextMenu(e.clientX, e.clientY, items); - }); const addBtn = box.querySelector('[data-quick="add"]'); if (addBtn) { if (locked) addBtn.hidden = true; - else addBtn.addEventListener("click", function () { const b = blank(); rows.push(b); render(); focusTitle(b); }); + else addBtn.addEventListener("click", function () { + const b = blank(); rows.push(b); render(); + const inp = tbody.querySelector('tr[data-i="' + rows.indexOf(b) + '"] input[data-field="title"]'); + if (inp) inp.focus(); + }); } // ── 크게 열기 — 같은 표(같은 줄·같은 저장)를 넓은 창으로 옮겨 쓴다. 닫으면 제자리로 ── @@ -11072,7 +11082,7 @@ if (expandBtn) expandBtn.focus(); } function onBigKey(e) { - if (e.key === "Escape" && modal && !document.querySelector(".pj-ctxmenu, .pj-modal:not([hidden])")) { e.preventDefault(); closeBig(); } + if (e.key === "Escape" && modal && !document.querySelector(".pj-ctxmenu, .pj-modal:not([hidden])")) { e.preventDefault(); e.stopPropagation(); closeBig(); } } function openBig() { if (modal) return; @@ -11101,7 +11111,7 @@ if (!force && busy()) return; try { const res = await api("GET", listUrl); - const blanks = rows.filter(function (r) { return !r.id && !parentOf(r) && !r.title && !r.projectId && !r.assignee; }).length; + const blanks = rows.filter(function (r) { return !r.id && !r.title && !r.projectId && !r.assignee; }).length; rows = (res.tasks || []).map(fromServer); for (let i = 0; i < blanks; i++) rows.push(blank()); padBlank(); @@ -11143,9 +11153,10 @@ await load(true); if (!unavailable && !locked) { await migrateLocal(); await load(true); } })(); - setInterval(function () { if (!document.hidden && ready) load(false); }, 30000); - document.addEventListener("visibilitychange", function () { if (!document.hidden && ready) load(false); }); - if (window.__PJ_TEST__) window.__pjMeetQuick = { load: load, rows: function () { return rows; }, openBig: openBig, closeBig: closeBig }; + setInterval(function () { if (!document.hidden && ready && !panelOpen()) load(false); }, 30000); + document.addEventListener("visibilitychange", function () { if (!document.hidden && ready && !panelOpen()) load(false); }); + if (window.__PJ_TEST__) window.__pjMeetQuick = { load: load, rows: function () { return rows; }, openBig: openBig, closeBig: closeBig, + settling: function () { return switching || Promise.resolve(); } }; } function initGoalMeeting() { diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 84c05e3..f0ce11c 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -125,6 +125,17 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g 설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다. +## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026) + +026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내. + +```bash +cd /opt/www/main +docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_026_$(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_026_meeting_quick_parent_task.sql +docker exec postgres-db psql -U postgres -d project_db -c "SELECT column_name FROM information_schema.columns WHERE table_name='goal_meeting_tasks' AND column_name='parent_task_id';" +``` + ## 회의록 작업 등록 표 마이그레이션 (025) 025는 `goal_meeting_tasks` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). 작업 등록 표를 주차별로 서버에 두어 모두가 같이 본다. diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index 6abdf8f..b4b516d 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -1206,9 +1206,12 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame `POST …/{id}/apply`(줄을 FOR UPDATE 로 잠그고 task_id 가 없을 때만 `_create_task_for` — 작업 창과 같은 권한·알림, 동시에 눌러도 하나). 보기·고치기 = 회의록을 볼 수 있는 사람 누구나(회의 완료면 409), 줄에 고를 수 있는 프로젝트 = 내가 멤버인 것만(403), 내가 멤버가 아닌 프로젝트를 가리키는 남의 줄은 프로젝트·섹션 이름·작업 링크를 가린다(`registered` 만). [적용] 뒤 줄은 고칠 수 없다. - **세부 작업 줄**(`parent_id`, 한 단계만): ↳ 버튼·우클릭 → 바로 아래 세부 작업 줄, 제목 칸 Tab = 위 줄의 세부 작업으로 · Shift+Tab = 위 단계로 - (`PUT … {parent_id}` — 세부 작업 줄 밑·자식 딸린 줄은 400). 세부 작업 줄은 위 줄의 프로젝트를 따르고 섹션이 없다 — [적용]은 위 줄이 먼저, - 서버가 위 줄이 만든 작업 밑에(그 작업의 프로젝트로) 세부 작업을 만든다. 위 줄을 지우면 세부 작업 줄도(CASCADE, 이미 만든 작업은 남음). + **작업 칸**(마이그레이션 026 `parent_task_id`): 프로젝트 → 섹션 → **작업** — 비우면 그 섹션에 새 작업, 이미 있는 작업을 고르면 [적용] 때 + 그 작업의 세부 작업으로(섹션 없음). 후보 = 그 섹션(섹션이 없으면 프로젝트)의 미완료 메인 작업(`GET /api/projects/{id}/tasks`). + 서버는 고른 작업이 그 프로젝트 것인지 확인(400), 프로젝트를 바꾸면 섹션·작업을 비우고, [적용] 때 그 작업이 없어졌거나 옮겨졌으면 400. + 026 미적용이면 작업 칸 저장만 503(나머지 그대로). (025 의 `parent_id` — 잠깐 있던 '표 안 줄끼리 세부 작업' — 는 화면·API 에서 뺐다, 열은 남김.) + **등록된 줄 제목 = 오른쪽 작업 창**: `/project/t/{id}?embed=1` 을 iframe 패널(`.pj-inbox-panel.pj-meet-task-panel`)에 — 수신함과 같이 + 바꾸기·닫기(Esc·바깥 클릭·작업 창 닫기) 전에 `__pjEmbedSettle`(저장 대기 → 실패면 버리기/계속 편집), 닫으면 표를 다시 읽는다. **[크게 열기]** = 같은 표(DOM 그대로)를 넓은 창(`.pj-meet-quick-modal`, body 에, 고르기 메뉴 아래 z-index)으로 옮겨 쓰고 Esc·×로 제자리. 화면은 빈 줄 3개를 화면에만 두고 처음 채우는 순간 POST, 그 뒤 칸마다 PUT(줄마다 차례대로), 30초마다·창을 다시 볼 때 다시 읽는다(입력·저장 중엔 건너뜀). diff --git a/scripts/sql/project_db_026_meeting_quick_parent_task.sql b/scripts/sql/project_db_026_meeting_quick_parent_task.sql new file mode 100644 index 0000000..3d2bff6 --- /dev/null +++ b/scripts/sql/project_db_026_meeting_quick_parent_task.sql @@ -0,0 +1,16 @@ +-- ===================================================================== +-- project_db 마이그레이션 026 — 회의록 작업 등록 표: "작업" 칸(이미 있는 작업의 세부 작업으로 등록) +-- ===================================================================== +-- 멱등(idempotent). 열 하나만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용. +-- +-- 왜(2026-10-12 사용자 요청): 작업 등록 표에서 프로젝트 → 섹션 → **작업** 까지 고를 수 있게 — 작업을 고르면 [적용] 때 +-- 그 작업의 세부 작업으로 만든다(비우면 예전처럼 그 섹션에 새 작업). 025 의 parent_id(표 안 줄끼리의 세부 작업)는 +-- 화면에서 쓰지 않는다(열·값은 그대로 둔다). +-- ===================================================================== +BEGIN; + +ALTER TABLE goal_meeting_tasks ADD COLUMN IF NOT EXISTS parent_task_id BIGINT NULL; -- 고른 상위 작업(tasks.id, FK 없음 — 작업이 지워져도 줄은 남는다) +COMMENT ON COLUMN goal_meeting_tasks.parent_task_id IS '작업 칸 — [적용] 때 이 작업의 세부 작업으로 만든다(NULL = 그 섹션에 새 작업)'; + +COMMIT; +SELECT 'project_db 026 meeting quick parent task ready' AS status; diff --git a/tests/js/goals_meeting_ui.test.js b/tests/js/goals_meeting_ui.test.js index 7bebab5..8038be0 100644 --- a/tests/js/goals_meeting_ui.test.js +++ b/tests/js/goals_meeting_ui.test.js @@ -523,7 +523,7 @@ function meetServer(env, st) { const out = function (r) { return { id: r.id, title: r.title || "", assignee_email: r.assignee_email || "", project_id: r.project_id || null, project_name: r.project_name || "", stage_id: r.stage_id || null, stage_name: r.stage_name || "", task_id: r.task_id, - parent_id: r.parent_id || null, + parent_task_id: r.parent_task_id || null, parent_task_title: r.parent_task_id ? (r.parent_task_title || "상세페이지 리뉴얼") : "", registered: r.task_id != null, visible: r.visible !== false, task_exists: true }; }; env.route("GET", /\/goals\/meetings\/([\d-]+)\/quick-tasks$/, function (u) { @@ -660,7 +660,9 @@ function meetServer(env, st) { // ════════════════════ [2g3] 작업 등록 = 주차별 서버 표 · 다른 사람 줄도 보임 · 제목 "N주차 작업 등록" · 브라우저 예전 표는 서버로 ════════════════════ await section(async function () { - const titles = function (d) { return Array.from(d.querySelectorAll('#pj-meet-quick tbody input[data-field="title"]')).map(function (i) { return i.value; }); }; + // 제목 — 입력칸(등록 전) 또는 등록된 줄의 제목 버튼·글자 + const titleOf = function (tr) { const i = tr.querySelector('input[data-field="title"]'); return i ? i.value : (tr.querySelector(".pj-meet-quick-open") || {}).textContent || ""; }; + const titles = function (d) { return Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")).map(titleOf); }; const env = makeEnv(PAGE.meeting_admin, MEET_URL); meetServer(env); quickServer(env, { rows: [ @@ -674,9 +676,9 @@ function meetServer(env, st) { const ts = titles(d); check("[2g3] 다른 사람이 적은·등록한 줄도 보임(이 주차만)", ts.indexOf("다른 사람이 적은 줄") >= 0 && ts.indexOf("다른 사람이 등록한 줄") >= 0 && ts.indexOf("다른 주차 줄") < 0, ts); - const hidden = Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")).find(function (tr) { return tr.querySelector("input").value === "남의 프로젝트 줄"; }); + const hidden = Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")).find(function (tr) { return titleOf(tr) === "남의 프로젝트 줄"; }); check("[2g3] 내가 멤버가 아닌 프로젝트 줄 — 이름 가림·작업 링크·삭제 없음", /볼 수 없는 프로젝트/.test(hidden.textContent) && /등록됨/.test(hidden.textContent) && - !hidden.querySelector("a") && !hidden.querySelector('[data-quick="delete"]')); + !hidden.querySelector("a") && !hidden.querySelector('[data-quick="delete"]') && !hidden.querySelector('[data-quick="open"]')); // 이 브라우저에만 있던 예전 표(이 주차 키 · 이번 주면 주차 없는 예전 키) → 서버로 옮기고 지움 for (const isNow of [false, true]) { const e2 = makeEnv(PAGE.meeting_admin, MEET_URL); @@ -693,50 +695,52 @@ function meetServer(env, st) { } }); - // ════════════════════ [2g4] 세부 작업 줄(↳·Tab·Shift+Tab) · [크게 열기] ════════════════════ + // ════════════════════ [2g4] 작업 칸(이미 있는 작업의 세부 작업으로) · 등록된 제목 = 오른쪽 작업 창 · [크게 열기] ════════════════════ await section(async function () { const env = makeEnv(PAGE.meeting_admin, MEET_URL); meetServer(env); - const q = quickServer(env, { rows: [{ id: 1, title: "부모 작업", project_id: 7, project_name: "브랜드" }] }); + const q = quickServer(env, { rows: [{ id: 1, title: "배너 시안", project_id: 7, project_name: "브랜드", stage_id: 71, stage_name: "할 일" }] }); + env.route("GET", /\/project\/api\/projects\/7\/tasks$/, function () { return { body: { tasks: [ + { id: 300, title: "상세페이지 리뉴얼", project_id: 7, stage_id: 71 }, + { id: 301, title: "다른 섹션 작업", project_id: 7, stage_id: 72 }, + { id: 302, title: "끝난 작업", project_id: 7, stage_id: 71, completed_at: "2026-09-01T00:00:00+09:00" }, + { id: 303, title: "이미 세부 작업", project_id: 7, stage_id: null, parent_task_id: 300 }] } }; }); await boot(env); await settle(); await wait(5); await settle(); const d = env.d; - const trs = function () { return Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")); }; - const inputOf = function (tr) { return tr.querySelector('input[data-field="title"]'); }; - const type = async function (inp, v) { - inp.value = v; inp.dispatchEvent(new env.w.Event("input", { bubbles: true })); - inp.dispatchEvent(new env.w.Event("focusout", { bubbles: true })); await settle(); await wait(5); await settle(); - }; - trs()[0].querySelector('[data-quick="add-sub"]').click(); await settle(); - const sub = trs()[1]; - check("[2g4] ↳ → 바로 아래 세부 작업 줄(들여쓰기·프로젝트는 위 줄·섹션 없음)", sub.classList.contains("is-sub") && - inputOf(sub).placeholder === "세부 작업 제목" && /브랜드/.test(sub.querySelector(".pj-meet-quick-inherit").textContent) && - d.activeElement === inputOf(sub)); - await type(inputOf(sub), "세부 하나"); - const saved = Object.values(q.rows).find(function (r) { return r.title === "세부 하나"; }); - check("[2g4] 세부 작업 줄 저장 = parent_id(위 줄), 프로젝트 칸 없이", !!saved && saved.parent_id === 1 && !saved.project_id, saved); - check("[2g4] 위 줄 [적용] 전에는 세부 작업 [적용] 못 함", trs()[1].querySelector('[data-quick="apply"]').disabled); - // 아래 빈 맨 위 단계 줄 — 제목을 쓰고 Tab = 위 줄(부모 작업)의 세부 작업으로, Shift+Tab = 다시 위 단계로 - const top = trs().find(function (tr) { return !tr.classList.contains("is-sub") && !inputOf(tr).value; }); - await type(inputOf(top), "둘째"); - const key = function (inp, shift) { - const e = new env.w.KeyboardEvent("keydown", { key: "Tab", shiftKey: !!shift, bubbles: true, cancelable: true }); - inp.dispatchEvent(e); return e.defaultPrevented; - }; - const tabbed = key(inputOf(trs().find(function (tr) { return inputOf(tr).value === "둘째"; }))); + const row = function () { return d.querySelector("#pj-meet-quick tbody tr"); }; + check("[2g4] 표 머리에 '작업' 칸, 예전 ↳(줄 세부 작업) 버튼 없음", + Array.from(d.querySelectorAll("#pj-meet-quick thead th")).map(function (t) { return t.textContent; }).indexOf("작업") === 4 && + !d.querySelector('[data-quick="add-sub"]')); + row().querySelector('[data-pick="task"]').click(); await settle(); await wait(5); await settle(); + const labels = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel); + check("[2g4] 작업 칸 목록 = '새 작업(섹션에)' + 그 섹션의 진행 중 메인 작업만", labels[0] === "새 작업 (‘할 일’ 섹션에)" && + labels.indexOf("상세페이지 리뉴얼") >= 0 && labels.indexOf("다른 섹션 작업") < 0 && labels.indexOf("끝난 작업") < 0 && labels.indexOf("이미 세부 작업") < 0, labels); + Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (n) { return itemLabel(n) === "상세페이지 리뉴얼"; }).click(); await settle(); await wait(5); await settle(); - const second = Object.values(q.rows).find(function (r) { return r.title === "둘째"; }); - check("[2g4] Tab = 위 줄의 세부 작업으로(저장)", tabbed && second.parent_id === 1 && - trs().find(function (tr) { return inputOf(tr).value === "둘째"; }).classList.contains("is-sub"), second); - key(inputOf(trs().find(function (tr) { return inputOf(tr).value === "둘째"; })), true); - await settle(); await wait(5); await settle(); - check("[2g4] Shift+Tab = 위 단계로(저장)", second.parent_id === null && - !trs().find(function (tr) { return inputOf(tr).value === "둘째"; }).classList.contains("is-sub"), second); + check("[2g4] 작업을 고르면 ↳ 표시·섹션 '—'·제목 칸 '세부 작업 제목'·서버 줄에 parent_task_id", + /↳ 상세페이지 리뉴얼/.test(row().querySelector('[data-pick="task"]').textContent) && /—/.test(row().children[3].textContent) && + row().querySelector('input[data-field="title"]').placeholder === "세부 작업 제목" && q.rows[1].parent_task_id === 300, q.rows[1]); + row().querySelector('[data-quick="apply"]').click(); await settle(); await wait(5); await settle(); + check("[2g4] 적용 → 서버 [적용](고른 작업 밑 세부 작업)", q.applied.length === 1 && q.applied[0].parent_task_id === 300, q.applied); + // 등록된 줄 — 제목을 누르면 오른쪽 작업 창(iframe, embed). 저장 확인이 '계속 편집'이면 닫히지 않음 + const open = row().querySelector('[data-quick="open"]'); + check("[2g4] 등록된 줄 제목 = 작업 창 열기 버튼", !!open && open.textContent === "배너 시안"); + open.click(); await settle(); + const panel = d.body.querySelector(".pj-meet-task-panel"); + check("[2g4] 오른쪽 작업 창(body 에) = /project/t/{id}?embed=1", !!panel && panel.classList.contains("is-open") && + panel.querySelector("iframe").getAttribute("src") === "/project/t/555?embed=1"); + let answer = false; + panel.querySelector("iframe").contentWindow.__pjEmbedSettle = function () { return Promise.resolve(answer); }; + d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle(); + check("[2g4] 작업 창 저장 실패에 '계속 편집' → 창 그대로", panel.classList.contains("is-open")); + answer = true; + d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle(); + check("[2g4] 저장이 끝나면 Esc 로 닫힘", !panel.classList.contains("is-open")); // 크게 열기 — 같은 표가 넓은 창으로(줄 그대로), Esc 로 제자리 - const nRows = trs().length; + const nRows = d.querySelectorAll("#pj-meet-quick tbody tr").length; d.querySelector('#pj-meet-quick [data-quick="expand"]').click(); await settle(); const modal = d.body.querySelector(".pj-meet-quick-modal"); - check("[2g4] 크게 열기 → 같은 표를 넓은 창으로(body 에, 제목 'N주차 작업 등록')", !!modal && !!modal.querySelector("table.pj-meet-quick-table") && - !d.querySelector("#pj-meet-quick table") && /4주차 작업 등록/.test(modal.querySelector("h3").textContent) && + check("[2g4] 크게 열기 → 같은 표를 넓은 창으로(제목 'N주차 작업 등록')", !!modal && /4주차 작업 등록/.test(modal.querySelector("h3").textContent) && modal.querySelectorAll("tbody tr").length === nRows && nRows > 0); d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); await settle(); check("[2g4] Esc → 닫히고 표는 제자리", !d.body.querySelector(".pj-meet-quick-modal") && !!d.querySelector("#pj-meet-quick table.pj-meet-quick-table")); diff --git a/tests/test_project_module.py b/tests/test_project_module.py index a3e18ed..334581c 100644 --- a/tests/test_project_module.py +++ b/tests/test_project_module.py @@ -1196,12 +1196,19 @@ def test_review_meeting_section_move(): _drop_meetings([w1, w2]) +def _clear_quick(*weeks) -> None: + """작업 등록 표 테스트 주차 비우기(로컬 테스트 DB — 앞선 실패한 실행의 줄이 남지 않게).""" + with ST._pool.connection() as conn: # noqa: SLF001 + conn.execute("DELETE FROM goal_meeting_tasks WHERE week_start = ANY(%s)", (list(weeks),)) + + def test_review_meeting_quick_tasks_shared(): """작업 등록 표(025) — 주차별 한 표를 모두가 같이 본다. 남의 프로젝트 이름은 가리고, [적용]은 동시에 눌러도 작업 하나.""" from app.modules.project import store w = store.month_weeks(2031, 12)[1][0] other = store.month_weeks(2031, 12)[2][0] + _clear_quick(w, other) p = _project("P-quick", ADMIN, (BOB,)) s = _stage(p["id"], by=ADMIN) done = _stage(p["id"], name="완료", done=True, by=ADMIN) @@ -1229,9 +1236,10 @@ def test_review_meeting_quick_tasks_shared(): assert t["stage_id"] == s["id"] and t["assignee_email"] == BOB # 등록된 줄은 더 못 고침(409), 다시 [적용]해도 그대로 assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"title": "x"}).status_code == 409 - # 세부 작업 줄 — 위 줄의 작업 밑에 만든다(섹션 없음) - r = req("POST", url, BOB, json={"title": "세부 하나", "project_id": p["id"], "parent_id": row["id"]}) + # 작업 칸 — 방금 만든 작업을 고르면 그 작업의 세부 작업으로(섹션 없음) + r = req("POST", url, BOB, json={"title": "세부 하나", "project_id": p["id"], "parent_task_id": tid}) sub = r.json()["task"] + assert sub["parent_task_id"] == tid and sub["parent_task_title"] == "상세페이지 수정2" r = req("POST", f"/project/api/goals/meeting-quick-tasks/{sub['id']}/apply", BOB) assert r.status_code == 201, r.text st_ = ST.get_task(task_id=r.json()["task"]["task_id"]) @@ -1246,39 +1254,35 @@ def test_review_meeting_quick_tasks_shared(): finally: _drop_meetings([w]) assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB).status_code == 200 - assert req("GET", url, BOB).json()["tasks"] == [] # 세부 작업 줄도 함께 + assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{sub['id']}", BOB).status_code == 200 + assert req("GET", url, BOB).json()["tasks"] == [] _ = done -def test_review_meeting_quick_subtask_rows(): - """세부 작업 줄 — 한 단계만, Tab(위 줄 밑으로)·Shift+Tab, [적용]은 위 줄 작업 밑에(위 줄 프로젝트).""" +def test_review_meeting_quick_parent_task_column(): + """작업 칸(026) — 그 프로젝트의 작업만, 프로젝트를 바꾸면 비움, 고른 작업이 사라지면 [적용] 400.""" from app.modules.project import store w = store.month_weeks(2032, 1)[1][0] - p = _project("P-quick-sub", ADMIN, (BOB,)) + _clear_quick(w) + p = _project("P-quick-pt", ADMIN, (BOB,)) + q = _project("P-quick-pt2", ADMIN, (BOB,)) s = _stage(p["id"], by=ADMIN) + base = ST.create_task(project_id=p["id"], title="기존 작업", stage_id=s["id"], created_by=ADMIN) + other = ST.create_task(project_id=q["id"], title="다른 프로젝트 작업", created_by=ADMIN) url = f"/project/api/goals/meetings/{w}/quick-tasks" put = lambda i, body: req("PUT", f"/project/api/goals/meeting-quick-tasks/{i}", BOB, json=body) - top = req("POST", url, BOB, json={"title": "부모", "project_id": p["id"], "stage_id": s["id"]}).json()["task"] - sub = req("POST", url, BOB, json={"title": "자식", "parent_id": top["id"]}).json()["task"] - other = req("POST", url, BOB, json={"title": "다른 줄"}).json()["task"] - assert req("POST", url, BOB, json={"title": "손자", "parent_id": sub["id"]}).status_code == 400 # 한 단계만 - assert put(other["id"], {"parent_id": sub["id"]}).status_code == 400 # 세부 작업 줄 밑 X - assert put(top["id"], {"parent_id": other["id"]}).status_code == 400 # 자식 딸린 줄은 세부 작업 X - assert put(other["id"], {"parent_id": other["id"]}).status_code == 400 - assert put(other["id"], {"parent_id": top["id"]}).json()["task"]["parent_id"] == top["id"] # Tab - assert put(other["id"], {"parent_id": None}).json()["task"]["parent_id"] is None # Shift+Tab - # 위 줄 전에는 세부 작업 [적용] 불가 → 위 줄 [적용] 뒤 세부 작업은 위 줄 작업 밑(섹션 없음) - assert req("POST", f"/project/api/goals/meeting-quick-tasks/{sub['id']}/apply", BOB).status_code == 400 - r = req("POST", f"/project/api/goals/meeting-quick-tasks/{top['id']}/apply", BOB) - parent_task = r.json()["task"]["task_id"] - r = req("POST", f"/project/api/goals/meeting-quick-tasks/{sub['id']}/apply", BOB) - assert r.status_code == 201, r.text - t = ST.get_task(task_id=r.json()["task"]["task_id"]) - assert (t["parent_task_id"], t["project_id"], t["stage_id"]) == (parent_task, p["id"], None) - for row in (top, other): - req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB) - assert req("GET", url, BOB).json()["tasks"] == [] + assert req("POST", url, BOB, json={"title": "x", "project_id": p["id"], "parent_task_id": other["id"]}).status_code == 400 + row = req("POST", url, BOB, json={"title": "세부", "project_id": p["id"], "parent_task_id": base["id"]}).json()["task"] + assert row["parent_task_id"] == base["id"] + moved = put(row["id"], {"project_id": q["id"]}).json()["task"] + assert moved["parent_task_id"] is None and moved["stage_id"] is None # 프로젝트가 바뀌면 작업·섹션을 비움 + assert put(row["id"], {"project_id": p["id"], "parent_task_id": base["id"]}).json()["task"]["parent_task_id"] == base["id"] + # 고른 작업이 지워지면 [적용]은 400(줄은 그대로) + ST.delete_task(task_id=base["id"], deleted_by=ADMIN) + assert req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", BOB).status_code == 400 + assert req("GET", url, BOB).json()["tasks"][0]["task_id"] is None + req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB) if __name__ == "__main__":