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' %} +
+ +
+ {% for y in (goal_years or []) %} + {{ y }}년 + {% endfor %} + {% if is_admin %} + + {% endif %} +
+
diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html new file mode 100644 index 0000000..daaf8e6 --- /dev/null +++ b/app/modules/project/templates/project/goals.html @@ -0,0 +1,172 @@ +{% extends "erp_base.html" %} + +{% block head_extra %} + + +{% endblock %} + +{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %} + +{% block content %} +{# 연간 목표 — 좌측 사이드바 "목표" → 연도. 스프레드시트처럼 한 표에 + ① 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자 + ② 업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글. + 입력·구조 변경은 관리자만(칸별 즉시 저장, project.js initGoals), 나머지는 보기만. + DB: project_db 013 (goal_years·goal_metrics·goal_areas·goal_rows·goal_cells). #} +
+
+ {% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %} + +
+
+

{{ goal_year }}년 목표

+ {% if board %} +
+ {% if is_admin %} + + + {% else %} + {% if board.sales_unit %}매출 단위: {{ board.sales_unit }}{% endif %} + 목표는 관리자만 입력할 수 있습니다. + {% endif %} +
+ {% endif %} +
+ +
+ {% if not goals_enabled %} +
연간 목표가 아직 준비되지 않았습니다(DB 마이그레이션 013 필요).
+ {% elif not board %} +
+

{{ goal_year }}년 목표가 아직 없습니다.

+ {% if is_admin %} +

만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).

