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:
2026-09-30 11:13:54 +09:00
parent b95206dcf4
commit ec78dd328d
15 changed files with 1315 additions and 13 deletions
+271
View File
@@ -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)),
)
# ════════════════════════════════════════════════════════════
# 직렬화
# ════════════════════════════════════════════════════════════
+225 -1
View File
@@ -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})
+83
View File
@@ -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}"
@@ -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 @@
<span class="pj-side-navtext">휴지통</span>
</a>
{% endif %}
{# 목표 — 누르면 바로 아래에 연도가 펼쳐지고, 연도를 누르면 오른쪽에 그해 전체 목표
(/project/goals/{연도}). 펼침 상태는 localStorage(pj_goal_open), 목표 화면에서는 항상 펼침.
연도 추가는 관리자만(마이그레이션 013). #}
{% set goal_open = side_active == 'goals' %}
<div class="pj-side-goal{% if goal_open %} is-open{% endif %}" id="pj-side-goal"
data-force-open="{{ 'true' if goal_open else 'false' }}">
<button type="button" class="pj-side-navlink pj-side-goal-toggle" id="pj-side-goal-toggle"
aria-expanded="{{ 'true' if goal_open else 'false' }}">
<span class="material-symbols-outlined pj-side-navic">flag</span>
<span class="pj-side-navtext">목표</span>
<span class="material-symbols-outlined pj-side-goal-caret">expand_more</span>
</button>
<div class="pj-side-goal-years" id="pj-side-goal-years"{% if not goal_open %} hidden{% endif %}>
{% for y in (goal_years or []) %}
<a class="pj-side-goal-year{% if side_active == 'goals' and y == goal_year_active %} is-active{% endif %}"
href="/project/goals/{{ y }}">{{ y }}년</a>
{% endfor %}
{% if is_admin %}
<button type="button" class="pj-side-goal-add" id="pj-goal-year-add"
data-next="{{ ((goal_years or [0]) | max) + 1 }}">+ 연도 추가</button>
{% endif %}
</div>
</div>
</nav>
<div class="pj-side-block pj-tree-block">
@@ -0,0 +1,172 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% 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). #}
<div class="pj-wrap pj-inbox-view pj-goal-view">
<div class="pj-layout">
{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}
<section class="pj-main">
<div class="pj-section-head">
<h2>{{ goal_year }}년 목표</h2>
{% if board %}
<div class="pj-goal-head-acts">
{% if is_admin %}
<label class="pj-goal-unit">매출 단위
<input type="text" id="pj-goal-unit" maxlength="20" placeholder="예: 백만원"
value="{{ board.sales_unit }}" data-year="{{ goal_year }}" />
</label>
<button type="button" class="pj-btn pj-btn-danger" id="pj-goal-year-del"
data-year="{{ goal_year }}">연도 삭제</button>
{% else %}
{% if board.sales_unit %}<span class="pj-goal-unit-ro">매출 단위: {{ board.sales_unit }}</span>{% endif %}
<span class="pj-goal-note">목표는 관리자만 입력할 수 있습니다.</span>
{% endif %}
</div>
{% endif %}
</div>
<div class="pj-view pj-goal-pane" id="pj-goal-pane">
{% if not goals_enabled %}
<div class="pj-empty">연간 목표가 아직 준비되지 않았습니다(DB 마이그레이션 013 필요).</div>
{% elif not board %}
<div class="pj-empty pj-goal-empty">
<p>{{ goal_year }}년 목표가 아직 없습니다.</p>
{% if is_admin %}
<p class="pj-goal-empty-sub">만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-goal-create" data-year="{{ goal_year }}">{{ goal_year }}년 목표 만들기</button>
{% endif %}
</div>
{% else %}
{% set sm = board.metrics.sales %}
{% set rm = board.metrics.roas %}
{% macro num_cell(metric, kind, labels, mo) -%}
<td class="pj-goal-numtd{% if mo == this_month %} is-now{% endif %}">
{%- if is_admin -%}
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
value="{{ labels.get(mo, '') }}" />
{%- else -%}
<span class="pj-goal-num" data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}">{{ labels.get(mo, '') }}</span>
{%- endif -%}
</td>
{%- endmacro %}
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
data-admin="{{ 'true' if is_admin else 'false' }}">
<thead>
<tr>
<th class="pj-goal-c1"></th>
<th class="pj-goal-c2"></th>
<th class="pj-goal-year-col">연간</th>
{% for mo in months %}<th class="{% if mo == this_month %}is-now{% endif %}">{{ mo }}월</th>{% endfor %}
</tr>
</thead>
{# ── 숫자 지표 ── #}
<tbody class="pj-goal-kpi">
<tr>
<th class="pj-goal-c1" rowspan="3">매출</th>
<th class="pj-goal-c2">목표</th>
<td class="pj-goal-sum" data-metric="sales" data-kind="target"></td>
{% for mo in months %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
</tr>
<tr>
<th class="pj-goal-c2">실적</th>
<td class="pj-goal-sum" data-metric="sales" data-kind="actual"></td>
{% for mo in months %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
</tr>
<tr class="pj-goal-rate-row">
<th class="pj-goal-c2">달성</th>
<td class="pj-goal-rate" data-month="0"></td>
{% for mo in months %}<td class="pj-goal-rate{% if mo == this_month %} is-now{% endif %}" data-month="{{ mo }}"></td>{% endfor %}
</tr>
<tr>
<th class="pj-goal-c1" rowspan="2">로아스</th>
<th class="pj-goal-c2">목표</th>
<td class="pj-goal-sum pj-goal-sum-na"></td>
{% for mo in months %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
</tr>
<tr>
<th class="pj-goal-c2">실적</th>
<td class="pj-goal-sum pj-goal-sum-na"></td>
{% for mo in months %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
</tr>
</tbody>
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #}
{% for area in board.areas %}
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color }}">
{% for row in area.rows %}
<tr data-row-id="{{ row.id }}">
{% if loop.first %}
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
<span class="pj-goal-area-text">{{ area.name }}</span>
{% if is_admin %}
<span class="pj-goal-tools">
<button type="button" class="pj-icon-btn" data-goal-act="area-rename" data-name="{{ area.name }}" title="이름 바꾸기">✎</button>
<button type="button" class="pj-icon-btn" data-goal-act="area-color" data-color="{{ area.color }}" title="색 바꾸기"><span class="material-symbols-outlined">palette</span></button>
<button type="button" class="pj-icon-btn" data-goal-act="area-up" title="위로">↑</button>
<button type="button" class="pj-icon-btn" data-goal-act="area-down" title="아래로">↓</button>
<button type="button" class="pj-icon-btn" data-goal-act="row-add" title="줄 추가">+</button>
<button type="button" class="pj-icon-btn" data-goal-act="area-del" data-name="{{ area.name }}" title="영역 삭제">×</button>
</span>
{% endif %}
</th>
{% endif %}
<th class="pj-goal-c2 pj-goal-row-label">
<span class="pj-goal-row-text">{{ row.label }}</span>
{% if is_admin %}
<span class="pj-goal-tools">
<button type="button" class="pj-icon-btn" data-goal-act="row-rename" data-label="{{ row.label }}" title="줄 이름 바꾸기">✎</button>
{% if area.rows | length > 1 %}
<button type="button" class="pj-icon-btn" data-goal-act="row-up" title="위로">↑</button>
<button type="button" class="pj-icon-btn" data-goal-act="row-down" title="아래로">↓</button>
<button type="button" class="pj-icon-btn" data-goal-act="row-del" data-label="{{ row.label }}" title="줄 삭제">×</button>
{% endif %}
</span>
{% endif %}
</th>
{% for mo in [0] + months %}
<td class="pj-goal-texttd{% if mo == 0 %} pj-goal-year-col{% endif %}{% if mo == this_month %} is-now{% endif %}">
{%- if is_admin -%}
<textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ mo }}"
placeholder="{{ '연간 목표' if mo == 0 else '' }}">{{ row.cells.get(mo, '') }}</textarea>
{%- else -%}
<div class="pj-goal-text-ro">{{ row.cells.get(mo, '') }}</div>
{%- endif -%}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
{% endfor %}
</table>
{% if is_admin %}
<div class="pj-goal-foot">
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다.</span>
</div>
{% endif %}
{% endif %}
</div>
</section>
</div>
</div>
{% if goal_area_colors %}<script>window.PJ_GOAL_COLORS = {{ goal_area_colors | tojson }};</script>{% endif %}
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260930a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260929h" />
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -79,7 +79,7 @@
<h2><span class="pjh-num">2</span>화면 구성</h2>
<div class="pjh-map" aria-hidden="true">
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말</span></div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 내 작업 · 휴지통<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>오른쪽 위: 범위(이 프로젝트 / 전체 프로젝트)<br>필터 바<br>작업들</div>
</div>
<h3>왼쪽 사이드바</h3>
@@ -88,6 +88,11 @@
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
<li><b>목표</b> — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 —
맨 위에 <b>매출</b>(목표·실적·달성률)과 <b>로아스</b>(목표·실적)를 달마다, 그 아래에 <b>업무 영역</b>(상품·마케팅·컨텐츠·유통 등)별로
연간·월별 계획을 적습니다. 매출의 <b>연간</b> 칸은 월 합계, <b>달성</b>은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다.
<b>입력은 관리자만</b> 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 <b>+ 연도 추가</b>로 새해 목표를
만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역 이름 칸에 마우스를 올려 이름·색·순서·줄 추가·삭제를 합니다.</li>
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
</ul>
@@ -116,6 +121,7 @@
<tr><td>새 프로젝트, 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
<tr><td>멤버 배정·제외</td><td>관리자</td></tr>
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
<tr><td>목표 보기</td><td>누구나 · <b>목표 입력·연도 추가·업무 영역 편집</b>은 관리자</td></tr>
</table>
</section>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260929h" />
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -104,5 +104,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260929h" defer></script>
<script src="/static/project.js?v=20260930a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260929h" />
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20260929h" defer></script>
<script src="/static/project.js?v=20260930a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260929h" />
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -491,5 +491,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20260929h" defer></script>
<script src="/static/project.js?v=20260930a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260929h" />
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260929h" defer></script>
<script src="/static/project.js?v=20260930a" defer></script>
{% endblock %}