feat(project): 연간 목표 — 사이드바 "목표" → 연도 → 그해 전체 목표 표
- 사이드바 휴지통 아래 "목표": 누르면 연도 목록이 펼쳐지고(올해는 항상), 관리자는 + 연도 추가
- /project/goals/{연도}: 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자 + 업무 영역
(상품·마케팅·컨텐츠·유통[콜라보·인플·쿠팡·기타])별 연간·월별 글을 스프레드시트처럼 한 표에
- 매출 연간 합계·달성률은 화면에서 계산, 칸별 즉시 저장, 영역 이름·색·순서·줄 추가/삭제
- 입력·구조 변경은 관리자만, 조회는 project 권한자 전원
- 새 연도는 가장 가까운 이전 연도의 영역 구성을 복사(처음이면 기본 4개 영역)
- DB 마이그레이션 013(goal_years·goal_metrics·goal_areas·goal_rows·goal_cells), 문서·도움말 갱신
- project.js/css 캐시 버전 20260930a
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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)),
|
||||
)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 직렬화
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
Reference in New Issue
Block a user