+ + {% endif %} +
+ {% else %} + {% set sm = board.metrics.sales %} + {% set rm = board.metrics.roas %} + {% macro num_cell(metric, kind, labels, mo) -%} + + {%- if is_admin -%} + + {%- else -%} + {{ labels.get(mo, '') }} + {%- endif -%} + + {%- endmacro %} + + + + + + + {% for mo in months %}{% 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 %} + + + + {# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #} + {% for area in board.areas %} + + {% for row in area.rows %} + + {% if loop.first %} + + {% endif %} + + {% for mo in [0] + months %} + + {% endfor %} + + {% endfor %} + + {% endfor %} +
연간{{ mo }}월
매출목표
실적
달성
로아스목표
실적
+ {{ area.name }} + {% if is_admin %} + + + + + + + + + {% endif %} + + {{ row.label }} + {% if is_admin %} + + + {% if area.rows | length > 1 %} + + + + {% endif %} + + {% endif %} + + {%- if is_admin -%} + + {%- else -%} +
{{ row.cells.get(mo, '') }}
+ {%- endif -%} +
+ {% if is_admin %} +
+ + 칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다. +
+ {% endif %} + {% endif %} +
+
+
+
+ +{% if goal_area_colors %}{% endif %} +{% 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 3828098..7facd9b 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 %} @@ -79,7 +79,7 @@

2화면 구성

왼쪽 사이드바

@@ -88,6 +88,11 @@
  • 수신함 — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (17장)
  • 내 작업 — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (15장)
  • 휴지통 — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (19장)
  • +
  • 목표 — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 — + 맨 위에 매출(목표·실적·달성률)과 로아스(목표·실적)를 달마다, 그 아래에 업무 영역(상품·마케팅·컨텐츠·유통 등)별로 + 연간·월별 계획을 적습니다. 매출의 연간 칸은 월 합계, 달성은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다. + 입력은 관리자만 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 + 연도 추가로 새해 목표를 + 만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역 이름 칸에 마우스를 올려 이름·색·순서·줄 추가·삭제를 합니다.
  • 프로젝트 — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 완료 프로젝트에 흐리게 모입니다.
  • 전체 멤버 — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.
  • @@ -116,6 +121,7 @@ 새 프로젝트, 프로젝트 수정·순서 바꾸기관리자 (+ · ✎ · ⣿ 버튼이 관리자에게만 보입니다) 멤버 배정·제외관리자 휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트관리자 + 목표 보기누구나 · 목표 입력·연도 추가·업무 영역 편집은 관리자 diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index 7418c64..5311b0d 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 13c2c37..2df7941 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 7db443f..1b92792 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 %} - + @@ -491,5 +491,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index 242c653..e5c5b54 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 a15dd02..2fb8502 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -1971,3 +1971,112 @@ html.pj-ui-scale .pj-task-modal-card { height: calc(100vh / var(--pj-z)); max-he html.pj-ui-scale .pj-modal-card { max-height: calc(90vh / var(--pj-z)); } html.pj-ui-scale .pj-mt-list { max-height: calc(50vh / var(--pj-z)); } html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); } + +/* ════════════════════════════════════════════════════════════ + 연간 목표 — 사이드바 "목표"(연도 펼침) + /project/goals/{연도} 표 + ════════════════════════════════════════════════════════════ */ +.pj-side-goal-caret { margin-left: auto; font-size: 18px; color: #8a9099; transition: transform .15s; } +.pj-side-goal.is-open .pj-side-goal-caret { transform: rotate(180deg); } +.pj-side-goal-years { display: flex; flex-direction: column; gap: 1px; padding: 2px 0 4px 37px; } +.pj-side-goal-years[hidden] { display: none; } +.pj-side-goal-year { + display: block; padding: 5px 8px; border-radius: 6px; font-size: 13px; font-weight: 600; + color: var(--pj-ink); text-decoration: none; +} +.pj-side-goal-year:hover { background: #f1f2f4; } +.pj-side-goal-year.is-active { background: var(--pj-accent-tint); color: var(--pj-accent-dark); } +.pj-side-goal-add { + align-self: flex-start; margin-top: 2px; padding: 4px 8px; border: none; background: transparent; + border-radius: 6px; color: var(--pj-ink-soft); font-size: 12.5px; cursor: pointer; +} +.pj-side-goal-add:hover { background: #f1f2f4; color: var(--pj-ink); } + +/* 표는 화면 폭 전체 — 내 작업·수신함의 읽기 폭 제한(1180px)을 푼다 */ +.pj-goal-view .pj-main { max-width: none; } +.pj-goal-head-acts { display: flex; align-items: center; gap: 10px; } +.pj-goal-unit { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--pj-ink-soft); } +.pj-goal-unit input { + width: 96px; height: 30px; padding: 0 8px; border: 1px solid var(--pj-border); border-radius: 7px; + font-size: 13px; color: var(--pj-ink); +} +.pj-goal-unit-ro { font-size: 12.5px; color: var(--pj-ink); } +.pj-goal-note { font-size: 12px; color: var(--pj-ink-soft); } +.pj-goal-empty p { margin: 0 0 10px; } +.pj-goal-empty-sub { font-size: 12.5px; } + +/* 가로·세로 스크롤은 이 칸 하나가 맡고, 머리 줄과 왼쪽 두 칸(구분·항목)은 붙어 있다 */ +.pj-goal-pane { flex: 1 1 auto; min-height: 0; overflow: auto; } +.pj-goal-table { + 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; +} +.pj-goal-table th, .pj-goal-table td { + border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top; +} +.pj-goal-table tr > :last-child { border-right: none; } +.pj-goal-table thead th { + position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 10px; + font-weight: 700; text-align: left; vertical-align: middle; white-space: nowrap; +} +.pj-goal-table thead th:not(.pj-goal-c1):not(.pj-goal-c2) { width: 150px; min-width: 150px; } +.pj-goal-table thead th.pj-goal-year-col { width: 210px; min-width: 210px; } +.pj-goal-table thead th.is-now { color: var(--pj-accent-dark); box-shadow: inset 0 -2px 0 var(--pj-accent); } +.pj-goal-c1, .pj-goal-c2 { + position: sticky; z-index: 2; width: 72px; min-width: 72px; max-width: 72px; + background: #fff; text-align: left; font-weight: 700; +} +.pj-goal-c1 { left: 0; } +.pj-goal-c2 { left: 72px; font-weight: 600; color: #3b4048; } +.pj-goal-table thead .pj-goal-c1, .pj-goal-table thead .pj-goal-c2 { z-index: 4; } +.pj-goal-table tbody th { padding: 7px 8px; } + +/* 숫자 지표 */ +.pj-goal-kpi td { height: 32px; vertical-align: middle; } +.pj-goal-kpi td.is-now { background: #faf9ff; } +input.pj-goal-num, span.pj-goal-num { + display: block; width: 100%; box-sizing: border-box; height: 32px; padding: 0 10px; border: none; + background: transparent; font: inherit; font-variant-numeric: tabular-nums; text-align: right; line-height: 32px; +} +input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: #fff; } +.pj-goal-sum { padding: 0 10px !important; text-align: right; font-weight: 700; background: #fafafb; + font-variant-numeric: tabular-nums; } +.pj-goal-rate { padding: 0 10px !important; text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; } +.pj-goal-rate.is-good { color: #1f8a4c; } +.pj-goal-rate.is-low { color: #c2410c; } +.pj-goal-kpi tr:last-child > * { border-bottom: 2px solid #d5d9de; } + +/* 업무 영역 — 영역 색(--goal-bg)이 줄 전체 배경(스프레드시트처럼) */ +.pj-goal-area > tr > th, .pj-goal-area > tr > td { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); } +.pj-goal-area > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); } +.pj-goal-area-name { font-size: 13px; font-weight: 800 !important; } +.pj-goal-area-text, .pj-goal-row-text { display: block; word-break: keep-all; overflow-wrap: anywhere; } +.pj-goal-tools { display: flex; flex-wrap: wrap; gap: 0; margin-top: 4px; opacity: 0; transition: opacity .12s; } +.pj-goal-area-name:hover .pj-goal-tools, .pj-goal-row-label:hover .pj-goal-tools, +.pj-goal-tools:focus-within { opacity: 1; } +.pj-goal-tools .pj-icon-btn { width: 20px; height: 20px; font-size: 13px; } +.pj-goal-tools .pj-icon-btn .material-symbols-outlined { font-size: 15px; } +.pj-goal-tools .pj-icon-btn:hover { background: rgba(255, 255, 255, .7); } +textarea.pj-goal-text { + display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 7px 9px; border: none; + background: transparent; font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden; +} +textarea.pj-goal-text:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .75); } +textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); } +.pj-goal-text-ro { min-height: 46px; padding: 7px 9px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; } +.pj-goal-area td.is-now { box-shadow: inset 2px 0 0 rgba(123, 104, 238, .35), inset -2px 0 0 rgba(123, 104, 238, .35); } +.pj-goal-texttd.pj-goal-year-col { font-weight: 600; } + +.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-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; } + +/* 영역 색 고르기 팝업(body 에 붙음) */ +.pj-goal-colorpop { + position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(4, 26px); gap: 6px; + padding: 10px; background: #fff; border: 1px solid var(--pj-border); border-radius: 10px; + box-shadow: 0 8px 24px rgba(16, 24, 40, .16); +} +.pj-goal-swatch { width: 26px; height: 26px; border-radius: 6px; border: 1px solid rgba(0, 0, 0, .12); cursor: pointer; padding: 0; } +.pj-goal-swatch:hover { transform: scale(1.08); } +.pj-goal-swatch.is-on { outline: 2px solid var(--pj-accent); outline-offset: 1px; } diff --git a/app/static/project.js b/app/static/project.js index ab533e9..c551a7c 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -7397,6 +7397,311 @@ document.addEventListener("mouseleave", hide); } + // ── 사이드바 "목표" — 누르면 바로 아래 연도 목록을 접었다 편다(localStorage pj_goal_open). + // 목표 화면에서는 항상 펼친 채로 시작(data-force-open). 관리자는 "+ 연도 추가". + function initGoalSide() { + const box = el("pj-side-goal"); + if (!box) return; + const btn = el("pj-side-goal-toggle"); + const list = el("pj-side-goal-years"); + function setOpen(open, remember) { + list.hidden = !open; + box.classList.toggle("is-open", open); + btn.setAttribute("aria-expanded", open ? "true" : "false"); + if (remember) { try { localStorage.setItem("pj_goal_open", open ? "1" : "0"); } catch (_) {} } + } + if (box.dataset.forceOpen !== "true") { + let saved = null; + try { saved = localStorage.getItem("pj_goal_open"); } catch (_) {} + if (saved === "1") setOpen(true, false); + } + btn.addEventListener("click", function () { setOpen(list.hidden, true); }); + const add = el("pj-goal-year-add"); + if (add) add.addEventListener("click", async function () { + const v = await prompt("추가할 연도를 입력하세요.", add.dataset.next || ""); + if (v == null || !String(v).trim()) return; + try { + const res = await api("POST", "/project/api/goals/years", { year: String(v).trim() }); + location.href = "/project/goals/" + res.year; + } catch (e) { showToast("연도 추가 실패: " + e.message, "error"); } + }); + } + + // ── 연간 목표 화면(/project/goals/{연도}) — 관리자만 입력, 칸마다 바로 저장. + // · 숫자(매출/로아스 목표·실적): 칸을 떠나거나 Enter 에 저장, 서버가 돌려준 표기(쉼표)로 바꿈. + // 매출 연간 합계와 달성률(실적÷목표)은 화면에서 계산. + // · 업무 영역 글: 치는 동안 0.8초 멈추면 저장, 칸을 떠날 때·페이지를 떠날 때도 저장. + // · 영역/줄 추가·이름·순서·삭제는 저장 후 새로고침(스크롤 위치는 되살림). + function initGoals() { + const pane = el("pj-goal-pane"); + if (!pane) return; + const SCROLL_KEY = "pj_goal_scroll"; + function reloadKeepScroll() { + try { sessionStorage.setItem(SCROLL_KEY, JSON.stringify([location.pathname, pane.scrollLeft, pane.scrollTop])); } catch (_) {} + location.reload(); + } + try { + const s = JSON.parse(sessionStorage.getItem(SCROLL_KEY) || "null"); + sessionStorage.removeItem(SCROLL_KEY); + if (s && s[0] === location.pathname) { pane.scrollLeft = s[1]; pane.scrollTop = s[2]; } + } catch (_) {} + + const create = el("pj-goal-create"); + if (create) create.addEventListener("click", async function () { + create.disabled = true; + try { + await api("POST", "/project/api/goals/years", { year: create.dataset.year }); + location.reload(); + } catch (e) { create.disabled = false; showToast("만들기 실패: " + e.message, "error"); } + }); + + const table = el("pj-goal-table"); + if (!table) return; + const year = table.dataset.year; + const isAdmin = table.dataset.admin === "true"; + + // ── 합계·달성률 ── + function numOf(node) { + const raw = (node.tagName === "INPUT" ? node.value : node.textContent) || ""; + const s = raw.replace(/[,%\s]/g, ""); + if (!s) return null; + const n = Number(s); + return isFinite(n) ? n : null; + } + function fmtNum(n) { + return (Math.round(n * 100) / 100).toLocaleString("ko-KR", { maximumFractionDigits: 2 }); + } + function values(metric, kind) { + const out = {}; + table.querySelectorAll('.pj-goal-num[data-metric="' + metric + '"][data-kind="' + kind + '"]') + .forEach(function (n) { out[n.dataset.month] = numOf(n); }); + return out; + } + function setRate(td, actual, target) { + td.classList.remove("is-good", "is-low"); + if (actual == null || !target) { td.textContent = ""; return; } + const r = actual / target * 100; + td.textContent = (Math.round(r * 10) / 10).toLocaleString("ko-KR") + "%"; + td.classList.add(r >= 100 ? "is-good" : "is-low"); + } + 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 ? "실적이 있는 달의 목표 합계 대비" : ""; + } + recompute(); + if (!isAdmin) return; + + // ── 숫자 칸 ── + table.querySelectorAll("input.pj-goal-num").forEach(function (inp) { + inp.dataset.saved = inp.value; + inp.addEventListener("focus", function () { inp.select(); }); + inp.addEventListener("input", recompute); + inp.addEventListener("keydown", function (e) { + if (e.key === "Enter") { e.preventDefault(); inp.blur(); } + else if (e.key === "Escape") { inp.value = inp.dataset.saved; recompute(); inp.blur(); } + }); + inp.addEventListener("change", async function () { + const d = inp.dataset; + try { + const res = await api("PUT", "/project/api/goals/" + year + "/metrics", + { metric: d.metric, kind: d.kind, month: parseInt(d.month, 10), value: inp.value }); + inp.value = res.label; + d.saved = res.label; + flashSaved(inp.parentElement); + } catch (e) { + inp.value = d.saved; + showToast("저장 실패: " + e.message, "error"); + } + recompute(); + }); + }); + + function flashSaved(node) { + node.classList.remove("is-saved"); + void node.offsetWidth; + node.classList.add("is-saved"); + } + + // ── 글 칸 ── + 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) { + clearTimeout(pending.get(ta)); + pending.delete(ta); + const body = ta.value; + if (body === ta.dataset.saved) return; + try { + await api("PUT", cellUrl(ta), { body: body }); + ta.dataset.saved = body; + flashSaved(ta.parentElement); + } catch (e) { showToast("저장 실패: " + e.message, "error"); } + } + table.querySelectorAll("textarea.pj-goal-text").forEach(function (ta) { + ta.dataset.saved = ta.value; + fit(ta); + ta.addEventListener("input", function () { + fit(ta); + clearTimeout(pending.get(ta)); + pending.set(ta, setTimeout(function () { saveText(ta); }, 800)); + }); + ta.addEventListener("blur", function () { saveText(ta); }); + }); + // 한 줄 안 칸들 높이는 표가 맞춘다 — 창 폭이 바뀌면 글 줄바꿈이 달라지니 다시 잰다. + window.addEventListener("resize", function () { + table.querySelectorAll("textarea.pj-goal-text").forEach(fit); + }); + window.addEventListener("beforeunload", function () { + pending.forEach(function (timer, ta) { + clearTimeout(timer); + if (ta.value === ta.dataset.saved) return; + try { + fetch(cellUrl(ta), { + method: "PUT", keepalive: true, headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ body: ta.value }), + }); + } catch (_) {} + }); + }); + + // ── 머리 — 매출 단위 · 연도 삭제 ── + const unit = el("pj-goal-unit"); + if (unit) { + unit.dataset.saved = unit.value; + unit.addEventListener("keydown", function (e) { if (e.key === "Enter") unit.blur(); }); + unit.addEventListener("change", async function () { + try { + await api("PUT", "/project/api/goals/" + year, { sales_unit: unit.value }); + unit.dataset.saved = unit.value; + showToast("매출 단위를 저장했습니다."); + } catch (e) { unit.value = unit.dataset.saved; showToast("저장 실패: " + e.message, "error"); } + }); + } + const del = el("pj-goal-year-del"); + if (del) del.addEventListener("click", async function () { + const v = await prompt(year + "년 목표를 모두 삭제합니다(숫자·업무 영역·글 전부, 되돌릴 수 없음).\n" + + "계속하려면 " + year + " 를 입력하세요.", ""); + if (v == null) return; + if (String(v).trim() !== String(year)) { showToast("연도가 달라 삭제하지 않았습니다."); return; } + try { + await api("DELETE", "/project/api/goals/" + year); + location.href = "/project/goals"; + } catch (e) { showToast("삭제 실패: " + e.message, "error"); } + }); + + // ── 업무 영역 추가 ── + const colors = window.PJ_GOAL_COLORS || []; + const addArea = el("pj-goal-area-add"); + if (addArea) addArea.addEventListener("click", async function () { + const name = await prompt("새 업무 영역 이름", ""); + if (name == null || !String(name).trim()) return; + const n = table.querySelectorAll(".pj-goal-area").length; + try { + await api("POST", "/project/api/goals/" + year + "/areas", + { name: String(name).trim(), color: colors.length ? colors[n % colors.length] : "" }); + reloadKeepScroll(); + } catch (e) { showToast("추가 실패: " + e.message, "error"); } + }); + + // ── 영역 색 고르기 — 팝업은 body 에(화면 배율 밖) ── + let colorPop = null; + function closeColorPop() { + if (!colorPop) return; + colorPop.remove(); + colorPop = null; + document.removeEventListener("mousedown", onColorDocDown, true); + } + function onColorDocDown(e) { if (colorPop && !colorPop.contains(e.target)) closeColorPop(); } + function openColorPop(anchor, areaId, current, tbody) { + closeColorPop(); + colorPop = document.createElement("div"); + colorPop.className = "pj-goal-colorpop"; + colorPop.innerHTML = colors.map(function (c) { + return ''; + }).join(""); + document.body.appendChild(colorPop); + const r = anchor.getBoundingClientRect(); + const w = colorPop.offsetWidth; + colorPop.style.left = Math.max(8, Math.min(r.left, document.documentElement.clientWidth - w - 8)) + "px"; + colorPop.style.top = (r.bottom + 6) + "px"; + colorPop.addEventListener("click", async function (e) { + const sw = e.target.closest(".pj-goal-swatch"); + if (!sw) return; + const c = sw.dataset.c; + closeColorPop(); + try { + await api("PUT", "/project/api/goals/areas/" + areaId, { color: c }); + tbody.style.setProperty("--goal-bg", c); + anchor.dataset.color = c; + } catch (err) { showToast("색 변경 실패: " + err.message, "error"); } + }); + setTimeout(function () { document.addEventListener("mousedown", onColorDocDown, true); }, 0); + } + + // ── 영역·줄 도구(✎ 색 ↑ ↓ + ×) — 이벤트 위임 ── + table.addEventListener("click", async function (e) { + const b = e.target.closest("[data-goal-act]"); + if (!b) return; + const act = b.dataset.goalAct; + const tbody = b.closest(".pj-goal-area"); + const tr = b.closest("tr"); + 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") { + 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안의 줄과 글도 모두 삭제됩니다.", + { okText: "삭제", cancelText: "취소" }); + if (!ok) return; + await api("DELETE", "/project/api/goals/areas/" + areaId); + } else if (act === "row-add") { + 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 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)); + reloadKeepScroll(); + } catch (err) { showToast("처리 실패: " + err.message, "error"); } + }); + } + // ── 휴지통(관리자 전용 화면) — [복구] 누르면 원래 id 그대로 되살리고 줄을 지운다. function initTrash() { const table = el("pj-trash-table"); @@ -7427,6 +7732,8 @@ // 좌측 프로젝트 목록 — 프로젝트 화면은 initProject 가 자기 데이터로 직접 연다. if (!document.querySelector(".pj-project-view")) initSideTree(); initTrash(); + initGoalSide(); + initGoals(); initMyTasks(); initProject(); initAllMembers(); diff --git a/docs/PROJECT_MODULE.md b/docs/PROJECT_MODULE.md index 85577b4..e492059 100644 --- a/docs/PROJECT_MODULE.md +++ b/docs/PROJECT_MODULE.md @@ -289,6 +289,8 @@ docker exec -i postgres-db psql -U postgres -d project_db \ < scripts/sql/project_db_011_project_icon.sql 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 # 4) 재배포 (git pull 후 반드시 --build) cd /opt/www/main && docker compose up -d --build web @@ -479,6 +481,32 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중 되돌린다. 팝업은 전부 `body` 에 붙어 배율 밖이라 좌표 보정 불필요(전체 검색 결과창도 body 로 옮김), 배율 안에서 마우스 거리로 크기를 바꾸는 작업 창 너비 조절만 `uiZoom()` 으로 나눈다. localStorage `pj_ui_scale`. +## 6-9. 연간 목표 (마이그레이션 013) + +- 좌측 사이드바 개인 메뉴 맨 아래 **목표**(`_side.html` `#pj-side-goal`) — 누르면 바로 아래 연도 목록이 접혔다 펴진다 + (`initGoalSide`, localStorage `pj_goal_open`, 목표 화면에선 항상 펼침). 연도 목록은 `router._goal_years_nav` + (`goal_years` 최근 연도 먼저 + **올해는 항상**, 013 미적용이면 올해만) — 사이드바를 그리는 모든 화면 컨텍스트에 `goal_years`. +- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정, + 이번 달 열 강조. + - **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) — + 매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, 연간은 실적이 있는 달의 목표 합계 대비)는 + 화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`. + - **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 8색·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은 + 못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경. +- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 관리자만**(`_require_admin`, 화면도 관리자에게만 입력칸·도구). +- 연도 추가(`POST /api/goals/years {year}`)는 가장 가까운 이전 연도(없으면 다음 연도)의 영역·줄 구조를 글 없이 복사, + 목표가 하나도 없으면 `store.DEFAULT_GOAL_AREAS`(상품·마케팅·컨텐츠·유통[콜라보·인플·쿠팡·기타]). 없는 연도 화면은 + 관리자에게 "목표 만들기" 버튼(GET 에서 자동 생성하지 않는다). 연도 삭제는 연도를 직접 입력해야 진행(CASCADE 전부 삭제). +- API(전부 관리자): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics` + `{metric,kind,month,value}`(빈값 = 지움, 응답 `label` 은 쉼표 표기) · `POST /api/goals/{y}/areas` `{name,color}` · + `PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` · + `PUT|DELETE /api/goals/rows/{id}` · `POST /api/goals/rows/{id}/move` · `PUT /api/goals/rows/{id}/cells/{month}` `{body}`. + 013 미적용 503, 없는 대상 404, 입력 오류 400(`_goal_call`). +- 화면 동작(`initGoals`): 숫자 칸은 Enter/칸 떠남에 저장(Esc 취소), 글 칸은 0.8초 멈춤·칸 떠남·페이지 떠남(keepalive)에 저장, + 저장되면 칸 테두리가 잠깐 초록. 영역/줄 추가·이름·순서·삭제는 저장 뒤 새로고침(스크롤 위치 sessionStorage 로 되살림), + 영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지). +- 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기. + ## 7. 추후 단계 작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩, diff --git a/scripts/sql/project_db_013_goals.sql b/scripts/sql/project_db_013_goals.sql new file mode 100644 index 0000000..f28f1e3 --- /dev/null +++ b/scripts/sql/project_db_013_goals.sql @@ -0,0 +1,77 @@ +-- ===================================================================== +-- project_db 마이그레이션 013 — 연간 목표(좌측 사이드바 "목표" → 연도) +-- ===================================================================== +-- 멱등(idempotent). DROP/TRUNCATE 없음. +-- +-- goal_years 목표를 둔 연도(사이드바 "목표" 아래 연도 목록). sales_unit = 매출 단위 글자(예: 백만원). +-- goal_metrics 숫자 지표 — 매출·로아스 × 목표·실적 × 1~12월. 달성률은 화면에서 계산(저장 안 함). +-- goal_areas 업무 영역(상품·마케팅·컨텐츠·유통 …) — 연도마다 따로, 색은 줄 배경. +-- goal_rows 영역 안의 줄(유통: 콜라보·인플·쿠팡·기타). 영역마다 최소 1줄(이름 없는 줄 가능). +-- goal_cells 줄 × 월 글. month 0 = 연간, 1~12 = 월. +-- +-- 입력은 관리자만(라우터 _require_admin), 조회는 project 권한자 전원. +-- 미적용이어도 앱은 동작한다 — 사이드바 "목표" 아래 연도만 나오고, 화면에 "마이그레이션 013 필요" 안내. +-- +-- 적용 (1회, 여러 번 돌려도 안전): +-- docker exec -i postgres-db psql -U postgres -d project_db \ +-- < scripts/sql/project_db_013_goals.sql +-- ===================================================================== + +\set ON_ERROR_STOP on +\connect project_db + +CREATE TABLE IF NOT EXISTS goal_years ( + year INT PRIMARY KEY CHECK (year BETWEEN 2000 AND 2100), + sales_unit TEXT NOT NULL DEFAULT '', + created_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS goal_metrics ( + year INT NOT NULL REFERENCES goal_years(year) ON DELETE CASCADE, + metric TEXT NOT NULL CHECK (metric IN ('sales', 'roas')), + kind TEXT NOT NULL CHECK (kind IN ('target', 'actual')), + month SMALLINT NOT NULL CHECK (month BETWEEN 1 AND 12), + value NUMERIC(18, 2) NOT NULL, + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (year, metric, kind, month) +); + +CREATE TABLE IF NOT EXISTS goal_areas ( + id BIGSERIAL PRIMARY KEY, + year INT NOT NULL REFERENCES goal_years(year) ON DELETE CASCADE, + name TEXT NOT NULL, + color TEXT NOT NULL DEFAULT '#fbe1d5', + sort_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_goal_areas_year ON goal_areas (year, sort_order, id); + +CREATE TABLE IF NOT EXISTS goal_rows ( + id BIGSERIAL PRIMARY KEY, + area_id BIGINT NOT NULL REFERENCES goal_areas(id) ON DELETE CASCADE, + label TEXT NOT NULL DEFAULT '', + sort_order INT NOT NULL DEFAULT 0 +); +CREATE INDEX IF NOT EXISTS idx_goal_rows_area ON goal_rows (area_id, sort_order, id); + +CREATE TABLE IF NOT EXISTS goal_cells ( + row_id BIGINT NOT NULL REFERENCES goal_rows(id) ON DELETE CASCADE, + month SMALLINT NOT NULL CHECK (month BETWEEN 0 AND 12), + body TEXT NOT NULL DEFAULT '', + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (row_id, month) +); + +COMMENT ON TABLE goal_years IS '연간 목표 — 연도 목록(사이드바 목표 아래)'; +COMMENT ON TABLE goal_metrics IS '연간 목표 — 매출/로아스 목표·실적 월별 숫자'; +COMMENT ON TABLE goal_areas IS '연간 목표 — 업무 영역(상품·마케팅·컨텐츠·유통 등)'; +COMMENT ON TABLE goal_rows IS '연간 목표 — 업무 영역 안의 줄(유통: 콜라보·인플·쿠팡·기타)'; +COMMENT ON TABLE goal_cells IS '연간 목표 — 줄×월 글. month 0 = 연간'; + +GRANT SELECT, INSERT, UPDATE, DELETE ON goal_years, goal_metrics, goal_areas, goal_rows, goal_cells TO project_app; +GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app; + +SELECT 'project_db 013 goals ready' AS status;