feat(project): 연간 목표 엑셀식 칸 병합(끌어 고르기·우클릭 병합/해제) + 월별 주간 회의록

엑셀식 칸 병합 (예전 Shift+클릭·병합 버튼·오른쪽/왼쪽 칸 병합 메뉴 대체)
- 글 칸을 마우스로 끌어(또는 Shift+클릭) 사각형 선택 → 우클릭 "셀 병합 (N줄 × M칸)" / "병합 해제"
- 같은 업무 영역 안 세로(row_span) + 같은 반기 월 칸 가로, 연간·상·하반기 칸은 세로로만
- 걸친 병합은 엑셀처럼 범위를 넓혀 흡수, 글은 왼쪽 위부터 이어 왼쪽 위 칸에, 해제하면 왼쪽 위 칸에 남음
- POST /api/goals/areas/{id}/merge {row_from,row_to,col_from,col_to} (db.merge_goal_rect), router._goal_area_layout(colspan·rowspan)
- 가려진 칸 저장 거절(세로 포함), 병합 안쪽 줄 끼우기 +1 / 가려진 줄 지우기 -1, 세로 병합에 걸린 줄 이동 거절

주간 회의록 (/project/goals/{연도}/meetings/{월}, 목표 표 월 머리 클릭)
- 주(월~일) 탭, 주마다 회의록: 이번주 할 일·목표 금액 | 지난주 할 일·목표·결과·달성률·평가
- 앞선 회의록 줄 이어받기(carry_from), 처음이면 목표 표 업무 영역 + 기본 양식 줄(유통 줄 쇼핑몰 연결 추측)
- 머리: 월 목표·지난주까지 누적·주당 필요 매출(페이싱)·전주 목표/결과/달성률·금주 목표/현재 실적
- 쇼핑몰 연결 줄의 결과·누적·주간 매출은 실적 모듈 performance_store 읽기 전용(없으면 직접 입력)
- 금액 입력 120만·1.5억·3천만·1억2천만, 참석자·결정 사항 메모, 줄 메뉴(추가·순서·쇼핑몰 연결·삭제), 인쇄

