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 %} -