feat(project): 연간 목표 — 사이드바 "목표" → 연도 → 그해 전체 목표 표

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-30 11:13:54 +09:00
parent b95206dcf4
commit ec78dd328d
15 changed files with 1315 additions and 13 deletions
+307
View File
@@ -7397,6 +7397,311 @@
document.addEventListener("mouseleave", hide);
}
// ── 사이드바 "목표" — 누르면 바로 아래 연도 목록을 접었다 편다(localStorage pj_goal_open).
// 목표 화면에서는 항상 펼친 채로 시작(data-force-open). 관리자는 "+ 연도 추가".
function initGoalSide() {
const box = el("pj-side-goal");
if (!box) return;
const btn = el("pj-side-goal-toggle");
const list = el("pj-side-goal-years");
function setOpen(open, remember) {
list.hidden = !open;
box.classList.toggle("is-open", open);
btn.setAttribute("aria-expanded", open ? "true" : "false");
if (remember) { try { localStorage.setItem("pj_goal_open", open ? "1" : "0"); } catch (_) {} }
}
if (box.dataset.forceOpen !== "true") {
let saved = null;
try { saved = localStorage.getItem("pj_goal_open"); } catch (_) {}
if (saved === "1") setOpen(true, false);
}
btn.addEventListener("click", function () { setOpen(list.hidden, true); });
const add = el("pj-goal-year-add");
if (add) add.addEventListener("click", async function () {
const v = await prompt("추가할 연도를 입력하세요.", add.dataset.next || "");
if (v == null || !String(v).trim()) return;
try {
const res = await api("POST", "/project/api/goals/years", { year: String(v).trim() });
location.href = "/project/goals/" + res.year;
} catch (e) { showToast("연도 추가 실패: " + e.message, "error"); }
});
}
// ── 연간 목표 화면(/project/goals/{연도}) — 관리자만 입력, 칸마다 바로 저장.
// · 숫자(매출/로아스 목표·실적): 칸을 떠나거나 Enter 에 저장, 서버가 돌려준 표기(쉼표)로 바꿈.
// 매출 연간 합계와 달성률(실적÷목표)은 화면에서 계산.
// · 업무 영역 글: 치는 동안 0.8초 멈추면 저장, 칸을 떠날 때·페이지를 떠날 때도 저장.
// · 영역/줄 추가·이름·순서·삭제는 저장 후 새로고침(스크롤 위치는 되살림).
function initGoals() {
const pane = el("pj-goal-pane");
if (!pane) return;
const SCROLL_KEY = "pj_goal_scroll";
function reloadKeepScroll() {
try { sessionStorage.setItem(SCROLL_KEY, JSON.stringify([location.pathname, pane.scrollLeft, pane.scrollTop])); } catch (_) {}
location.reload();
}
try {
const s = JSON.parse(sessionStorage.getItem(SCROLL_KEY) || "null");
sessionStorage.removeItem(SCROLL_KEY);
if (s && s[0] === location.pathname) { pane.scrollLeft = s[1]; pane.scrollTop = s[2]; }
} catch (_) {}
const create = el("pj-goal-create");
if (create) create.addEventListener("click", async function () {
create.disabled = true;
try {
await api("POST", "/project/api/goals/years", { year: create.dataset.year });
location.reload();
} catch (e) { create.disabled = false; showToast("만들기 실패: " + e.message, "error"); }
});
const table = el("pj-goal-table");
if (!table) return;
const year = table.dataset.year;
const isAdmin = table.dataset.admin === "true";
// ── 합계·달성률 ──
function numOf(node) {
const raw = (node.tagName === "INPUT" ? node.value : node.textContent) || "";
const s = raw.replace(/[,%\s]/g, "");
if (!s) return null;
const n = Number(s);
return isFinite(n) ? n : null;
}
function fmtNum(n) {
return (Math.round(n * 100) / 100).toLocaleString("ko-KR", { maximumFractionDigits: 2 });
}
function values(metric, kind) {
const out = {};
table.querySelectorAll('.pj-goal-num[data-metric="' + metric + '"][data-kind="' + kind + '"]')
.forEach(function (n) { out[n.dataset.month] = numOf(n); });
return out;
}
function setRate(td, actual, target) {
td.classList.remove("is-good", "is-low");
if (actual == null || !target) { td.textContent = ""; return; }
const r = actual / target * 100;
td.textContent = (Math.round(r * 10) / 10).toLocaleString("ko-KR") + "%";
td.classList.add(r >= 100 ? "is-good" : "is-low");
}
function recompute() {
const tg = values("sales", "target"), ac = values("sales", "actual");
let sumT = null, sumA = null;
for (let m = 1; m <= 12; m++) {
if (tg[m] != null) sumT = (sumT || 0) + tg[m];
if (ac[m] != null) sumA = (sumA || 0) + ac[m];
const td = table.querySelector('.pj-goal-rate[data-month="' + m + '"]');
if (td) setRate(td, ac[m], tg[m]);
}
const st = table.querySelector('.pj-goal-sum[data-metric="sales"][data-kind="target"]');
const sa = table.querySelector('.pj-goal-sum[data-metric="sales"][data-kind="actual"]');
if (st) st.textContent = sumT == null ? "" : fmtNum(sumT);
if (sa) sa.textContent = sumA == null ? "" : fmtNum(sumA);
// 연간 달성률은 실적이 들어온 달까지만 비교(남은 달 목표까지 넣으면 연중엔 항상 낮게 나온다).
let tUpTo = 0;
for (let m = 1; m <= 12; m++) if (ac[m] != null && tg[m] != null) tUpTo += tg[m];
const y0 = table.querySelector('.pj-goal-rate[data-month="0"]');
if (y0) setRate(y0, sumA, tUpTo);
if (y0) y0.dataset.tip = tUpTo ? "실적이 있는 달의 목표 합계 대비" : "";
}
recompute();
if (!isAdmin) return;
// ── 숫자 칸 ──
table.querySelectorAll("input.pj-goal-num").forEach(function (inp) {
inp.dataset.saved = inp.value;
inp.addEventListener("focus", function () { inp.select(); });
inp.addEventListener("input", recompute);
inp.addEventListener("keydown", function (e) {
if (e.key === "Enter") { e.preventDefault(); inp.blur(); }
else if (e.key === "Escape") { inp.value = inp.dataset.saved; recompute(); inp.blur(); }
});
inp.addEventListener("change", async function () {
const d = inp.dataset;
try {
const res = await api("PUT", "/project/api/goals/" + year + "/metrics",
{ metric: d.metric, kind: d.kind, month: parseInt(d.month, 10), value: inp.value });
inp.value = res.label;
d.saved = res.label;
flashSaved(inp.parentElement);
} catch (e) {
inp.value = d.saved;
showToast("저장 실패: " + e.message, "error");
}
recompute();
});
});
function flashSaved(node) {
node.classList.remove("is-saved");
void node.offsetWidth;
node.classList.add("is-saved");
}
// ── 글 칸 ──
function fit(ta) { ta.style.height = "auto"; ta.style.height = ta.scrollHeight + "px"; }
const pending = new Map(); // textarea → 타이머
function cellUrl(ta) { return "/project/api/goals/rows/" + ta.dataset.row + "/cells/" + ta.dataset.month; }
async function saveText(ta) {
clearTimeout(pending.get(ta));
pending.delete(ta);
const body = ta.value;
if (body === ta.dataset.saved) return;
try {
await api("PUT", cellUrl(ta), { body: body });
ta.dataset.saved = body;
flashSaved(ta.parentElement);
} catch (e) { showToast("저장 실패: " + e.message, "error"); }
}
table.querySelectorAll("textarea.pj-goal-text").forEach(function (ta) {
ta.dataset.saved = ta.value;
fit(ta);
ta.addEventListener("input", function () {
fit(ta);
clearTimeout(pending.get(ta));
pending.set(ta, setTimeout(function () { saveText(ta); }, 800));
});
ta.addEventListener("blur", function () { saveText(ta); });
});
// 한 줄 안 칸들 높이는 표가 맞춘다 — 창 폭이 바뀌면 글 줄바꿈이 달라지니 다시 잰다.
window.addEventListener("resize", function () {
table.querySelectorAll("textarea.pj-goal-text").forEach(fit);
});
window.addEventListener("beforeunload", function () {
pending.forEach(function (timer, ta) {
clearTimeout(timer);
if (ta.value === ta.dataset.saved) return;
try {
fetch(cellUrl(ta), {
method: "PUT", keepalive: true, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: ta.value }),
});
} catch (_) {}
});
});
// ── 머리 — 매출 단위 · 연도 삭제 ──
const unit = el("pj-goal-unit");
if (unit) {
unit.dataset.saved = unit.value;
unit.addEventListener("keydown", function (e) { if (e.key === "Enter") unit.blur(); });
unit.addEventListener("change", async function () {
try {
await api("PUT", "/project/api/goals/" + year, { sales_unit: unit.value });
unit.dataset.saved = unit.value;
showToast("매출 단위를 저장했습니다.");
} catch (e) { unit.value = unit.dataset.saved; showToast("저장 실패: " + e.message, "error"); }
});
}
const del = el("pj-goal-year-del");
if (del) del.addEventListener("click", async function () {
const v = await prompt(year + "년 목표를 모두 삭제합니다(숫자·업무 영역·글 전부, 되돌릴 수 없음).\n" +
"계속하려면 " + year + " 를 입력하세요.", "");
if (v == null) return;
if (String(v).trim() !== String(year)) { showToast("연도가 달라 삭제하지 않았습니다."); return; }
try {
await api("DELETE", "/project/api/goals/" + year);
location.href = "/project/goals";
} catch (e) { showToast("삭제 실패: " + e.message, "error"); }
});
// ── 업무 영역 추가 ──
const colors = window.PJ_GOAL_COLORS || [];
const addArea = el("pj-goal-area-add");
if (addArea) addArea.addEventListener("click", async function () {
const name = await prompt("새 업무 영역 이름", "");
if (name == null || !String(name).trim()) return;
const n = table.querySelectorAll(".pj-goal-area").length;
try {
await api("POST", "/project/api/goals/" + year + "/areas",
{ name: String(name).trim(), color: colors.length ? colors[n % colors.length] : "" });
reloadKeepScroll();
} catch (e) { showToast("추가 실패: " + e.message, "error"); }
});
// ── 영역 색 고르기 — 팝업은 body 에(화면 배율 밖) ──
let colorPop = null;
function closeColorPop() {
if (!colorPop) return;
colorPop.remove();
colorPop = null;
document.removeEventListener("mousedown", onColorDocDown, true);
}
function onColorDocDown(e) { if (colorPop && !colorPop.contains(e.target)) closeColorPop(); }
function openColorPop(anchor, areaId, current, tbody) {
closeColorPop();
colorPop = document.createElement("div");
colorPop.className = "pj-goal-colorpop";
colorPop.innerHTML = colors.map(function (c) {
return '<button type="button" class="pj-goal-swatch' + (c === current ? " is-on" : "") +
'" data-c="' + c + '" style="background:' + c + '"></button>';
}).join("");
document.body.appendChild(colorPop);
const r = anchor.getBoundingClientRect();
const w = colorPop.offsetWidth;
colorPop.style.left = Math.max(8, Math.min(r.left, document.documentElement.clientWidth - w - 8)) + "px";
colorPop.style.top = (r.bottom + 6) + "px";
colorPop.addEventListener("click", async function (e) {
const sw = e.target.closest(".pj-goal-swatch");
if (!sw) return;
const c = sw.dataset.c;
closeColorPop();
try {
await api("PUT", "/project/api/goals/areas/" + areaId, { color: c });
tbody.style.setProperty("--goal-bg", c);
anchor.dataset.color = c;
} catch (err) { showToast("색 변경 실패: " + err.message, "error"); }
});
setTimeout(function () { document.addEventListener("mousedown", onColorDocDown, true); }, 0);
}
// ── 영역·줄 도구(✎ 색 ↑ ↓ + ×) — 이벤트 위임 ──
table.addEventListener("click", async function (e) {
const b = e.target.closest("[data-goal-act]");
if (!b) return;
const act = b.dataset.goalAct;
const tbody = b.closest(".pj-goal-area");
const tr = b.closest("tr");
const areaId = tbody && tbody.dataset.areaId;
const rowId = tr && tr.dataset.rowId;
try {
if (act === "area-rename") {
const v = await prompt("업무 영역 이름", b.dataset.name || "");
if (v == null || !String(v).trim() || v === b.dataset.name) return;
await api("PUT", "/project/api/goals/areas/" + areaId, { name: String(v).trim() });
} else if (act === "area-color") {
openColorPop(b, areaId, b.dataset.color, tbody);
return;
} else if (act === "area-up" || act === "area-down") {
await api("POST", "/project/api/goals/areas/" + areaId + "/move", { direction: act === "area-up" ? -1 : 1 });
} else if (act === "area-del") {
const ok = await confirm("'" + (b.dataset.name || "") + "' 업무 영역을 삭제할까요?\n안의 줄과 글도 모두 삭제됩니다.",
{ okText: "삭제", cancelText: "취소" });
if (!ok) return;
await api("DELETE", "/project/api/goals/areas/" + areaId);
} else if (act === "row-add") {
const v = await prompt("새 줄 이름 (예: 쿠팡 — 비워 둬도 됩니다)", "");
if (v == null) return;
await api("POST", "/project/api/goals/areas/" + areaId + "/rows", { label: String(v).trim() });
} else if (act === "row-rename") {
const v = await prompt("줄 이름", b.dataset.label || "");
if (v == null || v === b.dataset.label) return;
await api("PUT", "/project/api/goals/rows/" + rowId, { label: String(v).trim() });
} else if (act === "row-up" || act === "row-down") {
await api("POST", "/project/api/goals/rows/" + rowId + "/move", { direction: act === "row-up" ? -1 : 1 });
} else if (act === "row-del") {
const label = b.dataset.label ? "'" + b.dataset.label + "' 줄" : "이 줄";
const ok = await confirm(label + "을 삭제할까요? 그 줄의 글도 모두 삭제됩니다.", { okText: "삭제", cancelText: "취소" });
if (!ok) return;
await api("DELETE", "/project/api/goals/rows/" + rowId);
} else return;
// 저장 안 된 글이 있으면 먼저 저장하고 새로고침
await Promise.all(Array.from(pending.keys()).map(saveText));
reloadKeepScroll();
} catch (err) { showToast("처리 실패: " + err.message, "error"); }
});
}
// ── 휴지통(관리자 전용 화면) — [복구] 누르면 원래 id 그대로 되살리고 줄을 지운다.
function initTrash() {
const table = el("pj-trash-table");
@@ -7427,6 +7732,8 @@
// 좌측 프로젝트 목록 — 프로젝트 화면은 initProject 가 자기 데이터로 직접 연다.
if (!document.querySelector(".pj-project-view")) initSideTree();
initTrash();
initGoalSide();
initGoals();
initMyTasks();
initProject();
initAllMembers();