diff --git a/CLAUDE.md b/CLAUDE.md index 48733d6..6acd029 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` 만. 마감 알림(`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`), 영역·줄 이름 클릭 바로 수정, 월 칸 가로 병합(`goal_cell_merges`, 반기 안에서만, Shift+클릭·우클릭) — 마이그레이션 014, 로아스는 % 표기. 마감 알림(`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 cb652f1..3cbc645 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -1840,6 +1840,11 @@ class ProjectStore: with self._pool.connection() as conn: return self._table_exists(conn, "goal_years") + def goals_halves_enabled(self) -> bool: + """상·하반기 글 칸·월 칸 병합(마이그레이션 014) 적용 여부.""" + with self._pool.connection() as conn: + return self._table_exists(conn, "goal_cell_merges") + def list_goal_years(self) -> list[int]: """목표를 만든 연도(최근 연도 먼저). 013 미적용이면 UndefinedTable.""" with self._pool.connection() as conn: @@ -1913,7 +1918,9 @@ class ProjectStore: """한 해 목표 표 전체. 연도가 없으면 None. metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}} - areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", ...}}]}] + areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", 13: "상반기 글", ...}, + merges: {시작월: 칸 수}}]}] + halves = 마이그레이션 014 적용 여부(상·하반기 글 칸·병합) """ with self._pool.connection() as conn: head = conn.execute( @@ -1940,6 +1947,13 @@ class ProjectStore: "WHERE a.year = %s", (year,), ).fetchall() + halves = self._table_exists(conn, "goal_cell_merges") + merge_rows = conn.execute( + "SELECT m.row_id, m.start_month, m.span FROM goal_cell_merges m " + "JOIN goal_rows r ON r.id = m.row_id JOIN goal_areas a ON a.id = r.area_id " + "WHERE a.year = %s", + (year,), + ).fetchall() if halves else [] metrics: dict[str, dict[str, dict[int, float]]] = { m: {k: {} for k in store.GOAL_KINDS} for m in store.GOAL_METRICS } @@ -1948,10 +1962,15 @@ class ProjectStore: cells: dict[int, dict[int, str]] = {} for c in cell_rows: cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"] + merges: dict[int, dict[int, int]] = {} + for g in merge_rows: + merges.setdefault(int(g["row_id"]), {})[int(g["start_month"])] = int(g["span"]) rows_by_area: dict[int, list[dict[str, Any]]] = {} for r in row_rows: + rid = int(r["id"]) rows_by_area.setdefault(int(r["area_id"]), []).append( - {"id": int(r["id"]), "label": r["label"], "cells": cells.get(int(r["id"]), {})} + {"id": rid, "label": r["label"], "cells": cells.get(rid, {}), + "merges": merges.get(rid, {})} ) areas = [ {"id": int(a["id"]), "name": a["name"], "color": a["color"], @@ -1959,7 +1978,7 @@ class ProjectStore: for a in area_rows ] return {"year": int(head["year"]), "sales_unit": head["sales_unit"], - "metrics": metrics, "areas": areas} + "metrics": metrics, "areas": areas, "halves": halves} def set_goal_metric( self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = "" @@ -2094,6 +2113,17 @@ class ProjectStore: with self._pool.connection() as conn: if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone(): raise KeyError(row_id) + if m != store.GOAL_YEAR: + halves = self._table_exists(conn, "goal_cell_merges") + if m > 12 and not halves: + raise store.GoalMigration014Needed() + # 병합된 칸의 가운데·끝 월(글은 병합 시작 월에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장 + if m <= 12 and halves and conn.execute( + "SELECT 1 FROM goal_cell_merges WHERE row_id = %s " + "AND start_month < %s AND start_month + span - 1 >= %s", + (row_id, m, m), + ).fetchone(): + raise ValueError("병합된 칸입니다. 새로고침해 주세요.") if not text: conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m)) else: @@ -2104,6 +2134,67 @@ class ProjectStore: (row_id, m, text, store.norm_str(updated_by, lower=True)), ) + def merge_goal_cells(self, *, row_id: int, start: Any, end: Any, updated_by: str = "") -> tuple[int, int]: + """업무 영역 줄의 start~end 월 칸을 가로로 합친다 → (시작 월, 칸 수). + + 걸쳐 있는 기존 병합은 통째로 흡수한다(병합은 서로 겹치지 않고 반기 안이라 범위도 반기 안). + 글은 범위 안 칸들의 글을 월 순서대로 줄바꿈으로 이어 시작 월 칸에 두고, 나머지 칸 글은 지운다.""" + s, e = store.validate_goal_merge(start, end) + who = store.norm_str(updated_by, lower=True) + with self._pool.connection() as conn: + with conn.transaction(): + if not self._table_exists(conn, "goal_cell_merges"): + raise store.GoalMigration014Needed() + if not conn.execute( + "SELECT 1 FROM goal_rows WHERE id = %s FOR UPDATE", (row_id,) + ).fetchone(): + raise KeyError(row_id) + for g in conn.execute( + "SELECT start_month, span FROM goal_cell_merges WHERE row_id = %s", (row_id,) + ).fetchall(): + gs, ge = int(g["start_month"]), int(g["start_month"]) + int(g["span"]) - 1 + if gs <= e and ge >= s: + s, e = min(s, gs), max(e, ge) + bodies = [ + str(c["body"]).strip() for c in conn.execute( + "SELECT body FROM goal_cells WHERE row_id = %s AND month BETWEEN %s AND %s " + "ORDER BY month", + (row_id, s, e), + ).fetchall() + ] + text = store.validate_goal_text("\n".join(b for b in bodies if b)) + conn.execute( + "DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month BETWEEN %s AND %s", + (row_id, s, e), + ) + conn.execute( + "DELETE FROM goal_cells WHERE row_id = %s AND month BETWEEN %s AND %s", + (row_id, s, e), + ) + if text: + conn.execute( + "INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s)", + (row_id, s, text, who), + ) + conn.execute( + "INSERT INTO goal_cell_merges (row_id, start_month, span, updated_by) " + "VALUES (%s, %s, %s, %s)", + (row_id, s, e - s + 1, who), + ) + return s, e - s + 1 + + def unmerge_goal_cells(self, *, row_id: int, start: int) -> None: + """병합 해제 — 글은 시작 월 칸에 그대로 남는다.""" + with self._pool.connection() as conn: + if not self._table_exists(conn, "goal_cell_merges"): + raise store.GoalMigration014Needed() + row = conn.execute( + "DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s RETURNING row_id", + (row_id, start), + ).fetchone() + if row is None: + raise KeyError(row_id) + # ════════════════════════════════════════════════════════════ # 직렬화 # ════════════════════════════════════════════════════════════ diff --git a/app/modules/project/router.py b/app/modules/project/router.py index d21331a..35d2b5a 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -2514,6 +2514,7 @@ def inbox_page(request: Request) -> HTMLResponse: # 조회: project 권한자 전원 · 입력/구조 변경: 관리자(is_admin) 전용 # ──────────────────────────────────────────────────────────── _GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)." +_GOALS_014_MSG = "상·하반기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다." def _fmt_goal_num(v: float | None) -> str: @@ -2525,10 +2526,37 @@ def _fmt_goal_num(v: float | None) -> str: return f"{v:,.2f}".rstrip("0").rstrip(".") +def _goal_label(metric: str, v: float | None) -> str: + """지표 칸 표기 — 로아스는 % 단위(499 → "499%"). 입력칸도 이 표기로 보이고, 저장 때 % 는 떼고 읽는다.""" + s = _fmt_goal_num(v) + return f"{s}%" if s and metric == "roas" else s + + +def _goal_row_layout(merges: dict[int, int], this_month: int) -> list[dict[str, Any]]: + """업무 영역 한 줄의 칸 배치 — 연간 · 1~6월 · 상반기 · 7~12월 · 하반기 순서. + + 월 칸은 병합(시작 월 → 칸 수)을 반영해 {"m", "span", "h"(1|2), "now"}, 연간·반기 칸은 {"m": 0|13|14}. + 병합 정보가 반기를 넘거나 겹치면(있을 수 없지만) 그 병합은 무시한다.""" + out: list[dict[str, Any]] = [{"m": store.GOAL_YEAR, "kind": "year"}] + for h, (lo, hi, half_m) in enumerate(((1, 6, store.GOAL_H1), (7, 12, store.GOAL_H2)), start=1): + mo = lo + while mo <= hi: + span = int(merges.get(mo, 1) or 1) + if span < 1 or mo + span - 1 > hi: + span = 1 + out.append({"m": mo, "span": span, "h": h, "kind": "month", + "now": mo <= this_month <= mo + span - 1}) + mo += span + out.append({"m": half_m, "kind": "half", "h": h}) + return out + + def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any: """목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400.""" try: return fn(*args, **kwargs) + except store.GoalMigration014Needed: + raise HTTPException(status_code=503, detail=_GOALS_014_MSG) except UndefinedTable: raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG) except KeyError: @@ -2562,11 +2590,15 @@ def goals_page(request: Request, year: int) -> HTMLResponse: admin = is_admin(user) enabled = st.goals_enabled() board = st.get_goal_board(year=year) if enabled else None - if board: - for m in board["metrics"].values(): - for kind in list(m): - m[kind + "_label"] = {mo: _fmt_goal_num(v) for mo, v in m[kind].items()} today = today_kst() + this_month = today.month if today.year == year else 0 + if board: + for metric, m in board["metrics"].items(): + for kind in list(m): + m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()} + for area in board["areas"]: + for row in area["rows"]: + row["layout"] = _goal_row_layout(row.get("merges") or {}, this_month) return render_template( request, "project/goals.html", @@ -2588,7 +2620,9 @@ def goals_page(request: Request, year: int) -> HTMLResponse: "goal_year": year, "board": board, "months": list(range(1, 13)), - "this_month": today.month if today.year == year else 0, + "halves": [(1, list(range(1, 7)), store.GOAL_H1, "상반기"), + (2, list(range(7, 13)), store.GOAL_H2, "하반기")], + "this_month": this_month, "goal_area_colors": list(store.GOAL_AREA_COLORS), }, ) @@ -2631,7 +2665,7 @@ def api_set_goal_metric(request: Request, year: int, payload: dict[str, Any] = B kind=str(payload.get("kind") or ""), month=payload.get("month"), value=value, updated_by=user["email"], ) - return JSONResponse({"ok": True, "value": value, "label": _fmt_goal_num(value)}) + return JSONResponse({"ok": True, "value": value, "label": _goal_label(str(payload.get("metric") or ""), value)}) @router.post("/api/goals/{year}/areas") @@ -2703,7 +2737,7 @@ def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = B def api_set_goal_cell( request: Request, row_id: int, month: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: - """업무 영역 칸 글 — month 0 = 연간, 1~12 = 월. 빈 글 = 지움.""" + """업무 영역 칸 글 — month 0 = 연간, 1~12 = 월, 13 = 상반기, 14 = 하반기(014). 빈 글 = 지움.""" user = _require_admin(request) st = _db_or_503(request) _goal_call( @@ -2711,3 +2745,24 @@ def api_set_goal_cell( body=payload.get("body", ""), updated_by=user["email"], ) return JSONResponse({"ok": True}) + + +@router.post("/api/goals/rows/{row_id}/merge") +def api_merge_goal_cells(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """월 칸 가로 병합 {start, end}(반기 안, 2칸 이상) — 걸친 병합은 흡수, 글은 이어서 시작 월 칸에.""" + user = _require_admin(request) + st = _db_or_503(request) + start, span = _goal_call( + st.merge_goal_cells, row_id=row_id, start=payload.get("start"), end=payload.get("end"), + updated_by=user["email"], + ) + return JSONResponse({"ok": True, "start": start, "span": span}) + + +@router.delete("/api/goals/rows/{row_id}/merge/{start}") +def api_unmerge_goal_cells(request: Request, row_id: int, start: int) -> JSONResponse: + """병합 해제 — 글은 시작 월 칸에 남는다.""" + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.unmerge_goal_cells, row_id=row_id, start=start) + return JSONResponse({"ok": True}) diff --git a/app/modules/project/store.py b/app/modules/project/store.py index af3e155..ffc4219 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -356,7 +356,7 @@ def validate_time(t: Any) -> str | None: # ════════════════════════════════════════════════════════════ # 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 # ════════════════════════════════════════════════════════════ -GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스 +GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스(단위 %) GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적 # 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄). # 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다. @@ -386,17 +386,46 @@ def validate_goal_year(y: Any) -> int: return v +class GoalMigration014Needed(RuntimeError): + """상·하반기 글 칸·월 칸 병합은 마이그레이션 014(goal_cell_merges) 뒤에만 된다.""" + + +GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간 +GOAL_H1 = 13 # 상반기(1~6월) — 마이그레이션 014 +GOAL_H2 = 14 # 하반기(7~12월) + + +def goal_half_of(month: int) -> int: + """1~6월 → 1(상반기), 7~12월 → 2(하반기).""" + return 1 if month <= 6 else 2 + + def validate_goal_month(m: Any, *, allow_year: bool = False) -> int: - """1~12월. allow_year 이면 0(연간)도 허용.""" + """1~12월. allow_year 이면 업무 영역 글 칸 — 0(연간)·13(상반기)·14(하반기)도 허용.""" try: v = int(m) except (TypeError, ValueError): raise ValueError("월이 올바르지 않습니다.") - if not ((0 if allow_year else 1) <= v <= 12): + if not ((0 if allow_year else 1) <= v <= (GOAL_H2 if allow_year else 12)): raise ValueError("월이 올바르지 않습니다.") return v +def validate_goal_merge(start: Any, end: Any) -> tuple[int, int]: + """월 칸 병합 범위(start~end 월, 2칸 이상) — 상반기·하반기를 넘지 않는다.""" + try: + s, e = int(start), int(end) + except (TypeError, ValueError): + raise ValueError("병합할 월이 올바르지 않습니다.") + if s > e: + s, e = e, s + if not (1 <= s and e <= 12) or s == e: + raise ValueError("병합은 1~12월 안에서 2칸 이상 골라야 합니다.") + if goal_half_of(s) != goal_half_of(e): + raise ValueError("상반기(1~6월)와 하반기(7~12월)를 넘어 병합할 수 없습니다.") + return s, e + + def validate_goal_value(v: Any) -> float | None: """지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움).""" s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "") diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index 135c790..040eafd 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 %} @@ -51,8 +51,9 @@ {% else %} {% set sm = board.metrics.sales %} {% set rm = board.metrics.roas %} + {# 월 칸은 pj-goal-m + data-h(1 = 상반기 1~6월, 2 = 하반기 7~12월) — 반기 접기(initGoals)가 이걸로 숨긴다 #} {% macro num_cell(metric, kind, labels, mo) -%} - + {%- if is_admin -%} {%- endmacro %} + data-admin="{{ 'true' if is_admin else 'false' }}" + data-halves="{{ 'true' if board.halves else 'false' }}"> {# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #} - {% for mo in months %}{% endfor %} + {% for h, hmonths, hm, hname in halves %} + {% for mo in hmonths %}{% endfor %} + {# 반기 칸 — 버튼으로 그 반기의 월 칸을 접었다 편다(localStorage pj_goal_fold) #} + + {% endfor %} - {# ── 숫자 지표 ── #} + {# ── 숫자 지표 — 연간·반기 칸은 화면에서 계산(매출 합계·달성률), 로아스는 % 단위 ── #} - - {% for mo in months %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %} + + {% for h, hmonths, hm, hname in halves %} + {% for mo in hmonths %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %} + + {% endfor %} - - {% for mo in months %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %} + + {% for h, hmonths, hm, hname in halves %} + {% for mo in hmonths %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %} + + {% endfor %} - - {% for mo in months %}{% endfor %} + + {% for h, hmonths, hm, hname in halves %} + {% for mo in hmonths %}{% endfor %} + + {% endfor %} - - {% for mo in months %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %} + + {% for h, hmonths, hm, hname in halves %} + {% for mo in hmonths %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %} + + {% endfor %} - - {% for mo in months %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %} + + {% for h, hmonths, hm, hname in halves %} + {% for mo in hmonths %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %} + + {% endfor %} - {# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #} + {# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(관리자) ── #} {% for area in board.areas %} {% for row in area.rows %} {% if loop.first %} {% endif %} - {% for mo in [0] + months %} - {% endfor %} @@ -156,7 +183,8 @@ {% if is_admin %}
- 칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다. + 칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다. + {%- if board.halves %} 월 칸은 Shift+클릭으로 여러 칸을 고른 뒤 병합하거나, 우클릭 메뉴로 병합·해제합니다.{% endif %}
{% endif %} {% endif %} @@ -169,5 +197,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 ba13cc6..a020d1d 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 %} @@ -89,10 +89,15 @@
  • 내 작업 — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (15장)
  • 휴지통 — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (19장)
  • 목표 — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 — - 맨 위에 매출(목표·실적·달성률)과 로아스(목표·실적)를 달마다, 그 아래에 업무 영역(상품·마케팅·컨텐츠·유통 등)별로 - 연간·월별 계획을 적습니다. 매출의 연간 칸은 월 합계, 달성은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다. + 맨 위에 매출(목표·실적·달성률)과 로아스(목표·실적, 단위 %)를 달마다, 그 아래에 업무 영역(상품·마케팅·컨텐츠·유통 등)별로 + 연간·반기·월별 계획을 적습니다. 6월 오른쪽에 상반기, 12월 오른쪽에 하반기 칸이 있고, 매출의 연간·반기 칸은 월 합계, + 달성은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다. 반기 칸 머리의 ‹ 버튼을 누르면 그 반기의 월 칸(1~6월 또는 7~12월)이 + 접히고, 다시 누르면 펼쳐집니다(접힌 상태는 내 브라우저에 기억). 입력은 관리자만 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 + 연도 추가로 새해 목표를 - 만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역 이름 칸에 마우스를 올려 이름·색·순서·줄 추가·삭제를 합니다.
  • + 만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역·줄 이름은 눌러서 그 자리에서 고치고(Enter 저장, Esc 취소), + 이름 칸에 마우스를 올려 색·순서·줄 추가·삭제를 합니다. 업무 영역의 월 칸은 병합할 수 있습니다 — 한 칸을 누르고 + Shift+클릭으로 같은 줄의 다른 칸까지 고른 뒤 떠 있는 "병합" 버튼을 누르거나, 칸을 우클릭해 "오른쪽/왼쪽 칸과 병합"·"병합 해제". + 병합은 상반기·하반기 안에서만 되고, 칸들의 글은 월 순서대로 첫 칸에 모입니다.
  • 프로젝트 — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 완료 프로젝트에 흐리게 모입니다.
  • 전체 멤버 — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.
  • diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index ac55de8..481fc4a 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 123be6c..3568651 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 9dc742a..c76f31f 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 b9abc13..da96667 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 e5fc976..c7c902a 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2006,8 +2006,10 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); } /* 가로·세로 스크롤은 이 칸 하나가 맡고, 머리 줄과 왼쪽 두 칸(구분·항목)은 붙어 있다 */ .pj-goal-pane { flex: 1 1 auto; min-height: 0; overflow: auto; } +/* width: 1px — table-layout: fixed 는 표 너비가 auto 가 아닐 때만 먹는다. 표는 칸 너비 합만큼 늘어나고, + 칸 너비가 머리 칸 width 로만 정해져야 반기 접기 애니메이션이 양방향으로 부드럽다(auto 면 펼 때 한 번에 튄다). */ .pj-goal-table { - border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px; + width: 1px; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px; color: var(--pj-ink); background: #fff; border: 1px solid #dfe2e6; border-radius: 10px; } /* 칸 너비는 여백·테두리 포함(border-box) — 안 그러면 padding 만큼 넓어진다 */ @@ -2093,6 +2095,58 @@ textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); } .pj-goal-numtd.is-saved, .pj-goal-texttd.is-saved { animation: pj-goal-saved 1s ease-out; } @keyframes pj-goal-saved { from { box-shadow: inset 0 0 0 2px #34a853; } to { box-shadow: inset 0 0 0 2px transparent; } } +.pj-goal-table th.is-saved { animation: pj-goal-saved 1s ease-out; } + +/* 상반기·하반기 칸 — 6월·12월 오른쪽. 앞 칸 오른쪽 테두리와 겹쳐 두 줄로 구분된다. */ +.pj-goal-table thead th.pj-goal-half-col { + width: 90px; min-width: 90px; max-width: 90px; padding: 0 6px; background: #eef0f3; +} +.pj-goal-table .pj-goal-half-col { border-left: 1px solid #cfd3d8; } +.pj-goal-kpi td.pj-goal-half-col { background: #f4f5f7; } +.pj-goal-texttd.pj-goal-half-col { font-weight: 600; } +.pj-goal-kpi td { white-space: nowrap; } +/* 반기 접기 버튼(반기 칸 머리) — 펼침 = ‹(왼쪽 월 칸을 접는다), 접힘 = 뒤집혀 ›, 강조색 */ +.pj-goal-fold { + display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px; + margin: 0 2px 0 -2px; padding: 0; border: none; border-radius: 5px; background: transparent; + color: var(--pj-ink-soft); cursor: pointer; vertical-align: -5px; +} +.pj-goal-fold:hover { background: #dfe2e7; color: var(--pj-ink); } +.pj-goal-fold .material-symbols-outlined { font-size: 18px; transition: transform .32s ease; } +.pj-goal-fold.is-folded { background: var(--pj-accent-tint); color: var(--pj-accent-dark); } +.pj-goal-fold.is-folded .material-symbols-outlined { transform: rotate(180deg); } +/* 접기 애니메이션 — 월 칸 너비를 0 으로(.is-shrunk) 줄인 뒤 숨김(.is-gone), 펼 땐 거꾸로(initGoals applyFold). + 줄어드는 동안 칸 안 글이 다시 줄바꿈돼 줄 높이가 출렁이지 않게 안쪽 내용은 원래 폭(85px × 칸 수)으로 고정해 잘라 낸다. */ +.pj-goal-table .pj-goal-m { overflow: hidden; } +.pj-goal-table.is-folding .pj-goal-m { + transition: width .32s ease, min-width .32s ease, max-width .32s ease, + padding .32s ease, border-right-width .32s ease; +} +.pj-goal-table.is-folding td.pj-goal-m > * { width: calc(85px * var(--span, 1) - 1px); } +.pj-goal-table thead th.pj-goal-m.is-shrunk, +.pj-goal-table td.pj-goal-m.is-shrunk { + width: 0; min-width: 0; max-width: 0; padding-left: 0 !important; padding-right: 0 !important; border-right-width: 0; +} +.pj-goal-table .pj-goal-m.is-gone { display: none; } + +/* 영역·줄 이름 — 눌러서 그 자리에서 수정(관리자) */ +.pj-goal-table [data-goal-edit] { cursor: text; border-radius: 5px; padding: 1px 3px; margin: -1px -3px; } +.pj-goal-table [data-goal-edit]:hover { background: rgba(255, 255, 255, .65); box-shadow: 0 0 0 1px rgba(0, 0, 0, .14); } +.pj-goal-table [data-goal-edit].is-editing { + background: #fff; box-shadow: 0 0 0 2px var(--pj-accent); outline: none; word-break: normal; +} +.pj-goal-row-text[data-goal-edit]:empty { min-height: 1.5em; } +.pj-goal-row-text[data-goal-edit]:empty:hover::before { content: "줄 이름"; color: rgba(0, 0, 0, .3); font-weight: 500; } + +/* 월 칸 병합 — Shift+클릭 선택 표시와 떠 있는 병합 버튼(body 에 붙음) */ +.pj-goal-table td.pj-goal-texttd.is-merge-sel { + box-shadow: inset 0 0 0 2px var(--pj-accent); + background-image: linear-gradient(rgba(123, 104, 238, .12), rgba(123, 104, 238, .12)); +} +.pj-goal-mergebar { position: fixed; z-index: 1000; } +.pj-goal-mergebar .pj-btn { display: inline-flex; align-items: center; gap: 4px; box-shadow: 0 6px 18px rgba(16, 24, 40, .2); } +.pj-goal-mergebar .material-symbols-outlined { font-size: 18px; } + .pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; } /* 영역 색 고르기 팝업(body 에 붙음) */ diff --git a/app/static/project.js b/app/static/project.js index 30bba60..f25ceeb 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -8025,27 +8025,104 @@ td.textContent = (Math.round(r * 10) / 10).toLocaleString("ko-KR") + "%"; td.classList.add(r >= 100 ? "is-good" : "is-low"); } + // 합계 칸 — 연간(0) · 상반기(13, 1~6월) · 하반기(14, 7~12월) + const SUM_SCOPES = [[0, 1, 12], [13, 1, 6], [14, 7, 12]]; function recompute() { const tg = values("sales", "target"), ac = values("sales", "actual"); - let sumT = null, sumA = null; for (let m = 1; m <= 12; m++) { - if (tg[m] != null) sumT = (sumT || 0) + tg[m]; - if (ac[m] != null) sumA = (sumA || 0) + ac[m]; const td = table.querySelector('.pj-goal-rate[data-month="' + m + '"]'); if (td) setRate(td, ac[m], tg[m]); } - const st = table.querySelector('.pj-goal-sum[data-metric="sales"][data-kind="target"]'); - const sa = table.querySelector('.pj-goal-sum[data-metric="sales"][data-kind="actual"]'); - if (st) st.textContent = sumT == null ? "" : fmtNum(sumT); - if (sa) sa.textContent = sumA == null ? "" : fmtNum(sumA); - // 연간 달성률은 실적이 들어온 달까지만 비교(남은 달 목표까지 넣으면 연중엔 항상 낮게 나온다). - let tUpTo = 0; - for (let m = 1; m <= 12; m++) if (ac[m] != null && tg[m] != null) tUpTo += tg[m]; - const y0 = table.querySelector('.pj-goal-rate[data-month="0"]'); - if (y0) setRate(y0, sumA, tUpTo); - if (y0) y0.dataset.tip = tUpTo ? "실적이 있는 달의 목표 합계 대비" : ""; + SUM_SCOPES.forEach(function (sc) { + let sumT = null, sumA = null, tUpTo = 0; + for (let m = sc[1]; m <= sc[2]; m++) { + if (tg[m] != null) sumT = (sumT || 0) + tg[m]; + if (ac[m] != null) sumA = (sumA || 0) + ac[m]; + // 달성률은 실적이 들어온 달까지만 비교(남은 달 목표까지 넣으면 기간 중엔 항상 낮게 나온다). + if (ac[m] != null && tg[m] != null) tUpTo += tg[m]; + } + const st = table.querySelector('.pj-goal-sum[data-metric="sales"][data-kind="target"][data-scope="' + sc[0] + '"]'); + const sa = table.querySelector('.pj-goal-sum[data-metric="sales"][data-kind="actual"][data-scope="' + sc[0] + '"]'); + if (st) st.textContent = sumT == null ? "" : fmtNum(sumT); + if (sa) sa.textContent = sumA == null ? "" : fmtNum(sumA); + const rt = table.querySelector('.pj-goal-rate[data-month="' + sc[0] + '"]'); + if (rt) { + setRate(rt, sumA, tUpTo); + rt.dataset.tip = tUpTo ? "실적이 있는 달의 목표 합계 대비" : ""; + } + }); } recompute(); + + // ── 상·하반기 접기 — 반기 칸 머리의 버튼이 그 반기 월 칸(.pj-goal-m[data-h])을 접었다 편다. + // 칸 너비를 0 으로 줄이는 애니메이션(.is-shrunk, CSS transition) 뒤 display:none(.is-gone), + // 펼 때는 거꾸로. 상태는 브라우저에 기억(localStorage pj_goal_fold). 보기만 하는 사람도 쓸 수 있다. + const FOLD_KEY = "pj_goal_fold"; + const FOLD_MS = 320; + const fold = { 1: false, 2: false }; + try { + const saved = JSON.parse(localStorage.getItem(FOLD_KEY) || "null"); + if (saved) { fold[1] = !!saved[1]; fold[2] = !!saved[2]; } + } catch (_) {} + const foldTimers = {}; + function halfCells(h) { return table.querySelectorAll('.pj-goal-m[data-h="' + h + '"]'); } + function syncFoldBtn(h) { + const btn = table.querySelector('.pj-goal-fold[data-h="' + h + '"]'); + if (!btn) return; + btn.classList.toggle("is-folded", fold[h]); + btn.setAttribute("aria-expanded", fold[h] ? "false" : "true"); + btn.title = (btn.dataset.label || "") + (fold[h] ? " 펼치기" : " 접기"); + delete btn.dataset.tip; // 공용 말풍선이 옮겨 둔 예전 문구 대신 새 title 을 쓰게 + const th = btn.closest("th"); + if (th) th.classList.toggle("is-folded", fold[h]); + } + function applyFold(h, animate) { + const cells = halfCells(h); + const folded = fold[h]; + clearTimeout(foldTimers[h]); + const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + syncFoldBtn(h); + if (!animate || reduce) { + cells.forEach(function (c) { c.classList.toggle("is-shrunk", folded); c.classList.toggle("is-gone", folded); }); + if (!folded) table.querySelectorAll('.pj-goal-m[data-h="' + h + '"] textarea.pj-goal-text').forEach(fit); + return; + } + table.classList.add("is-folding"); + if (folded) { + cells.forEach(function (c) { c.classList.add("is-shrunk"); }); + } else { + cells.forEach(function (c) { c.classList.remove("is-gone"); }); + void table.offsetWidth; // 너비 0 인 채로 한 번 그린 뒤 원래 너비로 늘린다 + cells.forEach(function (c) { c.classList.remove("is-shrunk"); }); + } + foldTimers[h] = setTimeout(function () { + if (folded) cells.forEach(function (c) { c.classList.add("is-gone"); }); + else table.querySelectorAll('.pj-goal-m[data-h="' + h + '"] textarea.pj-goal-text').forEach(fit); + if (!foldTimers[3 - h]) table.classList.remove("is-folding"); + delete foldTimers[h]; + }, FOLD_MS + 20); + } + table.querySelectorAll(".pj-goal-fold").forEach(function (btn) { + btn.addEventListener("click", function (e) { + e.stopPropagation(); + const h = btn.dataset.h; + fold[h] = !fold[h]; + try { localStorage.setItem(FOLD_KEY, JSON.stringify(fold)); } catch (_) {} + clearMergeSel(); + applyFold(h, true); + }); + }); + // 글 칸 높이 맞추기 — 접혀 안 보이는 칸은 건너뛴다(높이 0 으로 재져 펼쳤을 때 글이 잘림). 펼칠 때 다시 잰다. + function fit(ta) { + if (!ta.offsetParent) return; + ta.style.height = "auto"; + ta.style.height = ta.scrollHeight + "px"; + } + applyFold(1, false); + applyFold(2, false); + + // 병합 선택(Shift+클릭) — 관리자 전용, 아래에서 채운다. 접기 버튼이 먼저 부르므로 여기 둔다. + let clearMergeSel = function () {}; if (!isAdmin) return; // ── 숫자 칸 ── @@ -8080,7 +8157,6 @@ } // ── 글 칸 ── - function fit(ta) { ta.style.height = "auto"; ta.style.height = ta.scrollHeight + "px"; } const pending = new Map(); // textarea → 타이머 function cellUrl(ta) { return "/project/api/goals/rows/" + ta.dataset.row + "/cells/" + ta.dataset.month; } async function saveText(ta) { @@ -8199,7 +8275,13 @@ setTimeout(function () { document.addEventListener("mousedown", onColorDocDown, true); }, 0); } - // ── 영역·줄 도구(✎ 색 ↑ ↓ + ×) — 이벤트 위임 ── + // ── 영역·줄 도구(색 ↑ ↓ + ×) — 이벤트 위임. 이름 바꾸기는 이름을 눌러 그 자리에서(아래 startNameEdit) ── + function textOf(node, sel) { + const t = node && node.querySelector(sel); + return t ? t.textContent.trim() : ""; + } + // 저장 안 된 글이 있으면 먼저 저장(구조 변경·병합 전에 — 병합은 서버가 DB 의 글을 모은다) + function flushTexts() { return Promise.all(Array.from(pending.keys()).map(saveText)); } table.addEventListener("click", async function (e) { const b = e.target.closest("[data-goal-act]"); if (!b) return; @@ -8209,17 +8291,14 @@ const areaId = tbody && tbody.dataset.areaId; const rowId = tr && tr.dataset.rowId; try { - if (act === "area-rename") { - const v = await prompt("업무 영역 이름", b.dataset.name || ""); - if (v == null || !String(v).trim() || v === b.dataset.name) return; - await api("PUT", "/project/api/goals/areas/" + areaId, { name: String(v).trim() }); - } else if (act === "area-color") { + if (act === "area-color") { openColorPop(b, areaId, b.dataset.color, tbody); return; } else if (act === "area-up" || act === "area-down") { await api("POST", "/project/api/goals/areas/" + areaId + "/move", { direction: act === "area-up" ? -1 : 1 }); } else if (act === "area-del") { - const ok = await confirm("'" + (b.dataset.name || "") + "' 업무 영역을 삭제할까요?\n안의 줄과 글도 모두 삭제됩니다.", + const name = textOf(tbody, ".pj-goal-area-text"); + const ok = await confirm("'" + name + "' 업무 영역을 삭제할까요?\n안의 줄과 글도 모두 삭제됩니다.", { okText: "삭제", cancelText: "취소" }); if (!ok) return; await api("DELETE", "/project/api/goals/areas/" + areaId); @@ -8227,23 +8306,197 @@ const v = await prompt("새 줄 이름 (예: 쿠팡 — 비워 둬도 됩니다)", ""); if (v == null) return; await api("POST", "/project/api/goals/areas/" + areaId + "/rows", { label: String(v).trim() }); - } else if (act === "row-rename") { - const v = await prompt("줄 이름", b.dataset.label || ""); - if (v == null || v === b.dataset.label) return; - await api("PUT", "/project/api/goals/rows/" + rowId, { label: String(v).trim() }); } 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") { - const label = b.dataset.label ? "'" + b.dataset.label + "' 줄" : "이 줄"; + const lb = textOf(tr, ".pj-goal-row-text"); + const label = lb ? "'" + lb + "' 줄" : "이 줄"; const ok = await confirm(label + "을 삭제할까요? 그 줄의 글도 모두 삭제됩니다.", { okText: "삭제", cancelText: "취소" }); if (!ok) return; await api("DELETE", "/project/api/goals/rows/" + rowId); } else return; - // 저장 안 된 글이 있으면 먼저 저장하고 새로고침 - await Promise.all(Array.from(pending.keys()).map(saveText)); + await flushTexts(); reloadKeepScroll(); } catch (err) { showToast("처리 실패: " + err.message, "error"); } }); + + // ── 영역·줄 이름 — 눌러서 그 자리에서 수정(Enter·칸 떠남 = 저장, Esc = 취소). 서식 없이 글자만. ── + function startNameEdit(span) { + if (span.isContentEditable) return; + const kind = span.dataset.goalEdit; + const orig = span.textContent; + span.contentEditable = "true"; + span.classList.add("is-editing"); + span.focus(); + const r = document.createRange(); + r.selectNodeContents(span); + const sel = window.getSelection(); + sel.removeAllRanges(); + sel.addRange(r); + let done = false; + async function finish(save) { + if (done) return; + done = true; + span.contentEditable = "false"; + span.classList.remove("is-editing"); + span.removeEventListener("keydown", onKey); + span.removeEventListener("blur", onBlur); + const v = span.textContent.replace(/\s+/g, " ").trim(); + if (!save || v === orig.trim()) { span.textContent = orig; return; } + if (kind === "area" && !v) { + span.textContent = orig; + showToast("업무 영역 이름을 입력하세요.", "error"); + return; + } + span.textContent = v; + try { + if (kind === "area") { + await api("PUT", "/project/api/goals/areas/" + span.closest(".pj-goal-area").dataset.areaId, { name: v }); + } else { + await api("PUT", "/project/api/goals/rows/" + span.closest("tr").dataset.rowId, { label: v }); + } + flashSaved(span.closest("th")); + } catch (err) { + span.textContent = orig; + showToast("이름 변경 실패: " + err.message, "error"); + } + } + function onKey(e) { + if (isImeEnter(e)) return; + if (e.key === "Enter") { e.preventDefault(); span.blur(); } + else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); finish(false); span.blur(); } + } + function onBlur() { finish(true); } + span.addEventListener("keydown", onKey); + span.addEventListener("blur", onBlur); + } + table.addEventListener("click", function (e) { + const span = e.target.closest("[data-goal-edit]"); + if (span) startNameEdit(span); + }); + table.addEventListener("paste", function (e) { + const span = e.target.closest && e.target.closest("[data-goal-edit].is-editing"); + if (!span) return; + e.preventDefault(); + const text = ((e.clipboardData || window.clipboardData).getData("text/plain") || "").replace(/\s+/g, " "); + document.execCommand("insertText", false, text); + }); + + // ── 월 칸 병합(마이그레이션 014) — 한 줄의 같은 반기 안에서만. + // · Shift+클릭: 마지막으로 누른 월 칸부터 그 칸까지 고른 뒤 떠 있는 "N~M월 병합" 버튼 + // · 우클릭: 선택한 칸 병합 / 오른쪽·왼쪽 칸과 병합 / 병합 해제 + // 글은 서버가 월 순서대로 줄바꿈으로 이어 첫 칸에 모은다. 해제하면 글은 첫 칸에 남는다. + if (table.dataset.halves === "true") { + let anchor = null; // 마지막으로 누른 월 칸 + let mergeSel = null; // {row, h, start, end} + let mergeBar = null; + const monthTd = function (node) { + const td = node && node.closest && node.closest("td.pj-goal-texttd.pj-goal-m"); + return td && table.contains(td) ? td : null; + }; + const cellInfo = function (td) { + const m = parseInt(td.dataset.month, 10); + const span = parseInt(td.dataset.span || "1", 10); + return { row: td.closest("tr").dataset.rowId, h: td.dataset.h, start: m, end: m + span - 1, span: span }; + }; + clearMergeSel = function () { + mergeSel = null; + table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); }); + if (mergeBar) { mergeBar.remove(); mergeBar = null; } + }; + const mergeCells = async function (rowId, start, end) { + try { + await flushTexts(); + await api("POST", "/project/api/goals/rows/" + rowId + "/merge", { start: start, end: end }); + reloadKeepScroll(); + } catch (err) { showToast("병합 실패: " + err.message, "error"); } + }; + const unmergeCell = async function (rowId, start) { + try { + await flushTexts(); + await api("DELETE", "/project/api/goals/rows/" + rowId + "/merge/" + start); + reloadKeepScroll(); + } catch (err) { showToast("병합 해제 실패: " + err.message, "error"); } + }; + const showMergeSel = function (rowId, h, start, end) { + clearMergeSel(); + mergeSel = { row: rowId, h: h, start: start, end: end }; + let last = null; + table.querySelectorAll('tr[data-row-id="' + rowId + '"] > td.pj-goal-texttd.pj-goal-m[data-h="' + h + '"]') + .forEach(function (td) { + const c = cellInfo(td); + if (c.start >= start && c.end <= end) { td.classList.add("is-merge-sel"); last = td; } + }); + // 떠 있는 병합 버튼 — body 에 붙인다(화면 배율 밖) + mergeBar = document.createElement("div"); + mergeBar.className = "pj-goal-mergebar"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "pj-btn pj-btn-primary"; + btn.innerHTML = 'cell_merge'; + btn.appendChild(document.createTextNode(start + "~" + end + "월 병합")); + btn.addEventListener("click", function () { + const s = mergeSel; + clearMergeSel(); + if (s) mergeCells(s.row, s.start, s.end); + }); + mergeBar.appendChild(btn); + document.body.appendChild(mergeBar); + const r = last.getBoundingClientRect(); + const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight; + mergeBar.style.left = Math.max(8, Math.min(r.right - mergeBar.offsetWidth, vw - mergeBar.offsetWidth - 8)) + "px"; + mergeBar.style.top = Math.max(8, Math.min(r.bottom + 6, vh - mergeBar.offsetHeight - 8)) + "px"; + }; + table.addEventListener("mousedown", function (e) { + if (e.button !== 0) return; + const td = monthTd(e.target); + if (!td) return; + const c = cellInfo(td); + if (e.shiftKey && anchor && anchor.row === c.row && anchor.h === c.h && anchor.start !== c.start) { + e.preventDefault(); // 글 선택·포커스 이동 없이 범위만 고른다 + showMergeSel(c.row, c.h, Math.min(anchor.start, c.start), Math.max(anchor.end, c.end)); + return; + } + anchor = c; + clearMergeSel(); + }); + // 다른 곳을 누르거나 Esc·스크롤이면 선택 해제 + document.addEventListener("mousedown", function (e) { + if (!mergeSel || (mergeBar && mergeBar.contains(e.target)) || monthTd(e.target)) return; + clearMergeSel(); + }, true); + document.addEventListener("keydown", function (e) { if (e.key === "Escape" && mergeSel) clearMergeSel(); }); + pane.addEventListener("scroll", function () { if (mergeSel) clearMergeSel(); }); + table.addEventListener("contextmenu", function (e) { + const td = monthTd(e.target); + if (!td) return; + e.preventDefault(); + const c = cellInfo(td); + const isMonth = function (x) { return x && x.classList.contains("pj-goal-m") && x.dataset.h === c.h; }; + const items = []; + const s = mergeSel; + if (s && s.row === c.row && c.start >= s.start && c.end <= s.end) { + items.push({ label: "선택한 칸 병합 (" + s.start + "~" + s.end + "월)", + onClick: function () { clearMergeSel(); mergeCells(s.row, s.start, s.end); } }); + } + const next = td.nextElementSibling, prev = td.previousElementSibling; + if (isMonth(next)) { + const n = cellInfo(next); + items.push({ label: "오른쪽 칸과 병합 (" + c.start + "~" + n.end + "월)", + onClick: function () { mergeCells(c.row, c.start, n.end); } }); + } + if (isMonth(prev)) { + const p = cellInfo(prev); + items.push({ label: "왼쪽 칸과 병합 (" + p.start + "~" + c.end + "월)", + onClick: function () { mergeCells(c.row, p.start, c.end); } }); + } + if (c.span > 1) { + if (items.length) items.push(null); + items.push({ label: "병합 해제", onClick: function () { unmergeCell(c.row, c.start); } }); + } + if (items.length) showContextMenu(e.clientX, e.clientY, items); + }); + } } // ── 휴지통(관리자 전용 화면) — [복구] 누르면 원래 id 그대로 되살리고 줄을 지운다. diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index bf3df2d..ad0c0f0 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -293,6 +293,8 @@ docker exec -i postgres-db psql -U postgres -d project_db \ < scripts/sql/project_db_012_comment_replies_reactions.sql docker exec -i postgres-db psql -U postgres -d project_db \ < scripts/sql/project_db_013_goals.sql +docker exec -i postgres-db psql -U postgres -d project_db \ + < scripts/sql/project_db_014_goal_halves_merges.sql # 4) 재배포 (git pull 후 반드시 --build) cd /opt/www/main && docker compose up -d --build web @@ -509,6 +511,37 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중 영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지). - 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기. +### 6-9-1. 상·하반기 칸 · 반기 접기 · 이름 바로 수정 · 월 칸 병합 · 로아스 % (마이그레이션 014) + +- **열 순서** — 연간 · 1~6월 · **상반기** · 7~12월 · **하반기**. 템플릿 컨텍스트 `halves` + (`(반기, 월 목록, 글 칸 번호 13|14, 이름)`), 월 칸은 `pj-goal-m` + `data-h="1|2"`, 반기 칸은 `pj-goal-half-col`. + - 숫자 지표: 매출 목표·실적의 반기 칸 = 그 반기 월 합계(`data-scope="13|14"`, 연간은 `0`), 달성률은 연간과 같은 규칙 + (실적이 있는 달의 목표 합계 대비, `SUM_SCOPES`). 로아스 반기·연간 칸은 계산하지 않는다(회색). + - 업무 영역 글: `goal_cells.month` **13 = 상반기, 14 = 하반기**(014 가 CHECK 를 0~14 로 넓힘). 014 미적용이면 반기 글 칸은 + 보기 전용 빈 칸이고, 저장 API 는 503 "마이그레이션 014 필요"(`store.GoalMigration014Needed`). +- **반기 접기** — 반기 칸 머리의 버튼(`.pj-goal-fold`, 펼침 ‹ / 접힘 뒤집힌 › + 강조색)이 그 반기 월 칸을 접었다 편다. + 보기 전용 사용자도 쓸 수 있고 상태는 브라우저별 localStorage `pj_goal_fold`(`{"1":bool,"2":bool}`). + 애니메이션(`applyFold`): 접기 = `.is-shrunk`(칸 width·padding·테두리 → 0, `.is-folding` 동안만 transition .32s) 뒤 + `.is-gone`(display:none), 펴기 = 거꾸로. 줄어드는 동안 칸 안 내용은 원래 폭(`85px × --span`)으로 고정해 잘라 내서 줄 높이가 + 출렁이지 않는다. **표는 `width: 1px` + `table-layout: fixed`** — fixed 는 표 너비가 auto 가 아닐 때만 먹는다(auto 면 칸 너비가 + 내용을 따라가 펼칠 때 애니메이션 없이 한 번에 튄다). 표는 칸 너비 합만큼 늘어난다. 접힌 칸의 글 칸 높이는 잴 수 없어(`fit` 이 + `offsetParent` 없으면 건너뜀) 펼친 뒤 다시 잰다. `prefers-reduced-motion` 이면 애니메이션 없이. +- **영역·줄 이름 바로 수정**(관리자) — 이름(`[data-goal-edit="area|row"]`)을 누르면 contenteditable(`startNameEdit`) — + Enter·칸 떠남 = 저장, Esc = 취소, 붙여넣기는 글자만. 영역 이름 빈 값은 되돌림(서버도 400), 줄 이름은 빈 값 허용(빈 줄 이름은 + 마우스를 올리면 "줄 이름" 자리 표시). 예전 ✎(prompt) 버튼은 없앴고 도구 막대는 색·↑·↓·+·× 만. +- **월 칸 병합**(관리자, 014) — `goal_cell_merges(row_id, start_month, span)` — 한 줄 안에서 가로로만, **같은 반기 안에서만** + (DB CHECK + `store.validate_goal_merge`), 2칸 이상. 화면은 `router._goal_row_layout` 이 줄마다 칸 배치(병합이면 `colspan`)를 만든다. + - 고르기: 월 칸을 누른 뒤 **Shift+클릭**(같은 줄·같은 반기) → 칸 테두리 강조 + 떠 있는 "N~M월 병합" 버튼(`.pj-goal-mergebar`, + body 에 붙음). 다른 곳 누름·Esc·스크롤 = 선택 해제. + - 우클릭 메뉴: 선택한 칸 병합 / 오른쪽 칸과 병합 / 왼쪽 칸과 병합 / 병합 해제(병합된 칸). 월 칸에서는 브라우저 기본 우클릭 메뉴 대신 뜬다. + - `POST /api/goals/rows/{row_id}/merge {start, end}` → `db.merge_goal_cells`: 걸친 기존 병합은 통째로 흡수, 범위 안 칸들의 글을 + 월 순서대로 줄바꿈으로 이어 **시작 월 칸**에 두고 나머지 칸 글은 지운다(한 트랜잭션, 줄 FOR UPDATE). 화면은 먼저 저장 안 된 글을 + 저장(`flushTexts`)한 뒤 부르고 새로고침. `DELETE /api/goals/rows/{row_id}/merge/{start}` = 해제(글은 시작 월 칸에 남음). + - 병합된 칸의 가운데·끝 월로 늦게 온 글 저장은 400("병합된 칸입니다") — 다른 창에서 병합된 뒤의 저장이 숨은 칸에 쌓이지 않게. + - 새 연도 만들기(구조 복사)는 병합을 복사하지 않는다(줄 이름만). +- **로아스 단위 %** — 로아스 목표·실적 칸은 `499%` 처럼 보인다(`router._goal_label`, 저장 응답 `label` 도 같음). 입력은 `499`·`499%` + 둘 다 되고 저장 값은 숫자(`validate_goal_value` 가 `%` 를 뗀다). + ## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음) **권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙) diff --git a/scripts/sql/project_db_014_goal_halves_merges.sql b/scripts/sql/project_db_014_goal_halves_merges.sql new file mode 100644 index 0000000..df2e5a1 --- /dev/null +++ b/scripts/sql/project_db_014_goal_halves_merges.sql @@ -0,0 +1,45 @@ +-- ===================================================================== +-- project_db 마이그레이션 014 — 연간 목표: 상·하반기 칸 · 월 칸 병합 +-- ===================================================================== +-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — goal_cells 의 month CHECK 제약만 넓혀 다시 건다. +-- +-- goal_cells.month 0 = 연간, 1~12 = 월, 13 = 상반기, 14 = 하반기 +-- goal_cell_merges 업무 영역 줄의 월 칸 가로 병합. start_month 부터 span 칸(2칸 이상). +-- 상반기(1~6)·하반기(7~12)를 넘지 않는다(사이에 상반기 칸이 있고, 반기를 접을 수 있어서). +-- 글은 start_month 칸(goal_cells)에 둔다. +-- +-- 미적용이어도 목표 화면은 동작한다 — 상·하반기 글 칸과 병합만 "마이그레이션 014 필요". +-- +-- 적용 (1회, 여러 번 돌려도 안전): +-- docker exec -i postgres-db psql -U postgres -d project_db \ +-- < scripts/sql/project_db_014_goal_halves_merges.sql +-- ===================================================================== + +\set ON_ERROR_STOP on +\connect project_db + +BEGIN; + +ALTER TABLE goal_cells DROP CONSTRAINT IF EXISTS goal_cells_month_check; +ALTER TABLE goal_cells ADD CONSTRAINT goal_cells_month_check CHECK (month BETWEEN 0 AND 14); + +CREATE TABLE IF NOT EXISTS goal_cell_merges ( + row_id BIGINT NOT NULL REFERENCES goal_rows(id) ON DELETE CASCADE, + start_month SMALLINT NOT NULL, + span SMALLINT NOT NULL, + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (row_id, start_month), + CONSTRAINT goal_cell_merges_range CHECK ( + span >= 2 AND start_month >= 1 AND start_month + span - 1 <= 12 + AND (start_month <= 6) = (start_month + span - 1 <= 6) + ) +); + +COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 줄의 월 칸 가로 병합(반기 안에서만)'; + +GRANT SELECT, INSERT, UPDATE, DELETE ON goal_cell_merges TO project_app; + +COMMIT; + +SELECT 'project_db 014 goal halves/merges ready' AS status; diff --git a/tests/test_project_module.py b/tests/test_project_module.py index 36958bb..4d83fed 100644 --- a/tests/test_project_module.py +++ b/tests/test_project_module.py @@ -456,6 +456,75 @@ def test_store_date_range_unit(): raise AssertionError(args) +def test_store_goal_merge_unit(): + from app.modules.project import store + assert store.validate_goal_merge(3, 1) == (1, 3) + assert store.validate_goal_merge(7, 12) == (7, 12) + assert store.validate_goal_month(13, allow_year=True) == 13 + for args in ((6, 7), (3, 3), (0, 2), (11, 13)): + try: + store.validate_goal_merge(*args) + except ValueError: + continue + raise AssertionError(args) + + +# ════════════════════════════════════════════════════════════ +# 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기 +# ════════════════════════════════════════════════════════════ +def test_goal_halves_and_merges(): + year = 2060 + int(RUN, 16) % 40 + ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None + assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 + try: + board = ST.get_goal_board(year=year) + assert board["halves"] is True, "마이그레이션 014 적용 필요" + rid = board["areas"][0]["rows"][0]["id"] + cell = lambda m, body, who=ADMIN: req( # noqa: E731 + "PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body}) + # 상·하반기 글 칸(13·14), 범위 밖(15)은 400, 비관리자는 403 + assert cell(13, "상반기 글").status_code == 200 and cell(14, "하반기 글").status_code == 200 + assert cell(15, "x").status_code == 400 + assert cell(13, "y", BOB).status_code == 403 + for m, body in ((2, "이월"), (3, "삼월"), (5, "오월")): + assert cell(m, body).status_code == 200 + merge = lambda s, e: req( # noqa: E731 + "POST", f"/project/api/goals/rows/{rid}/merge", ADMIN, json={"start": s, "end": e}) + # 반기를 넘는 병합·한 칸 병합은 400 + assert merge(5, 8).status_code == 400 and merge(4, 4).status_code == 400 + r = merge(2, 3) + assert r.status_code == 200 and r.json() == {"ok": True, "start": 2, "span": 2}, r.text + cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] + assert cells[2] == "이월\n삼월" and 3 not in cells + # 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만) + assert cell(3, "늦은 저장").status_code == 400 + # 걸친 병합은 흡수: 3~5 → 2~5, 글은 월 순서대로 이어진다 + r = merge(3, 5) + assert r.json() == {"ok": True, "start": 2, "span": 4}, r.text + row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] + assert row["merges"] == {2: 4} and row["cells"][2] == "이월\n삼월\n오월" and 5 not in row["cells"] + assert row["cells"][13] == "상반기 글" and row["cells"][14] == "하반기 글" + # 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404 + assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 200 + assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 404 + row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] + assert row["merges"] == {} and row["cells"][2] == "이월\n삼월\n오월" + # 로아스 % 표기(입력에 % 가 있어도 숫자로 저장) + r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN, + json={"metric": "roas", "kind": "target", "month": 1, "value": "499%"}) + assert r.status_code == 200 and r.json()["label"] == "499%" and r.json()["value"] == 499 + r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN, + json={"metric": "sales", "kind": "target", "month": 1, "value": "1,200"}) + assert r.json()["label"] == "1,200" + # 영역·줄 이름(그 자리 수정이 쓰는 API) — 영역 이름은 빈 값 400, 줄 이름은 빈 값 허용 + aid = ST.get_goal_board(year=year)["areas"][0]["id"] + assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": ""}).status_code == 400 + assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": "상품2"}).status_code == 200 + assert req("PUT", f"/project/api/goals/rows/{rid}", ADMIN, json={"label": ""}).status_code == 200 + finally: + ST.delete_goal_year(year=year) + + if __name__ == "__main__": if not ENABLED: print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
    연간{{ mo }}월{{ mo }}월 + {{ hname }} +
    매출 목표
    실적
    달성
    로아스 목표
    실적
    - {{ area.name }} + {{ area.name }} {% if is_admin %} - - + {% endif %} - {{ row.label }} - {% if is_admin %} + {{ row.label }} + {% if is_admin and area.rows | length > 1 %} - - {% if area.rows | length > 1 %} - - {% endif %} + {% endif %} - {%- if is_admin -%} - + {% for c in row.layout %} + {% set editable = is_admin and (c.kind != 'half' or board.halves) %} + {% if c.kind == 'month' %} + 1 %} colspan="{{ c.span }}" style="--span: {{ c.span }}"{% endif %}> + {% else %} + + {% endif %} + {%- if editable -%} + {%- else -%} -
    {{ row.cells.get(mo, '') }}
    +
    {{ row.cells.get(c.m, '') }}
    {%- endif -%}