From 164153dc9c606b4240bafacc4daea08600434fd0 Mon Sep 17 00:00:00 2001 From: king Date: Thu, 1 Oct 2026 13:37:40 +0900 Subject: [PATCH] =?UTF-8?q?feat(project):=20=EB=AA=A9=ED=91=9C=20=ED=91=9C?= =?UTF-8?q?=203=EC=97=B4=EC=97=90=EC=84=9C=20=EC=A4=84=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20=3D=20=EA=B0=99=EC=9D=80=20=ED=95=AD=EB=AA=A9=20?= =?UTF-8?q?=EC=B9=B8(2=EC=97=B4)=20=EC=95=88=EC=97=90=20=E2=80=94=20?= =?UTF-8?q?=ED=95=AD=EB=AA=A9=20=EC=B9=B8=20=EB=AC=B6=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - goal_rows.label_cont(마이그레이션 016): 바로 위 줄 항목 칸에 묶임, 이름은 묶음 첫 줄, 2열 rowspan(_goal_label_spans) - 3열 우클릭 위/아래에 줄 추가 → same_label: 같은 항목 칸 안(이름 묻지 않음), 첫 줄 위면 새 줄이 첫 줄로 이름 넘겨받음 - 2열 메뉴·+ 줄 추가는 묶음 밖(묶음 맨 위/맨 아래 기준), 묶인 2열 우클릭 → 항목 칸 나누기(split-label) - 묶음 첫 줄 삭제 → 다음 줄이 첫 줄·이름 넘겨받음, 묶인 줄 이동 400, 새 연도 복사에 묶음 유지 - 캐시 버전 20261001k, DB 회귀 test_goal_label_groups, 문서 갱신 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- app/modules/project/db.py | 119 +++++++++++++++--- app/modules/project/router.py | 30 ++++- app/modules/project/store.py | 4 + .../templates/project/goal_meeting.html | 4 +- .../project/templates/project/goals.html | 11 +- .../project/templates/project/help.html | 2 +- .../project/templates/project/inbox.html | 4 +- .../project/templates/project/mytasks.html | 4 +- .../project/templates/project/project.html | 4 +- .../project/templates/project/trash.html | 4 +- app/static/project.js | 46 +++++-- docs/PROJECT_MODULE.md | 15 ++- .../project_db_016_goal_row_label_groups.sql | 26 ++++ tests/test_project_module.py | 44 +++++++ 15 files changed, 271 insertions(+), 48 deletions(-) create mode 100644 scripts/sql/project_db_016_goal_row_label_groups.sql diff --git a/CLAUDE.md b/CLAUDE.md index ace6819..6482e87 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, 섹션 기본 담당자 `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/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 6월·12월 오른쪽 상·하반기 칸(글 칸 month 13·14) + 반기 월 칸 접기 애니메이션(localStorage `pj_goal_fold`, 표는 `width:1px`+`table-layout:fixed`), 영역·줄 이름 클릭 바로 수정, **엑셀식 칸 병합**(마우스로 끌어 사각형 선택 → 우클릭 셀 병합/병합 해제, 같은 영역 안 세로 `row_span` + 같은 반기 월 칸 가로, 글은 왼쪽 위 칸 — `goal_cell_merges`, 마이그레이션 014·015), 로아스는 % 표기. 월 머리 → **주간 회의록**(`/project/goals/{연도}/meetings/{월}`, 주=월~일 탭, `goal_meetings`·`goal_meeting_items` 마이그레이션 015 — 지난 회의록 줄 이어받기(carry_from)로 지난주 할 일·목표·결과·평가 리뷰, 월 목표 대비 누적·주당 필요 매출, 유통 줄 쇼핑몰 연결 시 결과를 실적 모듈 `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` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 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, 섹션 기본 담당자 `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/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 6월·12월 오른쪽 상·하반기 칸(글 칸 month 13·14) + 반기 월 칸 접기 애니메이션(localStorage `pj_goal_fold`, 표는 `width:1px`+`table-layout:fixed`), 영역·줄 이름 클릭 바로 수정, **엑셀식 칸 병합**(마우스로 끌어 사각형 선택 → 우클릭 셀 병합/병합 해제, 같은 영역 안 세로 `row_span` + 같은 반기 월 칸 가로, 글은 왼쪽 위 칸 — `goal_cell_merges`, 마이그레이션 014·015), 3열 줄 추가는 같은 항목 칸(2열) 안에(`goal_rows.label_cont`, 마이그레이션 016), 구조 변경은 새로고침 없이 제자리 다시 그리기(`refreshTable`)+애니메이션, 로아스는 % 표기. 월 머리 → **주간 회의록**(`/project/goals/{연도}/meetings/{월}`, 주=월~일 탭, `goal_meetings`·`goal_meeting_items` 마이그레이션 015 — 지난 회의록 줄 이어받기(carry_from)로 지난주 할 일·목표·결과·평가 리뷰, 월 목표 대비 누적·주당 필요 매출, 유통 줄 쇼핑몰 연결 시 결과를 실적 모듈 `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` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 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` diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 0a850f1..2c3d0b0 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -1877,25 +1877,35 @@ class ProjectStore: (src["year"],), ).fetchall() plan = [] + groups = self._column_exists(conn, "goal_rows", "label_cont") for a in areas: labels = conn.execute( - "SELECT label FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", + "SELECT label" + (", label_cont" if groups else "") + " FROM goal_rows " + "WHERE area_id = %s ORDER BY sort_order, id", (a["id"],), ).fetchall() - plan.append((a["name"], a["color"], tuple(r["label"] for r in labels) or ("",))) + plan.append((a["name"], a["color"], + tuple((r["label"], bool(r.get("label_cont"))) for r in labels) or (("", False),))) else: - plan = list(store.DEFAULT_GOAL_AREAS) + plan = [(n, c, tuple((lb, False) for lb in labels)) for n, c, labels in store.DEFAULT_GOAL_AREAS] + groups = self._column_exists(conn, "goal_rows", "label_cont") for i, (name, color, labels) in enumerate(plan): aid = conn.execute( "INSERT INTO goal_areas (year, name, color, sort_order) " "VALUES (%s, %s, %s, %s) RETURNING id", (y, name, color, i), ).fetchone()["id"] - for j, label in enumerate(labels): - conn.execute( - "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)", - (aid, label, j), - ) + for j, (label, cont) in enumerate(labels): + if groups: + conn.execute( + "INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, %s, %s)", + (aid, label, cont and j > 0, j), + ) + else: + conn.execute( + "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)", + (aid, label, j), + ) def delete_goal_year(self, *, year: int) -> None: with self._pool.connection() as conn: @@ -1937,8 +1947,9 @@ class ProjectStore: "SELECT id, name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id", (year,), ).fetchall() + groups = self._column_exists(conn, "goal_rows", "label_cont") row_rows = conn.execute( - "SELECT r.id, r.area_id, r.label FROM goal_rows r " + "SELECT r.id, r.area_id, r.label" + (", r.label_cont" if groups else "") + " FROM goal_rows r " "JOIN goal_areas a ON a.id = r.area_id WHERE a.year = %s " "ORDER BY r.sort_order, r.id", (year,), @@ -1974,7 +1985,7 @@ class ProjectStore: rid = int(r["id"]) rows_by_area.setdefault(int(r["area_id"]), []).append( {"id": rid, "label": r["label"], "cells": cells.get(rid, {}), - "merges": merges.get(rid, {})} + "merges": merges.get(rid, {}), "label_cont": bool(r.get("label_cont"))} ) areas = [ {"id": int(a["id"]), "name": a["name"], "color": a["color"], @@ -1982,7 +1993,7 @@ class ProjectStore: for a in area_rows ] return {"year": int(head["year"]), "sales_unit": head["sales_unit"], - "metrics": metrics, "areas": areas, "halves": halves, "rect": rect} + "metrics": metrics, "areas": areas, "halves": halves, "rect": rect, "groups": groups} def set_goal_metric( self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = "" @@ -2084,15 +2095,35 @@ class ProjectStore: if 0 <= j < len(ids) and any(g["r1"] > g["r0"] and (g["r0"] <= i <= g["r1"] or g["r0"] <= j <= g["r1"]) for g in merges): raise ValueError("세로로 병합된 칸에 걸린 줄은 옮길 수 없습니다. 병합을 해제한 뒤 옮기세요.") + if 0 <= j < len(ids): + conts = self._label_conts(int(me["area_id"]), ids) + in_group = lambda k: conts[k] or (k + 1 < len(ids) and conts[k + 1]) # noqa: E731 + if in_group(i) or in_group(j): + raise ValueError("같은 항목 칸으로 묶인 줄은 옮길 수 없습니다. 항목 칸을 나눈 뒤 옮기세요.") self._move_goal_item("goal_rows", "area_id", row_id, direction) + def _label_conts(self, area_id: int, ids: list[int]) -> list[bool]: + """영역 줄 순서(ids)대로 label_cont — 016 미적용이면 모두 False.""" + with self._pool.connection() as conn: + if not self._column_exists(conn, "goal_rows", "label_cont"): + return [False] * len(ids) + got = {int(r["id"]): bool(r["label_cont"]) for r in conn.execute( + "SELECT id, label_cont FROM goal_rows WHERE area_id = %s", (area_id,)).fetchall()} + return [got.get(i, False) for i in ids] + def add_goal_row( - self, *, area_id: int, label: str = "", ref_row_id: int | None = None, place: str = "below" + self, *, area_id: int, label: str = "", ref_row_id: int | None = None, place: str = "below", + same_label: bool = False, ) -> int: - """줄 추가 — 기준 줄(ref_row_id)이 있으면 그 줄 위(place="above")/아래("below")에, 없으면 영역 맨 끝에.""" + """줄 추가 — 기준 줄(ref_row_id)이 있으면 그 줄 위(place="above")/아래("below")에, 없으면 영역 맨 끝에. + + same_label(3열에서 추가, 016) = 새 줄을 기준 줄과 **같은 항목 칸(2열)** 안에 넣는다: 아래면 새 줄이 묶음에 이어 붙고 + (label_cont), 위면 — 기준 줄이 묶음 첫 줄이면 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙는다.""" lb = store.validate_goal_row_label(label) if place not in ("above", "below"): raise ValueError("place 는 above 또는 below 입니다.") + if same_label and ref_row_id is None: + raise ValueError("같은 항목 칸에 추가하려면 기준 줄이 필요합니다.") with self._pool.connection() as conn: with conn.transaction(): if not conn.execute( @@ -2112,11 +2143,29 @@ class ProjectStore: ).fetchall()] if ref_row_id not in ids: raise KeyError(ref_row_id) - rid = int(conn.execute( - "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, 0) RETURNING id", - (area_id, lb), - ).fetchone()["id"]) + if same_label: + if not self._column_exists(conn, "goal_rows", "label_cont"): + raise store.GoalMigration016Needed() + ref = conn.execute("SELECT label, label_cont FROM goal_rows WHERE id = %s", (ref_row_id,)).fetchone() + if place == "above" and not ref["label_cont"]: + # 묶음 첫 줄 위 — 새 줄이 첫 줄(이름을 넘겨받음), 기준 줄은 이어 붙는다 + rid = int(conn.execute( + "INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, false, 0) " + "RETURNING id", (area_id, ref["label"]), + ).fetchone()["id"]) + conn.execute("UPDATE goal_rows SET label = '', label_cont = true WHERE id = %s", (ref_row_id,)) + else: + rid = int(conn.execute( + "INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, '', true, 0) " + "RETURNING id", (area_id,), + ).fetchone()["id"]) + else: + rid = int(conn.execute( + "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, 0) RETURNING id", + (area_id, lb), + ).fetchone()["id"]) i = ids.index(ref_row_id) + (1 if place == "below" else 0) + # 따로 추가(2열 메뉴·+)는 화면이 묶음의 맨 위(위에)·맨 아래(아래) 줄을 기준으로 보내 묶음 밖에 들어간다 # 세로 병합 안쪽(시작 줄 아래 ~ 마지막 줄)에 끼우면 엑셀처럼 그 병합이 한 줄 늘어난다 if self._table_exists(conn, "goal_cell_merges") and self._column_exists( conn, "goal_cell_merges", "row_span"): @@ -2172,8 +2221,44 @@ class ProjectStore: "DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s", (g["row_id"], g["start"]), ) + if self._column_exists(conn, "goal_rows", "label_cont"): + # 묶음 첫 줄을 지우면 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름을 넘겨받는다(비어 있으면) + me2 = conn.execute("SELECT label, label_cont, sort_order FROM goal_rows WHERE id = %s", + (row_id,)).fetchone() + if not me2["label_cont"]: + nxt = conn.execute( + "SELECT id, label, label_cont FROM goal_rows WHERE area_id = %s AND id <> %s " + "AND (sort_order, id) > (%s, %s) ORDER BY sort_order, id LIMIT 1", + (me["area_id"], row_id, me2["sort_order"], row_id), + ).fetchone() + if nxt and nxt["label_cont"]: + conn.execute( + "UPDATE goal_rows SET label_cont = false, label = CASE WHEN label = '' THEN %s ELSE label END " + "WHERE id = %s", (me2["label"], nxt["id"]), + ) conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,)) + def split_goal_label(self, *, row_id: int) -> int: + """항목 칸 나누기 — row_id(묶음 첫 줄) 아래 이어 붙은 줄들을 각자 항목 칸으로(이름은 빈 칸). 나눈 줄 수.""" + with self._pool.connection() as conn: + with conn.transaction(): + if not self._column_exists(conn, "goal_rows", "label_cont"): + raise store.GoalMigration016Needed() + me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s FOR UPDATE", (row_id,)).fetchone() + if me is None: + raise KeyError(row_id) + rows = conn.execute( + "SELECT id, label_cont FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (me["area_id"],) + ).fetchall() + ids = [int(r["id"]) for r in rows] + n = 0 + for r in rows[ids.index(row_id) + 1:]: + if not r["label_cont"]: + break + conn.execute("UPDATE goal_rows SET label_cont = false WHERE id = %s", (r["id"],)) + n += 1 + return n + def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None: m = store.validate_goal_month(month, allow_year=True) text = store.validate_goal_text(body) diff --git a/app/modules/project/router.py b/app/modules/project/router.py index 21d3a26..3cd8cb8 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -2516,6 +2516,7 @@ def inbox_page(request: Request) -> HTMLResponse: _GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)." _GOALS_014_MSG = "상·하반기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다." _GOALS_015_MSG = "세로 병합·연간/반기 칸 병합과 주간 회의록은 DB 마이그레이션 015 가 필요합니다." +_GOALS_016_MSG = "같은 항목 칸 안에 줄 추가(3열)는 DB 마이그레이션 016 이 필요합니다." def _fmt_goal_num(v: float | None) -> str: @@ -2568,6 +2569,20 @@ def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None: row["layout"] = out +def _goal_label_spans(rows: list[dict[str, Any]]) -> None: + """항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음). + 영역 첫 줄은 늘 묶음 첫 줄.""" + for k, row in enumerate(rows): + if k == 0 or not row.get("label_cont"): + row["label_cont"] = False + n = 1 + while k + n < len(rows) and rows[k + n].get("label_cont"): + n += 1 + row["label_span"] = n + else: + row["label_span"] = 0 + + def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any: """목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400.""" try: @@ -2576,6 +2591,8 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any: raise HTTPException(status_code=503, detail=_GOALS_014_MSG) except store.GoalMigration015Needed: raise HTTPException(status_code=503, detail=_GOALS_015_MSG) + except store.GoalMigration016Needed: + raise HTTPException(status_code=503, detail=_GOALS_016_MSG) except UndefinedTable: raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG) except KeyError: @@ -2617,6 +2634,7 @@ def goals_page(request: Request, year: int) -> HTMLResponse: m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()} for area in board["areas"]: _goal_area_layout(area["rows"], this_month) + _goal_label_spans(area["rows"]) return render_template( request, "project/goals.html", @@ -2730,7 +2748,8 @@ def api_add_goal_row(request: Request, area_id: int, payload: dict[str, Any] = B except (TypeError, ValueError): raise HTTPException(status_code=400, detail="ref_row_id 가 올바르지 않습니다.") rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", ""), - ref_row_id=ref_id, place=payload.get("place") or "below") + ref_row_id=ref_id, place=payload.get("place") or "below", + same_label=bool(payload.get("same_label"))) return JSONResponse({"ok": True, "id": rid}, status_code=201) @@ -2750,6 +2769,15 @@ def api_delete_goal_row(request: Request, row_id: int) -> JSONResponse: return JSONResponse({"ok": True}) +@router.post("/api/goals/rows/{row_id}/split-label") +def api_split_goal_label(request: Request, row_id: int) -> JSONResponse: + """항목 칸 나누기 — 묶음 첫 줄 아래 이어 붙은 줄들을 각자 항목 칸으로(016).""" + _require_admin(request) + st = _db_or_503(request) + n = _goal_call(st.split_goal_label, row_id=row_id) + return JSONResponse({"ok": True, "split": n}) + + @router.post("/api/goals/rows/{row_id}/move") def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: _require_admin(request) diff --git a/app/modules/project/store.py b/app/modules/project/store.py index 3eda245..82ea298 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -477,6 +477,10 @@ class GoalMigration015Needed(RuntimeError): """세로 병합·주간 회의록은 마이그레이션 015 뒤에만 된다.""" +class GoalMigration016Needed(RuntimeError): + """항목 칸(2열) 묶음(같은 항목 칸 안에 줄 추가)은 마이그레이션 016 뒤에만 된다.""" + + # 업무 영역 글 칸의 화면 순서 — 연간 · 1~6월 · 상반기 · 7~12월 · 하반기 GOAL_COL_ORDER: tuple[int, ...] = (0, 1, 2, 3, 4, 5, 6, GOAL_H1, 7, 8, 9, 10, 11, 12, GOAL_H2) diff --git a/app/modules/project/templates/project/goal_meeting.html b/app/modules/project/templates/project/goal_meeting.html index c456721..6f4b845 100644 --- a/app/modules/project/templates/project/goal_meeting.html +++ b/app/modules/project/templates/project/goal_meeting.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -246,5 +246,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index 25e7914..15e14d1 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 %} @@ -153,12 +153,14 @@ {% endif %} {% endif %} - + {# 항목 칸(2열) — 같은 항목 칸으로 묶인 줄(016 label_cont)은 묶음 첫 줄이 rowspan 으로 덮는다 #} + {% if not row.label_cont %} + 1 %} rowspan="{{ row.label_span }}"{% endif %} data-label-span="{{ row.label_span or 1 }}"> {{ row.label }} {# 줄 도구 — + = 이 줄 아래에 줄 추가, × = 줄 삭제(영역의 마지막 한 줄은 못 지움). 우클릭 메뉴로 위/아래 추가·삭제도 #} {% if is_admin %} - {% if area.rows | length > 1 %} + {% if area.rows | length > 1 and row.label_span == 1 %} {% endif %} @@ -169,6 +171,7 @@ {% endif %} + {% endif %} {# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #} {% for c in row.layout %} {% set editable = is_admin and (c.kind != 'half' or board.halves) %} @@ -207,5 +210,5 @@ {% include "project/_side_modals.html" %} {% 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 fff9bb5..eeff8e3 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 %} diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index 7fe167e..36a9f5c 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 %} @@ -104,5 +104,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 35ebeee..6159cb3 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/project.html b/app/modules/project/templates/project/project.html index e7788a0..6bcf4c2 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 %} - + @@ -496,5 +496,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index 66a6f04..56cd767 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.js b/app/static/project.js index 85901d4..68a1720 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -8437,7 +8437,7 @@ if (v == null) return; await api("POST", "/project/api/goals/areas/" + areaId + "/rows", { label: String(v).trim() }); } else if (act === "row-insert") { - if (!(await insertRow(tr, "below"))) return; + if (!(await insertRow(labelGroupBottom(tr), "below"))) return; // 항목 칸 묶음 아래(묶음 밖) } else if (act === "row-up" || act === "row-down") { await api("POST", "/project/api/goals/rows/" + rowId + "/move", { direction: act === "row-up" ? -1 : 1 }); } else if (act === "row-del") { @@ -8450,13 +8450,25 @@ }); // ── 줄(항목 칸) 추가·삭제 — 도구 막대의 +·× 와 항목 칸 우클릭 메뉴가 같이 쓴다. 한 일이 있으면 true. - async function insertRow(tr, place) { - const v = await prompt("새 줄 이름 (예: 쿠팡 — 비워 둬도 됩니다)", ""); - if (v == null) return false; + // sameLabel = 3열에서 추가 — 새 줄을 기준 줄과 같은 항목 칸(2열) 안에(이름을 묻지 않음, 016) + async function insertRow(tr, place, sameLabel) { + let label = ""; + if (!sameLabel) { + const v = await prompt("새 줄 이름 (예: 쿠팡 — 비워 둬도 됩니다)", ""); + if (v == null) return false; + label = String(v).trim(); + } await api("POST", "/project/api/goals/areas/" + tr.closest(".pj-goal-area").dataset.areaId + "/rows", - { label: String(v).trim(), ref_row_id: tr.dataset.rowId, place: place }); + { label: label, ref_row_id: tr.dataset.rowId, place: place, same_label: !!sameLabel }); return true; } + // 항목 칸(2열) 묶음의 맨 아래 줄 — 항목 칸 th 의 rowspan 만큼 + function labelGroupBottom(tr) { + const th = tr.querySelector("th.pj-goal-row-label"); + const span = th ? th.rowSpan || 1 : 1; + const rows = Array.from(tr.closest("tbody").rows); + return rows[Math.min(rows.length - 1, rows.indexOf(tr) + span - 1)]; + } async function deleteRow(tr) { const lb = textOf(tr, ".pj-goal-row-text"); const label = lb ? "'" + lb + "' 줄" : "이 줄"; @@ -8467,7 +8479,8 @@ } // 줄 메뉴 항목 — 항목 칸(2열)·연간 칸(3열) 우클릭이 같이 쓴다. top = 위에 추가할 기준 줄, bottom = 아래에 추가할 기준 줄 // (세로 병합된 연간 칸이면 맨 아래 줄), canDelete = 그 줄 하나를 지울 수 있을 때. - function rowMenuItems(top, bottom, canDelete) { + function rowMenuItems(top, bottom, canDelete, opts) { + opts = opts || {}; const run = function (fn) { return async function () { try { @@ -8477,9 +8490,15 @@ }; }; const items = [ - { label: "위에 줄 추가", onClick: run(function () { return insertRow(top, "above"); }) }, - { label: "아래에 줄 추가", onClick: run(function () { return insertRow(bottom, "below"); }) }, + { label: "위에 줄 추가", onClick: run(function () { return insertRow(top, "above", opts.sameLabel); }) }, + { label: "아래에 줄 추가", onClick: run(function () { return insertRow(bottom, "below", opts.sameLabel); }) }, ]; + if (opts.splitRow) { // 항목 칸 묶음 나누기 — 이어 붙은 줄들이 각자 항목 칸으로 + items.push({ label: "항목 칸 나누기", onClick: run(async function () { + await api("POST", "/project/api/goals/rows/" + opts.splitRow.dataset.rowId + "/split-label"); + return true; + }) }); + } // 영역의 마지막 한 줄은 못 지운다(영역을 지운다) — 서버도 400 if (canDelete && top.closest(".pj-goal-area").rows.length > 1) { items.push(null, { label: "줄 삭제", danger: true, onClick: run(async function () { @@ -8493,9 +8512,12 @@ if (!th || !table.contains(th) || e.target.closest(".is-editing")) return; e.preventDefault(); const tr = th.closest("tr"); - showContextMenu(e.clientX, e.clientY, rowMenuItems(tr, tr, true)); + // 2열 = 항목 칸 밖에 따로 추가(묶음의 맨 위·맨 아래 기준), 묶인 칸이면 "항목 칸 나누기"도 + showContextMenu(e.clientX, e.clientY, rowMenuItems(tr, labelGroupBottom(tr), true, + { splitRow: (th.rowSpan || 1) > 1 ? tr : null })); }); - // 3열(연간 칸) 우클릭에도 줄 추가·삭제 — 병합 메뉴가 있으면(014) 그 메뉴에 붙이고, 없으면 여기서 + // 3열(연간 칸) 우클릭에도 줄 추가·삭제 — 추가한 줄은 같은 항목 칸(2열) 안에 들어간다(sameLabel, 016). + // 병합 메뉴가 있으면(014) 그 메뉴에 붙이고, 없으면 여기서 function yearCellRows(td) { const tr = td.closest("tr"), rows = Array.from(td.closest("tbody").rows); const rspan = parseInt(td.dataset.rspan || "1", 10); @@ -8507,7 +8529,7 @@ if (!td || !table.contains(td)) return; e.preventDefault(); const r = yearCellRows(td); - showContextMenu(e.clientX, e.clientY, rowMenuItems(r.top, r.bottom, r.single)); + showContextMenu(e.clientX, e.clientY, rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true })); }); } @@ -8725,7 +8747,7 @@ if (td.dataset.month === "0" && s.n === 1) { // 3열(연간 칸) 하나 우클릭 — 줄 추가·삭제도 const r = yearCellRows(td); if (items.length) items.push(null); - rowMenuItems(r.top, r.bottom, r.single).forEach(function (it) { items.push(it); }); + rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }).forEach(function (it) { items.push(it); }); } if (!items.length) { clearMergeSel(); return; } e.preventDefault(); diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index 4f9b04a..28e17ca 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -297,6 +297,8 @@ docker exec -i postgres-db psql -U postgres -d project_db \ < scripts/sql/project_db_014_goal_halves_merges.sql docker exec -i postgres-db psql -U postgres -d project_db \ < scripts/sql/project_db_015_goal_rect_merges_meetings.sql +docker exec -i postgres-db psql -U postgres -d project_db \ + < scripts/sql/project_db_016_goal_row_label_groups.sql # 4) 재배포 (git pull 후 반드시 --build) cd /opt/www/main && docker compose up -d --build web @@ -561,8 +563,17 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중 저장된 열 너비가 늦게 적용돼 표가 줄었다 늘어나고 깜박이던 것을 없앴다. 애니메이션: 지운 줄은 흐려지며 사라지고, 남은 줄은 예전 자리에서 미끄러져 오고(FLIP, 0.28초), 새 줄은 위에서 내려오며 보라색으로 잠깐 강조(`is-new-row`), 병합·해제한 칸은 테두리 강조 (`is-merge-flash`). 동작 줄이기 설정이면 애니메이션 없이. 받아 오기 실패하면 예전처럼 새로고침. -- **3열(연간 칸) 우클릭 → 줄 메뉴**: 위에 줄 추가 · 아래에 줄 추가 · 줄 삭제(항목 칸 우클릭과 같은 `rowMenuItems`). 세로로 병합된 - 연간 칸이면 아래 추가는 병합의 맨 아래 줄 기준, 삭제는 없음. 병합 메뉴(셀 병합·해제)가 있으면 그 아래에 붙는다. +- **3열(연간 칸) 우클릭 → 줄 메뉴**: 위에 줄 추가 · 아래에 줄 추가 · 줄 삭제. **3열에서 추가한 줄은 같은 항목 칸(2열) 안에** 들어간다 + (2열은 하나, 3열부터 줄이 늘어남 — 이름을 묻지 않음, `same_label`, 마이그레이션 016). 세로로 병합된 연간 칸이면 아래 추가는 병합의 + 맨 아래 줄 기준, 삭제는 없음. 병합 메뉴(셀 병합·해제)가 있으면 그 아래에 붙는다. +- **항목 칸(2열) 묶음**(016 `goal_rows.label_cont` = 바로 위 줄 항목 칸에 묶임, 이름은 묶음 첫 줄에): 화면은 `router._goal_label_spans` + 가 묶음 첫 줄에 `label_span`(2열 rowspan), 이어 붙은 줄은 2열을 그리지 않는다. + - `POST /api/goals/areas/{id}/rows {ref_row_id, place, same_label: true}` → 아래 = 새 줄이 이어 붙음, 위 = 기준 줄이 묶음 첫 줄이면 + 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙음(이어 붙은 줄 위면 그냥 이어 붙음). 016 미적용이면 503. + - 2열 메뉴·+ 의 줄 추가는 **묶음 밖**(위 = 묶음 첫 줄 위, 아래 = 묶음 맨 아래 줄 아래, 이름 물음). 묶인 2열 우클릭 → **항목 칸 나누기** + (`POST /api/goals/rows/{첫 줄}/split-label` — 이어 붙은 줄들이 각자 빈 이름 항목 칸으로). + - 묶음 첫 줄 삭제 → 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름이 비어 있으면 넘겨받음. 묶인 줄(첫 줄·이어 붙은 줄)과 바꾸는 ↑↓ 이동은 400 + (나눈 뒤 이동), 묶음 첫 줄 도구 막대엔 ↑↓ 없음. 새 연도 만들기는 묶음도 복사한다. - **월 머리 → 주간 회의록** — 목표 표 머리의 월 칸을 누르면 `/project/goals/{연도}/meetings/{월}`(6-9-2). 링크(`a.pj-goal-mlink`)는 글자만이 아니라 **칸 전체**(absolute inset 0), 오른쪽 끝 너비 조절 손잡이(z-index 5)는 링크 위라 그대로 끌 수 있다. - **로아스 단위 %** — 로아스 목표·실적 칸은 `499%` 처럼 보인다(`router._goal_label`, 저장 응답 `label` 도 같음). 입력은 `499`·`499%` diff --git a/scripts/sql/project_db_016_goal_row_label_groups.sql b/scripts/sql/project_db_016_goal_row_label_groups.sql new file mode 100644 index 0000000..bc7eb15 --- /dev/null +++ b/scripts/sql/project_db_016_goal_row_label_groups.sql @@ -0,0 +1,26 @@ +-- ===================================================================== +-- project_db 마이그레이션 016 — 연간 목표: 항목 칸(2열) 묶음 +-- ===================================================================== +-- 멱등(idempotent). 칸 하나 추가뿐 — 기존 데이터는 그대로(모두 false = 지금과 같은 화면). +-- +-- goal_rows.label_cont = true → 이 줄의 항목 칸(2열)은 바로 위 줄의 항목 칸에 묶인다(이름은 묶음 첫 줄에만). +-- 3열(연간 칸)에서 "아래에 줄 추가"를 하면 새 줄이 같은 항목 칸 안에 들어간다(2열은 하나, 3열부터 줄이 늘어남). +-- +-- 미적용이어도 목표 화면은 동작한다 — 3열 줄 추가만 "마이그레이션 016 필요". +-- +-- 적용 (1회, 여러 번 돌려도 안전): +-- docker exec -i postgres-db psql -U postgres -d project_db \ +-- < scripts/sql/project_db_016_goal_row_label_groups.sql +-- ===================================================================== + +\set ON_ERROR_STOP on +\connect project_db + +BEGIN; + +ALTER TABLE goal_rows ADD COLUMN IF NOT EXISTS label_cont BOOLEAN NOT NULL DEFAULT false; +COMMENT ON COLUMN goal_rows.label_cont IS 'true = 항목 칸(2열)이 바로 위 줄 항목 칸에 묶임(이름은 묶음 첫 줄에)'; + +COMMIT; + +SELECT 'project_db 016 goal row label groups ready' AS status; diff --git a/tests/test_project_module.py b/tests/test_project_module.py index 1b7f090..3c47b9d 100644 --- a/tests/test_project_module.py +++ b/tests/test_project_module.py @@ -604,6 +604,50 @@ def test_goal_rect_merges(): ST.delete_goal_year(year=year) + +def test_goal_label_groups(): + """항목 칸(2열) 묶음(016): 3열 추가(same_label) 아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이 첫 줄(이름 넘겨받음), + 묶음 첫 줄 삭제 → 다음 줄이 첫 줄(이름 넘겨받음), 묶인 줄 이동 400, 항목 칸 나누기, 새 연도 복사에 묶음 유지.""" + year = 2060 + (int(RUN, 16) + 13) % 40 + for y in (year, year + 1): + ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None + assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 + try: + assert ST.get_goal_board(year=year)["groups"] is True, "마이그레이션 016 적용 필요" + aid = ST.get_goal_board(year=year)["areas"][0]["id"] + rows = lambda: [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731 + ids = lambda: [r["id"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731 + first = ids()[0] + assert req("PUT", f"/project/api/goals/rows/{first}", ADMIN, json={"label": "마케팅1"}).status_code == 200 + add = lambda body: req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json=body) # noqa: E731 + assert add({"ref_row_id": first, "place": "below", "same_label": True}).status_code == 201 + assert rows()[:2] == [("마케팅1", False), ("", True)] + # 같은 항목 칸 위(첫 줄 위) — 새 줄이 첫 줄, 이름을 넘겨받고 예전 첫 줄은 이어 붙음 + r = add({"ref_row_id": first, "place": "above", "same_label": True}) + assert r.status_code == 201 + assert rows()[:3] == [("마케팅1", False), ("", True), ("", True)], rows() + assert ids()[1] == first + assert add({"same_label": True}).status_code == 400 # 기준 줄 없음 + # 묶인 줄 이동 거절 + assert req("POST", f"/project/api/goals/rows/{first}/move", ADMIN, json={"direction": 1}).status_code == 400 + # 묶음 첫 줄 삭제 → 다음 줄이 첫 줄 + 이름 + head = ids()[0] + assert req("DELETE", f"/project/api/goals/rows/{head}", ADMIN).status_code == 200 + assert rows()[:2] == [("마케팅1", False), ("", True)], rows() + # 새 연도 복사 — 묶음 유지 + assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year + 1}).status_code == 201 + nxt = [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year + 1)["areas"][0]["rows"]] + assert nxt[:2] == [("마케팅1", False), ("", True)], nxt + # 항목 칸 나누기 + r = req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", ADMIN) + assert r.status_code == 200 and r.json()["split"] == 1 + assert rows()[:2] == [("마케팅1", False), ("", False)] + assert req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", BOB).status_code == 403 + finally: + for y in (year, year + 1): + ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None + + def test_goal_meetings(): """주간 회의록: 만들기(처음 = 목표 표 영역 + 기본 양식 줄, 유통 줄 쇼핑몰 추측), 다음 주 = 지난 회의록 줄 이어받기 (carry_from → prev), 금액 표기(만·억), 평가 값 검사, 줄 추가/이동/삭제, 화면·권한."""