마이그레이션 015(project_db): goal_cell_merges.row_span + CHECK 교체, goal_meetings, goal_meeting_items
캐시 버전 20261001c, 테스트(DB 회귀 test_goal_rect_merges·test_goal_meetings)·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 11:46:25 +09:00
parent 614747ffca
commit c9bce7c976
16 changed files with 1966 additions and 198 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+453 -49
View File
@@ -13,6 +13,7 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import re
import time import time
from datetime import date, datetime from datetime import date, datetime
from datetime import time as dtime from datetime import time as dtime
@@ -1919,8 +1920,9 @@ class ProjectStore:
metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}} metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}}
areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", 13: "상반기 글", ...}, areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", 13: "상반기 글", ...},
merges: {시작월: 칸 수}}]}] merges: {시작 칸: (가로 칸 수, 세로 줄 수)}}]}]
halves = 마이그레이션 014 적용 여부(상·하반기 글 칸·병합) halves = 마이그레이션 014 적용 여부(상·하반기 글 칸·병합)
rect = 마이그레이션 015 적용 여부(세로 병합·연간/반기 칸 병합·주간 회의록)
""" """
with self._pool.connection() as conn: with self._pool.connection() as conn:
head = conn.execute( head = conn.execute(
@@ -1948,8 +1950,9 @@ class ProjectStore:
(year,), (year,),
).fetchall() ).fetchall()
halves = self._table_exists(conn, "goal_cell_merges") halves = self._table_exists(conn, "goal_cell_merges")
rect = halves and self._column_exists(conn, "goal_cell_merges", "row_span")
merge_rows = conn.execute( merge_rows = conn.execute(
"SELECT m.row_id, m.start_month, m.span FROM goal_cell_merges m " "SELECT m.row_id, m.start_month, m.span" + (", m.row_span" if rect else "") + " FROM goal_cell_merges m "
"JOIN goal_rows r ON r.id = m.row_id JOIN goal_areas a ON a.id = r.area_id " "JOIN goal_rows r ON r.id = m.row_id JOIN goal_areas a ON a.id = r.area_id "
"WHERE a.year = %s", "WHERE a.year = %s",
(year,), (year,),
@@ -1962,9 +1965,10 @@ class ProjectStore:
cells: dict[int, dict[int, str]] = {} cells: dict[int, dict[int, str]] = {}
for c in cell_rows: for c in cell_rows:
cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"] cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"]
merges: dict[int, dict[int, int]] = {} merges: dict[int, dict[int, tuple[int, int]]] = {}
for g in merge_rows: for g in merge_rows:
merges.setdefault(int(g["row_id"]), {})[int(g["start_month"])] = int(g["span"]) merges.setdefault(int(g["row_id"]), {})[int(g["start_month"])] = (
int(g["span"]), int(g.get("row_span") or 1))
rows_by_area: dict[int, list[dict[str, Any]]] = {} rows_by_area: dict[int, list[dict[str, Any]]] = {}
for r in row_rows: for r in row_rows:
rid = int(r["id"]) rid = int(r["id"])
@@ -1978,7 +1982,7 @@ class ProjectStore:
for a in area_rows for a in area_rows
] ]
return {"year": int(head["year"]), "sales_unit": head["sales_unit"], return {"year": int(head["year"]), "sales_unit": head["sales_unit"],
"metrics": metrics, "areas": areas, "halves": halves} "metrics": metrics, "areas": areas, "halves": halves, "rect": rect}
def set_goal_metric( def set_goal_metric(
self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = "" self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = ""
@@ -2069,6 +2073,17 @@ class ProjectStore:
self._move_goal_item("goal_areas", "year", area_id, direction) self._move_goal_item("goal_areas", "year", area_id, direction)
def move_goal_row(self, *, row_id: int, direction: int) -> None: def move_goal_row(self, *, row_id: int, direction: int) -> None:
"""줄 순서 바꾸기 — 세로로 병합된 칸에 걸린 줄(자신 또는 바꿀 이웃)은 옮기지 않는다(엑셀처럼 병합을 먼저 해제)."""
with self._pool.connection() as conn:
me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()
if me is None:
raise KeyError(row_id)
ids, merges, _ = self._area_geometry(conn, int(me["area_id"]))
i = ids.index(row_id)
j = i + (1 if direction > 0 else -1)
if 0 <= j < len(ids) and any(g["r1"] > g["r0"] and (g["r0"] <= i <= g["r1"] or g["r0"] <= j <= g["r1"])
for g in merges):
raise ValueError("세로로 병합된 칸에 걸린 줄은 옮길 수 없습니다. 병합을 해제한 뒤 옮기세요.")
self._move_goal_item("goal_rows", "area_id", row_id, direction) self._move_goal_item("goal_rows", "area_id", row_id, direction)
def add_goal_row( def add_goal_row(
@@ -2102,6 +2117,17 @@ class ProjectStore:
(area_id, lb), (area_id, lb),
).fetchone()["id"]) ).fetchone()["id"])
i = ids.index(ref_row_id) + (1 if place == "below" else 0) i = ids.index(ref_row_id) + (1 if place == "below" else 0)
# 세로 병합 안쪽(시작 줄 아래 ~ 마지막 줄)에 끼우면 엑셀처럼 그 병합이 한 줄 늘어난다
if self._table_exists(conn, "goal_cell_merges") and self._column_exists(
conn, "goal_cell_merges", "row_span"):
_, merges, _ = self._area_geometry(conn, area_id)
for g in merges:
if g["r0"] < i <= g["r1"]:
conn.execute(
"UPDATE goal_cell_merges SET row_span = row_span + 1 "
"WHERE row_id = %s AND start_month = %s",
(g["row_id"], g["start"]),
)
ids.insert(i, rid) ids.insert(i, rid)
for n, x in enumerate(ids): for n, x in enumerate(ids):
conn.execute("UPDATE goal_rows SET sort_order = %s WHERE id = %s", (n, x)) conn.execute("UPDATE goal_rows SET sort_order = %s WHERE id = %s", (n, x))
@@ -2128,6 +2154,24 @@ class ProjectStore:
).fetchone()["n"] ).fetchone()["n"]
if n <= 1: if n <= 1:
raise ValueError("업무 영역의 마지막 줄은 지울 수 없습니다. 영역을 삭제하세요.") raise ValueError("업무 영역의 마지막 줄은 지울 수 없습니다. 영역을 삭제하세요.")
# 세로 병합에 가려진 줄이면 그 병합이 한 줄 준다(시작 줄을 지우면 병합도 같이 지워진다 — CASCADE)
if self._table_exists(conn, "goal_cell_merges") and self._column_exists(
conn, "goal_cell_merges", "row_span"):
ids, merges, _ = self._area_geometry(conn, int(me["area_id"]))
i = ids.index(row_id)
for g in merges:
if g["r0"] < i <= g["r1"]:
if g["span"] * (g["row_span"] - 1) >= 2:
conn.execute(
"UPDATE goal_cell_merges SET row_span = row_span - 1 "
"WHERE row_id = %s AND start_month = %s",
(g["row_id"], g["start"]),
)
else:
conn.execute(
"DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s",
(g["row_id"], g["start"]),
)
conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,)) 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: def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None:
@@ -2136,16 +2180,14 @@ class ProjectStore:
with self._pool.connection() as conn: with self._pool.connection() as conn:
if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone(): if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone():
raise KeyError(row_id) raise KeyError(row_id)
if m != store.GOAL_YEAR: halves = self._table_exists(conn, "goal_cell_merges")
halves = self._table_exists(conn, "goal_cell_merges") if m > 12 and not halves:
if m > 12 and not halves: raise store.GoalMigration014Needed()
raise store.GoalMigration014Needed() if halves:
# 병합된 칸의 가운데·끝 월(글은 병합 시작 월에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장 # 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장
if m <= 12 and halves and conn.execute( area_id = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()["area_id"]
"SELECT 1 FROM goal_cell_merges WHERE row_id = %s " ids, merges, _ = self._area_geometry(conn, int(area_id))
"AND start_month < %s AND start_month + span - 1 >= %s", if self._covered_by(merges, ids.index(row_id), store.GOAL_COL_ORDER.index(m)):
(row_id, m, m),
).fetchone():
raise ValueError("병합된 칸입니다. 새로고침해 주세요.") raise ValueError("병합된 칸입니다. 새로고침해 주세요.")
if not text: if not text:
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m)) conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m))
@@ -2157,54 +2199,125 @@ class ProjectStore:
(row_id, m, text, store.norm_str(updated_by, lower=True)), (row_id, m, text, store.norm_str(updated_by, lower=True)),
) )
def merge_goal_cells(self, *, row_id: int, start: Any, end: Any, updated_by: str = "") -> tuple[int, int]: # ── 엑셀식 사각형 병합 ─────────────────────────────────────────
"""업무 영역 줄의 start~end 월 칸을 가로로 합친다 → (시작 월, 칸 수). @staticmethod
def _column_exists(conn: Any, table: str, column: str) -> bool:
row = conn.execute(
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
"AND table_name = %s AND column_name = %s",
(table, column),
).fetchone()
return row is not None
걸쳐 있는 기존 병합은 통째로 흡수한다(병합은 서로 겹치지 않고 반기 안이라 범위도 반기 안). def _area_geometry(self, conn: Any, area_id: int) -> tuple[list[int], list[dict[str, Any]], bool]:
글은 범위 안 칸들의 글을 월 순서대로 줄바꿈으로 이어 시작 월 칸에 두고, 나머지 칸 글은 지운다.""" """업무 영역 하나의 병합 배치 — (줄 id 순서, 병합 목록, 세로 병합(015) 가능 여부).
s, e = store.validate_goal_merge(start, end) 병합 = {row_id, start, span, row_span, r0, r1(줄 순번), c0, c1(화면 칸 순번)}. 줄 범위는 영역 끝에서 자른다."""
ids = [int(r["id"]) for r in conn.execute(
"SELECT id FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (area_id,)
).fetchall()]
if not self._table_exists(conn, "goal_cell_merges"):
return ids, [], False
rect = self._column_exists(conn, "goal_cell_merges", "row_span")
rows = conn.execute(
"SELECT m.row_id, m.start_month, m.span" + (", m.row_span" if rect else "")
+ " FROM goal_cell_merges m JOIN goal_rows r ON r.id = m.row_id WHERE r.area_id = %s",
(area_id,),
).fetchall()
merges = []
for g in rows:
rid, start = int(g["row_id"]), int(g["start_month"])
if rid not in ids or start not in store.GOAL_COL_ORDER:
continue
r0 = ids.index(rid)
span, rs = int(g["span"]), int(g.get("row_span") or 1) if rect else 1
c0 = store.GOAL_COL_ORDER.index(start)
merges.append({"row_id": rid, "start": start, "span": span, "row_span": rs, "r0": r0,
"r1": min(len(ids) - 1, r0 + rs - 1), "c0": c0,
"c1": min(len(store.GOAL_COL_ORDER) - 1, c0 + span - 1)})
return ids, merges, rect
@staticmethod
def _covered_by(merges: list[dict[str, Any]], ri: int, ci: int) -> dict[str, Any] | None:
"""(줄 순번, 칸 순번)을 가리는 병합(시작 칸 자신은 빼고)."""
for g in merges:
if g["r0"] <= ri <= g["r1"] and g["c0"] <= ci <= g["c1"] and (ri, ci) != (g["r0"], g["c0"]):
return g
return None
def merge_goal_rect(
self, *, area_id: int, row_from: Any, row_to: Any, col_from: Any, col_to: Any, updated_by: str = ""
) -> dict[str, int]:
"""업무 영역 칸을 엑셀처럼 사각형으로 합친다 → {row_id(왼쪽 위 줄), start, span, row_span}.
줄은 같은 영역 안 연속된 줄, 칸은 화면 순서(연간·1~6월·상반기·7~12월·하반기) — 가로는 같은 반기 월 칸끼리만.
걸친 기존 병합은 통째로 흡수(엑셀이 선택을 넓히듯). 글은 범위 안 칸들의 글을 왼쪽 위부터 줄·칸 순서대로
줄바꿈으로 이어 왼쪽 위 칸에 두고, 나머지 칸 글은 지운다(글을 잃지 않게)."""
who = store.norm_str(updated_by, lower=True) who = store.norm_str(updated_by, lower=True)
try:
rf, rt = int(row_from), int(row_to)
except (TypeError, ValueError):
raise ValueError("병합할 줄이 올바르지 않습니다.")
store.validate_goal_rect_cols(col_from, col_to) # 칸 번호 검사(묶음 검사는 넓힌 뒤 다시)
with self._pool.connection() as conn: with self._pool.connection() as conn:
with conn.transaction(): with conn.transaction():
if not self._table_exists(conn, "goal_cell_merges"): if not self._table_exists(conn, "goal_cell_merges"):
raise store.GoalMigration014Needed() raise store.GoalMigration014Needed()
if not conn.execute( if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,)).fetchone():
"SELECT 1 FROM goal_rows WHERE id = %s FOR UPDATE", (row_id,) raise KeyError(area_id)
).fetchone(): ids, merges, rect = self._area_geometry(conn, area_id)
raise KeyError(row_id) if rf not in ids or rt not in ids:
for g in conn.execute( raise KeyError(rf if rf not in ids else rt)
"SELECT start_month, span FROM goal_cell_merges WHERE row_id = %s", (row_id,) r0, r1 = sorted((ids.index(rf), ids.index(rt)))
).fetchall(): c0, c1 = sorted((store.GOAL_COL_ORDER.index(int(col_from)), store.GOAL_COL_ORDER.index(int(col_to))))
gs, ge = int(g["start_month"]), int(g["start_month"]) + int(g["span"]) - 1 grown = True
if gs <= e and ge >= s: while grown: # 걸친 병합을 통째로 품을 때까지 넓힌다
s, e = min(s, gs), max(e, ge) grown = False
bodies = [ for g in merges:
str(c["body"]).strip() for c in conn.execute( if g["r0"] <= r1 and g["r1"] >= r0 and g["c0"] <= c1 and g["c1"] >= c0:
"SELECT body FROM goal_cells WHERE row_id = %s AND month BETWEEN %s AND %s " n = (min(r0, g["r0"]), max(r1, g["r1"]), min(c0, g["c0"]), max(c1, g["c1"]))
"ORDER BY month", if n != (r0, r1, c0, c1):
(row_id, s, e), r0, r1, c0, c1 = n
).fetchall() grown = True
] start, span = store.validate_goal_rect_cols(store.GOAL_COL_ORDER[c0], store.GOAL_COL_ORDER[c1])
text = store.validate_goal_text("\n".join(b for b in bodies if b)) row_span = r1 - r0 + 1
if span * row_span < 2:
raise ValueError("두 칸 이상 골라야 병합할 수 있습니다.")
if (row_span > 1 or start in (store.GOAL_YEAR, store.GOAL_H1, store.GOAL_H2)) and not rect:
raise store.GoalMigration015Needed()
rows_in = ids[r0:r1 + 1]
cols_in = list(store.GOAL_COL_ORDER[c0:c1 + 1])
bodies = {(int(c["row_id"]), int(c["month"])): str(c["body"]).strip() for c in conn.execute(
"SELECT row_id, month, body FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)",
(rows_in, cols_in),
).fetchall()}
text = store.validate_goal_text("\n".join(
bodies[(r, m)] for r in rows_in for m in cols_in if bodies.get((r, m))
))
conn.execute( conn.execute(
"DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month BETWEEN %s AND %s", "DELETE FROM goal_cell_merges WHERE row_id = ANY(%s) AND start_month = ANY(%s)",
(row_id, s, e), (rows_in, cols_in),
) )
conn.execute( conn.execute(
"DELETE FROM goal_cells WHERE row_id = %s AND month BETWEEN %s AND %s", "DELETE FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)", (rows_in, cols_in),
(row_id, s, e),
) )
anchor = rows_in[0]
if text: if text:
conn.execute( conn.execute(
"INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s)", "INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s)",
(row_id, s, text, who), (anchor, start, text, who),
) )
conn.execute( if rect:
"INSERT INTO goal_cell_merges (row_id, start_month, span, updated_by) " conn.execute(
"VALUES (%s, %s, %s, %s)", "INSERT INTO goal_cell_merges (row_id, start_month, span, row_span, updated_by) "
(row_id, s, e - s + 1, who), "VALUES (%s, %s, %s, %s, %s)",
) (anchor, start, span, row_span, who),
return s, e - s + 1 )
else:
conn.execute(
"INSERT INTO goal_cell_merges (row_id, start_month, span, updated_by) VALUES (%s, %s, %s, %s)",
(anchor, start, span, who),
)
return {"row_id": anchor, "start": start, "span": span, "row_span": row_span}
def unmerge_goal_cells(self, *, row_id: int, start: int) -> None: def unmerge_goal_cells(self, *, row_id: int, start: int) -> None:
"""병합 해제 — 글은 시작 월 칸에 그대로 남는다.""" """병합 해제 — 글은 시작 월 칸에 그대로 남는다."""
@@ -2218,6 +2331,297 @@ class ProjectStore:
if row is None: if row is None:
raise KeyError(row_id) raise KeyError(row_id)
# ════════════════════════════════════════════════════════════
# 주간 회의록 (마이그레이션 015) — 목표 표 월 머리 → 그 달 주차별 회의록
# ════════════════════════════════════════════════════════════
_MEETING_ITEM_COLS = ("id, week_start, section, section_color, label, content, target_amount, result_amount, "
"status, marketplace_code, carry_from, sort_order")
def meetings_enabled(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "goal_meetings")
def _require_meetings(self, conn: Any) -> None:
if not self._table_exists(conn, "goal_meetings"):
raise store.GoalMigration015Needed()
@staticmethod
def _meeting_item(r: dict[str, Any]) -> dict[str, Any]:
out = dict(r)
out["id"] = int(out["id"])
out["week_start"] = out["week_start"].isoformat()
for k in ("target_amount", "result_amount", "carry_from"):
out[k] = int(out[k]) if out.get(k) is not None else None
return out
def meeting_weeks(self, *, start: date, end: date) -> list[str]:
"""기간 안에 회의록이 있는 주(월요일) 목록."""
with self._pool.connection() as conn:
if not self._table_exists(conn, "goal_meetings"):
return []
rows = conn.execute(
"SELECT week_start FROM goal_meetings WHERE week_start BETWEEN %s AND %s ORDER BY week_start",
(start, end),
).fetchall()
return [r["week_start"].isoformat() for r in rows]
def get_meeting(self, *, week_start: date) -> dict[str, Any] | None:
"""한 주 회의록 — 머리(금주 목표·참석자·메모) + 줄(전주 줄 prev 포함). 없으면 None.
prev_meeting = 이 회의록보다 앞선 가장 가까운 회의록의 머리(전주 목표)."""
with self._pool.connection() as conn:
self._require_meetings(conn)
head = conn.execute(
"SELECT week_start, week_target, attendees, notes, updated_by, updated_at "
"FROM goal_meetings WHERE week_start = %s", (week_start,),
).fetchone()
if head is None:
return None
items = conn.execute(
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE week_start = %s "
"ORDER BY sort_order, id", (week_start,),
).fetchall()
prev_ids = [int(r["carry_from"]) for r in items if r["carry_from"] is not None]
prevs = {int(r["id"]): self._meeting_item(r) for r in conn.execute(
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE id = ANY(%s)", (prev_ids,),
).fetchall()} if prev_ids else {}
prev_head = conn.execute(
"SELECT week_start, week_target FROM goal_meetings WHERE week_start < %s "
"ORDER BY week_start DESC LIMIT 1", (week_start,),
).fetchone()
out_items = []
for r in items:
it = self._meeting_item(r)
it["prev"] = prevs.get(it["carry_from"]) if it["carry_from"] is not None else None
out_items.append(it)
return {
"week_start": head["week_start"].isoformat(),
"week_target": int(head["week_target"]) if head["week_target"] is not None else None,
"attendees": head["attendees"], "notes": head["notes"], "updated_by": head["updated_by"],
"updated_at": head["updated_at"].astimezone(KST).isoformat(timespec="minutes") if head["updated_at"] else "",
"items": out_items,
"prev_meeting": {"week_start": prev_head["week_start"].isoformat(),
"week_target": int(prev_head["week_target"]) if prev_head["week_target"] is not None
else None} if prev_head else None,
}
def create_meeting(self, *, week_start: date, sections: list[tuple[str, str]], created_by: str = "") -> bool:
"""회의록 만들기 — 이미 있으면 False. 앞선 가장 가까운 회의록이 있으면 그 줄(구역·이름·쇼핑몰 연결·순서)을
글 없이 이어받고(carry_from = 그 줄 → 이번 회의에서 지난주 할 일·목표·결과를 나란히 리뷰), 없으면 sections
(목표 표 업무 영역 이름·색)마다 기본 양식 줄(store.MEETING_TEMPLATE)로 시작한다."""
ws = store.validate_week_start(week_start)
who = store.norm_str(created_by, lower=True)
with self._pool.connection() as conn:
with conn.transaction():
self._require_meetings(conn)
ins = conn.execute(
"INSERT INTO goal_meetings (week_start, created_by, updated_by) VALUES (%s, %s, %s) "
"ON CONFLICT (week_start) DO NOTHING RETURNING week_start",
(ws, who, who),
).fetchone()
if ins is None:
return False
prev = conn.execute(
"SELECT week_start FROM goal_meetings WHERE week_start < %s ORDER BY week_start DESC LIMIT 1",
(ws,),
).fetchone()
prev_items = conn.execute(
"SELECT id, section, section_color, label, marketplace_code, sort_order FROM goal_meeting_items "
"WHERE week_start = %s ORDER BY sort_order, id", (prev["week_start"],),
).fetchall() if prev else []
if prev_items:
for n, r in enumerate(prev_items):
conn.execute(
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
"marketplace_code, carry_from, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], r["id"], n, who),
)
else:
n = 0
for name, color in sections or [(k, "") for k in store.MEETING_TEMPLATE]:
for label in store.MEETING_TEMPLATE.get(name, ("",)):
conn.execute(
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
"marketplace_code, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s)",
(ws, name, color, label, store.guess_meeting_market(name, label), n, who),
)
n += 1
return True
def delete_meeting(self, *, week_start: date) -> None:
with self._pool.connection() as conn:
self._require_meetings(conn)
row = conn.execute(
"DELETE FROM goal_meetings WHERE week_start = %s RETURNING week_start", (week_start,)
).fetchone()
if row is None:
raise KeyError(str(week_start))
def update_meeting(self, *, week_start: date, fields: dict[str, Any], updated_by: str = "") -> None:
"""머리 칸 — week_target(금주 목표 매출, 원) · attendees(참석자) · notes(결정 사항·메모)."""
sets: list[str] = []
params: list[Any] = []
if "week_target" in fields:
v = store.validate_meeting_amount(fields["week_target"])
if v is not None and v < 0:
raise ValueError("금주 목표는 0 이상이어야 합니다.")
sets.append("week_target = %s")
params.append(v)
if "attendees" in fields:
sets.append("attendees = %s")
params.append(store.validate_meeting_text(fields["attendees"], limit=500, what="참석자"))
if "notes" in fields:
sets.append("notes = %s")
params.append(store.validate_meeting_text(fields["notes"], what="메모"))
if not sets:
return
with self._pool.connection() as conn:
self._require_meetings(conn)
row = conn.execute(
f"UPDATE goal_meetings SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
"WHERE week_start = %s RETURNING week_start",
(*params, store.norm_str(updated_by, lower=True), week_start),
).fetchone()
if row is None:
raise KeyError(str(week_start))
def add_meeting_item(
self, *, week_start: date, section: str, section_color: str = "", label: str = "",
ref_item_id: int | None = None, place: str = "below", updated_by: str = "",
) -> int:
"""줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역)."""
sec = store.norm_str(section)
if not sec or len(sec) > store.MEETING_LABEL_MAX:
raise ValueError("구역 이름을 입력하세요(50자 이하).")
lb = store.validate_meeting_text(label, limit=store.MEETING_LABEL_MAX, what="줄 이름")
if place not in ("above", "below"):
raise ValueError("place 는 above 또는 below 입니다.")
with self._pool.connection() as conn:
with conn.transaction():
self._require_meetings(conn)
if not conn.execute(
"SELECT 1 FROM goal_meetings WHERE week_start = %s FOR UPDATE", (week_start,)
).fetchone():
raise KeyError(str(week_start))
rows = conn.execute(
"SELECT id, section, section_color FROM goal_meeting_items WHERE week_start = %s "
"ORDER BY sort_order, id", (week_start,),
).fetchall()
ids = [int(r["id"]) for r in rows]
color = store.norm_str(section_color) or next(
(r["section_color"] for r in rows if r["section"] == sec), "")
if ref_item_id is not None:
if ref_item_id not in ids:
raise KeyError(ref_item_id)
i = ids.index(ref_item_id) + (1 if place == "below" else 0)
else:
same = [n for n, r in enumerate(rows) if r["section"] == sec]
i = same[-1] + 1 if same else len(ids)
new_id = int(conn.execute(
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, "
"sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,0,%s) RETURNING id",
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
store.norm_str(updated_by, lower=True)),
).fetchone()["id"])
ids.insert(i, new_id)
for n, x in enumerate(ids):
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
return new_id
def update_meeting_item(self, *, item_id: int, fields: dict[str, Any], updated_by: str = "") -> dict[str, Any]:
"""줄 칸 — label · content(이번주 할 일) · target_amount · result_amount(그 주 결과, 원) · status(평가) ·
marketplace_code(실적 쇼핑몰 연결 — 결과 자동). 저장된 줄을 돌려준다."""
sets: list[str] = []
params: list[Any] = []
if "label" in fields:
sets.append("label = %s")
params.append(store.validate_meeting_text(fields["label"], limit=store.MEETING_LABEL_MAX, what="줄 이름"))
if "content" in fields:
sets.append("content = %s")
params.append(store.validate_meeting_text(fields["content"]))
for k in ("target_amount", "result_amount"):
if k in fields:
v = store.validate_meeting_amount(fields[k])
if k == "target_amount" and v is not None and v < 0:
raise ValueError("목표 금액은 0 이상이어야 합니다.")
sets.append(f"{k} = %s")
params.append(v)
if "status" in fields:
sets.append("status = %s")
params.append(store.validate_meeting_status(fields["status"]))
if "marketplace_code" in fields:
code = store.norm_str(fields["marketplace_code"], lower=True)
if len(code) > 30 or not re.fullmatch(r"[a-z0-9_]*", code):
raise ValueError("쇼핑몰 코드가 올바르지 않습니다.")
sets.append("marketplace_code = %s")
params.append(code)
with self._pool.connection() as conn:
self._require_meetings(conn)
if sets:
row = conn.execute(
f"UPDATE goal_meeting_items SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
f"WHERE id = %s RETURNING {self._MEETING_ITEM_COLS}",
(*params, store.norm_str(updated_by, lower=True), item_id),
).fetchone()
else:
row = conn.execute(
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE id = %s", (item_id,),
).fetchone()
if row is None:
raise KeyError(item_id)
return self._meeting_item(row)
def delete_meeting_item(self, *, item_id: int) -> None:
with self._pool.connection() as conn:
self._require_meetings(conn)
row = conn.execute("DELETE FROM goal_meeting_items WHERE id = %s RETURNING id", (item_id,)).fetchone()
if row is None:
raise KeyError(item_id)
def move_meeting_item(self, *, item_id: int, direction: int) -> None:
"""같은 구역 안에서 한 칸 위/아래."""
with self._pool.connection() as conn:
with conn.transaction():
self._require_meetings(conn)
me = conn.execute(
"SELECT week_start, section FROM goal_meeting_items WHERE id = %s", (item_id,)
).fetchone()
if me is None:
raise KeyError(item_id)
rows = conn.execute(
"SELECT id, section FROM goal_meeting_items WHERE week_start = %s ORDER BY sort_order, id "
"FOR UPDATE", (me["week_start"],),
).fetchall()
ids = [int(r["id"]) for r in rows]
i = ids.index(item_id)
j = i + (1 if direction > 0 else -1)
if not 0 <= j < len(ids) or rows[j]["section"] != me["section"]:
return
ids[i], ids[j] = ids[j], ids[i]
for n, x in enumerate(ids):
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]:
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
with self._pool.connection() as conn:
if not self._table_exists(conn, "goal_years"):
return {"sales_unit": "", "sales_target": None, "sales_actual": None, "roas_target": None}
head = conn.execute("SELECT sales_unit FROM goal_years WHERE year = %s", (year,)).fetchone()
vals = {(r["metric"], r["kind"]): float(r["value"]) for r in conn.execute(
"SELECT metric, kind, value FROM goal_metrics WHERE year = %s AND month = %s", (year, month),
).fetchall()}
return {"sales_unit": head["sales_unit"] if head else "", "sales_target": vals.get(("sales", "target")),
"sales_actual": vals.get(("sales", "actual")), "roas_target": vals.get(("roas", "target"))}
def goal_area_sections(self, *, year: int) -> list[tuple[str, str]]:
"""그 해 목표 표의 업무 영역(이름, 색) — 첫 회의록 구역. 없으면 빈 목록(기본 양식 구역)."""
with self._pool.connection() as conn:
if not self._table_exists(conn, "goal_areas"):
return []
rows = conn.execute(
"SELECT name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id", (year,)
).fetchall()
return [(r["name"], r["color"]) for r in rows]
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
# 직렬화 # 직렬화
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
+302 -27
View File
@@ -24,7 +24,7 @@ import logging
import threading import threading
import time import time
import uuid import uuid
from datetime import date from datetime import date, timedelta
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -2515,6 +2515,7 @@ def inbox_page(request: Request) -> HTMLResponse:
# ──────────────────────────────────────────────────────────── # ────────────────────────────────────────────────────────────
_GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)." _GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)."
_GOALS_014_MSG = "상·하반기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다." _GOALS_014_MSG = "상·하반기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다."
_GOALS_015_MSG = "세로 병합·연간/반기 칸 병합과 주간 회의록은 DB 마이그레이션 015 가 필요합니다."
def _fmt_goal_num(v: float | None) -> str: def _fmt_goal_num(v: float | None) -> str:
@@ -2532,23 +2533,39 @@ def _goal_label(metric: str, v: float | None) -> str:
return f"{s}%" if s and metric == "roas" else s return f"{s}%" if s and metric == "roas" else s
def _goal_row_layout(merges: dict[int, int], this_month: int) -> list[dict[str, Any]]: def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None:
"""업무 영역 한 줄의 칸 배치 — 연간 · 1~6월 · 상반기 · 7~12월 · 하반기 순서. """업무 영역 줄마다 칸 배치(row["layout"]) — 연간 · 1~6월 · 상반기 · 7~12월 · 하반기 순서, 엑셀식 사각형 병합.
월 칸은 병합(시작 월 → 칸 수)을 반영해 {"m", "span", "h"(1|2), "now"}, 연간·반기 칸은 {"m": 0|13|14}. 병합(row["merges"] = {시작 칸: (가로 칸 수, 세로 줄 수)})의 시작 칸은 {"span", "rspan"}(colspan/rowspan),
병합 정보가 반기를 넘거나 겹치면(있을 수 없지만) 그 병합은 무시한다.""" 병합에 가려진 칸은 빼고 그린다. 칸 = {"m", "kind": year|month|half, "h", "span", "rspan", "now"}.
out: list[dict[str, Any]] = [{"m": store.GOAL_YEAR, "kind": "year"}] 가로는 같은 반기 월 칸 안, 세로는 영역 끝까지로 자른다. 겹치는 병합(있을 수 없지만)은 나중 것을 무시."""
for h, (lo, hi, half_m) in enumerate(((1, 6, store.GOAL_H1), (7, 12, store.GOAL_H2)), start=1): order = store.GOAL_COL_ORDER
mo = lo covered: set[tuple[int, int]] = set()
while mo <= hi: anchors: dict[tuple[int, int], tuple[int, int]] = {}
span = int(merges.get(mo, 1) or 1) for ri, row in enumerate(rows):
if span < 1 or mo + span - 1 > hi: for start, (span, rspan) in sorted((row.get("merges") or {}).items()):
span = 1 if start not in order:
out.append({"m": mo, "span": span, "h": h, "kind": "month", continue
"now": mo <= this_month <= mo + span - 1}) ci = order.index(start)
mo += span cols = [c for c in range(ci, min(len(order), ci + span))
out.append({"m": half_m, "kind": "half", "h": h}) if store.goal_col_group(order[c]) == store.goal_col_group(start)]
return out rr = list(range(ri, min(len(rows), ri + max(1, rspan))))
cells = {(r, c) for r in rr for c in cols}
if (ri, ci) in covered or cells & set(anchors) - {(ri, ci)} or cells & covered:
continue
anchors[(ri, ci)] = (len(cols), len(rr))
covered |= cells - {(ri, ci)}
for ri, row in enumerate(rows):
out: list[dict[str, Any]] = []
for ci, m in enumerate(order):
if (ri, ci) in covered:
continue
span, rspan = anchors.get((ri, ci), (1, 1))
kind = "year" if m == store.GOAL_YEAR else "half" if m in (store.GOAL_H1, store.GOAL_H2) else "month"
h = 0 if kind == "year" else (1 if m == store.GOAL_H1 else 2) if kind == "half" else store.goal_half_of(m)
out.append({"m": m, "kind": kind, "h": h, "span": span, "rspan": rspan,
"now": kind == "month" and m <= this_month <= m + span - 1})
row["layout"] = out
def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any: def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
@@ -2557,6 +2574,8 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
return fn(*args, **kwargs) return fn(*args, **kwargs)
except store.GoalMigration014Needed: except store.GoalMigration014Needed:
raise HTTPException(status_code=503, detail=_GOALS_014_MSG) raise HTTPException(status_code=503, detail=_GOALS_014_MSG)
except store.GoalMigration015Needed:
raise HTTPException(status_code=503, detail=_GOALS_015_MSG)
except UndefinedTable: except UndefinedTable:
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG) raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
except KeyError: except KeyError:
@@ -2597,8 +2616,7 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
for kind in list(m): for kind in list(m):
m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()} m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()}
for area in board["areas"]: for area in board["areas"]:
for row in area["rows"]: _goal_area_layout(area["rows"], this_month)
row["layout"] = _goal_row_layout(row.get("merges") or {}, this_month)
return render_template( return render_template(
request, request,
"project/goals.html", "project/goals.html",
@@ -2754,22 +2772,279 @@ def api_set_goal_cell(
return JSONResponse({"ok": True}) return JSONResponse({"ok": True})
@router.post("/api/goals/rows/{row_id}/merge") @router.post("/api/goals/areas/{area_id}/merge")
def api_merge_goal_cells(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: def api_merge_goal_rect(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""월 칸 가로 병합 {start, end}(반기 안, 2칸 이상) — 걸친 병합은 흡수, 글은 이어서 시작 월 칸에.""" """엑셀식 병합 {row_from, row_to(줄 id), col_from, col_to(칸 번호 0·1~12·13·14)} — 같은 영역 안 사각형,
가로는 같은 반기 월 칸끼리. 걸친 병합은 흡수, 글은 왼쪽 위부터 이어서 왼쪽 위 칸에."""
user = _require_admin(request) user = _require_admin(request)
st = _db_or_503(request) st = _db_or_503(request)
start, span = _goal_call( res = _goal_call(
st.merge_goal_cells, row_id=row_id, start=payload.get("start"), end=payload.get("end"), st.merge_goal_rect, area_id=area_id, row_from=payload.get("row_from"), row_to=payload.get("row_to"),
updated_by=user["email"], col_from=payload.get("col_from"), col_to=payload.get("col_to"), updated_by=user["email"],
) )
return JSONResponse({"ok": True, "start": start, "span": span}) return JSONResponse({"ok": True, **res})
@router.delete("/api/goals/rows/{row_id}/merge/{start}") @router.delete("/api/goals/rows/{row_id}/merge/{start}")
def api_unmerge_goal_cells(request: Request, row_id: int, start: int) -> JSONResponse: def api_unmerge_goal_cells(request: Request, row_id: int, start: int) -> JSONResponse:
"""병합 해제 — 글은 시작 월 칸에 남는다.""" """병합 해제 — 글은 왼쪽 위(시작) 칸에 남는다(엑셀과 같음)."""
_require_admin(request) _require_admin(request)
st = _db_or_503(request) st = _db_or_503(request)
_goal_call(st.unmerge_goal_cells, row_id=row_id, start=start) _goal_call(st.unmerge_goal_cells, row_id=row_id, start=start)
return JSONResponse({"ok": True}) return JSONResponse({"ok": True})
# ════════════════════════════════════════════════════════════
# 주간 회의록 (마이그레이션 015) — 목표 표 월 머리 → /project/goals/{연도}/meetings/{월}?week=월요일
# 주 = 월요일~일요일. 지난주 목표·결과 리뷰 → 월 목표 달성을 위한 이번주 목표·할 일.
# 쇼핑몰 연결(유통 줄) 결과·전주/금주 매출·월 누적은 실적 모듈(performance_db)에서 읽기만 한다.
# ════════════════════════════════════════════════════════════
def _perf_sales(request: Request) -> Any:
"""실적 모듈 저장소(읽기 전용). 없거나 오류면 None — 회의록은 직접 입력만으로도 동작한다."""
return getattr(request.app.state, "performance_store", None)
def _perf_markets(perf: Any) -> list[dict[str, Any]]:
if perf is None:
return []
try:
return [m for m in perf.list_marketplaces() if m.get("enabled")]
except Exception: # noqa: BLE001 — 실적 DB 장애가 회의록을 막지 않게
logger.warning("performance marketplaces unavailable for meeting", exc_info=True)
return []
def _perf_sum(perf: Any, start: date, end: date, codes: list[str]) -> dict[str, int] | None:
"""기간 쇼핑몰별 매출 합(원, 취소·반품 차감 = 대시보드 총매출과 같은 값). 실적 모듈이 없으면 None."""
if perf is None or not codes or end < start:
return {} if perf is not None else None
try:
out: dict[str, int] = {}
for (_, code), amount in perf.daily_amounts(start, end, codes).items():
out[code] = out.get(code, 0) + int(amount)
return out
except Exception: # noqa: BLE001
logger.warning("performance sales unavailable for meeting", exc_info=True)
return None
def _meeting_view(request: Request, st: Any, *, year: int, month: int, week: date) -> dict[str, Any]:
"""회의록 화면 데이터 — 머리(월 목표·누적·남은 주 필요 매출·전주/금주 목표·결과) + 줄(전주 리뷰 포함)."""
today = today_kst()
meeting = st.get_meeting(week_start=week)
targets = st.goal_month_targets(year=year, month=month)
mult = store.sales_unit_multiplier(targets["sales_unit"])
perf = _perf_sales(request)
markets = _perf_markets(perf)
names = {m["code"]: m["name"] for m in markets}
sales_codes = [m["code"] for m in markets if m.get("include_in_sales")]
week_end = week + timedelta(days=6)
prev_start, prev_end = week - timedelta(days=7), week - timedelta(days=1)
first = date(year, month, 1)
last = date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1)
def total(a: date, b: date) -> int | None:
r = _perf_sum(perf, a, min(b, today), sales_codes)
return None if r is None else sum(r.values())
# 월 누적 = 이 주 앞까지(지난주 일요일까지) — 남은 목표를 이번 주 포함 남은 주로 나눠 "주당 필요 매출"
mtd_end = min(last, today, prev_end)
month_target_won = int(round(targets["sales_target"] * mult)) if targets["sales_target"] is not None and mult else None
mtd = total(first, mtd_end) if mtd_end >= first else 0
weeks_left = sum(1 for mon, _ in store.month_weeks(year, month) if mon >= week)
pm = meeting.get("prev_meeting") if meeting else None # 바로 앞 주 회의록이어야 "전주 목표"
need = None
if month_target_won is not None and mtd is not None and weeks_left:
need = max(0, month_target_won - mtd) // weeks_left
head = {
"sales_unit": targets["sales_unit"], "sales_target": targets["sales_target"],
"roas_target": targets["roas_target"], "month_target_won": month_target_won,
"mtd": mtd, "mtd_end": mtd_end.isoformat() if mtd_end >= first else "", "weeks_left": weeks_left,
"need_per_week": need,
"prev_target": pm["week_target"] if pm and pm["week_start"] == prev_start.isoformat() else None,
"prev_result": total(prev_start, prev_end) if prev_start <= today else None,
"week_result": total(week, week_end) if week <= today else None,
"perf": perf is not None,
}
if meeting:
# 줄마다 전주 결과 — 쇼핑몰 연결이면 그 주 실적(자동), 아니면 직접 입력한 결과
by_week: dict[str, dict[str, int] | None] = {}
for it in meeting["items"]:
prev = it.get("prev")
if not prev:
continue
auto = None
code = prev.get("marketplace_code") or ""
if code:
ws = prev["week_start"]
if ws not in by_week:
a = date.fromisoformat(ws)
by_week[ws] = _perf_sum(perf, a, min(a + timedelta(days=6), today),
[m["code"] for m in markets]) if a <= today else {}
got = by_week[ws]
auto = None if got is None else got.get(code, 0)
prev["auto_result"] = auto
prev["result"] = auto if auto is not None else prev.get("result_amount")
prev["market_name"] = names.get(code, code)
for it in meeting["items"]:
it["market_name"] = names.get(it["marketplace_code"], it["marketplace_code"]) if it["marketplace_code"] else ""
p = it.get("prev")
it["rate"] = (round(p["result"] / p["target_amount"] * 100, 1)
if p and p.get("result") is not None and p.get("target_amount") else None)
# 구역 묶음 — 이어진 같은 구역 줄을 한 덩어리로(표의 구역 칸 rowspan)
sections: list[dict[str, Any]] = []
for it in meeting["items"]:
if not sections or sections[-1]["name"] != it["section"]:
sections.append({"name": it["section"], "color": it["section_color"], "rows": []})
sections[-1]["rows"].append(it) # 키 이름 rows — 템플릿의 sec.items 는 dict.items 메서드가 된다
meeting["sections"] = sections
prev_items = [it["prev"] for it in meeting["items"] if it.get("prev")]
head["prev_items_target"] = sum(p["target_amount"] or 0 for p in prev_items) if prev_items else None
return {"meeting": meeting, "head": head, "markets": [{"code": m["code"], "name": m["name"]} for m in markets]}
@router.get("/goals/{year}/meetings/{month}", response_class=HTMLResponse)
def goal_meeting_page(request: Request, year: int, month: int, week: str | None = None) -> 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 or not 1 <= month <= 12:
raise HTTPException(status_code=404, detail="연도·월이 올바르지 않습니다.")
weeks = store.month_weeks(year, month)
today = today_kst()
sel = None
if week:
try:
sel = store.validate_week_start(week)
except ValueError:
sel = None
if sel is None or sel not in [w for w, _ in weeks]:
sel = next((w for w, e in weeks if w <= today <= e), weeks[0][0])
enabled = st.meetings_enabled()
existing = set(st.meeting_weeks(start=weeks[0][0], end=weeks[-1][0])) if enabled else set()
view = _meeting_view(request, st, year=year, month=month, week=sel) if enabled else {}
admin = is_admin(user)
return render_template(
request,
"project/goal_meeting.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": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": f"{year}년 {month}월 주간 회의록",
"page_subtitle": "지난주 리뷰와 이번주 목표",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"goal_year": year,
"goal_month": month,
"meetings_enabled": enabled,
"weeks": [{"start": w.isoformat(), "end": e.isoformat(), "n": i + 1, "label": f"{w.month}/{w.day}~{e.month}/{e.day}",
"has": w.isoformat() in existing, "now": w <= today <= e} for i, (w, e) in enumerate(weeks)],
"week": sel.isoformat(),
"week_n": next(i + 1 for i, (w, _) in enumerate(weeks) if w == sel),
"week_end": (sel + timedelta(days=6)).isoformat(),
"prev_week": (sel - timedelta(days=7)).isoformat(),
"meeting_status": store.MEETING_STATUS,
**view,
},
)
@router.get("/api/goals/meetings/{week_start}")
def api_get_meeting(request: Request, week_start: str, year: int, month: int) -> JSONResponse:
"""회의록 다시 읽기(저장 뒤 머리 숫자·달성률 갱신용) — 화면과 같은 계산."""
_require_user(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
if not 1 <= month <= 12:
raise HTTPException(status_code=400, detail="월이 올바르지 않습니다.")
view = _goal_call(_meeting_view, request, st, year=year, month=month, week=ws)
return JSONResponse(view)
@router.post("/api/goals/meetings/{week_start}")
def api_create_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""회의록 만들기(관리자) — 앞선 회의록 줄을 이어받거나, 처음이면 그 해 목표 표 업무 영역 + 기본 양식 줄."""
user = _require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
year = _goal_call(store.validate_goal_year, payload.get("year") or ws.year)
created = _goal_call(st.create_meeting, week_start=ws, sections=st.goal_area_sections(year=year),
created_by=user["email"])
return JSONResponse({"ok": True, "created": created}, status_code=201 if created else 200)
@router.put("/api/goals/meetings/{week_start}")
def api_update_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
fields = {k: payload[k] for k in ("week_target", "attendees", "notes") if k in payload}
_goal_call(st.update_meeting, week_start=ws, fields=fields, updated_by=user["email"])
return JSONResponse({"ok": True})
@router.delete("/api/goals/meetings/{week_start}")
def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
_goal_call(st.delete_meeting, week_start=ws)
return JSONResponse({"ok": True})
@router.post("/api/goals/meetings/{week_start}/items")
def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""줄 추가 {section, label?, ref_item_id?, place?: above|below} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝)."""
user = _require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
ref = payload.get("ref_item_id")
try:
ref_id = int(ref) if ref not in (None, "") else None
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="ref_item_id 가 올바르지 않습니다.")
item_id = _goal_call(
st.add_meeting_item, week_start=ws, section=payload.get("section", ""), label=payload.get("label", ""),
ref_item_id=ref_id, place=payload.get("place") or "below", updated_by=user["email"],
)
return JSONResponse({"ok": True, "id": item_id}, status_code=201)
@router.put("/api/goals/meeting-items/{item_id}")
def api_update_meeting_item(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""줄 칸 하나 — label·content·target_amount·result_amount·status·marketplace_code. 전주 결과·평가는
이번 회의 화면에서 지난주 줄(prev)의 result_amount·status 로 저장한다."""
user = _require_admin(request)
st = _db_or_503(request)
keys = ("label", "content", "target_amount", "result_amount", "status", "marketplace_code")
item = _goal_call(st.update_meeting_item, item_id=item_id,
fields={k: payload[k] for k in keys if k in payload}, updated_by=user["email"])
return JSONResponse({"ok": True, "item": item})
@router.delete("/api/goals/meeting-items/{item_id}")
def api_delete_meeting_item(request: Request, item_id: int) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.delete_meeting_item, item_id=item_id)
return JSONResponse({"ok": True})
@router.post("/api/goals/meeting-items/{item_id}/move")
def api_move_meeting_item(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.move_meeting_item, item_id=item_id, direction=int(payload.get("direction") or 0))
return JSONResponse({"ok": True})
+146
View File
@@ -7,6 +7,7 @@ DB 없이 단위 테스트 가능한 순수 함수만 둔다(malaysia.store 패
from __future__ import annotations from __future__ import annotations
import re import re
from datetime import date, timedelta
from html.parser import HTMLParser from html.parser import HTMLParser
from typing import Any from typing import Any
@@ -471,6 +472,151 @@ def validate_goal_text(body: Any) -> str:
return v return v
# ── 엑셀식 사각형 병합(마이그레이션 015) ──────────────────────────────
class GoalMigration015Needed(RuntimeError):
"""세로 병합·주간 회의록은 마이그레이션 015 뒤에만 된다."""
# 업무 영역 글 칸의 화면 순서 — 연간 · 1~6월 · 상반기 · 7~12월 · 하반기
GOAL_COL_ORDER: tuple[int, ...] = (0, 1, 2, 3, 4, 5, 6, GOAL_H1, 7, 8, 9, 10, 11, 12, GOAL_H2)
def goal_col_group(m: int) -> str:
"""병합 가능 묶음 — 가로 병합은 같은 묶음 안에서만(연간·반기 칸은 혼자, 월은 같은 반기끼리)."""
if m == GOAL_YEAR:
return "year"
if m in (GOAL_H1, GOAL_H2):
return f"half{1 if m == GOAL_H1 else 2}"
return f"months{goal_half_of(m)}"
def validate_goal_rect_cols(col_from: Any, col_to: Any) -> tuple[int, int]:
"""병합할 칸 범위(화면 순서의 양 끝 칸 번호) → (시작 칸 번호, 가로 칸 수).
가로로 여러 칸이면 같은 반기의 월 칸끼리만 — 연간·상반기·하반기 칸은 세로로만 합칠 수 있다."""
try:
a, b = int(col_from), int(col_to)
except (TypeError, ValueError):
raise ValueError("병합할 칸이 올바르지 않습니다.")
if a not in GOAL_COL_ORDER or b not in GOAL_COL_ORDER:
raise ValueError("병합할 칸이 올바르지 않습니다.")
ia, ib = sorted((GOAL_COL_ORDER.index(a), GOAL_COL_ORDER.index(b)))
cols = GOAL_COL_ORDER[ia:ib + 1]
if len({goal_col_group(m) for m in cols}) > 1:
raise ValueError("연간·상반기·하반기 칸은 세로로만, 월 칸은 같은 반기 안에서만 합칠 수 있습니다.")
return cols[0], len(cols)
# ── 주간 회의록(마이그레이션 015) — 월 머리를 누르면 그 달 주차별 회의록 ──────────
MEETING_STATUS: dict[str, str] = {"": "", "done": "완료", "partial": "일부", "miss": "미달"}
MEETING_TEXT_MAX = 4000
MEETING_LABEL_MAX = 50
# 첫 회의록(이전 주 회의록이 없을 때)의 구역별 줄 — 사용자 회의록 양식(2026-10). 목표 표의 업무 영역 이름과 같으면
# 그 줄들로, 없는 구역은 빈 줄 하나. 다음 주부터는 지난주 회의록 줄을 그대로 이어받는다.
MEETING_TEMPLATE: dict[str, tuple[str, ...]] = {
"상품": ("상품1", "상품2", "상품3", "상품4", "상품5"),
"마케팅": ("메타(숫자)", "구글", "네이버", "기타.신규"),
"컨텐츠": ("내용1", "내용2", "내용3", "내용4", "내용5"),
"유통": ("신규 인플루언서", "콜라보", "쿠팡", "네이버", "gs", "토스", "애터미", "해외", "오프라인", "기타"),
}
# 유통 줄 이름 → 실적 모듈 쇼핑몰 코드(그 주 결과를 실적에서 자동으로). 첫 단어 기준, 소문자 비교.
MEETING_MARKET_GUESS: tuple[tuple[str, str], ...] = (
("쿠팡", "coupang"), ("네이버", "naver"), ("스마트스토어", "naver"), ("gs", "gsshop"), ("토스", "toss"),
("11번가", "elevenst"), ("카페24", "cafe24"), ("자사몰", "cafe24"), ("롯데", "lotteon"), ("지마켓", "gmarket"),
("g마켓", "gmarket"), ("카카오", "kakao"), ("오늘의집", "ohouse"),
)
def guess_meeting_market(section: str, label: str) -> str:
"""유통 구역 줄 이름으로 실적 쇼핑몰 코드 추측(없으면 ""). 마케팅의 "네이버"(광고)는 연결하지 않는다."""
if norm_str(section) != "유통":
return ""
lb = norm_str(label).lower()
for word, code in MEETING_MARKET_GUESS:
if lb.startswith(word):
return code
return ""
def week_monday(d: date) -> date:
return d - timedelta(days=d.weekday())
def month_weeks(year: int, month: int) -> list[tuple[date, date]]:
"""그 달과 겹치는 주(월요일~일요일) 목록 — 1주차 = 1일이 들어 있는 주."""
first = date(year, month, 1)
last = (date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1))
out, mon = [], week_monday(first)
while mon <= last:
out.append((mon, mon + timedelta(days=6)))
mon += timedelta(days=7)
return out
def validate_week_start(v: Any) -> date:
try:
d = date.fromisoformat(str(v).strip()[:10])
except ValueError:
raise ValueError("주 시작일이 올바르지 않습니다.")
if d.weekday() != 0:
raise ValueError("주 시작일은 월요일이어야 합니다.")
if not 2000 <= d.year <= 2100:
raise ValueError("주 시작일이 올바르지 않습니다.")
return d
def _korean_amount(s: str) -> float:
""""1억2천만"·"3천만"·"1.5억"·"120만"·"3천5백" → 숫자. 단위 없는 숫자는 그대로. 틀리면 ValueError."""
def small(t: str) -> float: # 만 아래 자리 — 천·백·십
val = 0.0
for unit, mul in (("천", 1_000), ("백", 100), ("십", 10)):
if unit in t:
a, t = t.split(unit, 1)
val += (float(a) if a else 1.0) * mul
return val + (float(t) if t else 0.0)
total, rest = 0.0, s
for unit, mul in (("억", 100_000_000), ("만", 10_000)):
if unit in rest:
a, rest = rest.split(unit, 1)
total += (small(a) if a else 1.0) * mul
return total + small(rest)
def validate_meeting_amount(v: Any) -> int | None:
"""금액(원) — 쉼표·공백·"원" 은 떼고, "120만"·"1.5억"·"3천만"·"1억2천만" 도 읽는다. 빈값은 None(=지움)."""
s = norm_str(v).replace(",", "").replace(" ", "").rstrip("원")
if not s:
return None
try:
f = _korean_amount(s)
except ValueError:
raise ValueError(f"금액은 숫자로 입력하세요(예: 1,200,000 · 120만 · 1.5억 · 3천만): {v}")
if f != f or abs(f) >= 1e15:
raise ValueError(f"금액 범위를 벗어났습니다: {v}")
return int(round(f))
def validate_meeting_text(v: Any, *, limit: int = MEETING_TEXT_MAX, what: str = "내용") -> str:
s = str(v or "").replace("\r\n", "\n").strip()
if len(s) > limit:
raise ValueError(f"{what}은(는) {limit}자까지 쓸 수 있습니다.")
return s
def validate_meeting_status(v: Any) -> str:
s = norm_str(v)
if s not in MEETING_STATUS:
raise ValueError("평가 값이 올바르지 않습니다.")
return s
def sales_unit_multiplier(unit: str) -> int | None:
"""목표 표의 매출 단위 글자 → 원 배수("백만원" → 1,000,000). 모르는 단위면 None(원 환산 안 함)."""
u = norm_str(unit).replace(" ", "").rstrip("원") or ""
table = {"": 1, "천": 1_000, "만": 10_000, "십만": 100_000, "백만": 1_000_000, "천만": 10_000_000, "억": 100_000_000}
return table.get(u)
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str: def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}" return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
@@ -0,0 +1,232 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
{%- macro won(v) -%}{% if v is not none %}{{ "{:,}".format(v) }}{% endif %}{%- endmacro -%}
{%- macro num(v) -%}{% if v is not none %}{% if v == v | int %}{{ "{:,}".format(v | int) }}{% else %}{{ "{:,.2f}".format(v) }}{% endif %}{% endif %}{%- endmacro -%}
{% block content %}
{# 주간 회의록 — 목표 표 월 머리를 누르면 열린다(/project/goals/{연도}/meetings/{월}?week=월요일).
주(월~일)마다 회의록 하나: 머리(월 목표·지난주까지 누적·주당 필요 매출, 전주 목표·결과, 금주 목표·현재)
+ 구역(목표 표 업무 영역)별 줄 — 이번주 할 일·목표 금액 | 전주 할 일·목표·결과·달성률·평가.
전주 칸은 지난 회의록의 같은 줄(carry_from). 쇼핑몰 연결 줄의 결과·전주/금주 매출·누적은 실적 모듈에서 자동.
입력은 관리자만(칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015 (goal_meetings·goal_meeting_items). #}
<div class="pj-wrap pj-inbox-view pj-goal-view pj-meet-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 pj-meet-head">
<div class="pj-meet-title">
<a class="pj-meet-back" href="/project/goals/{{ goal_year }}" title="{{ goal_year }}년 목표로"><span class="material-symbols-outlined">arrow_back</span></a>
<h2>{{ goal_year }}년 {{ goal_month }}월 주간 회의록</h2>
{% set pm = goal_month - 1 if goal_month > 1 else 12 %}{% set py = goal_year if goal_month > 1 else goal_year - 1 %}
{% set nm = goal_month + 1 if goal_month < 12 else 1 %}{% set ny = goal_year if goal_month < 12 else goal_year + 1 %}
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ py }}/meetings/{{ pm }}">‹ {{ pm }}월</a>
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ ny }}/meetings/{{ nm }}">{{ nm }}월 ›</a>
</div>
{% if meeting and is_admin %}
<div class="pj-goal-head-acts">
<button type="button" class="pj-btn" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
<button type="button" class="pj-btn pj-btn-danger" id="pj-meet-del">회의록 삭제</button>
</div>
{% elif meeting %}
<div class="pj-goal-head-acts">
<button type="button" class="pj-btn" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
<span class="pj-goal-note">회의록은 관리자만 입력할 수 있습니다.</span>
</div>
{% endif %}
</div>
<div class="pj-view pj-meet-pane" id="pj-meet-pane" data-week="{{ week }}" data-year="{{ goal_year }}"
data-month="{{ goal_month }}" data-admin="{{ 'true' if is_admin else 'false' }}">
{# 주차 탭 — 주 = 월요일~일요일, 1주차 = 1일이 들어 있는 주. 점 = 회의록 있음 #}
<nav class="pj-meet-weeks" aria-label="주차">
{% for w in weeks %}
<a class="pj-meet-week{% if w.start == week %} is-on{% endif %}{% if w.now %} is-now{% endif %}"
href="?week={{ w.start }}">
<b>{{ w.n }}주차</b><span>{{ w.label }}</span>
{% if w.has %}<i class="pj-meet-dot" title="회의록 있음"></i>{% endif %}
{% if w.now %}<em>이번 주</em>{% endif %}
</a>
{% endfor %}
</nav>
{% if not meetings_enabled %}
<div class="pj-empty">주간 회의록이 아직 준비되지 않았습니다(DB 마이그레이션 015 필요).</div>
{% elif not meeting %}
<div class="pj-empty pj-goal-empty">
<p>{{ week_n }}주차({{ week }} ~ {{ week_end }}) 회의록이 아직 없습니다.</p>
{% if is_admin %}
<p class="pj-goal-empty-sub">만들면 앞선 회의록의 줄(구역·항목·쇼핑몰 연결)을 이어받아, 지난주 할 일·목표·결과를 나란히 리뷰할 수 있습니다.
처음이면 {{ goal_year }}년 목표 표의 업무 영역과 기본 양식 줄로 시작합니다.</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-meet-create">{{ week_n }}주차 회의록 만들기</button>
{% endif %}
</div>
{% else %}
{% set h = head %}
{% set edit = is_admin %}
{# ── 머리 — 월 목표 대비 누적·남은 주 필요 매출 / 전주 리뷰 / 금주 목표 ── #}
<div class="pj-meet-kpis">
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">월 목표 매출</span>
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">목표 표에 없음</span>{% endif %}</span>
{% if h.month_target_won is not none and h.sales_unit and h.sales_unit != '원' %}<span class="pj-meet-kpi-sub">= {{ won(h.month_target_won) }}원</span>{% endif %}
</div>
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">월 누적 실적 <small>(지난주까지)</small></span>
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ won(h.mtd) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
{% if h.month_target_won and h.mtd is not none %}<span class="pj-meet-kpi-sub">달성 {{ "%.1f" | format(h.mtd / h.month_target_won * 100) }}%</span>{% endif %}
</div>
<div class="pj-meet-kpi is-accent">
<span class="pj-meet-kpi-label">주당 필요 매출 <small>(남은 {{ h.weeks_left }}주)</small></span>
<span class="pj-meet-kpi-val">{% if h.need_per_week is not none %}{{ won(h.need_per_week) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
<span class="pj-meet-kpi-sub">월 목표 − 누적을 이번 주 포함 남은 주로 나눈 값</span>
</div>
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">목표 ROAS</span>
<span class="pj-meet-kpi-val">{% if h.roas_target is not none %}{{ num(h.roas_target) }}<small>%</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</div>
</div>
<div class="pj-meet-kpis is-week">
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">전주 목표</span>
<span class="pj-meet-kpi-val">{% if h.prev_target is not none %}{{ won(h.prev_target) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</div>
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">전주 결과 <small>({{ prev_week[5:] | replace('-', '/') }}~ 실적)</small></span>
<span class="pj-meet-kpi-val">{% if h.prev_result is not none %}{{ won(h.prev_result) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
</div>
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">전주 달성률</span>
{% if h.prev_target and h.prev_result is not none %}{% set r = h.prev_result / h.prev_target * 100 %}
<span class="pj-meet-kpi-val {{ 'is-good' if r >= 100 else 'is-low' }}">{{ "%.1f" | format(r) }}<small>%</small></span>
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
</div>
<div class="pj-meet-kpi is-input">
<span class="pj-meet-kpi-label">금주 목표</span>
{% if edit %}
<span class="pj-meet-kpi-val"><input type="text" class="pj-meet-amount" id="pj-meet-target" inputmode="decimal"
autocomplete="off" placeholder="{{ won(h.need_per_week) if h.need_per_week is not none else '예: 30,000,000' }}"
value="{{ won(meeting.week_target) }}" /><small>원</small></span>
{% else %}
<span class="pj-meet-kpi-val">{% if meeting.week_target is not none %}{{ won(meeting.week_target) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
{% endif %}
{% if h.need_per_week is not none %}<span class="pj-meet-kpi-sub">필요 {{ won(h.need_per_week) }}원</span>{% endif %}
</div>
<div class="pj-meet-kpi">
<span class="pj-meet-kpi-label">금주 현재 실적</span>
<span class="pj-meet-kpi-val">{% if h.week_result is not none %}{{ won(h.week_result) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
{% if meeting.week_target and h.week_result is not none %}<span class="pj-meet-kpi-sub">목표의 {{ "%.1f" | format(h.week_result / meeting.week_target * 100) }}%</span>{% endif %}
</div>
</div>
{% if not h.perf %}<p class="pj-goal-note">실적 모듈이 연결되지 않아 실적·누적·쇼핑몰 자동 결과는 비어 있습니다(결과는 직접 입력).</p>{% endif %}
<label class="pj-meet-attend">참석자
{% if edit %}<input type="text" id="pj-meet-attendees" maxlength="500" placeholder="예: 대표, 마케팅팀, 유통팀" value="{{ meeting.attendees }}" />
{% else %}<span>{{ meeting.attendees or '—' }}</span>{% endif %}
</label>
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
<table class="pj-meet-table" id="pj-meet-table">
{# table-layout: fixed 는 첫 줄(묶음 머리, colspan)로 너비를 정하므로 열 너비는 colgroup 으로 #}
<colgroup>
<col class="pj-meet-w-sec" /><col class="pj-meet-w-label" /><col /><col class="pj-meet-w-amt" />
<col /><col class="pj-meet-w-amt" /><col class="pj-meet-w-amt" /><col class="pj-meet-w-rate" /><col class="pj-meet-w-eval" />
</colgroup>
<thead>
<tr class="pj-meet-group">
<th colspan="2"></th>
<th colspan="2" class="is-this">이번주 ({{ week[5:] | replace('-', '/') }} ~ {{ week_end[5:] | replace('-', '/') }})</th>
<th colspan="5" class="is-prev">지난주 리뷰</th>
</tr>
<tr>
<th class="pj-meet-c-sec">구역</th>
<th class="pj-meet-c-label">항목</th>
<th class="pj-meet-c-text">이번주 할 일 · 행사</th>
<th class="pj-meet-c-amt">목표 금액</th>
<th class="pj-meet-c-text is-prev">지난주 할 일</th>
<th class="pj-meet-c-amt is-prev">지난주 목표</th>
<th class="pj-meet-c-amt is-prev">결과</th>
<th class="pj-meet-c-rate is-prev">달성률</th>
<th class="pj-meet-c-eval is-prev">평가</th>
</tr>
</thead>
{% for sec in meeting.sections %}
<tbody class="pj-meet-sec" data-section="{{ sec.name }}" style="--goal-bg: {{ sec.color or '#fff' }}">
{% for it in sec.rows %}
{% set p = it.prev %}
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}" data-market="{{ it.marketplace_code }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
{% if loop.first %}
<th class="pj-meet-c-sec" rowspan="{{ sec.rows | length }}">{{ sec.name }}
{% if edit %}<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
</th>
{% endif %}
<th class="pj-meet-c-label">
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
{% if it.market_name %}<span class="pj-meet-market" title="결과를 실적 모듈 {{ it.market_name }} 매출에서 자동으로">{{ it.market_name }}</span>{% endif %}
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
</th>
<td class="pj-meet-c-text">
{% if edit %}<textarea class="pj-meet-text" rows="1" data-field="content" placeholder="이번주 할 일·행사">{{ it.content }}</textarea>
{% else %}<div class="pj-meet-ro">{{ it.content }}</div>{% endif %}
</td>
<td class="pj-meet-c-amt">
{% if edit %}<input type="text" class="pj-meet-amount" data-field="target_amount" inputmode="decimal" autocomplete="off" value="{{ won(it.target_amount) }}" />
{% else %}{{ won(it.target_amount) }}{% endif %}
</td>
{% if p %}
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{{ p.content }}</div></td>
<td class="pj-meet-c-amt is-prev">{{ won(p.target_amount) }}</td>
<td class="pj-meet-c-amt is-prev">
{% if p.auto_result is not none %}
<span class="pj-meet-auto" title="실적 모듈 {{ p.market_name }} {{ p.week_start }} 주 매출(자동)">{{ won(p.auto_result) }}</span>
{% elif edit %}<input type="text" class="pj-meet-amount" data-field="result_amount" data-target="prev" inputmode="decimal" autocomplete="off" value="{{ won(p.result_amount) }}" placeholder="결과" />
{% else %}{{ won(p.result_amount) }}{% endif %}
</td>
<td class="pj-meet-c-rate is-prev" data-rate>{% if it.rate is not none %}<span class="{{ 'is-good' if it.rate >= 100 else 'is-low' }}">{{ it.rate }}%</span>{% endif %}</td>
<td class="pj-meet-c-eval is-prev">
{% if edit %}
<select class="pj-meet-eval" data-field="status" data-target="prev" data-v="{{ p.status }}">
{% for k, v in meeting_status.items() %}<option value="{{ k }}"{% if k == p.status %} selected{% endif %}>{{ v or '—' }}</option>{% endfor %}
</select>
{% else %}<span class="pj-meet-eval-ro" data-v="{{ p.status }}">{{ meeting_status[p.status] or '—' }}</span>{% endif %}
</td>
{% else %}
<td class="pj-meet-c-text is-prev is-none" colspan="5"><span class="pj-muted">지난 회의록에 없는 줄</span></td>
{% endif %}
</tr>
{% endfor %}
</tbody>
{% endfor %}
</table>
{% if edit %}
<div class="pj-goal-foot">
<button type="button" class="pj-btn" id="pj-meet-sec-new">+ 구역 추가</button>
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 금액은 원 단위(120만·1.5억도 됨). 항목을 우클릭하거나 ⋯ 를 누르면
줄 추가·순서·삭제·쇼핑몰 연결(결과를 실적에서 자동). 지난주 결과·평가는 지난 회의록 줄에 저장됩니다.</span>
</div>
{% endif %}
<div class="pj-meet-notes">
<h3>결정 사항 · 메모</h3>
{% if edit %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
</div>
{% endif %}
</div>
</section>
</div>
</div>
{% if markets %}<script>window.PJ_MEET_MARKETS = {{ markets | tojson }};</script>{% endif %}
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261001c" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001b" /> <link rel="stylesheet" href="/static/project.css?v=20261001c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -74,7 +74,8 @@
{# 연간·월·반기 칸도 머리 칸 오른쪽 끝을 끌어 너비 조절(data-col: y · m1~m12 · h1 · h2) #} {# 연간·월·반기 칸도 머리 칸 오른쪽 끝을 끌어 너비 조절(data-col: y · m1~m12 · h1 · h2) #}
<th class="pj-goal-year-col" data-col="y">연간<span class="pj-goal-colresize" data-col="y" title="끌어서 너비 조절"></span></th> <th class="pj-goal-year-col" data-col="y">연간<span class="pj-goal-colresize" data-col="y" title="끌어서 너비 조절"></span></th>
{% for h, hmonths, hm, hname in halves %} {% for h, hmonths, hm, hname in halves %}
{% for mo in hmonths %}<th class="pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-col="m{{ mo }}"><span class="pj-goal-mlabel">{{ mo }}월</span><span class="pj-goal-colresize" data-col="m{{ mo }}" title="끌어서 너비 조절"></span></th>{% endfor %} {# 월 이름을 누르면 그 달 주간 회의록(/goals/{연도}/meetings/{월}) #}
{% for mo in hmonths %}<th class="pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-col="m{{ mo }}"><a class="pj-goal-mlabel pj-goal-mlink" href="/project/goals/{{ goal_year }}/meetings/{{ mo }}" title="{{ mo }}월 주간 회의록">{{ mo }}월</a><span class="pj-goal-colresize" data-col="m{{ mo }}" title="끌어서 너비 조절"></span></th>{% endfor %}
{# 반기 칸 — 버튼으로 그 반기의 월 칸을 접었다 편다(localStorage pj_goal_fold) #} {# 반기 칸 — 버튼으로 그 반기의 월 칸을 접었다 편다(localStorage pj_goal_fold) #}
<th class="pj-goal-half-col" data-h="{{ h }}" data-col="h{{ h }}"> <th class="pj-goal-half-col" data-h="{{ h }}" data-col="h{{ h }}">
<button type="button" class="pj-goal-fold" data-h="{{ h }}" aria-expanded="true" <button type="button" class="pj-goal-fold" data-h="{{ h }}" aria-expanded="true"
@@ -167,14 +168,13 @@
</span> </span>
{% endif %} {% endif %}
</th> </th>
{# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #}
{% for c in row.layout %} {% for c in row.layout %}
{% set editable = is_admin and (c.kind != 'half' or board.halves) %} {% set editable = is_admin and (c.kind != 'half' or board.halves) %}
{% if c.kind == 'month' %} {% set merged = c.span > 1 or c.rspan > 1 %}
<td class="pj-goal-texttd pj-goal-m{% if c.span > 1 %} is-merged{% endif %}{% if c.now %} is-now{% endif %}" <td class="pj-goal-texttd {{ 'pj-goal-m' if c.kind == 'month' else ('pj-goal-year-col' if c.kind == 'year' else 'pj-goal-half-col') }}{% if merged %} is-merged{% endif %}{% if c.now %} is-now{% endif %}"
data-h="{{ c.h }}" data-month="{{ c.m }}" data-span="{{ c.span }}"{% if c.span > 1 %} colspan="{{ c.span }}" style="--span: {{ c.span }}"{% endif %}> {% if c.kind == 'month' %}data-h="{{ c.h }}" {% endif %}data-month="{{ c.m }}" data-span="{{ c.span }}" data-rspan="{{ c.rspan }}"
{% else %} {%- if c.span > 1 %} colspan="{{ c.span }}" style="--span: {{ c.span }}"{% endif %}{% if c.rspan > 1 %} rowspan="{{ c.rspan }}"{% endif %}>
<td class="pj-goal-texttd {{ 'pj-goal-year-col' if c.kind == 'year' else 'pj-goal-half-col' }}" data-month="{{ c.m }}">
{% endif %}
{%- if editable -%} {%- if editable -%}
<textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ c.m }}" <textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ c.m }}"
placeholder="{{ '연간 목표' if c.m == 0 else ('상반기 목표' if c.m == 13 else ('하반기 목표' if c.m == 14 else '')) }}">{{ row.cells.get(c.m, '') }}</textarea> placeholder="{{ '연간 목표' if c.m == 0 else ('상반기 목표' if c.m == 13 else ('하반기 목표' if c.m == 14 else '')) }}">{{ row.cells.get(c.m, '') }}</textarea>
@@ -192,7 +192,8 @@
<div class="pj-goal-foot"> <div class="pj-goal-foot">
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button> <button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다. 항목 칸을 우클릭하면 줄을 추가·삭제합니다. <span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다. 항목 칸을 우클릭하면 줄을 추가·삭제합니다.
{%- if board.halves %} 월 칸은 Shift+클릭으로 여러 칸을 고른 뒤 병합하거나, 우클릭 메뉴로 병합·해제합니다.{% endif %}</span> {%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
</div> </div>
{% endif %} {% endif %}
{% endif %} {% endif %}
@@ -205,5 +206,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261001b" defer></script> <script src="/static/project.js?v=20261001c" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001b" /> <link rel="stylesheet" href="/static/project.css?v=20261001c" />
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" /> <link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001b" /> <link rel="stylesheet" href="/static/project.css?v=20261001c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -104,5 +104,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261001b" defer></script> <script src="/static/project.js?v=20261001c" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001b" /> <link rel="stylesheet" href="/static/project.css?v=20261001c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }} "today": {{ today | tojson }}
} }
</script> </script>
<script src="/static/project.js?v=20261001b" defer></script> <script src="/static/project.js?v=20261001c" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001b" /> <link rel="stylesheet" href="/static/project.css?v=20261001c" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host --> <!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host --> <!-- 타임라인 vis-timeline — self-host -->
@@ -496,5 +496,5 @@
</script> </script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script> <script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261001b" defer></script> <script src="/static/project.js?v=20261001c" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261001b" /> <link rel="stylesheet" href="/static/project.css?v=20261001c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261001b" defer></script> <script src="/static/project.js?v=20261001c" defer></script>
{% endblock %} {% endblock %}
+139 -4
View File
@@ -2147,17 +2147,152 @@ textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
.pj-goal-row-text[data-goal-edit]:empty { min-height: 1.5em; } .pj-goal-row-text[data-goal-edit]:empty { min-height: 1.5em; }
.pj-goal-row-text[data-goal-edit]:empty:hover::before { content: "줄 이름"; color: rgba(0, 0, 0, .3); font-weight: 500; } .pj-goal-row-text[data-goal-edit]:empty:hover::before { content: "줄 이름"; color: rgba(0, 0, 0, .3); font-weight: 500; }
/* 월 칸 병합 — Shift+클릭 선택 표시와 떠 있는 병합 버튼(body 에 붙음) */ /* 칸 병합 — 끌어서(또는 Shift+클릭) 고른 범위 표시. 우클릭 메뉴로 셀 병합·병합 해제 */
.pj-goal-table td.pj-goal-texttd.is-merge-sel { .pj-goal-table td.pj-goal-texttd.is-merge-sel {
box-shadow: inset 0 0 0 2px var(--pj-accent); box-shadow: inset 0 0 0 2px var(--pj-accent);
background-image: linear-gradient(rgba(123, 104, 238, .12), rgba(123, 104, 238, .12)); background-image: linear-gradient(rgba(123, 104, 238, .12), rgba(123, 104, 238, .12));
} }
.pj-goal-mergebar { position: fixed; z-index: 1000; }
.pj-goal-mergebar .pj-btn { display: inline-flex; align-items: center; gap: 4px; box-shadow: 0 6px 18px rgba(16, 24, 40, .2); }
.pj-goal-mergebar .material-symbols-outlined { font-size: 18px; }
.pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; } .pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; }
/* 칸 병합 — 끌어서 고르는 동안 글 선택 막기 */
html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important; cursor: cell !important; }
/* 월 머리 → 그 달 주간 회의록 */
.pj-goal-mlink { color: inherit; text-decoration: none; border-radius: 5px; padding: 2px 4px; }
.pj-goal-mlink:hover { color: var(--pj-accent-dark); background: var(--pj-accent-tint); }
.pj-btn-sm { padding: 4px 10px; font-size: 12.5px; text-decoration: none; display: inline-flex; align-items: center; }
/* ════════════════════════════════════════════════════════════
주간 회의록(goal_meeting.html) — 주차 탭 · 머리 숫자 카드 · 구역별 줄(이번주 | 지난주 리뷰) · 메모
════════════════════════════════════════════════════════════ */
.pj-meet-pane { flex: 1 1 auto; min-height: 0; overflow: auto; }
.pj-meet-title { display: flex; align-items: center; gap: 8px; }
.pj-meet-title h2 { margin: 0 6px 0 0; }
.pj-meet-back { display: inline-flex; color: var(--pj-ink-soft); border-radius: 6px; padding: 2px; }
.pj-meet-back:hover { background: #f1f2f4; color: var(--pj-ink); }
.pj-goal-head-acts .pj-btn .material-symbols-outlined { font-size: 17px; vertical-align: -3px; }
.pj-meet-weeks { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 14px; padding-top: 9px; } /* "이번 주" 꼬리표 자리 */
.pj-meet-week {
position: relative; display: flex; flex-direction: column; gap: 1px; min-width: 104px; padding: 7px 12px;
border: 1px solid var(--pj-border); border-radius: 10px; background: #fff; color: var(--pj-ink); text-decoration: none;
}
.pj-meet-week b { font-size: 13px; }
.pj-meet-week span { font-size: 11.5px; color: var(--pj-ink-soft); }
.pj-meet-week em { position: absolute; top: -8px; right: 8px; font-style: normal; font-size: 10.5px; font-weight: 700;
padding: 0 6px; border-radius: 999px; background: var(--pj-accent); color: #fff; }
.pj-meet-week:hover { border-color: #cfd3d8; background: #fafafb; }
.pj-meet-week.is-on { border-color: var(--pj-accent); box-shadow: inset 0 0 0 1px var(--pj-accent); background: var(--pj-accent-tint); }
.pj-meet-dot { position: absolute; top: 9px; right: 9px; width: 7px; height: 7px; border-radius: 50%; background: #34a853; }
.pj-meet-kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-bottom: 8px; }
.pj-meet-kpis.is-week { grid-template-columns: repeat(5, minmax(0, 1fr)); margin-bottom: 12px; }
.pj-meet-kpi {
display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; border: 1px solid var(--pj-border);
border-radius: 10px; background: #fff; min-width: 0;
}
.pj-meet-kpi.is-accent { border-color: #cfc6fb; background: #faf9ff; }
.pj-meet-kpi.is-input { border-color: #f6c69a; background: #fffaf4; }
.pj-meet-kpi-label { font-size: 12px; color: var(--pj-ink-soft); font-weight: 600; }
.pj-meet-kpi-label small { font-weight: 500; }
.pj-meet-kpi-val { font-size: 19px; font-weight: 800; font-variant-numeric: tabular-nums; display: flex; align-items: baseline; gap: 3px; }
.pj-meet-kpi-val small { font-size: 12px; font-weight: 600; color: var(--pj-ink-soft); }
.pj-meet-kpi-val.is-good { color: #1f8a4c; }
.pj-meet-kpi-val.is-low { color: #c2410c; }
.pj-meet-kpi-sub { font-size: 11.5px; color: var(--pj-ink-soft); }
.pj-meet-kpi .pj-meet-amount {
font-size: 18px; font-weight: 800; height: 30px; width: 100%; max-width: 190px; text-align: left;
border: 1px solid #f3d2b0; border-radius: 7px; background: #fff; padding: 0 8px;
}
@media (max-width: 1100px) { .pj-meet-kpis, .pj-meet-kpis.is-week { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.pj-meet-attend { display: flex; align-items: center; gap: 8px; margin: 0 0 10px; font-size: 12.5px; font-weight: 600; color: var(--pj-ink-soft); }
.pj-meet-attend input { flex: 0 1 420px; height: 30px; padding: 0 8px; border: 1px solid var(--pj-border); border-radius: 7px; font: inherit; color: var(--pj-ink); font-weight: 500; }
.pj-meet-table {
width: 100%; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px;
background: #fff; border: 1px solid #dfe2e6; border-radius: 10px; color: var(--pj-ink);
}
.pj-meet-table th, .pj-meet-table td {
box-sizing: border-box; border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top;
}
.pj-meet-table tr > :last-child { border-right: none; }
.pj-meet-table thead th {
position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 8px; font-weight: 700;
text-align: center; vertical-align: middle; white-space: nowrap;
}
.pj-meet-table thead tr.pj-meet-group th { top: 0; height: 26px; font-size: 12px; }
.pj-meet-table thead tr:nth-child(2) th { top: 26px; }
.pj-meet-table thead th.is-this { background: #fff7ed; color: #9a4b0b; }
.pj-meet-table thead th.is-prev { background: #f1f3f6; color: #4b5563; }
.pj-meet-w-sec { width: 80px; }
.pj-meet-w-label { width: 160px; }
.pj-meet-w-amt { width: 122px; }
.pj-meet-w-rate { width: 76px; }
.pj-meet-w-eval { width: 88px; }
.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); }
.pj-meet-sec > tr > td.is-prev { background: #fafbfc; }
.pj-meet-sec > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
.pj-meet-sec th { padding: 7px 8px; vertical-align: middle; text-align: center; }
th.pj-meet-c-sec { position: relative; font-size: 13px; font-weight: 800; }
.pj-meet-sec-add {
display: block; margin: 4px auto 0; width: 22px; height: 22px; border: 1px dashed rgba(0, 0, 0, .25); border-radius: 6px;
background: rgba(255, 255, 255, .6); color: var(--pj-ink-soft); cursor: pointer; line-height: 18px; opacity: 0; transition: opacity .12s;
}
th.pj-meet-c-sec:hover .pj-meet-sec-add, .pj-meet-sec-add:focus { opacity: 1; }
th.pj-meet-c-label { position: relative; font-weight: 600; color: #3b4048; text-align: left; }
.pj-meet-label { word-break: keep-all; overflow-wrap: anywhere; }
.pj-meet-label[data-meet-edit] { cursor: text; border-radius: 5px; padding: 1px 3px; margin: -1px -3px; }
.pj-meet-label[data-meet-edit]:hover { background: rgba(255, 255, 255, .65); box-shadow: 0 0 0 1px rgba(0, 0, 0, .14); }
.pj-meet-label.is-editing { background: #fff; box-shadow: 0 0 0 2px var(--pj-accent); outline: none; }
.pj-meet-label[data-meet-edit]:empty { display: inline-block; min-width: 3em; min-height: 1.4em; }
.pj-meet-market {
display: inline-block; margin-left: 4px; padding: 0 6px; border-radius: 999px; font-size: 10.5px; font-weight: 700;
background: #e8f1ff; color: #1d4ed8; vertical-align: 1px;
}
.pj-meet-more { position: absolute; top: 3px; right: 2px; width: 24px; height: 24px; opacity: 0; transition: opacity .12s; }
.pj-meet-more .material-symbols-outlined { font-size: 18px; }
th.pj-meet-c-label:hover .pj-meet-more, .pj-meet-more:focus { opacity: 1; }
textarea.pj-meet-text, .pj-meet-notes textarea {
display: block; width: 100%; box-sizing: border-box; min-height: 38px; padding: 6px; border: none; background: transparent;
font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden;
}
textarea.pj-meet-text:focus, .pj-meet-notes textarea:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .8); }
.pj-meet-ro { min-height: 38px; padding: 6px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
.pj-meet-table td.pj-meet-c-amt { text-align: right; vertical-align: middle; padding: 0 6px; font-variant-numeric: tabular-nums; }
input.pj-meet-amount {
display: block; width: 100%; box-sizing: border-box; height: 34px; padding: 0 4px; border: none; background: transparent;
font: inherit; text-align: right; font-variant-numeric: tabular-nums;
}
input.pj-meet-amount:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: #fff; }
input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
.pj-meet-auto { color: #1d4ed8; font-weight: 600; }
.pj-meet-auto::before { content: "자동 "; font-size: 10.5px; font-weight: 700; color: #6b8fd6; }
.pj-meet-c-rate { text-align: right; vertical-align: middle !important; padding: 0 6px !important; font-weight: 700; }
.pj-meet-c-rate .is-good { color: #1f8a4c; }
.pj-meet-c-rate .is-low { color: #c2410c; }
.pj-meet-c-eval { vertical-align: middle !important; text-align: center; }
select.pj-meet-eval { width: calc(100% - 8px); height: 28px; margin: 0 4px; border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; font: inherit; }
select.pj-meet-eval[data-v="done"], .pj-meet-eval-ro[data-v="done"] { color: #1f8a4c; font-weight: 700; }
select.pj-meet-eval[data-v="partial"], .pj-meet-eval-ro[data-v="partial"] { color: #b45309; font-weight: 700; }
select.pj-meet-eval[data-v="miss"], .pj-meet-eval-ro[data-v="miss"] { color: #c22b10; font-weight: 700; }
.pj-meet-table td.is-none { vertical-align: middle; padding: 0 8px; font-size: 12px; }
.pj-meet-table td.is-saved, .pj-meet-table th.is-saved, .pj-meet-notes textarea.is-saved, #pj-meet-attendees.is-saved {
animation: pj-goal-saved 1s ease-out;
}
.pj-meet-notes { margin: 16px 0 8px; }
.pj-meet-notes h3 { margin: 0 0 6px; font-size: 14px; }
.pj-meet-notes textarea, .pj-meet-notes .pj-meet-ro { border: 1px solid #dfe2e6; border-radius: 10px; background: #fff; min-height: 90px; padding: 10px; }
/* 인쇄 — 회의록 표만 */
@media print {
.erp-sidebar, .erp-topbar, .pj-side, .pj-goal-head-acts, .pj-meet-weeks, .pj-goal-foot, .pj-meet-more, .pj-meet-sec-add,
.pj-meet-back, .pj-meet-title .pj-btn { display: none !important; }
.pj-meet-pane { overflow: visible; }
.pj-meet-table thead th { position: static; }
input.pj-meet-amount, select.pj-meet-eval { border: none; appearance: none; }
}
/* 영역 색 고르기 팝업(body 에 붙음) */ /* 영역 색 고르기 팝업(body 에 붙음) */
.pj-goal-colorpop { .pj-goal-colorpop {
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px; position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
+396 -83
View File
@@ -8458,123 +8458,435 @@
document.execCommand("insertText", false, text); document.execCommand("insertText", false, text);
}); });
// ── 월 칸 병합(마이그레이션 014) — 한 줄의 같은 반기 안에서만. // ── 칸 병합 — 엑셀처럼: 업무 영역 글 칸을 마우스로 끌어(또는 Shift+클릭) 사각형으로 고른 뒤 우클릭 → 셀 병합,
// · Shift+클릭: 마지막으로 누른 월 칸부터 그 칸까지 고른 뒤 떠 있는 "N~M월 병합" 버튼 // 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남는다). 같은 업무 영역 안에서만, 가로는 같은 반기 월 칸끼리
// · 우클릭: 선택한 칸 병합 / 오른쪽·왼쪽 칸과 병합 / 병합 해제 // (연간·상반기·하반기 칸은 세로로만). 고른 범위가 병합된 칸에 걸치면 엑셀처럼 그 칸 전체로 넓힌다.
// 글은 서버가 월 순서대로 줄바꿈으로 이어 첫 칸에 모은다. 해제하면 글은 첫 칸에 남는다. // 병합하면 서버가 범위 안 글을 왼쪽 위부터 이어 왼쪽 위 칸에 모은다(글을 잃지 않게).
if (table.dataset.halves === "true") { if (table.dataset.halves === "true") {
let anchor = null; // 마지막으로 누른 월 칸 const ORDER = [0, 1, 2, 3, 4, 5, 6, 13, 7, 8, 9, 10, 11, 12, 14]; // store.GOAL_COL_ORDER
let mergeSel = null; // {row, h, start, end} const groupOf = function (m) { return m === 0 ? "y" : m === 13 ? "h1" : m === 14 ? "h2" : (m <= 6 ? "m1" : "m2"); };
let mergeBar = null; const textTd = function (node) {
const monthTd = function (node) { const td = node && node.closest && node.closest("td.pj-goal-texttd");
const td = node && node.closest && node.closest("td.pj-goal-texttd.pj-goal-m"); return td && table.contains(td) && td.closest("tbody.pj-goal-area") ? td : null;
return td && table.contains(td) ? td : null;
}; };
const cellInfo = function (td) { // 영역 하나의 칸 배치 — 칸마다 덮는 사각형(줄 순번 r0~r1, 칸 순번 c0~c1)
const m = parseInt(td.dataset.month, 10); const gridOf = function (tbody) {
const span = parseInt(td.dataset.span || "1", 10); const cells = [];
return { row: td.closest("tr").dataset.rowId, h: td.dataset.h, start: m, end: m + span - 1, span: span }; Array.prototype.forEach.call(tbody.rows, function (tr, ri) {
tr.querySelectorAll("td.pj-goal-texttd").forEach(function (td) {
const ci = ORDER.indexOf(parseInt(td.dataset.month, 10));
const span = parseInt(td.dataset.span || "1", 10), rspan = parseInt(td.dataset.rspan || "1", 10);
cells.push({ td: td, r0: ri, r1: ri + rspan - 1, c0: ci, c1: ci + span - 1, merged: span > 1 || rspan > 1 });
});
});
return cells;
}; };
const cellOf = function (cells, td) { return cells.find(function (c) { return c.td === td; }); };
const hits = function (c, s) { return c.r0 <= s.r1 && c.r1 >= s.r0 && c.c0 <= s.c1 && c.c1 >= s.c0; };
// 걸친 병합 칸을 통째로 품을 때까지 넓힌다(엑셀 선택과 같음)
const expand = function (cells, s) {
let grown = true;
while (grown) {
grown = false;
cells.forEach(function (c) {
if (!hits(c, s)) return;
const n = { r0: Math.min(s.r0, c.r0), r1: Math.max(s.r1, c.r1), c0: Math.min(s.c0, c.c0), c1: Math.max(s.c1, c.c1) };
if (n.r0 !== s.r0 || n.r1 !== s.r1 || n.c0 !== s.c0 || n.c1 !== s.c1) { s = n; grown = true; }
});
}
return s;
};
let sel = null; // {tbody, cells, r0, r1, c0, c1, n(칸 수)}
let anchorCell = null; // 마지막으로 누른 칸 {tbody, cell}
let drag = null;
clearMergeSel = function () { clearMergeSel = function () {
mergeSel = null; sel = null;
table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); }); table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); });
if (mergeBar) { mergeBar.remove(); mergeBar = null; }
}; };
const mergeCells = async function (rowId, start, end) { const paint = function () {
table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); });
if (!sel) return;
sel.cells.forEach(function (c) { if (hits(c, sel)) c.td.classList.add("is-merge-sel"); });
};
const select = function (tbody, a, b) {
const cells = gridOf(tbody);
const ca = cellOf(cells, a), cb = cellOf(cells, b);
if (!ca || !cb) return;
const s = expand(cells, { r0: Math.min(ca.r0, cb.r0), r1: Math.max(ca.r1, cb.r1),
c0: Math.min(ca.c0, cb.c0), c1: Math.max(ca.c1, cb.c1) });
sel = Object.assign({ tbody: tbody, cells: cells, n: cells.filter(function (c) { return hits(c, s); }).length }, s);
paint();
};
const mergeSel = async function (s) {
const cols = ORDER.slice(s.c0, s.c1 + 1);
const groups = cols.map(groupOf).filter(function (g, i, a) { return a.indexOf(g) === i; });
if (groups.length > 1) {
showToast("연간·상반기·하반기 칸은 세로로만, 월 칸은 같은 반기 안에서만 합칠 수 있습니다.", "error");
return;
}
const rows = s.tbody.rows;
try { try {
await flushTexts(); await flushTexts();
await api("POST", "/project/api/goals/rows/" + rowId + "/merge", { start: start, end: end }); await api("POST", "/project/api/goals/areas/" + s.tbody.dataset.areaId + "/merge", {
row_from: rows[s.r0].dataset.rowId, row_to: rows[s.r1].dataset.rowId, col_from: cols[0], col_to: cols[cols.length - 1],
});
reloadKeepScroll(); reloadKeepScroll();
} catch (err) { showToast("병합 실패: " + err.message, "error"); } } catch (err) { showToast("병합 실패: " + err.message, "error"); }
}; };
const unmergeCell = async function (rowId, start) { const unmerge = async function (cellsToSplit) {
try { try {
await flushTexts(); await flushTexts();
await api("DELETE", "/project/api/goals/rows/" + rowId + "/merge/" + start); for (const c of cellsToSplit) {
await api("DELETE", "/project/api/goals/rows/" + c.td.closest("tr").dataset.rowId + "/merge/" + c.td.dataset.month);
}
reloadKeepScroll(); reloadKeepScroll();
} catch (err) { showToast("병합 해제 실패: " + err.message, "error"); } } catch (err) { showToast("병합 해제 실패: " + err.message, "error"); }
}; };
const showMergeSel = function (rowId, h, start, end) {
clearMergeSel(); // 끌어서 고르기 — 다른 칸으로 넘어가는 순간부터 범위 선택(글 선택·입력칸 포커스는 막는다)
mergeSel = { row: rowId, h: h, start: start, end: end };
let last = null;
table.querySelectorAll('tr[data-row-id="' + rowId + '"] > td.pj-goal-texttd.pj-goal-m[data-h="' + h + '"]')
.forEach(function (td) {
const c = cellInfo(td);
if (c.start >= start && c.end <= end) { td.classList.add("is-merge-sel"); last = td; }
});
// 떠 있는 병합 버튼 — body 에 붙인다(화면 배율 밖)
mergeBar = document.createElement("div");
mergeBar.className = "pj-goal-mergebar";
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pj-btn pj-btn-primary";
btn.innerHTML = '<span class="material-symbols-outlined">cell_merge</span>';
btn.appendChild(document.createTextNode(start + "~" + end + "월 병합"));
btn.addEventListener("click", function () {
const s = mergeSel;
clearMergeSel();
if (s) mergeCells(s.row, s.start, s.end);
});
mergeBar.appendChild(btn);
document.body.appendChild(mergeBar);
const r = last.getBoundingClientRect();
const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight;
mergeBar.style.left = Math.max(8, Math.min(r.right - mergeBar.offsetWidth, vw - mergeBar.offsetWidth - 8)) + "px";
mergeBar.style.top = Math.max(8, Math.min(r.bottom + 6, vh - mergeBar.offsetHeight - 8)) + "px";
};
table.addEventListener("mousedown", function (e) { table.addEventListener("mousedown", function (e) {
if (e.button !== 0) return; if (e.button !== 0) return;
const td = monthTd(e.target); const td = textTd(e.target);
if (!td) return; if (!td) return;
const c = cellInfo(td); const tbody = td.closest("tbody");
if (e.shiftKey && anchor && anchor.row === c.row && anchor.h === c.h && anchor.start !== c.start) { if (e.shiftKey && anchorCell && anchorCell.tbody === tbody && anchorCell.td !== td) {
e.preventDefault(); // 글 선택·포커스 이동 없이 범위만 고른다 e.preventDefault(); // Shift+클릭 = 마지막으로 누른 칸부터 여기까지
showMergeSel(c.row, c.h, Math.min(anchor.start, c.start), Math.max(anchor.end, c.end)); select(tbody, anchorCell.td, td);
return; return;
} }
anchor = c;
clearMergeSel(); clearMergeSel();
anchorCell = { tbody: tbody, td: td };
drag = { tbody: tbody, td: td, moved: false };
}); });
// 다른 곳을 누르거나 Esc·스크롤이면 선택 해제 table.addEventListener("mouseover", function (e) {
if (!drag) return;
const td = textTd(e.target);
if (!td || td.closest("tbody") !== drag.tbody) return;
if (td === drag.td && !drag.moved) return;
if (!drag.moved) {
drag.moved = true;
document.documentElement.classList.add("pj-goal-selecting");
if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
}
const s = window.getSelection && window.getSelection();
if (s && s.removeAllRanges) s.removeAllRanges();
select(drag.tbody, drag.td, td);
});
document.addEventListener("mouseup", function () {
if (!drag) return;
drag = null;
document.documentElement.classList.remove("pj-goal-selecting");
});
// 다른 곳을 누르거나 Esc 면 선택 해제
document.addEventListener("mousedown", function (e) { document.addEventListener("mousedown", function (e) {
if (!mergeSel || (mergeBar && mergeBar.contains(e.target)) || monthTd(e.target)) return; if (sel && !textTd(e.target) && !e.target.closest(".pj-ctxmenu")) clearMergeSel();
clearMergeSel();
}, true); }, true);
document.addEventListener("keydown", function (e) { if (e.key === "Escape" && mergeSel) clearMergeSel(); }); document.addEventListener("keydown", function (e) { if (e.key === "Escape" && sel) clearMergeSel(); });
pane.addEventListener("scroll", function () { if (mergeSel) clearMergeSel(); });
// 우클릭 — 셀 병합(고른 범위가 2칸 이상) / 병합 해제(병합된 칸). 해당 없으면 브라우저 기본 메뉴
table.addEventListener("contextmenu", function (e) { table.addEventListener("contextmenu", function (e) {
const td = monthTd(e.target); const td = textTd(e.target);
if (!td) return; if (!td) return;
e.preventDefault(); const tbody = td.closest("tbody");
const c = cellInfo(td); if (!sel || sel.tbody !== tbody || !sel.cells.some(function (c) { return c.td === td && hits(c, sel); })) {
const isMonth = function (x) { return x && x.classList.contains("pj-goal-m") && x.dataset.h === c.h; }; select(tbody, td, td); // 범위 밖을 우클릭하면 그 칸만(엑셀처럼)
}
const s = sel;
const inSel = s.cells.filter(function (c) { return hits(c, s); });
const mergedIn = inSel.filter(function (c) { return c.merged; });
const items = []; const items = [];
const s = mergeSel; if (s.n >= 2) {
if (s && s.row === c.row && c.start >= s.start && c.end <= s.end) { const rowsN = s.r1 - s.r0 + 1, colsN = s.c1 - s.c0 + 1;
items.push({ label: "선택한 칸 병합 (" + s.start + "~" + s.end + "월)", items.push({ label: "셀 병합 (" + rowsN + "줄 × " + colsN + "칸)", onClick: function () { clearMergeSel(); mergeSel(s); } });
onClick: function () { clearMergeSel(); mergeCells(s.row, s.start, s.end); } });
} }
const next = td.nextElementSibling, prev = td.previousElementSibling; if (mergedIn.length) {
if (isMonth(next)) { items.push({ label: "병합 해제" + (mergedIn.length > 1 ? " (" + mergedIn.length + "곳)" : ""),
const n = cellInfo(next); onClick: function () { clearMergeSel(); unmerge(mergedIn); } });
items.push({ label: "오른쪽 칸과 병합 (" + c.start + "~" + n.end + "월)",
onClick: function () { mergeCells(c.row, c.start, n.end); } });
} }
if (isMonth(prev)) { if (!items.length) { clearMergeSel(); return; }
const p = cellInfo(prev); e.preventDefault();
items.push({ label: "왼쪽 칸과 병합 (" + p.start + "~" + c.end + "월)", showContextMenu(e.clientX, e.clientY, items);
onClick: function () { mergeCells(c.row, p.start, c.end); } });
}
if (c.span > 1) {
if (items.length) items.push(null);
items.push({ label: "병합 해제", onClick: function () { unmergeCell(c.row, c.start); } });
}
if (items.length) showContextMenu(e.clientX, e.clientY, items);
}); });
} }
} }
// ── 주간 회의록(/project/goals/{연도}/meetings/{월}?week=) — 관리자만 입력, 칸마다 바로 저장.
// · 글(이번주 할 일·메모): 0.8초 멈춤·칸 떠남·페이지 떠남에 저장. 금액·참석자: 칸 떠남·Enter 에 저장.
// · 지난주 결과·평가는 지난 회의록의 같은 줄(tr data-prev)에 저장하고 달성률을 바로 다시 그린다.
// · 줄 추가·순서·삭제·쇼핑몰 연결·구역 추가는 저장 뒤 새로고침(스크롤 위치 되살림). 메뉴는 body 에 붙는다.
function initGoalMeeting() {
const pane = el("pj-meet-pane");
if (!pane) return;
const week = pane.dataset.week, year = pane.dataset.year;
const isAdmin = pane.dataset.admin === "true";
const SCROLL_KEY = "pj_meet_scroll";
function reloadKeepScroll() {
try { sessionStorage.setItem(SCROLL_KEY, JSON.stringify([location.pathname + location.search, window.scrollY, 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 + location.search) { window.scrollTo(0, s[1]); pane.scrollTop = s[2]; }
} catch (_) {}
const won = function (v) { return v == null || v === "" ? "" : Number(v).toLocaleString("ko-KR"); };
const printBtn = el("pj-meet-print");
if (printBtn) printBtn.addEventListener("click", function () { window.print(); });
const create = el("pj-meet-create");
if (create) create.addEventListener("click", async function () {
create.disabled = true;
try {
await api("POST", "/project/api/goals/meetings/" + week, { year: year });
location.reload();
} catch (e) { create.disabled = false; showToast("만들기 실패: " + e.message, "error"); }
});
if (!isAdmin) return;
const table = el("pj-meet-table");
function flashSaved(node) {
if (!node) return;
node.classList.remove("is-saved");
void node.offsetWidth;
node.classList.add("is-saved");
}
function fit(ta) {
if (!ta.offsetParent) return;
ta.style.height = "auto";
ta.style.height = ta.scrollHeight + "px";
}
const meetingUrl = "/project/api/goals/meetings/" + week;
function itemUrl(id) { return "/project/api/goals/meeting-items/" + id; }
// ── 머리 — 금주 목표·참석자·메모 ──
const tgt = el("pj-meet-target");
if (tgt) {
tgt.dataset.saved = tgt.value;
tgt.addEventListener("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); tgt.blur(); } });
tgt.addEventListener("change", async function () {
try {
await api("PUT", meetingUrl, { week_target: tgt.value });
reloadKeepScroll(); // 달성률·필요 매출 문구를 서버 계산으로 다시
} catch (e) { tgt.value = tgt.dataset.saved; showToast("저장 실패: " + e.message, "error"); }
});
}
const att = el("pj-meet-attendees");
if (att) att.addEventListener("change", async function () {
try { await api("PUT", meetingUrl, { attendees: att.value }); flashSaved(att); }
catch (e) { showToast("저장 실패: " + e.message, "error"); }
});
// ── 글 칸(이번주 할 일·메모) — 멈추면 저장 ──
const pending = new Map(); // textarea → {timer, save}
function queue(ta, save) {
const p = pending.get(ta);
if (p) clearTimeout(p.timer);
pending.set(ta, { timer: setTimeout(function () { flush(ta); }, 800), save: save });
}
async function flush(ta) {
const p = pending.get(ta);
if (!p) return;
clearTimeout(p.timer);
pending.delete(ta);
if (ta.value === ta.dataset.saved) return;
try { await p.save(ta.value); ta.dataset.saved = ta.value; flashSaved(ta.closest("td") || ta); }
catch (e) { showToast("저장 실패: " + e.message, "error"); }
}
function flushAll() { return Promise.all(Array.from(pending.keys()).map(flush)); }
const notes = el("pj-meet-notes");
if (notes) {
notes.dataset.saved = notes.value;
const save = function (v) { return api("PUT", meetingUrl, { notes: v }); };
notes.addEventListener("input", function () { fit(notes); queue(notes, save); });
notes.addEventListener("blur", function () { flush(notes); });
fit(notes);
}
if (table) table.querySelectorAll("textarea.pj-meet-text").forEach(function (ta) {
ta.dataset.saved = ta.value;
const id = ta.closest("tr").dataset.item;
const save = function (v) { return api("PUT", itemUrl(id), { content: v }); };
fit(ta);
ta.addEventListener("input", function () { fit(ta); queue(ta, save); });
ta.addEventListener("blur", function () { flush(ta); });
});
window.addEventListener("resize", function () { document.querySelectorAll("textarea.pj-meet-text, #pj-meet-notes").forEach(fit); });
window.addEventListener("beforeunload", function () {
pending.forEach(function (p, ta) {
clearTimeout(p.timer);
if (ta.value === ta.dataset.saved) return;
const isNotes = ta.id === "pj-meet-notes";
try {
fetch(isNotes ? meetingUrl : itemUrl(ta.closest("tr").dataset.item), {
method: "PUT", keepalive: true, headers: { "Content-Type": "application/json" },
body: JSON.stringify(isNotes ? { notes: ta.value } : { content: ta.value }),
});
} catch (_) {}
});
});
if (!table) return;
// ── 달성률(지난주 결과 ÷ 지난주 목표) ──
function paintRate(tr, result) {
const td = tr.querySelector("[data-rate]");
if (!td) return;
const target = Number(tr.dataset.prevTarget || 0);
if (result == null || !target) { td.innerHTML = ""; return; }
const r = Math.round(result / target * 1000) / 10;
td.innerHTML = '<span class="' + (r >= 100 ? "is-good" : "is-low") + '">' + r.toLocaleString("ko-KR") + "%</span>";
}
// ── 금액 칸 — 이번주 목표 금액(이 줄) · 지난주 결과(지난 회의록 줄) ──
table.querySelectorAll("input.pj-meet-amount").forEach(function (inp) {
inp.dataset.saved = inp.value;
inp.addEventListener("focus", function () { inp.select(); });
inp.addEventListener("keydown", function (e) {
if (e.key === "Enter") { e.preventDefault(); inp.blur(); }
else if (e.key === "Escape") { inp.value = inp.dataset.saved; inp.blur(); }
});
inp.addEventListener("change", async function () {
const tr = inp.closest("tr");
const toPrev = inp.dataset.target === "prev";
const body = {};
body[inp.dataset.field] = inp.value;
try {
const res = await api("PUT", itemUrl(toPrev ? tr.dataset.prev : tr.dataset.item), body);
inp.value = won(res.item[inp.dataset.field]);
inp.dataset.saved = inp.value;
if (toPrev) paintRate(tr, res.item.result_amount);
flashSaved(inp.closest("td"));
} catch (e) { inp.value = inp.dataset.saved; showToast("저장 실패: " + e.message, "error"); }
});
});
// ── 평가(지난주 줄) ──
table.querySelectorAll("select.pj-meet-eval").forEach(function (selEl) {
selEl.addEventListener("change", async function () {
const tr = selEl.closest("tr");
try {
await api("PUT", itemUrl(tr.dataset.prev), { status: selEl.value });
selEl.dataset.v = selEl.value;
flashSaved(selEl.closest("td"));
} catch (e) { selEl.value = selEl.dataset.v || ""; showToast("저장 실패: " + e.message, "error"); }
});
});
// ── 줄 이름 — 눌러서 그 자리에서 수정(Enter·칸 떠남 = 저장, Esc = 취소) ──
table.addEventListener("click", function (e) {
const span = e.target.closest("[data-meet-edit]");
if (!span || span.isContentEditable) return;
const orig = span.textContent;
const tr = span.closest("tr");
span.contentEditable = "true";
span.classList.add("is-editing");
span.focus();
const r = document.createRange();
r.selectNodeContents(span);
const s = window.getSelection();
s.removeAllRanges();
s.addRange(r);
let done = false;
async function finish(save) {
if (done) return;
done = true;
span.contentEditable = "false";
span.classList.remove("is-editing");
span.removeEventListener("keydown", onKey);
span.removeEventListener("blur", onBlur);
const v = span.textContent.replace(/\s+/g, " ").trim();
if (!save || v === orig.trim()) { span.textContent = orig; return; }
span.textContent = v;
try { await api("PUT", itemUrl(tr.dataset.item), { label: v }); flashSaved(span.closest("th")); }
catch (err) { span.textContent = orig; showToast("이름 변경 실패: " + err.message, "error"); }
}
function onKey(ev) {
if (isImeEnter(ev)) return;
if (ev.key === "Enter") { ev.preventDefault(); span.blur(); }
else if (ev.key === "Escape") { ev.preventDefault(); ev.stopPropagation(); finish(false); span.blur(); }
}
function onBlur() { finish(true); }
span.addEventListener("keydown", onKey);
span.addEventListener("blur", onBlur);
});
// ── 줄 메뉴(⋯ · 항목 우클릭) — 위/아래 줄 추가 · 순서 · 쇼핑몰 연결 · 삭제 ──
async function run(fn) {
try {
if (!(await fn())) return;
await flushAll();
reloadKeepScroll();
} catch (err) { showToast("처리 실패: " + err.message, "error"); }
}
async function addRow(section, ref, place) {
const v = await prompt("새 줄 이름 (예: 쿠팡 — 비워 둬도 됩니다)", "");
if (v == null) return false;
await api("POST", meetingUrl + "/items", { section: section, label: String(v).trim(), ref_item_id: ref, place: place });
return true;
}
function marketMenu(x, y, tr) {
const markets = window.PJ_MEET_MARKETS || [];
if (!markets.length) { showToast("실적 모듈 쇼핑몰 목록을 불러오지 못했습니다.", "error"); return; }
const cur = tr.dataset.market || "";
const pick = function (code) {
return function () { run(async function () { await api("PUT", itemUrl(tr.dataset.item), { marketplace_code: code }); return true; }); };
};
showContextMenu(x, y, [{ label: "연결 안 함(결과 직접 입력)", checked: !cur, onClick: pick("") }, null].concat(
markets.map(function (m) { return { label: m.name, checked: m.code === cur, onClick: pick(m.code) }; })));
}
function rowMenu(x, y, tr) {
const id = tr.dataset.item, section = tr.dataset.section;
const label = (tr.querySelector(".pj-meet-label") || {}).textContent || "";
showContextMenu(x, y, [
{ label: "위에 줄 추가", onClick: function () { run(function () { return addRow(section, id, "above"); }); } },
{ label: "아래에 줄 추가", onClick: function () { run(function () { return addRow(section, id, "below"); }); } },
{ label: "위로", onClick: function () { run(async function () { await api("POST", itemUrl(id) + "/move", { direction: -1 }); return true; }); } },
{ label: "아래로", onClick: function () { run(async function () { await api("POST", itemUrl(id) + "/move", { direction: 1 }); return true; }); } },
{ label: "쇼핑몰 연결(결과 자동)…", onClick: function () { setTimeout(function () { marketMenu(x, y, tr); }, 0); } },
null,
{ label: "줄 삭제", danger: true, onClick: function () {
run(async function () {
const ok = await confirm("'" + (label.trim() || "이 줄") + "' 줄을 삭제할까요? 이번주 할 일·금액도 함께 삭제됩니다.",
{ okText: "삭제", cancelText: "취소" });
if (!ok) return false;
await api("DELETE", itemUrl(id));
return true;
});
} },
]);
}
table.addEventListener("click", function (e) {
const b = e.target.closest("[data-meet-act]");
if (!b) return;
const tr = b.closest("tr");
if (b.dataset.meetAct === "menu") {
const r = b.getBoundingClientRect();
rowMenu(r.left, r.bottom + 4, tr);
} else if (b.dataset.meetAct === "sec-add") {
run(function () { return addRow(b.closest("tbody").dataset.section, null, "below"); });
}
});
table.addEventListener("contextmenu", function (e) {
const th = e.target.closest("th.pj-meet-c-label");
if (!th || e.target.closest(".is-editing")) return;
e.preventDefault();
rowMenu(e.clientX, e.clientY, th.closest("tr"));
});
const secNew = el("pj-meet-sec-new");
if (secNew) secNew.addEventListener("click", function () {
run(async function () {
const name = await prompt("새 구역 이름 (예: 물류)", "");
if (name == null || !String(name).trim()) return false;
await api("POST", meetingUrl + "/items", { section: String(name).trim(), label: "" });
return true;
});
});
const del = el("pj-meet-del");
if (del) del.addEventListener("click", async function () {
const ok = await confirm("이 주 회의록을 삭제할까요? 줄·금액·메모가 모두 삭제되고, 다음 주 회의록의 '지난주' 칸도 비게 됩니다.",
{ okText: "삭제", cancelText: "취소" });
if (!ok) return;
try { await api("DELETE", meetingUrl); location.reload(); }
catch (e) { showToast("삭제 실패: " + e.message, "error"); }
});
}
// ── 휴지통(관리자 전용 화면) — [복구] 누르면 원래 id 그대로 되살리고 줄을 지운다. // ── 휴지통(관리자 전용 화면) — [복구] 누르면 원래 id 그대로 되살리고 줄을 지운다.
function initTrash() { function initTrash() {
const table = el("pj-trash-table"); const table = el("pj-trash-table");
@@ -8610,6 +8922,7 @@
initTrash(); initTrash();
initGoalSide(); initGoalSide();
initGoals(); initGoals();
initGoalMeeting();
initMyTasks(); initMyTasks();
initProject(); initProject();
initAllMembers(); initAllMembers();
+59 -9
View File
@@ -295,6 +295,8 @@ docker exec -i postgres-db psql -U postgres -d project_db \
< scripts/sql/project_db_013_goals.sql < scripts/sql/project_db_013_goals.sql
docker exec -i postgres-db psql -U postgres -d project_db \ docker exec -i postgres-db psql -U postgres -d project_db \
< scripts/sql/project_db_014_goal_halves_merges.sql < scripts/sql/project_db_014_goal_halves_merges.sql
docker exec -i postgres-db psql -U postgres -d project_db \
< scripts/sql/project_db_015_goal_rect_merges_meetings.sql
# 4) 재배포 (git pull 후 반드시 --build) # 4) 재배포 (git pull 후 반드시 --build)
cd /opt/www/main && docker compose up -d --build web cd /opt/www/main && docker compose up -d --build web
@@ -531,19 +533,67 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
Enter·칸 떠남 = 저장, Esc = 취소, 붙여넣기는 글자만. 영역 이름 빈 값은 되돌림(서버도 400), 줄 이름은 빈 값 허용(빈 줄 이름은 Enter·칸 떠남 = 저장, Esc = 취소, 붙여넣기는 글자만. 영역 이름 빈 값은 되돌림(서버도 400), 줄 이름은 빈 값 허용(빈 줄 이름은
마우스를 올리면 "줄 이름" 자리 표시). 예전 ✎(prompt) 버튼은 없앴고 도구 막대는 색·↑·↓·+·× 만. 마우스를 올리면 "줄 이름" 자리 표시). 예전 ✎(prompt) 버튼은 없앴고 도구 막대는 색·↑·↓·+·× 만.
- **줄 추가·삭제(항목 칸)**(관리자) — 줄 이름 칸 도구 막대: ↑·↓(줄 2개 이상)·**+ = 이 줄 아래에 줄 추가**·×(줄 2개 이상). 항목 칸 **우클릭 메뉴**: 위에 줄 추가 / 아래에 줄 추가 / 줄 삭제(영역의 마지막 한 줄이면 없음). 추가는 이름을 묻고(비워도 됨) `db.add_goal_row(ref_row_id, place)` 가 영역 줄 순서를 다시 매긴다(영역 FOR UPDATE). 영역 이름 칸의 + 는 예전처럼 맨 끝에 추가. - **줄 추가·삭제(항목 칸)**(관리자) — 줄 이름 칸 도구 막대: ↑·↓(줄 2개 이상)·**+ = 이 줄 아래에 줄 추가**·×(줄 2개 이상). 항목 칸 **우클릭 메뉴**: 위에 줄 추가 / 아래에 줄 추가 / 줄 삭제(영역의 마지막 한 줄이면 없음). 추가는 이름을 묻고(비워도 됨) `db.add_goal_row(ref_row_id, place)` 가 영역 줄 순서를 다시 매긴다(영역 FOR UPDATE). 영역 이름 칸의 + 는 예전처럼 맨 끝에 추가.
- **월 칸 병합**(관리자, 014) — `goal_cell_merges(row_id, start_month, span)` — 한 줄 안에서 가로로만, **같은 반기 안에서만** - **칸 병합 — 엑셀식**(관리자, 014 + 015, 2026-10-01에 예전 Shift+클릭·떠 있는 병합 버튼·오른쪽/왼쪽 칸과 병합 메뉴를 대체)
(DB CHECK + `store.validate_goal_merge`), 2칸 이상. 화면은 `router._goal_row_layout` 이 줄마다 칸 배치(병합이면 `colspan`)를 만든다. — `goal_cell_merges(row_id, start_month, span, row_span)`. 시작 칸 = **왼쪽 위**(row_id = 맨 위 줄, start_month = 왼쪽 칸 번호).
- 고르기: 월 칸을 누른 뒤 **Shift+클릭**(같은 줄·같은 반기) → 칸 테두리 강조 + 떠 있는 "N~M월 병합" 버튼(`.pj-goal-mergebar`, - 범위: **같은 업무 영역 안 연속된 줄**(세로, `row_span` — 015) × 화면 순서(연간 · 1~6월 · 상반기 · 7~12월 · 하반기 =
body 에 붙음). 다른 곳 누름·Esc·스크롤 = 선택 해제. `store.GOAL_COL_ORDER`)의 연속된 칸. 가로는 **같은 반기 월 칸끼리만**, 연간(0)·상반기(13)·하반기(14) 칸은 **세로로만**
- 우클릭 메뉴: 선택한 칸 병합 / 오른쪽 칸과 병합 / 왼쪽 칸과 병합 / 병합 해제(병합된 칸). 월 칸에서는 브라우저 기본 우클릭 메뉴 대신 뜬다. (`store.validate_goal_rect_cols`, DB CHECK). 015 미적용이면 예전처럼 한 줄 월 칸 가로 병합만(세로·연간/반기는 503).
- `POST /api/goals/rows/{row_id}/merge {start, end}` → `db.merge_goal_cells`: 걸친 기존 병합은 통째로 흡수, 범위 안 칸들의 글을 - 고르기: 글 칸을 **마우스로 끌기**(다른 칸으로 넘어가는 순간부터 범위 선택, 글 선택·포커스는 막음 — `html.pj-goal-selecting`)
월 순서대로 줄바꿈으로 이어 **시작 월 칸**에 두고 나머지 칸 글은 지운다(한 트랜잭션, 줄 FOR UPDATE). 화면은 먼저 저장 안 된 글을 또는 **Shift+클릭**(마지막으로 누른 칸부터). 범위가 병합된 칸에 걸치면 **엑셀처럼 그 칸 전체로 넓힌다**(`expand`). 칸 한 번 클릭은
저장(`flushTexts`)한 뒤 부르고 새로고침. `DELETE /api/goals/rows/{row_id}/merge/{start}` = 해제(글은 시작 월 칸에 남음). 그대로 입력. 다른 곳 누름·Esc = 해제.
- 병합된 칸의 가운데·끝 월로 늦게 온 글 저장은 400("병합된 칸입니다") — 다른 창에서 병합된 뒤의 저장이 숨은 칸에 쌓이지 않게. - **우클릭**: "셀 병합 (N줄 × M칸)"(2칸 이상) · "병합 해제"(범위 안 병합된 칸, 여러 곳이면 개수). 범위 밖을 우클릭하면 그 칸만
고른 것으로(엑셀과 같음). 해당 메뉴가 없으면 브라우저 기본 메뉴. 묶음이 다른 가로 범위는 서버를 부르지 않고 안내.
- `POST /api/goals/areas/{area_id}/merge {row_from, row_to(줄 id), col_from, col_to(칸 번호)}` → `db.merge_goal_rect`: 영역 FOR UPDATE,
걸친 병합 흡수(넓힌 뒤 묶음 다시 검사), 범위 안 글을 **왼쪽 위부터 줄·칸 순서대로 줄바꿈으로 이어 왼쪽 위 칸에**(글을 잃지 않게 —
엑셀은 왼쪽 위 값만 남기지만 여기선 잇는다), 나머지 칸 글·안쪽 병합은 지운다. 응답 `{row_id, start, span, row_span}`.
`DELETE /api/goals/rows/{row_id}/merge/{start}` = 해제 — **글은 왼쪽 위 칸에 남는다**(엑셀과 같음). 화면은 저장 안 된 글을 먼저
저장(`flushTexts`)한 뒤 부르고 새로고침.
- 화면 배치: `router._goal_area_layout` 이 영역 단위로 칸마다 `{m, kind, h, span, rspan, now}` — 시작 칸은 `colspan`·`rowspan`,
가려진 칸은 그리지 않는다(세로는 영역 끝, 가로는 같은 묶음 안으로 자름). 반기 접기는 병합 칸도 `pj-goal-m[data-h]` 로 함께 숨김.
- 가려진 칸으로 늦게 온 글 저장은 400("병합된 칸입니다", `_area_geometry`·`_covered_by` — 가로·세로 모두).
- 줄 작업과 세로 병합(엑셀처럼): 병합 **안쪽에 줄 끼우기** → `row_span + 1` · **가려진 줄 지우기** → `row_span − 1`(1칸이 되면 병합 삭제) ·
맨 위(시작) 줄 지우기 → 병합도 지워짐(CASCADE) · 세로 병합에 걸린 줄(자신이나 바꿀 이웃)의 **↑↓ 이동은 400**(해제 뒤 이동).
- 새 연도 만들기(구조 복사)는 병합을 복사하지 않는다(줄 이름만). - 새 연도 만들기(구조 복사)는 병합을 복사하지 않는다(줄 이름만).
- **월 이름 → 주간 회의록** — 목표 표 머리의 "N월"(`a.pj-goal-mlink`)을 누르면 `/project/goals/{연도}/meetings/{월}`(6-9-2).
- **로아스 단위 %** — 로아스 목표·실적 칸은 `499%` 처럼 보인다(`router._goal_label`, 저장 응답 `label` 도 같음). 입력은 `499`·`499%` - **로아스 단위 %** — 로아스 목표·실적 칸은 `499%` 처럼 보인다(`router._goal_label`, 저장 응답 `label` 도 같음). 입력은 `499`·`499%`
둘 다 되고 저장 값은 숫자(`validate_goal_value` 가 `%` 를 뗀다). 둘 다 되고 저장 값은 숫자(`validate_goal_value` 가 `%` 를 뗀다).
### 6-9-2. 주간 회의록 (마이그레이션 015)
지난주 목표·결과를 리뷰하고 월 목표를 달성하기 위한 이번주 목표·할 일을 정하는 회의(WBR — Weekly Business Review)용.
참고한 도구 방식: **WBR 지표 자동 집계**(목표 대비 누적·주당 필요 매출 = 페이싱), **Fellow·Notion 회의 템플릿의 이월**(지난 회의
항목을 다음 회의로 이어받아 나란히 리뷰), **OKR 체크인 평가**(완료/일부/미달).
- 화면 `/project/goals/{연도}/meetings/{월}?week={월요일}`(`goal_meeting.html`, `initGoalMeeting`) — 목표 표 월 머리를 누르면 열린다.
- **주차 탭**: 그 달과 겹치는 주(월~일, `store.month_weeks`, 1주차 = 1일이 든 주 — 앞뒤 달과 겹치는 주는 양쪽 달에 같은 회의록).
점 = 회의록 있음, "이번 주" 꼬리표. 기본 선택 = 이번 주(그 달이면) 아니면 1주차. ‹ 이전 달 · 다음 달 › 링크, ← 목표 표.
- **머리 숫자**(`router._meeting_view`): 월 목표 매출(목표 표 숫자 + 단위, 단위가 원/천/만/십만/백만/천만/억이면 원 환산 —
`store.sales_unit_multiplier`) · **월 누적 실적(지난주 일요일까지)** · **주당 필요 매출** = (월 목표 − 누적) ÷ 이번 주 포함 남은 주 수 ·
목표 ROAS(목표 표) / 전주 목표(바로 앞 주 회의록의 금주 목표) · **전주 결과** · 전주 달성률 · **금주 목표**(입력, 칸 안내 = 필요 매출) ·
금주 현재 실적. 실적·누적·결과는 **실적 모듈 `performance_store.daily_amounts`(대시보드 총매출과 같은 값, 매출 집계 쇼핑몰)** 에서
읽기만 한다 — 실적 모듈이 없거나 오류면 빈칸("직접 입력" 안내), 회의록은 그대로 동작.
- **줄**(구역 = 목표 표 업무 영역, 표의 구역 칸 rowspan): 항목 | **이번주 할 일·행사** | **목표 금액** ‖ 지난주 리뷰: 지난주 할 일 |
지난주 목표 | **결과** | 달성률 | **평가**(— · 완료 · 일부 · 미달). 지난주 칸 = 이 줄의 `carry_from`(지난 회의록 같은 줄).
결과는 그 줄이 **쇼핑몰 연결**(`marketplace_code`)이면 실적 모듈의 그 주(지난 회의록 주 월~일) 그 쇼핑몰 매출 **자동**("자동" 표시),
아니면 직접 입력 — **지난 회의록 줄의 `result_amount`·`status` 에 저장**(그 주 결과는 그 주 줄에 남는다). 달성률은 저장 즉시 화면 계산.
- 참석자 · **결정 사항·메모**. 인쇄 버튼(인쇄용 CSS — 사이드바·탭·도구 숨김).
- 데이터: `goal_meetings(week_start 월요일 PK, week_target 원, attendees, notes)` · `goal_meeting_items(week_start FK CASCADE, section,
section_color, label, content, target_amount, result_amount, status '', done, partial, miss, marketplace_code, carry_from FK SET NULL,
sort_order)`. 금액은 **원 정수** — 입력은 `1,200,000`·`120만`·`1.5억`·`3천만`·`1억2천만` 다 된다(`store.validate_meeting_amount`).
- **만들기**(관리자, `POST /api/goals/meetings/{월요일} {year}`, GET 에서 자동 생성 안 함): 앞선 가장 가까운 회의록이 있으면 그 줄(구역·이름·
색·쇼핑몰 연결·순서)을 글 없이 이어받고 `carry_from` 연결, 없으면 그 해 목표 표 업무 영역마다 **기본 양식 줄**(`store.MEETING_TEMPLATE` —
상품1~5 / 메타(숫자)·구글·네이버·기타.신규 / 내용1~5 / 신규 인플루언서·콜라보·쿠팡·네이버·gs·토스·애터미·해외·오프라인·기타, 없는 구역은
빈 줄 하나). **유통** 구역 줄 이름으로 쇼핑몰 연결 추측(`store.guess_meeting_market`: 쿠팡·네이버/스마트스토어·gs·토스·11번가·카페24/자사몰·
롯데·지마켓·카카오·오늘의집 — 마케팅의 "네이버"는 광고라 연결 안 함). 줄 추가 때도 같은 추측.
- 편집(관리자, 칸별 즉시 저장 — 목표 표와 같은 권한): 글 0.8초 멈춤·칸 떠남·페이지 떠남(keepalive), 금액 Enter·칸 떠남(서버 표기로 바꿈),
금주 목표 저장 뒤엔 머리 숫자를 서버 계산으로 다시(새로고침). **항목 우클릭·⋯ 메뉴**: 위/아래에 줄 추가 · 위로/아래로(같은 구역 안) ·
쇼핑몰 연결(결과 자동)…(연결 안 함 + 실적 모듈 사용 중 쇼핑몰, 현재 값 체크) · 줄 삭제. 구역 칸 + = 그 구역 끝에 줄, [+ 구역 추가].
줄 이름은 눌러서 그 자리에서 수정. 회의록 삭제 = 그 주 줄 전부 삭제, 다음 주 회의록의 지난주 칸은 빈다(carry_from NULL).
- API(관리자, 조회는 `project` 권한자): `GET /api/goals/meetings/{월요일}?year=&month=`(화면과 같은 계산) · `POST|PUT|DELETE
/api/goals/meetings/{월요일}`(PUT `{week_target, attendees, notes}`) · `POST /api/goals/meetings/{월요일}/items {section, label?,
ref_item_id?, place?}` · `PUT|DELETE /api/goals/meeting-items/{id}`(PUT `{label, content, target_amount, result_amount, status,
marketplace_code}`) · `POST /api/goals/meeting-items/{id}/move {direction}`. 015 미적용 503, 월요일 아님·금액 형식 400.
## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음) ## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음)
**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙) **권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙)
@@ -0,0 +1,78 @@
-- =====================================================================
-- project_db 마이그레이션 015 — 연간 목표: 엑셀식 사각형 병합 · 주간 회의록
-- =====================================================================
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — goal_cell_merges 의 CHECK 제약만 바꿔 다시 건다.
--
-- ① goal_cell_merges.row_span — 병합을 세로로도(같은 업무 영역 안 연속된 줄). 시작 칸 = 왼쪽 위.
-- 가로(span)는 예전처럼 같은 반기의 월 칸 안에서만, 연간(0)·상반기(13)·하반기(14) 칸은 세로로만(span 1).
-- 가린 줄은 "시작 줄부터 영역 줄 순서로 row_span 줄". 글은 시작 칸(goal_cells)에만.
-- ② goal_meetings / goal_meeting_items — 월 머리를 누르면 열리는 주간 회의록(주 = 월요일~일요일).
-- 한 주 = 회의록 하나(week_start = 그 주 월요일). 항목은 구역(상품·마케팅·컨텐츠·유통 …)별 줄:
-- 이번주 할 일 · 목표 금액(원), 그 주 결과(원, 다음 주 회의에서 리뷰)·평가, 실적 모듈 쇼핑몰 연결(결과 자동),
-- carry_from = 전주 같은 줄(지난주 할 일·목표·결과를 나란히 보여 준다).
--
-- 미적용이어도 목표 화면은 동작한다 — 세로 병합·회의록만 "마이그레이션 015 필요".
--
-- 적용 (1회, 여러 번 돌려도 안전):
-- docker exec -i postgres-db psql -U postgres -d project_db \
-- < scripts/sql/project_db_015_goal_rect_merges_meetings.sql
-- =====================================================================
\set ON_ERROR_STOP on
\connect project_db
BEGIN;
-- ① 사각형 병합 ─────────────────────────────────────────────────────
ALTER TABLE goal_cell_merges ADD COLUMN IF NOT EXISTS row_span SMALLINT NOT NULL DEFAULT 1;
ALTER TABLE goal_cell_merges DROP CONSTRAINT IF EXISTS goal_cell_merges_range;
ALTER TABLE goal_cell_merges ADD CONSTRAINT goal_cell_merges_range CHECK (
span >= 1 AND row_span >= 1 AND span * row_span >= 2
AND (
(start_month IN (0, 13, 14) AND span = 1)
OR (start_month BETWEEN 1 AND 12 AND start_month + span - 1 <= 12
AND (start_month <= 6) = (start_month + span - 1 <= 6))
)
);
COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 칸 병합(가로: 반기 안 월 칸, 세로: 같은 영역 안 줄 row_span)';
-- ② 주간 회의록 ─────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS goal_meetings (
week_start DATE PRIMARY KEY CHECK (EXTRACT(ISODOW FROM week_start) = 1),
week_target BIGINT NULL CHECK (week_target IS NULL OR week_target >= 0), -- 금주 목표 매출(원)
attendees TEXT NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '', -- 결정 사항·메모
created_by TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_by TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS goal_meeting_items (
id BIGSERIAL PRIMARY KEY,
week_start DATE NOT NULL REFERENCES goal_meetings(week_start) ON DELETE CASCADE,
section TEXT NOT NULL DEFAULT '', -- 구역 이름(상품·마케팅·컨텐츠·유통 …)
section_color TEXT NOT NULL DEFAULT '',
label TEXT NOT NULL DEFAULT '', -- 줄 이름(쿠팡·메타 …)
content TEXT NOT NULL DEFAULT '', -- 이번주 할 일·행사 내용
target_amount BIGINT NULL CHECK (target_amount IS NULL OR target_amount >= 0),
result_amount BIGINT NULL, -- 그 주 결과(직접 입력, 쇼핑몰 연결이면 실적 자동)
status TEXT NOT NULL DEFAULT '' CHECK (status IN ('', 'done', 'partial', 'miss')),
marketplace_code TEXT NOT NULL DEFAULT '', -- 실적 모듈 쇼핑몰 코드(결과 자동)
carry_from BIGINT NULL REFERENCES goal_meeting_items(id) ON DELETE SET NULL,
sort_order INT NOT NULL DEFAULT 0,
updated_by TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_goal_meeting_items_week ON goal_meeting_items (week_start, sort_order, id);
CREATE INDEX IF NOT EXISTS idx_goal_meeting_items_carry ON goal_meeting_items (carry_from);
COMMENT ON TABLE goal_meetings IS '연간 목표 — 주간 회의록(주 = 월~일, week_start = 월요일)';
COMMENT ON TABLE goal_meeting_items IS '연간 목표 — 주간 회의록 줄(구역·이번주 할 일·목표/결과 금액·전주 줄 carry_from)';
GRANT SELECT, INSERT, UPDATE, DELETE ON goal_meetings, goal_meeting_items TO project_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
COMMIT;
SELECT 'project_db 015 goal rect merges/meetings ready' AS status;
+140 -6
View File
@@ -20,7 +20,7 @@ import tempfile
import threading import threading
import types import types
import uuid import uuid
from datetime import timedelta from datetime import date, timedelta
from urllib.parse import urlparse from urllib.parse import urlparse
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -480,6 +480,7 @@ def test_goal_halves_and_merges():
board = ST.get_goal_board(year=year) board = ST.get_goal_board(year=year)
assert board["halves"] is True, "마이그레이션 014 적용 필요" assert board["halves"] is True, "마이그레이션 014 적용 필요"
rid = board["areas"][0]["rows"][0]["id"] rid = board["areas"][0]["rows"][0]["id"]
aid0 = board["areas"][0]["id"]
cell = lambda m, body, who=ADMIN: req( # noqa: E731 cell = lambda m, body, who=ADMIN: req( # noqa: E731
"PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body}) "PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body})
# 상·하반기 글 칸(13·14), 범위 밖(15)은 400, 비관리자는 403 # 상·하반기 글 칸(13·14), 범위 밖(15)은 400, 비관리자는 403
@@ -488,21 +489,22 @@ def test_goal_halves_and_merges():
assert cell(13, "y", BOB).status_code == 403 assert cell(13, "y", BOB).status_code == 403
for m, body in ((2, "이월"), (3, "삼월"), (5, "오월")): for m, body in ((2, "이월"), (3, "삼월"), (5, "오월")):
assert cell(m, body).status_code == 200 assert cell(m, body).status_code == 200
merge = lambda s, e: req( # noqa: E731 merge = lambda s, e: req( # noqa: E731 — 엑셀식 병합 API(한 줄 가로)
"POST", f"/project/api/goals/rows/{rid}/merge", ADMIN, json={"start": s, "end": e}) "POST", f"/project/api/goals/areas/{aid0}/merge", ADMIN,
json={"row_from": rid, "row_to": rid, "col_from": s, "col_to": e})
# 반기를 넘는 병합·한 칸 병합은 400 # 반기를 넘는 병합·한 칸 병합은 400
assert merge(5, 8).status_code == 400 and merge(4, 4).status_code == 400 assert merge(5, 8).status_code == 400 and merge(4, 4).status_code == 400
r = merge(2, 3) r = merge(2, 3)
assert r.status_code == 200 and r.json() == {"ok": True, "start": 2, "span": 2}, r.text assert r.status_code == 200 and r.json() == {"ok": True, "row_id": rid, "start": 2, "span": 2, "row_span": 1}, r.text
cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"]
assert cells[2] == "이월\n삼월" and 3 not in cells assert cells[2] == "이월\n삼월" and 3 not in cells
# 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만) # 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만)
assert cell(3, "늦은 저장").status_code == 400 assert cell(3, "늦은 저장").status_code == 400
# 걸친 병합은 흡수: 3~5 → 2~5, 글은 월 순서대로 이어진다 # 걸친 병합은 흡수: 3~5 → 2~5, 글은 월 순서대로 이어진다
r = merge(3, 5) r = merge(3, 5)
assert r.json() == {"ok": True, "start": 2, "span": 4}, r.text assert r.json() == {"ok": True, "row_id": rid, "start": 2, "span": 4, "row_span": 1}, r.text
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
assert row["merges"] == {2: 4} and row["cells"][2] == "이월\n삼월\n오월" and 5 not in row["cells"] assert row["merges"] == {2: (4, 1)} and row["cells"][2] == "이월\n삼월\n오월" and 5 not in row["cells"]
assert row["cells"][13] == "상반기 글" and row["cells"][14] == "하반기 글" assert row["cells"][13] == "상반기 글" and row["cells"][14] == "하반기 글"
# 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404 # 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 200 assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 200
@@ -540,6 +542,138 @@ def test_goal_halves_and_merges():
ST.delete_goal_year(year=year) ST.delete_goal_year(year=year)
# ════════════════════════════════════════════════════════════
# 연간 목표 — 엑셀식 사각형 병합 · 주간 회의록(마이그레이션 015)
# ════════════════════════════════════════════════════════════
def test_goal_rect_merges():
"""세로 병합(같은 영역 연속 줄)·연간/반기 칸 세로 병합, 걸친 병합 흡수, 가린 칸 저장 거절,
줄 끼우기/지우기에 따라 row_span 증감, 세로 병합에 걸린 줄 이동 거절, 다른 영역 줄 404."""
year = 2060 + (int(RUN, 16) + 7) % 40
ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
try:
assert ST.get_goal_board(year=year)["rect"] is True, "마이그레이션 015 적용 필요"
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
rows = lambda: ST.get_goal_board(year=year)["areas"][0]["rows"] # noqa: E731
while len(rows()) < 4: # 이전 연도 구조를 복사해 줄이 더 있을 수도 — 앞 4줄로 시험
req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json={"label": "채움"})
r1, r2, r3, r4 = [r["id"] for r in rows()][:4]
put = lambda rid, m, body: req("PUT", f"/project/api/goals/rows/{rid}/cells/{m}", ADMIN, json={"body": body}) # noqa: E731
assert put(r1, 0, "연간1").status_code == 200 and put(r2, 0, "연간2").status_code == 200
assert put(r2, 4, "사월2").status_code == 200
merge = lambda a, b, c0, c1, who=ADMIN: req( # noqa: E731
"POST", f"/project/api/goals/areas/{aid}/merge", who,
json={"row_from": a, "row_to": b, "col_from": c0, "col_to": c1})
# 연간 칸 세로 3줄 — 글은 위에서부터 이어 붙어 맨 위 칸에
r = merge(r1, r3, 0, 0)
assert r.status_code == 200 and r.json() == {"ok": True, "row_id": r1, "start": 0, "span": 1, "row_span": 3}, r.text
b = rows()
assert b[0]["merges"] == {0: (1, 3)} and b[0]["cells"][0] == "연간1\n연간2" and 0 not in b[1]["cells"]
assert put(r2, 0, "가린 칸").status_code == 400 # 가려진 칸 저장 거절
# 연간 + 1월 가로(묶음이 다름)·비관리자·다른 영역 줄 → 400·403·404
assert merge(r1, r1, 0, 1).status_code == 400
assert merge(r1, r2, 3, 4, BOB).status_code == 403
other = ST.get_goal_board(year=year)["areas"]
if len(other) > 1:
assert merge(r1, other[1]["rows"][0]["id"], 3, 3).status_code == 404
# 사각형 2줄 × 2칸(3~4월) → 걸친 병합으로 넓히기: 4월 r2 ~ 5월 r3 → 3~5월 × r2~r3
assert merge(r1, r2, 3, 4).json()["row_span"] == 2
r = merge(r2, r3, 4, 5)
assert r.json() == {"ok": True, "row_id": r1, "start": 3, "span": 3, "row_span": 3}, r.text
assert rows()[0]["cells"].get(3) == "사월2"
# 세로 병합에 걸린 줄 이동 거절, 걸리지 않은 맨 아래 줄(r4)은 위로 못 감(r3 이 걸림) / 병합 해제 뒤엔 됨
assert req("POST", f"/project/api/goals/rows/{r2}/move", ADMIN, json={"direction": 1}).status_code == 400
assert req("POST", f"/project/api/goals/rows/{r4}/move", ADMIN, json={"direction": -1}).status_code == 400
# 병합 안쪽에 줄 끼우기 → row_span +1, 가려진 줄 지우기 → -1
assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN,
json={"label": "끼움", "ref_row_id": r1, "place": "below"}).status_code == 201
assert rows()[0]["merges"] == {0: (1, 4), 3: (3, 4)}
assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN,
json={"label": "아래", "ref_row_id": r4, "place": "below"}).status_code == 201
assert rows()[0]["merges"] == {0: (1, 4), 3: (3, 4)} # 병합 밖이면 그대로
ins = rows()[1]["id"]
assert req("DELETE", f"/project/api/goals/rows/{ins}", ADMIN).status_code == 200
assert rows()[0]["merges"] == {0: (1, 3), 3: (3, 3)}
# 해제 — 글은 왼쪽 위 칸에
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/0", ADMIN).status_code == 200
b = rows()
assert b[0]["merges"] == {3: (3, 3)} and b[0]["cells"][0] == "연간1\n연간2"
assert put(r2, 0, "이제 됨").status_code == 200
finally:
ST.delete_goal_year(year=year)
def test_goal_meetings():
"""주간 회의록: 만들기(처음 = 목표 표 영역 + 기본 양식 줄, 유통 줄 쇼핑몰 추측), 다음 주 = 지난 회의록 줄 이어받기
(carry_from → prev), 금액 표기(만·억), 평가 값 검사, 줄 추가/이동/삭제, 화면·권한."""
base = date(2001, 1, 1) + timedelta(days=7 * (int(RUN, 16) % 400)) # 월요일(앞선 회의록이 없을 먼 과거)
assert base.weekday() == 0
w1, w2 = base, base + timedelta(days=7)
for w in (w2, w1):
try:
ST.delete_meeting(week_start=w)
except KeyError:
pass
try:
assert req("POST", f"/project/api/goals/meetings/{w1}", BOB, json={"year": w1.year}).status_code == 403
assert req("POST", f"/project/api/goals/meetings/{w1 + timedelta(days=1)}", ADMIN, json={}).status_code == 400
r = req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year})
assert r.status_code == 201 and r.json()["created"] is True, r.text
assert req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year}).json()["created"] is False
m1 = ST.get_meeting(week_start=w1)
secs = [s for s in dict.fromkeys(it["section"] for it in m1["items"])]
assert secs[:4] == ["상품", "마케팅", "컨텐츠", "유통"], secs
coupang = next(it for it in m1["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
assert coupang["marketplace_code"] == "coupang"
assert next(it for it in m1["items"] if it["section"] == "마케팅" and it["label"] == "네이버")["marketplace_code"] == ""
put = lambda iid, body, who=ADMIN: req("PUT", f"/project/api/goals/meeting-items/{iid}", who, json=body) # noqa: E731
r = put(coupang["id"], {"content": "추석 타임딜", "target_amount": "1,200만"})
assert r.status_code == 200 and r.json()["item"]["target_amount"] == 12_000_000, r.text
assert put(coupang["id"], {"target_amount": "abc"}).status_code == 400
assert put(coupang["id"], {"status": "bogus"}).status_code == 400
assert put(coupang["id"], {"content": "x"}, BOB).status_code == 403
assert req("PUT", f"/project/api/goals/meetings/{w1}", ADMIN,
json={"week_target": "3천만", "attendees": "대표", "notes": "메모"}).status_code == 200
# 다음 주 — 줄을 이어받고 전주 칸(prev)에 지난주 할 일·목표
assert req("POST", f"/project/api/goals/meetings/{w2}", ADMIN, json={"year": w2.year}).status_code == 201
m2 = ST.get_meeting(week_start=w2)
assert len(m2["items"]) == len(m1["items"]) and all(it["content"] == "" for it in m2["items"])
c2 = next(it for it in m2["items"] if it["carry_from"] == coupang["id"])
assert c2["prev"]["content"] == "추석 타임딜" and c2["prev"]["target_amount"] == 12_000_000
assert m2["prev_meeting"] == {"week_start": w1.isoformat(), "week_target": 30_000_000}
# 지난주 결과·평가는 지난 회의록 줄에 저장
assert put(coupang["id"], {"result_amount": "1.5억", "status": "done"}).json()["item"]["result_amount"] == 150_000_000
# 줄 추가(기준 줄 아래)·이동(같은 구역 안)·삭제, 새 구역
r = req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN,
json={"section": "유통", "label": "롯데온", "ref_item_id": c2["id"], "place": "below"})
assert r.status_code == 201, r.text
new_id = r.json()["id"]
labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]]
assert labels[labels.index("쿠팡") + 1] == "롯데온"
assert next(it for it in ST.get_meeting(week_start=w2)["items"] if it["id"] == new_id)["marketplace_code"] == "lotteon"
assert req("POST", f"/project/api/goals/meeting-items/{new_id}/move", ADMIN, json={"direction": -1}).status_code == 200
labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]]
assert labels.index("롯데온") < labels.index("쿠팡")
assert req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN, json={"section": "물류"}).status_code == 201
assert ST.get_meeting(week_start=w2)["items"][-1]["section"] == "물류"
assert req("DELETE", f"/project/api/goals/meeting-items/{new_id}", ADMIN).status_code == 200
# 화면 — 그 달 주차 탭, 회의록 줄
page = req("GET", f"/project/goals/{w2.year}/meetings/{w2.month}?week={w2}", BOB)
assert page.status_code == 200 and page.text.startswith("project/goal_meeting.html"), page.text
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", BOB)
assert v.status_code == 200 and v.json()["meeting"]["week_start"] == w2.isoformat()
# 지난 회의록을 지우면 다음 주 전주 칸은 비고(carry_from NULL), 회의록은 남는다
assert req("DELETE", f"/project/api/goals/meetings/{w1}", ADMIN).status_code == 200
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w2)["items"])
finally:
for w in (w2, w1):
try:
ST.delete_meeting(week_start=w)
except KeyError:
pass
if __name__ == "__main__": if __name__ == "__main__":
if not ENABLED: if not ENABLED:
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set") print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")