diff --git a/CLAUDE.md b/CLAUDE.md index 94889b8..0944b6e 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`). 마감 알림(`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`). 연간 목표(마이그레이션 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` 상세는 `docs/PROJECT_OVERVIEW.md`. diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 21b0745..179712f 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -1701,6 +1701,277 @@ class ProjectStore: ts = row["ts"] if row else None return ts.isoformat() if ts else "" + # ════════════════════════════════════════════════════════════ + # 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 → 목표 표 + # ════════════════════════════════════════════════════════════ + def goals_enabled(self) -> bool: + with self._pool.connection() as conn: + return self._table_exists(conn, "goal_years") + + def list_goal_years(self) -> list[int]: + """목표를 만든 연도(최근 연도 먼저). 013 미적용이면 UndefinedTable.""" + with self._pool.connection() as conn: + rows = conn.execute("SELECT year FROM goal_years ORDER BY year DESC").fetchall() + return [int(r["year"]) for r in rows] + + def create_goal_year(self, *, year: int, created_by: str = "") -> None: + """연도 추가 — 가장 가까운 이전 연도(없으면 가장 가까운 다음 연도)의 업무 영역·줄 + 구조를 글 없이 복사한다. 목표를 둔 연도가 하나도 없으면 기본 영역(DEFAULT_GOAL_AREAS).""" + y = store.validate_goal_year(year) + with self._pool.connection() as conn: + with conn.transaction(): + row = conn.execute( + "INSERT INTO goal_years (year, created_by) VALUES (%s, %s) " + "ON CONFLICT (year) DO NOTHING RETURNING year", + (y, store.norm_str(created_by, lower=True)), + ).fetchone() + if row is None: + raise ValueError(f"{y}년 목표는 이미 있습니다.") + src = conn.execute( + "SELECT year FROM goal_years WHERE year <> %s " + "ORDER BY (year > %s), abs(year - %s) LIMIT 1", + (y, y, y), + ).fetchone() + if src: + areas = conn.execute( + "SELECT id, name, color, sort_order FROM goal_areas " + "WHERE year = %s ORDER BY sort_order, id", + (src["year"],), + ).fetchall() + plan = [] + for a in areas: + labels = conn.execute( + "SELECT label 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 ("",))) + else: + plan = list(store.DEFAULT_GOAL_AREAS) + 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), + ) + + def delete_goal_year(self, *, year: int) -> None: + with self._pool.connection() as conn: + row = conn.execute( + "DELETE FROM goal_years WHERE year = %s RETURNING year", (year,) + ).fetchone() + if row is None: + raise KeyError(year) + + def update_goal_year(self, *, year: int, sales_unit: str) -> None: + unit = store.norm_str(sales_unit)[:20] + with self._pool.connection() as conn: + row = conn.execute( + "UPDATE goal_years SET sales_unit = %s WHERE year = %s RETURNING year", + (unit, year), + ).fetchone() + if row is None: + raise KeyError(year) + + def get_goal_board(self, *, year: int) -> dict[str, Any] | None: + """한 해 목표 표 전체. 연도가 없으면 None. + + metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}} + areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", ...}}]}] + """ + with self._pool.connection() as conn: + head = conn.execute( + "SELECT year, sales_unit FROM goal_years WHERE year = %s", (year,) + ).fetchone() + if head is None: + return None + metric_rows = conn.execute( + "SELECT metric, kind, month, value FROM goal_metrics WHERE year = %s", (year,) + ).fetchall() + area_rows = conn.execute( + "SELECT id, name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id", + (year,), + ).fetchall() + row_rows = conn.execute( + "SELECT r.id, r.area_id, r.label 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,), + ).fetchall() + cell_rows = conn.execute( + "SELECT c.row_id, c.month, c.body FROM goal_cells c " + "JOIN goal_rows r ON r.id = c.row_id JOIN goal_areas a ON a.id = r.area_id " + "WHERE a.year = %s", + (year,), + ).fetchall() + metrics: dict[str, dict[str, dict[int, float]]] = { + m: {k: {} for k in store.GOAL_KINDS} for m in store.GOAL_METRICS + } + for r in metric_rows: + metrics[r["metric"]][r["kind"]][int(r["month"])] = float(r["value"]) + cells: dict[int, dict[int, str]] = {} + for c in cell_rows: + cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"] + rows_by_area: dict[int, list[dict[str, Any]]] = {} + for r in row_rows: + rows_by_area.setdefault(int(r["area_id"]), []).append( + {"id": int(r["id"]), "label": r["label"], "cells": cells.get(int(r["id"]), {})} + ) + areas = [ + {"id": int(a["id"]), "name": a["name"], "color": a["color"], + "rows": rows_by_area.get(int(a["id"]), [])} + for a in area_rows + ] + return {"year": int(head["year"]), "sales_unit": head["sales_unit"], + "metrics": metrics, "areas": areas} + + def set_goal_metric( + self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = "" + ) -> None: + if metric not in store.GOAL_METRICS or kind not in store.GOAL_KINDS: + raise ValueError("지표 종류가 올바르지 않습니다.") + m = store.validate_goal_month(month) + with self._pool.connection() as conn: + if not conn.execute("SELECT 1 FROM goal_years WHERE year = %s", (year,)).fetchone(): + raise KeyError(year) + if value is None: + conn.execute( + "DELETE FROM goal_metrics WHERE year=%s AND metric=%s AND kind=%s AND month=%s", + (year, metric, kind, m), + ) + else: + conn.execute( + "INSERT INTO goal_metrics (year, metric, kind, month, value, updated_by) " + "VALUES (%s,%s,%s,%s,%s,%s) " + "ON CONFLICT (year, metric, kind, month) DO UPDATE " + "SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()", + (year, metric, kind, m, value, store.norm_str(updated_by, lower=True)), + ) + + def add_goal_area(self, *, year: int, name: str, color: str = "") -> int: + nm = store.validate_goal_area_name(name) + col = store.validate_goal_color(color) + with self._pool.connection() as conn: + with conn.transaction(): + if not conn.execute("SELECT 1 FROM goal_years WHERE year = %s", (year,)).fetchone(): + raise KeyError(year) + aid = conn.execute( + "INSERT INTO goal_areas (year, name, color, sort_order) VALUES (%s, %s, %s, " + "(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_areas WHERE year = %s)) " + "RETURNING id", + (year, nm, col, year), + ).fetchone()["id"] + conn.execute("INSERT INTO goal_rows (area_id, label) VALUES (%s, '')", (aid,)) + return int(aid) + + def update_goal_area(self, *, area_id: int, fields: dict[str, Any]) -> None: + sets: list[str] = [] + params: list[Any] = [] + if "name" in fields: + sets.append("name = %s") + params.append(store.validate_goal_area_name(fields["name"])) + if "color" in fields: + sets.append("color = %s") + params.append(store.validate_goal_color(fields["color"])) + if not sets: + return + with self._pool.connection() as conn: + row = conn.execute( + f"UPDATE goal_areas SET {', '.join(sets)} WHERE id = %s RETURNING id", + (*params, area_id), + ).fetchone() + if row is None: + raise KeyError(area_id) + + def delete_goal_area(self, *, area_id: int) -> None: + with self._pool.connection() as conn: + row = conn.execute("DELETE FROM goal_areas WHERE id = %s RETURNING id", (area_id,)).fetchone() + if row is None: + raise KeyError(area_id) + + def _move_goal_item(self, table: str, parent_col: str, item_id: int, direction: int) -> None: + """영역(연도 안)·줄(영역 안) 순서를 한 칸 위/아래로 — 같은 부모 안에서 번호를 다시 매긴다.""" + with self._pool.connection() as conn: + with conn.transaction(): + me = conn.execute( + f"SELECT {parent_col} AS p FROM {table} WHERE id = %s", (item_id,) + ).fetchone() + if me is None: + raise KeyError(item_id) + ids = [int(r["id"]) for r in conn.execute( + f"SELECT id FROM {table} WHERE {parent_col} = %s ORDER BY sort_order, id", + (me["p"],), + ).fetchall()] + i = ids.index(item_id) + j = i + (1 if direction > 0 else -1) + if not 0 <= j < len(ids): + return + ids[i], ids[j] = ids[j], ids[i] + for n, x in enumerate(ids): + conn.execute(f"UPDATE {table} SET sort_order = %s WHERE id = %s", (n, x)) + + def move_goal_area(self, *, area_id: int, direction: int) -> None: + self._move_goal_item("goal_areas", "year", area_id, direction) + + def move_goal_row(self, *, row_id: int, direction: int) -> None: + self._move_goal_item("goal_rows", "area_id", row_id, direction) + + def add_goal_row(self, *, area_id: int, label: str = "") -> int: + lb = store.validate_goal_row_label(label) + with self._pool.connection() as conn: + if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s", (area_id,)).fetchone(): + raise KeyError(area_id) + rid = conn.execute( + "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, " + "(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_rows WHERE area_id = %s)) " + "RETURNING id", + (area_id, lb, area_id), + ).fetchone()["id"] + return int(rid) + + def update_goal_row(self, *, row_id: int, label: str) -> None: + lb = store.validate_goal_row_label(label) + with self._pool.connection() as conn: + row = conn.execute( + "UPDATE goal_rows SET label = %s WHERE id = %s RETURNING id", (lb, row_id) + ).fetchone() + if row is None: + raise KeyError(row_id) + + def delete_goal_row(self, *, row_id: int) -> None: + """줄 삭제 — 영역의 마지막 한 줄은 지울 수 없다(영역을 지운다).""" + with self._pool.connection() as conn: + with conn.transaction(): + me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone() + if me is None: + raise KeyError(row_id) + n = conn.execute( + "SELECT count(*) AS n FROM goal_rows WHERE area_id = %s", (me["area_id"],) + ).fetchone()["n"] + if n <= 1: + raise ValueError("업무 영역의 마지막 줄은 지울 수 없습니다. 영역을 삭제하세요.") + conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,)) + + 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) + 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 not text: + conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m)) + else: + conn.execute( + "INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s) " + "ON CONFLICT (row_id, month) DO UPDATE " + "SET body = EXCLUDED.body, updated_by = EXCLUDED.updated_by, updated_at = now()", + (row_id, m, text, store.norm_str(updated_by, lower=True)), + ) + # ════════════════════════════════════════════════════════════ # 직렬화 # ════════════════════════════════════════════════════════════ diff --git a/app/modules/project/router.py b/app/modules/project/router.py index e1baf60..6b3c735 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -42,7 +42,7 @@ from fastapi.responses import ( JSONResponse, RedirectResponse, ) -from psycopg.errors import UndefinedColumn +from psycopg.errors import UndefinedColumn, UndefinedTable from app.timezone import KST, now_kst, today_kst @@ -393,6 +393,22 @@ def _nav_projects(st: Any, user: dict[str, Any], admin: bool) -> list[dict[str, ] +def _goal_years_nav(st: Any) -> list[int]: + """좌측 사이드바 "목표" 아래 연도 목록(최근 연도 먼저). 올해는 목표를 아직 안 + 만들었어도 항상 보인다(누르면 관리자에게 "목표 만들기"). 013 미적용이면 올해만.""" + this_year = today_kst().year + try: + years = st.list_goal_years() + except UndefinedTable: + years = [] + except Exception: # noqa: BLE001 — 사이드바 때문에 화면 전체가 죽지 않게 + logger.exception("goal years 조회 실패") + years = [] + if this_year not in years: + years.append(this_year) + return sorted(set(years), reverse=True) + + def _build_tree(projects: list[dict[str, Any]]) -> list[dict[str, Any]]: """평면 프로젝트 목록 → parent_id 기준 트리(children 키).""" by_id: dict[int, dict[str, Any]] = {} @@ -582,6 +598,7 @@ def my_tasks_page(request: Request) -> HTMLResponse: "page_subtitle": "내가 담당자인 작업을 한 곳에서 봅니다.", "force_sidebar_collapsed": True, "nav_projects": nav_projects, + "goal_years": _goal_years_nav(st), "my_tasks": my_tasks, "my_open_total": my_open_total, "mention_unread": _safe_mention_unread(st, user["email"]), @@ -791,6 +808,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse: "my_open_total": my_open_total, "mention_unread": mention_unread, "nav_projects": nav_projects, + "goal_years": _goal_years_nav(st), "stages": stages, "tasks": all_tasks, "members": members, @@ -2067,6 +2085,7 @@ def trash_page(request: Request) -> HTMLResponse: "is_admin": True, "nav_items": build_erp_nav(user, active="project"), "nav_projects": _nav_projects(st, user, True), + "goal_years": _goal_years_nav(st), "my_open_total": st.count_my_open(assignee_email=user["email"]), "mention_unread": _safe_mention_unread(st, user["email"]), "page_title": "휴지통", @@ -2162,6 +2181,7 @@ def inbox_page(request: Request) -> HTMLResponse: "is_admin": admin, "nav_items": build_erp_nav(user, active="project"), "nav_projects": nav_projects, + "goal_years": _goal_years_nav(st), "my_open_total": my_open_total, "page_title": "수신함", "page_subtitle": "나를 태그한 작업과 프로젝트 알림", @@ -2173,3 +2193,207 @@ def inbox_page(request: Request) -> HTMLResponse: "mention_unread": _safe_mention_unread(st, user["email"]), }, ) + + +# ──────────────────────────────────────────────────────────── +# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 → 목표 표 +# 조회: project 권한자 전원 · 입력/구조 변경: 관리자(is_admin) 전용 +# ──────────────────────────────────────────────────────────── +_GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)." + + +def _fmt_goal_num(v: float | None) -> str: + """지표 숫자 표시 — 천 단위 쉼표, 소수는 필요한 만큼만(12.50 → 12.5).""" + if v is None: + return "" + if float(v).is_integer(): + return f"{int(v):,}" + return f"{v:,.2f}".rstrip("0").rstrip(".") + + +def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any: + """목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400.""" + try: + return fn(*args, **kwargs) + except UndefinedTable: + raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG) + except KeyError: + raise HTTPException(status_code=404, detail="대상을 찾을 수 없습니다. 새로고침해 주세요.") + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + + +@router.get("/goals") +def goals_home(request: Request) -> RedirectResponse: + """사이드바 "목표" 자체 주소 — 가장 최근 연도(없으면 올해)로.""" + _require_user(request) + st = _store(request) + years = _goal_years_nav(st) if st is not None else [today_kst().year] + return RedirectResponse(url=f"/project/goals/{years[0]}", status_code=303) + + +@router.get("/goals/{year}", response_class=HTMLResponse) +def goals_page(request: Request, year: int) -> HTMLResponse: + """한 해 전체 목표 — 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자 + + 업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글. 입력은 관리자만.""" + from app.main import build_erp_nav, render_template # noqa: WPS433 + from app.store import is_admin # noqa: WPS433 + + user = _require_user(request) + st = _store(request) + if st is None: + return _render_config_needed(request, user) + if not 2000 <= year <= 2100: + raise HTTPException(status_code=404, detail="연도가 올바르지 않습니다.") + 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() + return render_template( + request, + "project/goals.html", + { + "user": user, + "is_admin": admin, + "nav_items": build_erp_nav(user, active="project"), + "nav_projects": _nav_projects(st, user, admin), + "goal_years": _goal_years_nav(st), + "goal_year_active": year, + "my_open_total": st.count_my_open(assignee_email=user["email"]), + "mention_unread": _safe_mention_unread(st, user["email"]), + "page_title": f"{year}년 목표", + "page_subtitle": "한 해 전체 목표와 업무 영역별 계획", + "force_sidebar_collapsed": True, + "color_palette": list(store.COLOR_PALETTE), + "project_icons": list(store.PROJECT_ICONS), + "goals_enabled": enabled, + "goal_year": year, + "board": board, + "months": list(range(1, 13)), + "this_month": today.month if today.year == year else 0, + "goal_area_colors": list(store.GOAL_AREA_COLORS), + }, + ) + + +@router.post("/api/goals/years") +def api_create_goal_year(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """연도 추가(관리자) — 가장 가까운 이전 연도의 영역·줄 구조를 글 없이 복사.""" + user = _require_admin(request) + st = _db_or_503(request) + y = _goal_call(store.validate_goal_year, payload.get("year")) + _goal_call(st.create_goal_year, year=y, created_by=user["email"]) + return JSONResponse({"ok": True, "year": y}, status_code=201) + + +@router.put("/api/goals/{year}") +def api_update_goal_year(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.update_goal_year, year=year, sales_unit=payload.get("sales_unit", "")) + return JSONResponse({"ok": True}) + + +@router.delete("/api/goals/{year}") +def api_delete_goal_year(request: Request, year: int) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.delete_goal_year, year=year) + return JSONResponse({"ok": True}) + + +@router.put("/api/goals/{year}/metrics") +def api_set_goal_metric(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """매출/로아스 목표·실적 한 칸 — {metric, kind, month, value}. value 빈값 = 지움.""" + user = _require_admin(request) + st = _db_or_503(request) + value = _goal_call(store.validate_goal_value, payload.get("value")) + _goal_call( + st.set_goal_metric, year=year, metric=str(payload.get("metric") or ""), + 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)}) + + +@router.post("/api/goals/{year}/areas") +def api_add_goal_area(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + aid = _goal_call(st.add_goal_area, year=year, name=payload.get("name", ""), color=payload.get("color", "")) + return JSONResponse({"ok": True, "id": aid}, status_code=201) + + +@router.put("/api/goals/areas/{area_id}") +def api_update_goal_area(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + fields = {k: payload[k] for k in ("name", "color") if k in payload} + _goal_call(st.update_goal_area, area_id=area_id, fields=fields) + return JSONResponse({"ok": True}) + + +@router.delete("/api/goals/areas/{area_id}") +def api_delete_goal_area(request: Request, area_id: int) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.delete_goal_area, area_id=area_id) + return JSONResponse({"ok": True}) + + +@router.post("/api/goals/areas/{area_id}/move") +def api_move_goal_area(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.move_goal_area, area_id=area_id, direction=int(payload.get("direction") or 0)) + return JSONResponse({"ok": True}) + + +@router.post("/api/goals/areas/{area_id}/rows") +def api_add_goal_row(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", "")) + return JSONResponse({"ok": True, "id": rid}, status_code=201) + + +@router.put("/api/goals/rows/{row_id}") +def api_update_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.update_goal_row, row_id=row_id, label=payload.get("label", "")) + return JSONResponse({"ok": True}) + + +@router.delete("/api/goals/rows/{row_id}") +def api_delete_goal_row(request: Request, row_id: int) -> JSONResponse: + _require_admin(request) + st = _db_or_503(request) + _goal_call(st.delete_goal_row, row_id=row_id) + return JSONResponse({"ok": True}) + + +@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) + st = _db_or_503(request) + _goal_call(st.move_goal_row, row_id=row_id, direction=int(payload.get("direction") or 0)) + return JSONResponse({"ok": True}) + + +@router.put("/api/goals/rows/{row_id}/cells/{month}") +def api_set_goal_cell( + request: Request, row_id: int, month: int, payload: dict[str, Any] = Body(...) +) -> JSONResponse: + """업무 영역 칸 글 — month 0 = 연간, 1~12 = 월. 빈 글 = 지움.""" + user = _require_admin(request) + st = _db_or_503(request) + _goal_call( + st.set_goal_cell, row_id=row_id, month=month, + body=payload.get("body", ""), updated_by=user["email"], + ) + return JSONResponse({"ok": True}) diff --git a/app/modules/project/store.py b/app/modules/project/store.py index f7a679e..a93eb8a 100644 --- a/app/modules/project/store.py +++ b/app/modules/project/store.py @@ -329,6 +329,89 @@ def validate_time(t: Any) -> str | None: return f"{hh:02d}:{mm:02d}" +# ════════════════════════════════════════════════════════════ +# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 +# ════════════════════════════════════════════════════════════ +GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스 +GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적 +# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색만(글자는 항상 진한 색). +GOAL_AREA_COLORS: tuple[str, ...] = ( + "#fbe1d5", "#d9f2d0", "#d4d4d4", "#f0cdec", + "#dbe8fb", "#fff2c2", "#e3dcfb", "#d3f0ee", +) +# 새 연도를 만들 때 이전 연도가 없으면 이 영역으로 시작한다(이전 연도가 있으면 그 구조를 복사). +DEFAULT_GOAL_AREAS: tuple[tuple[str, str, tuple[str, ...]], ...] = ( + ("상품", "#fbe1d5", ("",)), + ("마케팅", "#d9f2d0", ("",)), + ("컨텐츠", "#d4d4d4", ("",)), + ("유통", "#f0cdec", ("콜라보", "인플", "쿠팡", "기타")), +) +GOAL_TEXT_MAX = 4000 + + +def validate_goal_year(y: Any) -> int: + try: + v = int(str(y).strip()) + except (TypeError, ValueError): + raise ValueError("연도가 올바르지 않습니다.") + if not 2000 <= v <= 2100: + raise ValueError("연도는 2000 ~ 2100 사이여야 합니다.") + return v + + +def validate_goal_month(m: Any, *, allow_year: bool = False) -> int: + """1~12월. allow_year 이면 0(연간)도 허용.""" + try: + v = int(m) + except (TypeError, ValueError): + raise ValueError("월이 올바르지 않습니다.") + if not ((0 if allow_year else 1) <= v <= 12): + raise ValueError("월이 올바르지 않습니다.") + return v + + +def validate_goal_value(v: Any) -> float | None: + """지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움).""" + s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "") + if not s: + return None + try: + f = float(s) + except ValueError: + raise ValueError(f"숫자가 아닙니다: {v}") + if f != f or abs(f) >= 1e16: # NaN · NUMERIC(18,2) 범위 밖 + raise ValueError(f"숫자 범위를 벗어났습니다: {v}") + return round(f, 2) + + +def validate_goal_area_name(name: Any) -> str: + v = norm_str(name) + if not v: + raise ValueError("업무 영역 이름을 입력하세요.") + if len(v) > 50: + raise ValueError("업무 영역 이름은 50자 이하로 입력하세요.") + return v + + +def validate_goal_row_label(label: Any) -> str: + v = norm_str(label) + if len(v) > 50: + raise ValueError("줄 이름은 50자 이하로 입력하세요.") + return v + + +def validate_goal_color(color: Any) -> str: + v = norm_str(color).lower() + return v if v in GOAL_AREA_COLORS else GOAL_AREA_COLORS[0] + + +def validate_goal_text(body: Any) -> str: + v = str(body or "").replace("\r\n", "\n").strip() + if len(v) > GOAL_TEXT_MAX: + raise ValueError(f"칸 하나에 {GOAL_TEXT_MAX}자까지 쓸 수 있습니다.") + return v + + def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str: return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}" diff --git a/app/modules/project/templates/project/_side.html b/app/modules/project/templates/project/_side.html index 31d80f0..a8dd22c 100644 --- a/app/modules/project/templates/project/_side.html +++ b/app/modules/project/templates/project/_side.html @@ -7,7 +7,9 @@ my_open_total 진행 중인 내 업무 개수 (내 업무 배지) nav_projects 프로젝트 목록(평면) current_pid 지금 보고 있는 프로젝트 id (내 업무/수신함 화면이면 0) - side_active 'inbox' | 'mytasks' | 'trash' | '' — 개인 메뉴 활성 표시 + side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시 + goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함) + goal_year_active 목표 화면에서 보고 있는 연도 is_admin 프로젝트 생성/수정/삭제 권한 목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림), 새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #} @@ -46,6 +48,29 @@ 휴지통 {% endif %} + {# 목표 — 누르면 바로 아래에 연도가 펼쳐지고, 연도를 누르면 오른쪽에 그해 전체 목표 + (/project/goals/{연도}). 펼침 상태는 localStorage(pj_goal_open), 목표 화면에서는 항상 펼침. + 연도 추가는 관리자만(마이그레이션 013). #} + {% set goal_open = side_active == 'goals' %} +
{{ goal_year }}년 목표가 아직 없습니다.
+ {% if is_admin %} +만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).
+ + {% endif %} +| + | + | 연간 | + {% for mo in months %}{{ mo }}월 | {% endfor %} +
|---|---|---|---|
| 매출 | +목표 | ++ {% for mo in months %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %} + | |
| 실적 | ++ {% for mo in months %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %} + | ||
| 달성 | ++ {% for mo in months %} | {% endfor %} + | |
| 로아스 | +목표 | ++ {% for mo in months %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %} + | |
| 실적 | ++ {% for mo in months %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %} + | ||
| + {{ area.name }} + {% if is_admin %} + + + + + + + + + {% endif %} + | + {% endif %} ++ {{ row.label }} + {% if is_admin %} + + + {% if area.rows | length > 1 %} + + + + {% endif %} + + {% endif %} + | + {% for mo in [0] + months %} +
+ {%- if is_admin -%}
+
+ {%- else -%}
+ {{ row.cells.get(mo, '') }}
+ {%- endif -%}
+ |
+ {% endfor %}
+