Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cd0a509215 | |||
| 7647e4b20f | |||
| 2c8542339d | |||
| b32f2ac3a3 | |||
| e726f986db | |||
| 36a6866b96 | |||
| db39d3b383 | |||
| dc2008c5b3 | |||
| 494d84f7c2 | |||
| 44f6ca4ef7 | |||
| 7f9c7a24d3 | |||
| 22af196d56 | |||
| 20232baf06 | |||
| 035cb83d6f | |||
| 114af59b26 | |||
| 6a38fdb06a | |||
| d387048ebf | |||
| 71516713c5 | |||
| d21670f6af | |||
| 2434bce35e | |||
| f02742497a | |||
| 968892d811 | |||
| a3a9444c3b | |||
| e1006c63de | |||
| 21981eb946 | |||
| ac4f2653af | |||
| 51727e419a | |||
| b791f7be68 | |||
| 334b83c973 | |||
| 6ea4a2e0f9 | |||
| ec5d7e2efe | |||
| 737191c170 | |||
| f199eda322 | |||
| 9161e0901f | |||
| 5460c7f676 | |||
| 2a9f6f5628 | |||
| 58dbb7ef3e | |||
| 75b82024de | |||
| 4af1ad8848 | |||
| 164153dc9c | |||
| ac0672bc11 | |||
| 24dd3acd09 | |||
| 4efe7cef58 | |||
| 2dab20f718 | |||
| be298777af | |||
| 45a671940b | |||
| 601971d43d | |||
| c9bce7c976 | |||
| 614747ffca | |||
| 931cc0d1d9 | |||
| b6b4f8c360 | |||
| ff81d80cf9 | |||
| 01000757f3 | |||
| d75dec2a50 | |||
| a45f78217c | |||
| d3761183c3 | |||
| 5d07770ce2 |
+1
-1
@@ -376,7 +376,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
},
|
||||
{
|
||||
"key": "project",
|
||||
"title": "프로젝트 관리",
|
||||
"title": "Project",
|
||||
"subtitle": "Projects",
|
||||
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
||||
"url": "/project/",
|
||||
|
||||
@@ -36,10 +36,23 @@ class CupangDBStore:
|
||||
open=False,
|
||||
)
|
||||
self._pool.open(wait=False)
|
||||
self._weight_col: bool | None = None # 마이그레이션 007(weight_g) 적용 여부 — 한 번 확인되면 기억
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
def weight_enabled(self) -> bool:
|
||||
"""cupang_products.weight_g(포장무게, 마이그레이션 007) 가 있는가. 있으면 기억(없으면 다음에 다시 확인)."""
|
||||
if self._weight_col:
|
||||
return True
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM information_schema.columns "
|
||||
"WHERE table_name = 'cupang_products' AND column_name = 'weight_g'"
|
||||
).fetchone()
|
||||
self._weight_col = row is not None
|
||||
return self._weight_col
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 입고센터 (cupang_centers)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -300,32 +313,39 @@ class CupangDBStore:
|
||||
product_name: str,
|
||||
coupang_item_code: str | None = None,
|
||||
sort_order: int = 0,
|
||||
weight_g: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""제품 등록/수정.
|
||||
|
||||
coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기).
|
||||
weight_g(포장무게 g) 가 None 이면 기존 값을 유지한다(수기 추가에서 비워 두면 그대로). 007 미적용이면 무시.
|
||||
"""
|
||||
code = (product_code or "").strip()
|
||||
name = (product_name or "").strip()
|
||||
cic = None if coupang_item_code is None else coupang_item_code.strip()
|
||||
if not code or not name:
|
||||
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
||||
weight = self.weight_enabled()
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cupang_products
|
||||
(product_code, product_name, coupang_item_code, sort_order)
|
||||
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s)
|
||||
(product_code, product_name, coupang_item_code, sort_order"""
|
||||
+ (", weight_g" if weight else "") + """)
|
||||
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s"""
|
||||
+ (", %(w)s" if weight else "") + """)
|
||||
ON CONFLICT (product_code) DO UPDATE
|
||||
SET product_name = EXCLUDED.product_name,
|
||||
coupang_item_code = COALESCE(
|
||||
%(cic)s, cupang_products.coupang_item_code
|
||||
),
|
||||
),"""
|
||||
+ ("\n weight_g = COALESCE(%(w)s, cupang_products.weight_g)," if weight else "")
|
||||
+ """
|
||||
sort_order = EXCLUDED.sort_order,
|
||||
active = TRUE
|
||||
RETURNING *
|
||||
""",
|
||||
{"code": code, "name": name, "cic": cic, "sort": sort_order},
|
||||
{"code": code, "name": name, "cic": cic, "sort": sort_order, "w": weight_g},
|
||||
).fetchone()
|
||||
return self._product_serialize(row)
|
||||
|
||||
@@ -345,8 +365,11 @@ class CupangDBStore:
|
||||
product_name: str,
|
||||
product_code: str,
|
||||
coupang_item_code: str = "",
|
||||
weight_g: Any = ...,
|
||||
) -> dict[str, Any]:
|
||||
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드).
|
||||
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드/포장무게).
|
||||
|
||||
weight_g: 정수 g 또는 None(지움). 넘기지 않으면(...) 그대로 — 007 미적용이면 무시.
|
||||
|
||||
제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의
|
||||
product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지).
|
||||
@@ -356,6 +379,7 @@ class CupangDBStore:
|
||||
cic = (coupang_item_code or "").strip()
|
||||
if not name or not code:
|
||||
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
||||
set_weight = weight_g is not ... and self.weight_enabled() # 트랜잭션 밖에서 확인(연결을 겹쳐 잡지 않게)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
old = conn.execute(
|
||||
@@ -378,11 +402,12 @@ class CupangDBStore:
|
||||
UPDATE cupang_products
|
||||
SET product_name = %s,
|
||||
product_code = %s,
|
||||
coupang_item_code = %s
|
||||
coupang_item_code = %s"""
|
||||
+ (", weight_g = %s" if set_weight else "") + """
|
||||
WHERE id = %s
|
||||
RETURNING *
|
||||
""",
|
||||
(name, code, cic, product_id),
|
||||
(name, code, cic) + ((weight_g,) if set_weight else ()) + (product_id,),
|
||||
).fetchone()
|
||||
if code != old_code:
|
||||
# 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지).
|
||||
@@ -1081,6 +1106,8 @@ class CupangDBStore:
|
||||
out["active"] = bool(out.get("active", True))
|
||||
out["sort_order"] = int(out.get("sort_order", 0))
|
||||
out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip()
|
||||
w = out.get("weight_g") # 007 미적용이면 키 없음 → None
|
||||
out["weight_g"] = int(w) if w is not None else None
|
||||
for k in ("created_at", "updated_at"):
|
||||
v = out.get(k)
|
||||
if isinstance(v, datetime):
|
||||
|
||||
@@ -193,10 +193,17 @@ def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
||||
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
|
||||
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
|
||||
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
|
||||
BOX_WEIGHT_HEADER = "무게(g)" # with_weight 일 때 5열 — 상자 무게 합계(상자번호처럼 상자 단위로 세로 병합)
|
||||
BOX_WEIGHT_WIDTH_PX = 80
|
||||
|
||||
|
||||
def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, Any]]) -> Any:
|
||||
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일)."""
|
||||
def build_box_list_workbook(
|
||||
shipment: dict[str, Any], box_list: list[dict[str, Any]], *, with_weight: bool = False
|
||||
) -> Any:
|
||||
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일).
|
||||
|
||||
with_weight 면 5열 "무게(g)" — 상자마다 box["weight_g"](라우터 _attach_box_weights), 모르면 빈칸."""
|
||||
headers = BOX_HEADERS + ([BOX_WEIGHT_HEADER] if with_weight else [])
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
@@ -215,10 +222,10 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
|
||||
|
||||
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
|
||||
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
|
||||
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(BOX_HEADERS))
|
||||
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
|
||||
|
||||
header_fill = PatternFill("solid", fgColor=HEADER_BG)
|
||||
for idx, name in enumerate(BOX_HEADERS, start=1):
|
||||
for idx, name in enumerate(headers, start=1):
|
||||
cell = ws.cell(row=2, column=idx, value=name)
|
||||
cell.font = Font(bold=True)
|
||||
cell.alignment = center_align
|
||||
@@ -235,18 +242,27 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
|
||||
ws.cell(row=row, column=3, value=it.get("product_code") or "")
|
||||
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
|
||||
row += 1
|
||||
# 한 상자에 여러 제품이면 상자번호 칸을 세로로 합친다.
|
||||
if with_weight and contents:
|
||||
w = entry.get("weight_g")
|
||||
ws.cell(row=first, column=5, value=(int(w) if w is not None else None))
|
||||
ws.cell(row=first, column=5).number_format = "#,##0"
|
||||
# 한 상자에 여러 제품이면 상자번호(·무게) 칸을 세로로 합친다.
|
||||
if row - first > 1:
|
||||
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
|
||||
if with_weight:
|
||||
ws.merge_cells(start_row=first, start_column=5, end_row=row - 1, end_column=5)
|
||||
|
||||
last = row - 1
|
||||
for r in range(3, last + 1):
|
||||
for col in range(1, len(BOX_HEADERS) + 1):
|
||||
for col in range(1, len(headers) + 1):
|
||||
cell = ws.cell(row=r, column=col)
|
||||
cell.border = box
|
||||
cell.alignment = left_align if col == 2 else center_align
|
||||
|
||||
for col, px in BOX_WIDTHS_PX.items():
|
||||
widths = dict(BOX_WIDTHS_PX)
|
||||
if with_weight:
|
||||
widths[5] = BOX_WEIGHT_WIDTH_PX
|
||||
for col, px in widths.items():
|
||||
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
|
||||
ws.row_dimensions[1].height = 24
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
|
||||
from .holidays import holiday_name, is_holiday
|
||||
from .store import SHIP_METHODS
|
||||
from .store import SHIP_METHODS, parse_weight_g
|
||||
|
||||
router = APIRouter(prefix="/cupang", tags=["cupang"])
|
||||
|
||||
@@ -411,6 +411,8 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
||||
]
|
||||
calc = _compute_boxes(store, items)
|
||||
total_qty = sum(it["quantity"] for it in items)
|
||||
box_list = _expand_box_list(ship, calc, items)
|
||||
box_weight = _attach_box_weights(store, box_list)
|
||||
|
||||
return render_template(
|
||||
request,
|
||||
@@ -424,7 +426,9 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
||||
"shipment": ship,
|
||||
"items": items,
|
||||
"calc": calc,
|
||||
"box_list": _expand_box_list(ship, calc, items),
|
||||
"box_list": box_list,
|
||||
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
|
||||
"box_weight": box_weight,
|
||||
"total_qty": total_qty,
|
||||
},
|
||||
)
|
||||
@@ -432,7 +436,7 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
||||
|
||||
@router.get("/{shipment_id:int}/boxes.xlsx")
|
||||
def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
||||
"""상자 목록(상자번호·제품명·제품코드·수량) 엑셀 다운로드."""
|
||||
"""상자 목록(상자번호·제품명·제품코드·수량·무게) 엑셀 다운로드."""
|
||||
from io import BytesIO # noqa: WPS433
|
||||
|
||||
from fastapi.responses import StreamingResponse # noqa: WPS433
|
||||
@@ -457,8 +461,9 @@ def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
||||
for ln in (ship.get("lines") or [])
|
||||
]
|
||||
box_list = _expand_box_list(ship, _compute_boxes(store, items), items)
|
||||
with_weight = _attach_box_weights(store, box_list)
|
||||
|
||||
wb = build_box_list_workbook(ship, box_list)
|
||||
wb = build_box_list_workbook(ship, box_list, with_weight=with_weight)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
@@ -1185,6 +1190,36 @@ def _compute_boxes(store: Any, raw_items: list[Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
|
||||
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
|
||||
|
||||
상자에 넣는 값: weight_g = 아는 무게의 합(상자 안 제품 무게가 하나도 없으면 None),
|
||||
weight_missing = 무게가 없는 제품코드 목록(일부만 없으면 합계는 그 제품을 뺀 값).
|
||||
포장무게 칸(마이그레이션 007)이 없으면 아무것도 넣지 않고 False.
|
||||
"""
|
||||
if not store.weight_enabled():
|
||||
return False
|
||||
weights = {
|
||||
str(p.get("product_code") or "").strip(): p.get("weight_g")
|
||||
for p in store.list_products(include_inactive=True)
|
||||
}
|
||||
for box in box_list:
|
||||
contents = box.get("items") or []
|
||||
total, missing = 0, []
|
||||
for it in contents:
|
||||
code = str(it.get("product_code") or "").strip()
|
||||
w = weights.get(code)
|
||||
if w is None:
|
||||
if code not in missing:
|
||||
missing.append(code)
|
||||
continue
|
||||
total += int(w) * int(it.get("quantity") or 0)
|
||||
known = any(weights.get(str(it.get("product_code") or "").strip()) is not None for it in contents)
|
||||
box["weight_g"] = total if known else None
|
||||
box["weight_missing"] = missing
|
||||
return True
|
||||
|
||||
|
||||
def _expand_box_list(
|
||||
shipment: dict[str, Any], calc: dict[str, Any], items: list[dict[str, Any]]
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -1349,6 +1384,8 @@ def products_page(request: Request) -> HTMLResponse:
|
||||
"page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.",
|
||||
"products": store.list_products(include_inactive=True),
|
||||
"registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)],
|
||||
# 포장무게(g) — 마이그레이션 007 적용 전이면 무게 칸을 숨긴다
|
||||
"weight_enabled": store.weight_enabled(),
|
||||
"search_enabled": bool(reader and reader.enabled),
|
||||
"search_reason": (reader.reason if reader else ""),
|
||||
},
|
||||
@@ -1412,6 +1449,7 @@ def product_upsert(
|
||||
product_code: str = Form(...),
|
||||
product_name: str = Form(...),
|
||||
coupang_item_code: str = Form(""),
|
||||
weight_g: str = Form(""),
|
||||
sort_order: int = Form(0),
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> RedirectResponse:
|
||||
@@ -1422,9 +1460,10 @@ def product_upsert(
|
||||
store.upsert_product(
|
||||
product_code=product_code,
|
||||
product_name=product_name,
|
||||
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드를 유지한다.
|
||||
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드·포장무게를 유지한다.
|
||||
coupang_item_code=(coupang_item_code.strip() or None),
|
||||
sort_order=sort_order,
|
||||
weight_g=parse_weight_g(weight_g),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
@@ -1457,7 +1496,8 @@ def product_edit(
|
||||
payload: dict[str, Any] = Body(...),
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> JSONResponse:
|
||||
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code}."""
|
||||
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code, weight_g?}.
|
||||
weight_g 키가 있으면 저장(빈 값 = 지움), 없으면 무게는 그대로."""
|
||||
store = _store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="cupang_db 미설정")
|
||||
@@ -1467,6 +1507,7 @@ def product_edit(
|
||||
product_name=str(payload.get("product_name") or ""),
|
||||
product_code=str(payload.get("product_code") or ""),
|
||||
coupang_item_code=str(payload.get("coupang_item_code") or ""),
|
||||
weight_g=(parse_weight_g(payload.get("weight_g")) if "weight_g" in payload else ...),
|
||||
)
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.")
|
||||
|
||||
@@ -94,3 +94,32 @@ def compute_boxes(quantity: int, units_per_box: int | None) -> dict[str, Any]:
|
||||
"remainder_units": qty % upb,
|
||||
"required_boxes": math.ceil(qty / upb),
|
||||
}
|
||||
|
||||
|
||||
# 제품 포장무게(g) — cupang_products.weight_g (마이그레이션 007). 0 ~ 1,000,000g, 정수.
|
||||
WEIGHT_MAX_G = 1_000_000
|
||||
|
||||
|
||||
def parse_weight_g(value: Any) -> int | None:
|
||||
"""포장무게 입력 → 그램 정수. 빈 값은 None(미입력).
|
||||
|
||||
"1,070" · " 1,070 " · "1070g" · "1070.0" 처럼 쉼표·공백·g 단위가 붙어도 읽는다.
|
||||
숫자가 아니거나 음수·소수(0.5g 등)·범위 밖이면 ValueError.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip().replace(",", "").replace(" ", "")
|
||||
if s.lower().endswith("g"):
|
||||
s = s[:-1]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
f = float(s)
|
||||
except ValueError:
|
||||
raise ValueError(f"포장무게는 숫자(g)로 입력하세요: {value}")
|
||||
if f != f or f < 0 or f != int(f):
|
||||
raise ValueError(f"포장무게는 0 이상의 정수(g)로 입력하세요: {value}")
|
||||
v = int(f)
|
||||
if v > WEIGHT_MAX_G:
|
||||
raise ValueError(f"포장무게가 너무 큽니다(최대 {WEIGHT_MAX_G:,}g): {value}")
|
||||
return v
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cpg">
|
||||
@@ -34,6 +34,12 @@
|
||||
<input class="erp-input" type="text" name="product_code" required placeholder="예: MS-1012" /></label>
|
||||
<label class="erp-field"><span>쿠팡상품코드</span>
|
||||
<input class="erp-input" type="text" name="coupang_item_code" placeholder="예: 1234567890" /></label>
|
||||
{% if weight_enabled %}
|
||||
{# 포장무게(g) — 쉼표·g 붙여도 됨(1,070). 비워 두면 같은 제품코드의 기존 무게 유지 #}
|
||||
<label class="erp-field cpg-weight-field"><span>포장무게(g)</span>
|
||||
<input class="erp-input" type="text" name="weight_g" inputmode="numeric" autocomplete="off"
|
||||
pattern="\s*[0-9][0-9,]*\s*(g|G)?\s*" title="숫자(g)로 입력하세요. 예: 1,070" placeholder="예: 1,070" /></label>
|
||||
{% endif %}
|
||||
<button type="submit" class="erp-btn erp-btn-primary">추가</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -60,6 +66,7 @@
|
||||
<th><button type="button" class="cpg-sort" data-sort-key="name">제품명<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||
<th><button type="button" class="cpg-sort" data-sort-key="code">제품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||
<th><button type="button" class="cpg-sort" data-sort-key="cpcode">쿠팡상품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||
{% if weight_enabled %}<th class="cpg-weight-col"><button type="button" class="cpg-sort" data-sort-key="weight">포장무게<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>{% endif %}
|
||||
<th>상태</th>
|
||||
<th>동작</th>
|
||||
</tr>
|
||||
@@ -68,10 +75,12 @@
|
||||
{% for p in products %}
|
||||
<tr data-name="{{ p.product_name }}" data-code="{{ p.product_code }}"
|
||||
data-cpcode="{{ p.coupang_item_code }}"
|
||||
data-weight="{{ p.weight_g if p.weight_g is not none else '' }}"
|
||||
class="cpg-prod-row{% if not p.active %} is-inactive{% endif %}">
|
||||
<td title="{{ p.product_name }}">{{ p.product_name }}</td>
|
||||
<td title="{{ p.product_code }}">{{ p.product_code }}</td>
|
||||
<td class="cpg-cpcode" title="{{ p.coupang_item_code }}">{% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}<span class="erp-muted">—</span>{% endif %}</td>
|
||||
{% if weight_enabled %}<td class="cpg-weight-col">{% if p.weight_g is not none %}{{ "{:,}".format(p.weight_g) }}<span class="cpg-weight-unit">g</span>{% else %}<span class="erp-muted">—</span>{% endif %}</td>{% endif %}
|
||||
<td>
|
||||
<!-- 배지 자체가 토글 버튼: 클릭 → 활성/비활성 전환 -->
|
||||
<button type="button" class="erp-badge cpg-active-toggle
|
||||
@@ -92,7 +101,7 @@
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% if not products %}
|
||||
<tr class="cpg-no-sort"><td colspan="5" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
|
||||
<tr class="cpg-no-sort"><td colspan="{{ 6 if weight_enabled else 5 }}" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -117,6 +126,10 @@
|
||||
rows.sort(function (a, b) {
|
||||
var av = a.getAttribute("data-" + state.key) || "";
|
||||
var bv = b.getAttribute("data-" + state.key) || "";
|
||||
if (state.key === "weight") { // 포장무게 — 숫자 크기순, 무게 없는 줄은 늘 맨 뒤
|
||||
if (!av || !bv) return (av ? 0 : 1) - (bv ? 0 : 1);
|
||||
return (Number(av) - Number(bv)) * state.dir;
|
||||
}
|
||||
return collator.compare(av, bv) * state.dir;
|
||||
});
|
||||
rows.forEach(function (r) { tbody.appendChild(r); });
|
||||
@@ -150,6 +163,10 @@
|
||||
<input class="erp-input" type="text" id="cpg-edit-code" /></label>
|
||||
<label class="erp-field"><span>쿠팡상품코드</span>
|
||||
<input class="erp-input" type="text" id="cpg-edit-cpcode" placeholder="비우면 지워집니다" /></label>
|
||||
{% if weight_enabled %}
|
||||
<label class="erp-field"><span>포장무게(g)</span>
|
||||
<input class="erp-input" type="text" id="cpg-edit-weight" inputmode="numeric" autocomplete="off" placeholder="예: 1,070 (비우면 지워집니다)" /></label>
|
||||
{% endif %}
|
||||
<p class="erp-muted" id="cpg-edit-msg" style="margin:0;font-size:12px;"></p>
|
||||
<div class="cpg-dlg-actions erp-page-actions">
|
||||
<button type="button" class="erp-btn erp-btn-outline" data-edit-close>취소</button>
|
||||
@@ -167,6 +184,7 @@
|
||||
var elName = document.getElementById("cpg-edit-name");
|
||||
var elCode = document.getElementById("cpg-edit-code");
|
||||
var elCp = document.getElementById("cpg-edit-cpcode");
|
||||
var elW = document.getElementById("cpg-edit-weight"); // 마이그레이션 007 전이면 없음
|
||||
var elMsg = document.getElementById("cpg-edit-msg");
|
||||
var saveBtn = document.getElementById("cpg-edit-save");
|
||||
var editingId = null;
|
||||
@@ -181,6 +199,10 @@
|
||||
elName.value = row.getAttribute("data-name") || "";
|
||||
elCode.value = row.getAttribute("data-code") || "";
|
||||
elCp.value = row.getAttribute("data-cpcode") || "";
|
||||
if (elW) {
|
||||
var w = row.getAttribute("data-weight") || "";
|
||||
elW.value = w ? Number(w).toLocaleString("ko-KR") : "";
|
||||
}
|
||||
elMsg.textContent = "";
|
||||
dlg.hidden = false;
|
||||
elName.focus();
|
||||
@@ -200,6 +222,12 @@
|
||||
product_code: (elCode.value || "").trim(),
|
||||
coupang_item_code: (elCp.value || "").trim()
|
||||
};
|
||||
if (elW) {
|
||||
// 포장무게 — 쉼표·g 는 서버가 읽는다. 숫자가 아니면 여기서 먼저 막는다(빈 값 = 지움)
|
||||
var wv = (elW.value || "").trim();
|
||||
if (wv && !/^[0-9][0-9,]*\s*g?$/i.test(wv)) { elMsg.textContent = "포장무게는 숫자(g)로 입력하세요. 예: 1,070"; return; }
|
||||
body.weight_g = wv;
|
||||
}
|
||||
if (!body.product_name || !body.product_code) {
|
||||
elMsg.textContent = "제품명과 제품코드는 필수입니다."; return;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
||||
@@ -80,9 +80,10 @@
|
||||
<col class="cpg-boxno-c-name" />
|
||||
<col class="cpg-boxno-c-code" />
|
||||
<col class="cpg-boxno-c-qty" />
|
||||
{% if box_weight %}<col class="cpg-boxno-c-weight" />{% endif %}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th></tr>
|
||||
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th>{% if box_weight %}<th title="상자에 든 제품의 수량 × 포장무게(설정(제품명)) 합계">무게</th>{% endif %}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for b in box_list %}
|
||||
@@ -94,11 +95,21 @@
|
||||
<td title="{{ it.product_name }}">{{ it.product_name }}</td>
|
||||
<td class="cpg-boxno-code">{{ it.product_code }}</td>
|
||||
<td class="cpg-calc-num">{{ it.quantity }}</td>
|
||||
{% if box_weight and loop.first %}
|
||||
{# 상자 무게 합계 — 상자번호처럼 상자 단위로 한 칸. 무게 없는 제품이 있으면 표시 #}
|
||||
{% set miss = b.weight_missing or [] %}
|
||||
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
|
||||
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
|
||||
{%- if b.weight_g is not none -%}
|
||||
{{ "{:,}".format(b.weight_g) }}<span class="cpg-weight-unit">g</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
{% if not box_list %}
|
||||
<tr><td colspan="4" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
||||
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -1,22 +1,604 @@
|
||||
"""토스쇼핑 — 판매자 API.
|
||||
"""토스쇼핑 — 토스쇼핑 API(shopping-fep).
|
||||
|
||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
||||
문서: https://shopping-docs.toss.im/dev (전체 목록 llms.txt, 각 쪽 주소 뒤에 .md 를 붙이면 원문)
|
||||
|
||||
인증(공식 방식): 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > 자체 개발 → [키 발급](호출 IP 입력) →
|
||||
Access Key·Secret Key. OAuth2 client_credentials 로 토큰을 받는다.
|
||||
POST https://oauth2.cert.toss.im/token (form: grant_type=client_credentials, client_id=Access Key,
|
||||
client_secret=Secret Key, scope=toss-shopping-fep:write)
|
||||
응답 expires_in 은 약 1년 — 매번 새로 받으면 이용이 제한될 수 있어(문서 안내) 암호화 저장해 두고 재사용,
|
||||
401 이면 한 번만 새로 받는다. **키 발급 때 넣은 IP(이 서버 외부 IP)에서만 호출된다.**
|
||||
API 는 https://shopping-fep.toss.im, 헤더 Authorization: Bearer {token}. HTTP 200 + resultType FAIL 로 오류를 준다.
|
||||
호출 제한: 셀러·API 별 읽기 초당 50회(넘으면 TOO_MANY_REQUEST).
|
||||
|
||||
매출 = 토스쇼핑 파트너스 "순 거래액" = 매출 − 환불(2026-10-01 사용자 지정, 9/6 화면: 매출 29,600 − 환불 11,900 = 17,700).
|
||||
- 매출 SALE — 주문 내역 조회 GET /api/v3/shopping-fep/orders/v2?startDate=&endDate=&limit=50&nextCursor=
|
||||
(한 번에 31일까지, 상태 생략 = 전체 상태, 커서 페이지). 줄 = 주문상품(orderProductId), 묶음 = 주문(orderId).
|
||||
주문 하나 = 사건 하나(`toss:{orderId}`), 날짜 = 주문 시각(orderedAt, 한국 날짜 — 토스쇼핑은 주문 = 결제),
|
||||
금액 = 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외. 할인(totalDiscountPrice = 토스쇼핑 할인 + 토스페이 할인)은
|
||||
discount_amount 로만 보관. 결제 전(BEFORE_PAYMENT)만 빼고 결제 뒤 취소·반품도 주문일 매출에 둔다(화면 "매출"도 환불 전 금액).
|
||||
- 환불 CANCEL/RETURN — 환불일에 뺀다. 주문상품 하나에 한 번(사건 ID `toss:R{orderProductId}`). `merge_refunds`:
|
||||
① 클레임 목록 GET /api/v3/shopping-fep/claims(날짜 조건이 없어 전체를 넘긴다)의 환불 완료(isRefunded) CANCEL·RETURN —
|
||||
날짜 = refundedDt(한국 날짜). 반품은 이것뿐(주문 내역엔 반품 완료 날짜가 없다).
|
||||
② 클레임이 없는 결제취소 — 주문 내역의 canceledAt(한국 날짜). 결제완료 단계의 고객 취소는 클레임이 생기지 않는다(문서).
|
||||
기간보다 CANCEL_LOOKBACK_DAYS(90)일 앞 주문까지 불러 다른 날 주문을 기간 안에 취소한 것도 잡는다.
|
||||
금액 = 그 주문상품의 price(판매가 × 수량, 매출과 같은 기준), 주문 내역에 없으면(90일보다 오래된 주문) 클레임 order.price.
|
||||
9/6 실데이터: 9/5 주문(276435356)을 9/6 취소 11,900 — 클레임(CANCEL/COMPLETED)·canceledAt 둘 다 9/6 = 화면 환불 11,900.
|
||||
정산 건별(settlement-steps)의 REFUND 는 이 취소를 담지 않아(구매확정 전 취소는 정산에 안 올라옴) 쓰지 않는다.
|
||||
- 설정 화면 "쇼핑몰 원본 데이터 확인"에 날짜별 매출·환불·순 거래액과 환불 출처별(정산·취소 시각·클레임) 비교.
|
||||
- 구매자·수령인 이름·연락처·주소·요청사항은 저장하지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
import re
|
||||
import time
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
TokenExpired,
|
||||
)
|
||||
from .naver import field_summary, flatten
|
||||
|
||||
TOKEN_URL = "https://oauth2.cert.toss.im/token"
|
||||
HOST = "https://shopping-fep.toss.im"
|
||||
ORDERS_PATH = "/api/v3/shopping-fep/orders/v2"
|
||||
SETTLEMENT_PATH = "/api/v3/shopping-fep/settlement-steps"
|
||||
SETTLEMENT_SIZE = 100 # 문서 1~100
|
||||
SCOPE = "toss-shopping-fep:write"
|
||||
EVENT_PREFIX = "toss:"
|
||||
PAGE_SIZE = 50 # 문서 최대 50
|
||||
WINDOW_DAYS = 31 # 한 번에 31일까지
|
||||
MAX_PAGES = 2000 # 한 구간 10만 건 — 무한 반복 방지
|
||||
TOKEN_MARGIN_SEC = 3600 # 만료 1시간 전이면 새로 받는다(토큰은 약 1년)
|
||||
CALL_INTERVAL_SEC = 0.1 # 읽기 초당 50회 제한 — 넉넉히
|
||||
RETRY_429 = 3
|
||||
PROBE_MAX_DAYS = 31
|
||||
KST = timezone(timedelta(hours=9))
|
||||
|
||||
# 결제 전 주문만 매출에서 뺀다. 결제 뒤 취소·반품은 주문일 매출에 두고 원본 확인 표에 참고로 따로 보인다.
|
||||
EXCLUDED_STATUS = frozenset({"BEFORE_PAYMENT"})
|
||||
CLAIMED_STATUS = frozenset({"CANCELED_PAYMENT", "COMPLETED_RETURN"})
|
||||
STATUS_KO = {
|
||||
"BEFORE_PAYMENT": "결제전", "PAID": "결제완료", "PREPARING_PRODUCT": "상품준비중", "DELIVERING": "배송중",
|
||||
"DELIVERED": "배송완료", "CONFIRMED_ORDER": "구매확정", "CLAIM_REQUESTED_CANCEL": "취소요청",
|
||||
"CANCELED_PAYMENT": "결제취소", "CLAIM_REJECTED_CANCEL": "취소거절", "REQUESTED_EXCHANGE": "교환요청",
|
||||
"ONGOING_EXCHANGE": "교환중", "COMPLETED_EXCHANGE": "교환완료", "CLAIM_REJECTED_EXCHANGE": "교환거절",
|
||||
"REQUESTED_RETURN": "반품요청", "ONGOING_RETURN": "반품중", "COMPLETED_RETURN": "반품완료",
|
||||
"CLAIM_REJECTED_RETURN": "반품거절", "CLAIM_COLLECTING": "수거중", "CLAIM_COLLECTED": "수거완료",
|
||||
"CLAIM_DELIVERING": "재배송중",
|
||||
}
|
||||
# 원본 데이터 확인에서 값을 숨기는 항목(개인정보·자유 입력)
|
||||
PERSONAL_KEYS = frozenset({
|
||||
"ordererName", "ordererPhone", "ordererRealPhone", "receiverName", "receiverPhone", "receiverRealPhone",
|
||||
"address", "detailAddress", "zipCode", "shippingNote", "shippingTrackingNumber",
|
||||
# 클레임 목록(order.* · 수거 주소 · 요청 사유 자유 입력 · 첨부 사진)
|
||||
"ordererPhoneNumber", "receiverPhoneNumber", "returnAddress", "requestReason", "requestDetailReason",
|
||||
"requestImages[]",
|
||||
})
|
||||
CLAIMS_PATH = "/api/v3/shopping-fep/claims"
|
||||
CLAIM_PAGE_SIZE = 100
|
||||
CLAIM_MAX_PAGES = 100 # 클레임 목록은 날짜로 못 거른다(전체를 넘긴다) — 1만 건까지
|
||||
CANCEL_LOOKBACK_DAYS = 90 # 환불 후보(주문 취소 시각): 이만큼 전 주문까지 본다
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
try:
|
||||
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def kst_day(value: Any) -> date | None:
|
||||
"""주문 시각 → 한국 날짜. 시간대가 붙어 있으면(Z, +00:00 …) 한국 시간으로 바꾸고, 없으면 한국 시간으로 본다."""
|
||||
s = str(value or "").strip()
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s)
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
dt = dt.astimezone(KST)
|
||||
return dt.date()
|
||||
|
||||
|
||||
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||
"""주문상품 → 주문 하나로 합침(주문일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||
금액 = price(판매가 × 수량) 합(할인 전, 배송비 제외). 할인·배송비·취소/반품분은 참고용으로 모은다.
|
||||
배송비는 묶음(deliveryFeeGroupId)마다 한 번만 센다."""
|
||||
orders: dict[str, dict[str, Any]] = {}
|
||||
ship_groups: set[str] = set()
|
||||
for it in items:
|
||||
oid = str(it.get("orderId") or "")
|
||||
day = kst_day(it.get("orderedAt"))
|
||||
status = str(it.get("orderProductStatus") or "")
|
||||
if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS:
|
||||
continue
|
||||
o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
|
||||
"discount": 0, "names": [], "opt": "", "statuses": []})
|
||||
price = _won(it.get("price"))
|
||||
o["amount"] += price
|
||||
if status in CLAIMED_STATUS:
|
||||
o["claimed"] += price
|
||||
group = str(it.get("deliveryFeeGroupId") or f"{oid}-{it.get('orderProductId')}")
|
||||
if group not in ship_groups:
|
||||
ship_groups.add(group)
|
||||
o["ship"] += _won(it.get("deliveryFee"))
|
||||
o["qty"] += _won(it.get("quantity"))
|
||||
o["discount"] += _won(it.get("totalDiscountPrice"))
|
||||
name = str(it.get("productName") or "")
|
||||
if name and name not in o["names"]:
|
||||
o["names"].append(name)
|
||||
o["opt"] = o["opt"] or str(it.get("optionName") or "")
|
||||
if status and status not in o["statuses"]:
|
||||
o["statuses"].append(status)
|
||||
return orders
|
||||
|
||||
|
||||
def refund_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""정산 건별 목록 → 환불(stepType REFUND) 상품 줄만, 환불일(transactionTs 한국 날짜)이 [start, end] 인 것.
|
||||
금액은 양수로(사건에서 − 를 붙인다). 배송비 줄(orderProductId 없음)은 매출에 배송비를 넣지 않으므로 뺀다."""
|
||||
out = []
|
||||
for it in items:
|
||||
if str(it.get("stepType") or "") != "REFUND" or not it.get("orderProductId") or not it.get("orderId"):
|
||||
continue
|
||||
day = kst_day(it.get("transactionTs"))
|
||||
if day is None or not (start <= day <= end):
|
||||
continue
|
||||
amount = abs(_won(it.get("orderProductPrice"))) or abs(_won(it.get("stockPrice"))) * max(1, _won(it.get("quantity")))
|
||||
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it["orderProductId"]),
|
||||
"_day": day, "_ts": str(it.get("transactionTs") or ""), "amount": amount,
|
||||
"qty": _won(it.get("quantity")), "name": str(it.get("displayProductName") or ""),
|
||||
"order_day": kst_day(it.get("originTransactionTs"))})
|
||||
return out
|
||||
|
||||
|
||||
def cancel_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""환불 후보 — 주문 내역의 취소 시각(canceledAt 한국 날짜)이 [start, end] 인 주문상품. 금액 = price(판매가 × 수량)."""
|
||||
out = []
|
||||
for it in items:
|
||||
day = kst_day(it.get("canceledAt"))
|
||||
if not it.get("orderId") or day is None or not (start <= day <= end):
|
||||
continue
|
||||
status = str(it.get("orderProductStatus") or "")
|
||||
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it.get("orderProductId") or ""), "_day": day,
|
||||
"amount": _won(it.get("price")), "status": status, "note": STATUS_KO.get(status, status),
|
||||
"order_day": kst_day(it.get("orderedAt"))})
|
||||
return out
|
||||
|
||||
|
||||
def claim_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""환불 후보 — 클레임 목록의 환불 완료(isRefunded, refundedDt 한국 날짜)가 [start, end] 인 것.
|
||||
금액 = order.price(문서: "상품 가격" — 수량을 곱한 값인지 실데이터로 확인), 수량은 note 에."""
|
||||
out = []
|
||||
for it in items:
|
||||
day = kst_day(it.get("refundedDt"))
|
||||
order = it.get("order") if isinstance(it.get("order"), dict) else {}
|
||||
product = it.get("product") if isinstance(it.get("product"), dict) else {}
|
||||
if not it.get("isRefunded") or day is None or not (start <= day <= end) or not order.get("id"):
|
||||
continue
|
||||
out.append({"orderId": str(order["id"]), "orderProductId": str(order.get("orderProductId") or ""), "_day": day,
|
||||
"amount": _won(order.get("price")), "note": f"{it.get('type') or '?'}/{it.get('status') or '?'} · "
|
||||
f"수량 {_won(product.get('quantity'))}", "order_day": kst_day(order.get("createdDt"))})
|
||||
return out
|
||||
|
||||
|
||||
def merge_refunds(order_items: Iterable[dict[str, Any]], claims: Iterable[dict[str, Any]],
|
||||
start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""환불 규칙 — 클레임 환불 완료(CANCEL·RETURN, refundedDt) + 클레임이 없는 결제취소(canceledAt), 주문상품마다 한 번.
|
||||
금액은 주문 내역의 price(판매가 × 수량)를 우선(없으면 클레임 order.price). 날짜가 [start, end] 인 것만.
|
||||
클레임이 있는 주문상품은 그 클레임 날짜만 쓴다(기간 밖이어도 취소 시각으로 다시 넣지 않음 — 날짜가 바뀌지 않게)."""
|
||||
order_items = list(order_items)
|
||||
by_op = {str(it.get("orderProductId")): it for it in order_items if it.get("orderProductId")}
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
claimed_ops: set[str] = set()
|
||||
for c in claims:
|
||||
order = c.get("order") if isinstance(c.get("order"), dict) else {}
|
||||
product = c.get("product") if isinstance(c.get("product"), dict) else {}
|
||||
kind = str(c.get("type") or "")
|
||||
op = str(order.get("orderProductId") or "")
|
||||
if not c.get("isRefunded") or kind not in ("CANCEL", "RETURN") or not order.get("id") or not op:
|
||||
continue
|
||||
claimed_ops.add(op)
|
||||
day = kst_day(c.get("refundedDt"))
|
||||
if day is None or not (start <= day <= end) or op in out:
|
||||
continue
|
||||
it = by_op.get(op) or {}
|
||||
out[op] = {"orderId": str(order["id"]), "orderProductId": op, "_day": day, "type": kind,
|
||||
"amount": _won(it["price"]) if "price" in it else _won(order.get("price")),
|
||||
"qty": _won(it.get("quantity")) or _won(product.get("quantity")),
|
||||
"name": str(it.get("productName") or product.get("name") or ""),
|
||||
"order_day": kst_day(it.get("orderedAt") or order.get("createdDt"))}
|
||||
for r in cancel_rows(order_items, start, end):
|
||||
op = r["orderProductId"]
|
||||
if not op or op in claimed_ops or op in out or r["status"] != "CANCELED_PAYMENT":
|
||||
continue
|
||||
it = by_op.get(op) or {}
|
||||
out[op] = {"orderId": r["orderId"], "orderProductId": op, "_day": r["_day"], "type": "CANCEL",
|
||||
"amount": r["amount"], "qty": _won(it.get("quantity")), "name": str(it.get("productName") or ""),
|
||||
"order_day": kst_day(it.get("orderedAt"))}
|
||||
return sorted(out.values(), key=lambda x: (x["_day"], x["orderId"], x["orderProductId"]))
|
||||
|
||||
|
||||
def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값·합계 숨김)."""
|
||||
fields = field_summary([flatten(r) for r in rows])
|
||||
for f in fields:
|
||||
if f["name"].rsplit(".", 1)[-1] in PERSONAL_KEYS:
|
||||
f["personal"], f["sample"], f["sum"] = True, "", None
|
||||
return fields
|
||||
|
||||
|
||||
class TossAdapter(MarketplaceAdapter):
|
||||
code = "toss"
|
||||
name = "토스쇼핑"
|
||||
auth_type = "api_key"
|
||||
note = "입력 항목은 연동 단계에서 토스쇼핑 판매자 API 문서로 확정합니다."
|
||||
auth_type = "oauth"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://shopping-docs.toss.im/dev"
|
||||
note = ("토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발에서 발급한 Access Key·Secret Key 를 입력합니다. "
|
||||
"키 발급 때 이 서버의 외부 IP 를 등록해야 호출됩니다.")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_call = 0.0
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
# 키 이름(api_key·api_secret)은 처음 만든 입력칸 그대로 — 이미 저장한 값이 이어진다.
|
||||
return [
|
||||
CredentialField("seller_id", "판매자 ID"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
CredentialField("api_secret", "API Secret", secret=True, required=False),
|
||||
CredentialField("api_key", "Access Key", secret=True,
|
||||
help="토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발의 Access Key"),
|
||||
CredentialField("api_secret", "Secret Key", secret=True,
|
||||
help="같은 화면의 Secret Key"),
|
||||
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
||||
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
||||
]
|
||||
|
||||
# ── 인증 ──────────────────────────────────────────────
|
||||
def _token(self, ctx: AdapterContext, *, force: bool = False) -> str:
|
||||
"""저장된 토큰이 1시간 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장."""
|
||||
if not force:
|
||||
tok = ctx.credentials.get("access_token")
|
||||
try:
|
||||
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
||||
except ValueError:
|
||||
exp = 0.0
|
||||
if tok and exp - time.time() > TOKEN_MARGIN_SEC:
|
||||
return tok
|
||||
return self._issue_token(ctx)
|
||||
|
||||
def _issue_token(self, ctx: AdapterContext) -> str:
|
||||
import httpx # 지연 import
|
||||
|
||||
access_key = ctx.credentials.get("api_key").strip()
|
||||
secret_key = ctx.credentials.get("api_secret").strip()
|
||||
if not access_key or not secret_key:
|
||||
raise NotConfigured("Access Key 와 Secret Key 를 입력하세요.")
|
||||
form = {"grant_type": "client_credentials", "client_id": access_key, "client_secret": secret_key,
|
||||
"scope": SCOPE}
|
||||
try:
|
||||
res = httpx.post(TOKEN_URL, data=form, timeout=ctx.timeout_sec,
|
||||
headers={"Accept": "application/json; charset=UTF-8"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"토스 인증 서버 연결 실패: {type(exc).__name__}") from None
|
||||
body = self._json(res)
|
||||
if res.status_code >= 400 or not body.get("access_token"):
|
||||
msg = self._err_text(body, res)
|
||||
if res.status_code in (400, 401, 403):
|
||||
raise AuthFailed(f"토스쇼핑 토큰 발급 실패({res.status_code}): {msg}. Access Key·Secret Key 와 "
|
||||
"키 발급 때 등록한 IP(이 서버 외부 IP)를 확인하세요.")
|
||||
raise ApiError(f"토스쇼핑 토큰 발급 오류({res.status_code}): {msg}")
|
||||
tok = str(body["access_token"])
|
||||
expires_in = _won(body.get("expires_in")) or 24 * 3600
|
||||
ctx.credentials.set("access_token", tok)
|
||||
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
||||
return tok
|
||||
|
||||
def authenticate(self, ctx: AdapterContext) -> None:
|
||||
super().authenticate(ctx)
|
||||
self._token(ctx)
|
||||
|
||||
def refresh_token(self, ctx: AdapterContext) -> None:
|
||||
self._token(ctx, force=True)
|
||||
|
||||
# ── 호출 ──────────────────────────────────────────────
|
||||
@staticmethod
|
||||
def _json(res: Any) -> dict[str, Any]:
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
return {}
|
||||
return body if isinstance(body, dict) else {"data": body}
|
||||
|
||||
@staticmethod
|
||||
def _err_text(body: dict[str, Any], res: Any) -> str:
|
||||
err = body.get("error")
|
||||
if isinstance(err, dict):
|
||||
parts = [str(err.get(k)) for k in ("errorCode", "errorType", "reason", "message") if err.get(k)]
|
||||
else:
|
||||
parts = [str(body.get(k)) for k in ("error", "error_description", "code", "message") if body.get(k)]
|
||||
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""GET — 호출 간격 유지, 429·TOO_MANY_REQUEST 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더.
|
||||
성공이면 success 내용을 돌려준다(토스쇼핑은 HTTP 200 + resultType FAIL 로도 오류를 준다)."""
|
||||
import httpx # 지연 import
|
||||
|
||||
retried_auth = False
|
||||
for attempt in range(RETRY_429 + 1):
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
headers = {"Authorization": f"Bearer {self._token(ctx)}", "Accept": "application/json"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"토스쇼핑 API 연결 실패: {type(exc).__name__}") from None
|
||||
finally:
|
||||
self._last_call = time.monotonic()
|
||||
body = self._json(res)
|
||||
err = body.get("error") if isinstance(body.get("error"), dict) else {}
|
||||
limited = res.status_code == 429 or "TOO_MANY" in str(err.get("errorCode") or err.get("errorType") or "")
|
||||
if limited and attempt < RETRY_429:
|
||||
time.sleep(1.0 * (2 ** attempt))
|
||||
continue
|
||||
if res.status_code == 401 and not retried_auth:
|
||||
retried_auth = True
|
||||
self._token(ctx, force=True)
|
||||
continue
|
||||
if res.status_code == 401:
|
||||
raise TokenExpired(f"토스쇼핑 인증 만료·거부(401): {self._err_text(body, res)}")
|
||||
if res.status_code == 403:
|
||||
raise AuthFailed(f"토스쇼핑 권한 거부(403): {self._err_text(body, res)}. 키 발급 때 등록한 IP"
|
||||
"(이 서버 외부 IP)를 확인하세요.")
|
||||
if limited:
|
||||
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"토스쇼핑 API 오류({res.status_code}): {self._err_text(body, res)}")
|
||||
if body.get("resultType") == "FAIL":
|
||||
raise ApiError(f"토스쇼핑 API 오류: {self._err_text(body, res)}")
|
||||
success = body.get("success")
|
||||
return success if isinstance(success, dict) else {}
|
||||
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
|
||||
def _window_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||
"""조회 기간 [a, b](31일 이하)의 주문상품 전체 — 모든 상태, 커서로 끝까지."""
|
||||
params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE}
|
||||
out: list[dict[str, Any]] = []
|
||||
cursor = None
|
||||
for _ in range(MAX_PAGES):
|
||||
body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})})
|
||||
rows = [r for r in body.get("results") or [] if isinstance(r, dict)]
|
||||
out.extend(rows)
|
||||
cursor = body.get("nextCursor")
|
||||
if not cursor or not rows:
|
||||
break
|
||||
return out
|
||||
|
||||
def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||
"""거래일 기준 [a, b](31일 이하)의 정산 건별 줄 전체(결제·환불·배송비), nextToken 으로 끝까지."""
|
||||
params: dict[str, Any] = {"dateCondition": "TRANSACTION_DATE", "fromDate": a.isoformat(),
|
||||
"toDate": b.isoformat(), "size": SETTLEMENT_SIZE}
|
||||
out: list[dict[str, Any]] = []
|
||||
token = None
|
||||
for _ in range(MAX_PAGES):
|
||||
body = self._get(ctx, SETTLEMENT_PATH, {**params, **({"nextToken": token} if token else {})})
|
||||
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||
out.extend(rows)
|
||||
token = body.get("nextToken")
|
||||
if not token or not rows:
|
||||
break
|
||||
return out
|
||||
|
||||
def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||
"""클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지."""
|
||||
out: list[dict[str, Any]] = []
|
||||
token = None
|
||||
for _ in range(CLAIM_MAX_PAGES):
|
||||
body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})})
|
||||
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||
out.extend(rows)
|
||||
token = body.get("nextToken")
|
||||
if not token or not rows or body.get("hasNext") is False:
|
||||
break
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _windows(start: date, end: date) -> list[tuple[date, date]]:
|
||||
windows = []
|
||||
a = start
|
||||
while a <= end:
|
||||
b = min(end, a + timedelta(days=WINDOW_DAYS - 1))
|
||||
windows.append((a, b))
|
||||
a = b + timedelta(days=1)
|
||||
return windows
|
||||
|
||||
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
"""주문 내역(매출) — 31일 구간마다 진행 막대 한 칸(plan 은 부르는 쪽이 주문 + 정산 구간 수로 정한다)."""
|
||||
for a, b in self._windows(start, end):
|
||||
rows = self._window_items(ctx, a, b)
|
||||
ctx.progress.step(items=len(rows))
|
||||
yield from rows
|
||||
|
||||
def _refund_items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
"""정산 건별(환불이 들어 있음) — 31일 구간마다 진행 막대 한 칸."""
|
||||
for a, b in self._windows(start, end):
|
||||
rows = self._settlement_items(ctx, a, b)
|
||||
ctx.progress.step(items=len(rows))
|
||||
yield from rows
|
||||
|
||||
def _lookback_items(self, ctx: AdapterContext, start: date) -> list[dict[str, Any]]:
|
||||
"""기간 앞 CANCEL_LOOKBACK_DAYS 일의 주문상품 — 다른 날 주문을 기간 안에 취소한 것을 찾는 용도."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for a, b in self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)):
|
||||
rows = self._window_items(ctx, a, b)
|
||||
ctx.progress.step(items=len(rows))
|
||||
out.extend(rows)
|
||||
return out
|
||||
|
||||
def _plan(self, ctx: AdapterContext, start: date, end: date, extra: int = 0) -> None:
|
||||
"""진행 막대: 기간 주문 구간 + 앞 90일 주문 구간 + 클레임 목록 1단계 (+ 원본 확인의 정산 구간)."""
|
||||
back = len(self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)))
|
||||
ctx.progress.plan(len(self._windows(start, end)) + back + 1 + extra, "단계")
|
||||
|
||||
def _claims_step(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||
claims = self._claims(ctx)
|
||||
ctx.progress.step(items=len(claims))
|
||||
return claims
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def collect(self, ctx: AdapterContext, start: date, end: date) -> tuple[int, list[SaleEvent]]:
|
||||
"""매출(주문일) + 환불(환불일, merge_refunds). 주문 내역은 환불 금액·취소 시각에도 쓰여 한 번만 부른다."""
|
||||
self.authenticate(ctx)
|
||||
self._plan(ctx, start, end)
|
||||
items = list(self._items(ctx, start, end))
|
||||
back = self._lookback_items(ctx, start)
|
||||
claims = self._claims_step(ctx)
|
||||
events: list[SaleEvent] = []
|
||||
for o in group_orders(items, start, end).values():
|
||||
events.extend(self.normalize_order(o))
|
||||
for r in merge_refunds(back + items, claims, start, end):
|
||||
events.extend(self.normalize_refund(r))
|
||||
for ev in events:
|
||||
ev.validate()
|
||||
return len(items) + len(claims), events
|
||||
|
||||
def normalize_refund(self, r: dict[str, Any]) -> list[SaleEvent]:
|
||||
oid, day = str(r.get("orderId") or ""), r.get("_day")
|
||||
if not oid or day is None or not r.get("orderProductId"):
|
||||
return []
|
||||
kind = "RETURN" if r.get("type") == "RETURN" else "CANCEL"
|
||||
return [SaleEvent(
|
||||
event_type=kind, external_event_id=f"{EVENT_PREFIX}R{r['orderProductId']}", external_order_id=oid,
|
||||
external_line_id=str(r["orderProductId"]), event_date=day, order_date=r.get("order_day"),
|
||||
amount=-abs(int(r.get("amount") or 0)), product_name=str(r.get("name") or "")[:200],
|
||||
quantity=int(r.get("qty") or 0), order_status="반품 환불" if kind == "RETURN" else "취소 환불",
|
||||
)]
|
||||
|
||||
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
|
||||
oid, day = str(o.get("orderId") or ""), o.get("_day")
|
||||
if not oid or day is None:
|
||||
return []
|
||||
names = o.get("names") or []
|
||||
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||
statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []]
|
||||
return [SaleEvent(
|
||||
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid,
|
||||
order_date=day, payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)),
|
||||
product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0),
|
||||
discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50],
|
||||
)]
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
# 입력한 새 값으로 시험할 수 있으니 저장된 토큰을 쓰지 않고 항상 새로 받는다.
|
||||
super().authenticate(ctx)
|
||||
self._token(ctx, force=True)
|
||||
today = today_kst()
|
||||
body = self._get(ctx, ORDERS_PATH, {"startDate": today.isoformat(), "endDate": today.isoformat(), "limit": 1})
|
||||
n = len(body.get("results") or [])
|
||||
more = " 이상" if body.get("nextCursor") else ""
|
||||
return f"토스쇼핑 API 연결 정상(토큰 발급·주문 조회 확인, 오늘 주문상품 {n}건{more})."
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""기간(최대 31일)을 실제로 불러 항목별 합계·상태별 합계와 날짜별 매출·환불·순 거래액(= 저장되는 값)을 돌려준다.
|
||||
환불은 출처별(클레임 환불 완료·주문 취소 시각·정산 REFUND)로도 나란히 보여 파트너스 화면과 맞춰 볼 수 있게.
|
||||
개인정보 항목은 값 없이 이름만. 저장하지 않는다."""
|
||||
self.authenticate(ctx)
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
self._plan(ctx, day, to, extra=len(self._windows(day, to)))
|
||||
try:
|
||||
items = list(self._items(ctx, day, to))
|
||||
back = self._lookback_items(ctx, day)
|
||||
except AdapterError as exc:
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
|
||||
{"key": "orders", "label": "주문 내역", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||
by_status: dict[str, list[dict[str, Any]]] = {}
|
||||
for it in items:
|
||||
by_status.setdefault(str(it.get("orderProductStatus") or "?"), []).append(it)
|
||||
probes = [{"key": "orders", "label": "주문 내역(전체 상태, 주문상품 단위)", "path": ORDERS_PATH,
|
||||
"ok": True, "count": len(items), "fields": summary(items)}]
|
||||
for st, rows in sorted(by_status.items()):
|
||||
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
|
||||
+ (" — 매출 제외(결제 전)" if st in EXCLUDED_STATUS else
|
||||
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""),
|
||||
"path": "orderProductStatus", "ok": True, "count": len(rows),
|
||||
"fields": [f for f in summary(rows) if f["sum"] is not None]})
|
||||
claims_err = ""
|
||||
try:
|
||||
claims = self._claims_step(ctx)
|
||||
probes.append({"key": "claims", "label": "클레임 목록(전체 — 날짜 조건 없음)", "path": CLAIMS_PATH, "ok": True,
|
||||
"count": len(claims), "fields": summary(claims)})
|
||||
except AdapterError as exc:
|
||||
claims, claims_err = [], exc.message[:300]
|
||||
probes.append({"key": "claims", "label": "클레임 목록", "path": CLAIMS_PATH, "ok": False, "error": claims_err})
|
||||
settle_err = ""
|
||||
try:
|
||||
settle = list(self._refund_items(ctx, day, to))
|
||||
probes.append({"key": "settlement", "label": "정산 건별(거래일 기준, 결제·환불·배송비 줄 전체 — 참고)",
|
||||
"path": SETTLEMENT_PATH + " (TRANSACTION_DATE)", "ok": True, "count": len(settle),
|
||||
"fields": summary(settle)})
|
||||
except AdapterError as exc:
|
||||
settle, settle_err = [], exc.message[:300]
|
||||
probes.append({"key": "settlement", "label": "정산 건별(참고)", "path": SETTLEMENT_PATH, "ok": False,
|
||||
"error": settle_err})
|
||||
|
||||
refunds = merge_refunds(back + items, claims, day, to) # 저장되는 환불(현재 규칙)
|
||||
# ── 환불 출처별 — 파트너스 화면 "환불"과 맞춰 보는 용도 ──
|
||||
candidates: list[dict[str, Any]] = [
|
||||
{"key": "rule", "label": "적용 규칙(클레임 환불 + 클레임 없는 결제취소)", "rows": [
|
||||
{**r, "note": "반품" if r["type"] == "RETURN" else "취소"}
|
||||
for r in refunds], "error": claims_err},
|
||||
{"key": "claims", "label": "클레임 환불 완료(refundedDt, 금액 order.price)", "rows": claim_rows(claims, day, to),
|
||||
"error": claims_err},
|
||||
{"key": "canceled", "label": f"주문 취소 시각(canceledAt, {CANCEL_LOOKBACK_DAYS}일 전 주문까지)",
|
||||
"rows": cancel_rows(back + items, day, to), "error": ""},
|
||||
{"key": "settlement", "label": "정산 REFUND 상품 줄(거래일) — 참고", "rows": [
|
||||
{**r, "note": "정산 REFUND"} for r in refund_rows(settle, day, to)],
|
||||
"error": settle_err},
|
||||
]
|
||||
for c in candidates:
|
||||
c["days"] = {}
|
||||
for r in c["rows"]:
|
||||
k = r["_day"].isoformat()
|
||||
c["days"][k] = c["days"].get(k, 0) + r["amount"]
|
||||
c["rows"] = [{"date": r["_day"].isoformat(), "orderDate": r["order_day"].isoformat() if r.get("order_day") else "",
|
||||
"orderId": r["orderId"], "orderProductId": r["orderProductId"],
|
||||
"amount": r["amount"], "note": r.get("note") or ""}
|
||||
for r in sorted(c["rows"], key=lambda x: (x["_day"], x["orderId"]))][:200]
|
||||
|
||||
days = []
|
||||
orders = group_orders(items, day, to)
|
||||
d = day
|
||||
while d <= to:
|
||||
day_orders = [o for o in orders.values() if o["_day"] == d]
|
||||
sales = sum(o["amount"] for o in day_orders)
|
||||
refund = sum(r["amount"] for r in refunds if r["_day"] == d)
|
||||
days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sales, "claimed": refund,
|
||||
"ship": sales - refund})
|
||||
d += timedelta(days=1)
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||
"refund_candidates": candidates,
|
||||
"day_cols": {"amount": "매출(주문일)", "claimed": "환불(환불일)", "ship": "순 거래액(저장되는 매출)"},
|
||||
"rule": "순 거래액 = 매출 − 환불. 매출 = 주문일(orderedAt) 기준 주문상품 price(판매가 × 수량) 합(할인 전, "
|
||||
"배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외). 환불 = 클레임 환불 완료(취소·반품, refundedDt) + "
|
||||
"클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 그 주문상품 price. 환불일 기준"}
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
|
||||
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
|
||||
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
|
||||
- 쇼핑몰별 [중지]: SyncJob.stop_shop(code) → 그 쇼핑몰만 같은 방식(다음 API 호출 직전, 저장 안 함)으로 멈추고 "중지됨",
|
||||
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 저장 중이면 못 멈춘다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,8 +41,17 @@ class ShopProgress(Progress):
|
||||
self.unit = "단계"
|
||||
self.status = self.label = self.message = ""
|
||||
self.started_at = self.finished_at = 0.0
|
||||
self.stop_requested = False # 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def stop(self) -> bool:
|
||||
"""[중지] — 대기·수집 중일 때만(저장 중·끝난 뒤엔 못 멈춤). 받아들였으면 True."""
|
||||
with self._lock:
|
||||
if self.state not in ("waiting", "running"):
|
||||
return False
|
||||
self.stop_requested = True
|
||||
return True
|
||||
|
||||
# ── 어댑터가 부르는 쪽(Progress) ──
|
||||
def plan(self, total: int, unit: str = "단계") -> None:
|
||||
with self._lock:
|
||||
@@ -52,11 +63,18 @@ class ShopProgress(Progress):
|
||||
|
||||
def check(self) -> None:
|
||||
if self.cancel_requested and self.state == "running":
|
||||
raise Cancelled("사용자가 업데이트를 취소했습니다.")
|
||||
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
|
||||
"사용자가 업데이트를 취소했습니다.")
|
||||
|
||||
@property
|
||||
def cancel_requested(self) -> bool:
|
||||
return bool(self.job is not None and self.job.cancel_requested)
|
||||
"""멈춰야 하나 — 업데이트 전체 취소 또는 이 쇼핑몰만 중지."""
|
||||
return self.stop_requested or bool(self.job is not None and self.job.cancel_requested)
|
||||
|
||||
@property
|
||||
def stopped_only(self) -> bool:
|
||||
"""이 쇼핑몰만 중지(전체 취소가 아님) — 업데이트는 다음 쇼핑몰로 계속된다."""
|
||||
return self.stop_requested and not (self.job is not None and self.job.cancel_requested)
|
||||
|
||||
def step(self, n: int = 1, *, items: int = 0) -> None:
|
||||
self.check()
|
||||
@@ -91,7 +109,8 @@ class ShopProgress(Progress):
|
||||
|
||||
def cancelled(self) -> None:
|
||||
with self._lock:
|
||||
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
|
||||
self.state, self.status = "cancelled", "cancelled"
|
||||
self.message = "중지됨" if self.stopped_only else "취소됨"
|
||||
self.finished_at = time.time()
|
||||
|
||||
def skip(self, message: str) -> None:
|
||||
@@ -118,7 +137,7 @@ class ShopProgress(Progress):
|
||||
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
|
||||
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
|
||||
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
|
||||
"fraction": round(self.fraction(), 4),
|
||||
"stop_requested": self.stop_requested, "fraction": round(self.fraction(), 4),
|
||||
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
|
||||
}
|
||||
|
||||
@@ -148,6 +167,14 @@ class SyncJob:
|
||||
if not self.finished_at and not self.cancel_requested:
|
||||
self.cancel_requested, self.cancelled_by = True, user
|
||||
|
||||
def stop_shop(self, code: str) -> bool:
|
||||
"""쇼핑몰별 [중지] — 그 쇼핑몰만 멈추고 다음 쇼핑몰로. 끝난 작업·없는 쇼핑몰·저장 중·끝난 쇼핑몰은 False."""
|
||||
with self._lock:
|
||||
if self.finished_at:
|
||||
return False
|
||||
shop = next((s for s in self.shops if s.code == code), None)
|
||||
return bool(shop is not None and shop.stop())
|
||||
|
||||
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
|
||||
with self._lock:
|
||||
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
|
||||
|
||||
@@ -115,7 +115,8 @@ def dashboard_page(
|
||||
def settings_page(request: Request):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
g = common.guard(request, admin=True)
|
||||
# 모듈 권한자 누구나 들어온다 — 일반 사용자는 수수료율만(쇼핑몰 표의 다른 칸·다른 카드는 템플릿이 관리자에게만 그린다).
|
||||
g = common.guard(request)
|
||||
if not isinstance(g, tuple):
|
||||
return g
|
||||
store, user = g
|
||||
@@ -227,6 +228,25 @@ def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
|
||||
return JSONResponse({"job": job.snapshot()})
|
||||
|
||||
|
||||
@router.post("/api/sync/jobs/{job_id}/shops/{code}/stop")
|
||||
def api_sync_stop_shop(request: Request, job_id: str, code: str) -> JSONResponse:
|
||||
"""쇼핑몰별 [중지] — 시작한 사람 또는 관리자. 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, 기존 매출 그대로)
|
||||
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰은 차례가 오면 건너뛴다. 저장 중·끝난 쇼핑몰은 409."""
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
_, user = common.require_store(request)
|
||||
job = jobs.get_job(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
||||
if job.user and job.user != user["email"] and not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 중지할 수 있습니다.")
|
||||
if not job.stop_shop(code):
|
||||
raise HTTPException(status_code=409, detail="이미 끝났거나 저장 중인 쇼핑몰은 중지할 수 없습니다.")
|
||||
return JSONResponse({"job": job.snapshot()})
|
||||
|
||||
|
||||
@router.get("/api/sync/current")
|
||||
def api_sync_current(request: Request) -> JSONResponse:
|
||||
common.require_store(request)
|
||||
@@ -251,7 +271,7 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 관리자(설정)
|
||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@router.put("/api/marketplaces/{code}")
|
||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
@@ -267,7 +287,7 @@ def api_update_marketplace(request: Request, code: str, payload: dict[str, Any]
|
||||
|
||||
@router.post("/api/marketplaces/{code}/rates")
|
||||
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, user = common.require_store(request, admin=True)
|
||||
store, user = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||
_code_or_404(store, code)
|
||||
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
||||
try:
|
||||
@@ -288,14 +308,14 @@ def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...
|
||||
|
||||
@router.get("/api/marketplaces/{code}/rates")
|
||||
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||
_code_or_404(store, code)
|
||||
return JSONResponse({"rates": store.list_rates(code)})
|
||||
|
||||
|
||||
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
||||
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||
_code_or_404(store, code)
|
||||
if not store.delete_rate(code, rate_id):
|
||||
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
||||
|
||||
@@ -102,9 +102,9 @@ class SyncService:
|
||||
if progress is not None:
|
||||
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
|
||||
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||
if progress is not None and progress.cancel_requested: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
|
||||
if progress is not None and progress.cancel_requested: # [업데이트 취소]·쇼핑몰 [중지] 뒤 차례가 온 쇼핑몰
|
||||
progress.cancelled()
|
||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
||||
return {**result, "cancelled": True, "status": "cancelled", "message": progress.message}
|
||||
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
||||
if run_id is None:
|
||||
if progress is not None:
|
||||
@@ -140,11 +140,13 @@ class SyncService:
|
||||
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
|
||||
"message": f"{upserted}건 반영"}
|
||||
except Cancelled:
|
||||
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
||||
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
|
||||
# 수집 중 취소·중지 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
||||
# 쇼핑몰 [중지]면 이 쇼핑몰만 멈추고 sync_all 이 다음 쇼핑몰로 넘어간다.
|
||||
stopped = progress is not None and progress.stopped_only
|
||||
self._store.finish_run(run_id, ok=False, error="쇼핑몰 중지" if stopped else "업데이트 취소")
|
||||
if progress is not None:
|
||||
progress.cancelled()
|
||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
||||
return {**result, "cancelled": True, "status": "cancelled", "message": "중지됨" if stopped else "취소됨"}
|
||||
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
|
||||
status, message = self._failure(exc, ctx)
|
||||
logger.warning("performance sync %s failed: %s %s", code, status, message)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
|
||||
{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
||||
{% if is_admin %}
|
||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">설정</a>
|
||||
{% endif %}
|
||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">{{ '설정' if is_admin else '수수료 설정' }}</a>
|
||||
</nav>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -239,4 +239,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
<section class="perf perf-settings" id="perf-settings">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
{% if not key_info.ok %}
|
||||
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
|
||||
{% if is_admin and not key_info.ok %}
|
||||
<div class="perf-notice is-warn">
|
||||
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
||||
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
||||
@@ -18,26 +19,31 @@
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">쇼핑몰 설정</h2>
|
||||
{% if is_admin %}
|
||||
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
|
||||
{% else %}
|
||||
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-set-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">쇼핑몰</th>
|
||||
<th>사용</th>
|
||||
<th>매출 집계</th>
|
||||
{% if is_admin %}<th>사용</th>
|
||||
<th>매출 집계</th>{% endif %}
|
||||
<th>수수료율</th>
|
||||
<th>API 설정</th>
|
||||
<th>연결 상태</th>
|
||||
{% if is_admin %}<th>API 설정</th>
|
||||
<th>연결 상태</th>{% endif %}
|
||||
<th>마지막 동기화</th>
|
||||
<th></th>
|
||||
{% if is_admin %}<th></th>{% endif %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
|
||||
<th class="perf-td-label" scope="row">{{ r.name }}</th>
|
||||
{% if is_admin %}
|
||||
<td class="perf-center">
|
||||
<label class="perf-switch" title="사용 여부">
|
||||
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
|
||||
@@ -48,11 +54,13 @@
|
||||
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
||||
</label>
|
||||
</td>
|
||||
{% endif %}
|
||||
<td class="perf-rate-cell">
|
||||
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
|
||||
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
|
||||
</td>
|
||||
{% if is_admin %}
|
||||
<td>
|
||||
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
||||
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
||||
@@ -65,11 +73,14 @@
|
||||
<i></i>{{ r.status_label }}</span>
|
||||
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||
{% if is_admin %}
|
||||
<td class="perf-nowrap">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -77,10 +88,11 @@
|
||||
</div>
|
||||
<p class="perf-foot perf-muted">
|
||||
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
||||
상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
|
||||
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% if is_admin %}
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
||||
@@ -123,12 +135,14 @@
|
||||
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.</p>
|
||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
|
||||
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.</p>
|
||||
<div class="perf-sample-form">
|
||||
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
||||
<option value="naver">네이버 스마트스토어</option>
|
||||
<option value="elevenst">11번가</option>
|
||||
<option value="gsshop">GS샵</option>
|
||||
<option value="toss">토스쇼핑</option>
|
||||
</select>
|
||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
@@ -174,7 +188,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
|
||||
@@ -379,6 +379,279 @@ def test_sync_isolation_redaction_and_dedupe():
|
||||
assert r3["skipped"]
|
||||
|
||||
|
||||
|
||||
def _toss_item(order_id, op_id, ordered_at, price, *, status="PAID", qty=1, dc=0, ship=0, group=None, name="밀폐용기"):
|
||||
"""토스쇼핑 주문 내역 조회 results[] 한 줄(주문상품) — 개인정보 항목 포함(저장 안 되는지 확인용)."""
|
||||
return {"orderId": order_id, "orderProductId": op_id, "orderedAt": ordered_at, "orderProductStatus": status,
|
||||
"productName": name, "optionName": "3개입", "quantity": qty, "price": price, "originPrice": price,
|
||||
"totalDiscountPrice": dc, "tossShoppingDiscount": dc, "tossPayDiscount": 0, "tossPayPoint": 0,
|
||||
"deliveryFee": ship, "deliveryFeeGroupId": group,
|
||||
"ordererName": "홍길동", "ordererPhone": "010-1234-5678", "receiverName": "홍길동",
|
||||
"receiverPhone": "010-1234-5678", "address": "서울시 어딘가", "detailAddress": "101호", "zipCode": "01234",
|
||||
"shippingNote": "문 앞에 두세요 010-9999-8888"}
|
||||
|
||||
|
||||
class _TossCreds(dict):
|
||||
def get(self, k, default=""):
|
||||
return dict.get(self, k, default)
|
||||
|
||||
def has(self, k):
|
||||
return bool(dict.get(self, k))
|
||||
|
||||
def set(self, k, v):
|
||||
self[k] = v
|
||||
|
||||
|
||||
def test_toss_token_and_connection():
|
||||
"""토스쇼핑: Access Key·Secret Key → OAuth2 토큰(form, scope 고정) → Bearer 로 주문 내역 조회.
|
||||
HTTP 200 + resultType FAIL 도 오류, 401 이면 토큰 한 번 새로 받기. 키·토큰은 오류 문구에 없음."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import toss as ts
|
||||
from app.modules.performance.adapters.base import AdapterContext, AdapterError
|
||||
|
||||
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="ACCESS-KEY-1", api_secret="SECRET-KEY-1"))
|
||||
seen = {"posts": [], "gets": []}
|
||||
|
||||
def post(url, data=None, timeout=None, headers=None):
|
||||
seen["posts"].append((url, dict(data)))
|
||||
return httpx.Response(200, json={"access_token": f"TOKEN-{len(seen['posts'])}", "expires_in": 31535999,
|
||||
"token_type": "Bearer", "scope": "toss-shopping-fep:write"})
|
||||
|
||||
def get(url, params=None, headers=None, timeout=None):
|
||||
seen["gets"].append((url, dict(params), headers["Authorization"]))
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {
|
||||
"results": [_toss_item(1, 11, "2026-09-30T10:00:00", 12000)], "nextCursor": "c2"}})
|
||||
|
||||
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
|
||||
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
|
||||
try:
|
||||
msg = ts.TossAdapter().test_connection(ctx)
|
||||
assert "연결 정상" in msg and "1건 이상" in msg
|
||||
url, form = seen["posts"][0]
|
||||
assert url == "https://oauth2.cert.toss.im/token"
|
||||
assert form == {"grant_type": "client_credentials", "client_id": "ACCESS-KEY-1",
|
||||
"client_secret": "SECRET-KEY-1", "scope": "toss-shopping-fep:write"}
|
||||
gurl, params, auth = seen["gets"][0]
|
||||
assert gurl == "https://shopping-fep.toss.im/api/v3/shopping-fep/orders/v2" and auth == "Bearer TOKEN-1"
|
||||
assert params["startDate"] == params["endDate"] and params["limit"] == 1
|
||||
assert ctx.credentials["access_token"] == "TOKEN-1" and int(ctx.credentials["access_token_expires_at"]) > 0
|
||||
# 저장된 토큰은 다시 쓴다(매번 발급하지 않음) — 401 이면 한 번만 새로 받는다
|
||||
n_posts = len(seen["posts"])
|
||||
statuses = iter([401, 200])
|
||||
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||
next(statuses), json={"resultType": "SUCCESS", "success": {"results": [], "nextCursor": None}})
|
||||
assert ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1)) == []
|
||||
assert len(seen["posts"]) == n_posts + 1 and ctx.credentials["access_token"] == f"TOKEN-{n_posts + 1}"
|
||||
# HTTP 200 + resultType FAIL → API 오류
|
||||
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||
200, json={"resultType": "FAIL", "error": {"errorCode": "INVALID_DATE_RANGE", "reason": "조회 기간 초과"}})
|
||||
try:
|
||||
ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1))
|
||||
except AdapterError as exc:
|
||||
assert exc.status == "api_error" and "INVALID_DATE_RANGE" in exc.message
|
||||
else:
|
||||
raise AssertionError("API 오류여야 합니다")
|
||||
# 토큰 발급 거부 → 인증 실패(키는 문구에 없음)
|
||||
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(
|
||||
401, json={"error": "invalid_client", "error_description": "client authentication failed"})
|
||||
try:
|
||||
ts.TossAdapter().test_connection(ctx)
|
||||
except AuthFailed as exc:
|
||||
assert "invalid_client" in exc.message and "SECRET-KEY-1" not in exc.message
|
||||
assert "ACCESS-KEY-1" not in exc.message
|
||||
else:
|
||||
raise AssertionError("인증 실패여야 합니다")
|
||||
# 주문 조회 403(IP 미등록 등) → 인증 실패 + IP 안내, 토큰은 문구에 없음
|
||||
httpx.post = post
|
||||
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||
403, json={"resultType": "FAIL", "error": {"errorCode": "FORBIDDEN", "reason": "허용되지 않은 IP"}})
|
||||
try:
|
||||
ts.TossAdapter().test_connection(ctx)
|
||||
except AuthFailed as exc:
|
||||
assert "허용되지 않은 IP" in exc.message and "TOKEN-" not in exc.message
|
||||
else:
|
||||
raise AssertionError("권한 거부여야 합니다")
|
||||
finally:
|
||||
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||
|
||||
|
||||
def _toss_step(step, order_id, op_id, ts, price, *, qty=1):
|
||||
"""정산 건별 목록 items[] 한 줄 — op_id None = 배송비 줄."""
|
||||
return {"orderId": order_id, "orderProductId": op_id, "transactionTs": ts, "originTransactionTs": "2026-08-31T16:00:00Z",
|
||||
"stepType": step, "orderProductPrice": price, "stockPrice": price // max(1, qty), "quantity": qty,
|
||||
"displayProductName": "밀폐용기", "orderProductStatus": "CANCELED_PAYMENT" if step == "REFUND" else "CONFIRMED_ORDER"}
|
||||
|
||||
|
||||
def _toss_claim(cid, kind, status, order_id, op_id, price, *, refunded=None, created="2026-08-01T10:00:00", qty=1):
|
||||
"""클레임 목록 items[] 한 줄 — refunded = 환불 완료 일시(없으면 미환불). 개인정보·자유 입력 항목 포함."""
|
||||
return {"id": cid, "type": kind, "status": status, "isRefunded": bool(refunded), "refundedDt": refunded,
|
||||
"requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동",
|
||||
"order": {"id": order_id, "orderProductId": op_id, "price": price, "createdDt": created,
|
||||
"ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"},
|
||||
"product": {"id": 3, "name": "밀폐용기", "quantity": qty}}
|
||||
|
||||
|
||||
def test_toss_collect_sales():
|
||||
"""토스쇼핑 매출 = 파트너스 "순 거래액" = 매출 − 환불(9/6 화면: 29,600 − 11,900 = 17,700, 9/5 주문을 9/6 취소).
|
||||
매출 = 주문 단위, 주문일(한국 날짜), 주문상품 price 합(할인 전·배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외).
|
||||
환불 = 클레임 환불 완료(취소·반품, refundedDt) + 클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 주문상품 price.
|
||||
기간 앞 90일 주문까지 불러 다른 날 주문의 환불도 잡는다. 31일 구간 + 커서. 구매자 정보는 저장 안 함."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import toss as ts
|
||||
|
||||
def item(*a, canceled=None, **kw):
|
||||
it = _toss_item(*a, **kw)
|
||||
if canceled:
|
||||
it["canceledAt"] = canceled
|
||||
return it
|
||||
|
||||
pages = {
|
||||
("2026-08-01", None): ([item(1, 11, "2026-08-31T23:30:00+09:00", 20000, qty=2, dc=1000, ship=3000, group=7),
|
||||
item(1, 12, "2026-08-31T23:30:00+09:00", 5000, ship=3000, group=7, name="뚜껑")], "p2"),
|
||||
("2026-08-01", "p2"): ([item(2, 21, "2026-08-31T16:00:00Z", 9900, status="CANCELED_PAYMENT", # 9/1 01:00 KST
|
||||
canceled="2026-08-31T17:30:00Z"), # 9/1 02:30 — 클레임 없음
|
||||
item(3, 31, "2026-08-31T09:00:00", 4000, status="BEFORE_PAYMENT")], None),
|
||||
("2026-09-01", None): ([item(4, 41, "2026-09-01T10:00:00", 15000, status="COMPLETED_RETURN"),
|
||||
item(6, 61, "2026-09-02T10:00:00", 5000, status="CANCELED_PAYMENT",
|
||||
canceled="2026-09-02T11:00:00")], None), # 클레임 환불은 9/5(기간 밖) → 여기선 안 뺌
|
||||
# 기간 앞 90일(5/3~7/31) 조회의 마지막 구간 — 7/15 주문을 8/10 에 취소(클레임 있음)
|
||||
("2026-07-04", None): ([item(5, 51, "2026-07-15T10:00:00", 7000, qty=2, status="CANCELED_PAYMENT",
|
||||
canceled="2026-08-10T09:00:00")], None),
|
||||
}
|
||||
claims = [
|
||||
_toss_claim(1, "RETURN", "COMPLETED", 4, 41, 15000, refunded="2026-09-02T09:00:00"),
|
||||
_toss_claim(2, "CANCEL", "COMPLETED", 5, 51, 3500, refunded="2026-08-10T09:05:00", qty=2), # 금액은 주문 price 7,000
|
||||
_toss_claim(3, "CANCEL", "COMPLETED", 6, 61, 5000, refunded="2026-09-05T10:00:00"), # 기간 밖
|
||||
_toss_claim(4, "CANCEL", "COMPLETED", 8, 81, 4400, refunded="2026-08-15T10:00:00"), # 90일보다 오래된 주문
|
||||
_toss_claim(5, "EXCHANGE", "COMPLETED", 1, 11, 20000, refunded="2026-09-01T10:00:00"), # 교환 → 제외
|
||||
_toss_claim(6, "CANCEL", "REQUESTED", 1, 12, 5000), # 미환불 → 제외
|
||||
]
|
||||
calls, ccalls = [], []
|
||||
|
||||
def get(url, params=None, headers=None, timeout=None):
|
||||
if url.endswith("/claims"):
|
||||
ccalls.append(params.get("nextToken"))
|
||||
page = claims[:3] if not params.get("nextToken") else claims[3:]
|
||||
tok = None if params.get("nextToken") else "c2"
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": page, "nextToken": tok,
|
||||
"hasNext": tok is not None}})
|
||||
assert not url.endswith("/settlement-steps"), "수집은 정산 건별을 부르지 않는다"
|
||||
calls.append((params["startDate"], params["endDate"], params.get("nextCursor")))
|
||||
rows, cur = pages.get((params["startDate"], params.get("nextCursor")), ([], None))
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": cur}})
|
||||
|
||||
def post(url, data=None, timeout=None, headers=None):
|
||||
return httpx.Response(200, json={"access_token": "TOKEN-T", "expires_in": 31535999})
|
||||
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
|
||||
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
|
||||
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
|
||||
try:
|
||||
r = SyncService(st, creds).sync_marketplace("toss", date(2026, 8, 1), date(2026, 9, 2))
|
||||
finally:
|
||||
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||
assert r["ok"], r
|
||||
assert [c for c in calls if c[0] >= "2026-08-01"] == [
|
||||
("2026-08-01", "2026-08-31", None), ("2026-08-01", "2026-08-31", "p2"), ("2026-09-01", "2026-09-02", None)]
|
||||
assert [(a, b) for a, b, _ in calls if a < "2026-08-01"] == [
|
||||
("2026-05-03", "2026-06-02"), ("2026-06-03", "2026-07-03"), ("2026-07-04", "2026-07-31")] # 앞 90일
|
||||
assert ccalls == [None, "c2"] # 클레임 목록 끝까지
|
||||
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "toss"}
|
||||
refunds = {k: v for k, v in ev_.items() if k.startswith("toss:R")}
|
||||
assert set(ev_) - set(refunds) == {"toss:1", "toss:2", "toss:4", "toss:6"} # 결제 전(3)만 제외
|
||||
assert {k: (v["amount"], v["sales_date"], v["event_type"]) for k, v in refunds.items()} == {
|
||||
"toss:R21": (-9900, date(2026, 9, 1), "CANCEL"), # 클레임 없는 결제취소 → canceledAt
|
||||
"toss:R41": (-15000, date(2026, 9, 2), "RETURN"), # 반품 → 클레임 refundedDt
|
||||
"toss:R51": (-7000, date(2026, 8, 10), "CANCEL"), # 앞 90일 주문 — 금액은 주문 price(판매가 × 수량)
|
||||
"toss:R81": (-4400, date(2026, 8, 15), "CANCEL"), # 주문 내역에 없는 오래된 주문 → 클레임 order.price
|
||||
} # R61: 클레임 환불(9/5)이 기간 밖 → canceledAt(9/2)으로 넣지 않음, 교환·미환불 클레임 제외
|
||||
# 환불 사건에도 원래 주문일 — 대시보드 금액 클릭 상세의 "주문일" 열(9/6 화면: 9/5 주문을 9/6 취소)
|
||||
assert {k: v["order_date"] for k, v in refunds.items()} == {
|
||||
"toss:R21": date(2026, 9, 1), "toss:R41": date(2026, 9, 1), "toss:R51": date(2026, 7, 15),
|
||||
"toss:R81": date(2026, 8, 1)}
|
||||
net = {}
|
||||
for v in ev_.values():
|
||||
net[v["sales_date"]] = net.get(v["sales_date"], 0) + v["amount"]
|
||||
assert net == {date(2026, 8, 10): -7000, date(2026, 8, 15): -4400, date(2026, 8, 31): 25000,
|
||||
date(2026, 9, 1): 9900 + 15000 - 9900, date(2026, 9, 2): 5000 - 15000}
|
||||
assert ev_["toss:1"]["amount"] == 25000 and ev_["toss:1"]["discount_amount"] == 1000 # 할인 전·배송비 제외
|
||||
assert ev_["toss:1"]["quantity"] == 3 and ev_["toss:1"]["product_name"] == "밀폐용기 외 1건"
|
||||
assert ev_["toss:1"]["sales_date"] == date(2026, 8, 31)
|
||||
assert ev_["toss:2"]["amount"] == 9900 and ev_["toss:2"]["sales_date"] == date(2026, 9, 1) # UTC → 한국 날짜
|
||||
assert ev_["toss:4"]["amount"] == 15000 and ev_["toss:4"]["order_status"] == "반품완료"
|
||||
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
|
||||
|
||||
|
||||
def test_toss_reconcile_hides_personal():
|
||||
import time as _t
|
||||
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import toss as ts
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
|
||||
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
|
||||
access_token_expires_at=str(int(_t.time()) + 99999)))
|
||||
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
|
||||
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
|
||||
steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)]
|
||||
|
||||
# 다른 날(8/20) 주문을 9/10 에 취소 — 기간 앞(90일) 주문 조회에서만 보인다
|
||||
old = {**_toss_item(7, 71, "2026-08-20T10:00:00", 11900, status="CANCELED_PAYMENT"), "canceledAt": "2026-09-10T09:00:00"}
|
||||
claims = [{"id": 1, "type": "RETURN", "status": "COMPLETED", "isRefunded": True, "refundedDt": "2026-09-10T12:00:00",
|
||||
"requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동",
|
||||
"order": {"id": 8, "orderProductId": 81, "price": 5000, "createdDt": "2026-08-25T10:00:00",
|
||||
"ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"},
|
||||
"product": {"id": 3, "name": "밀폐용기", "quantity": 1}},
|
||||
{"id": 2, "type": "CANCEL", "status": "REQUESTED", "isRefunded": False, "order": {"id": 9, "price": 777}}]
|
||||
|
||||
def get(url, params=None, headers=None, timeout=None):
|
||||
if url.endswith("/settlement-steps"):
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": steps, "nextToken": None}})
|
||||
if url.endswith("/claims"):
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": claims, "nextToken": None,
|
||||
"hasNext": False}})
|
||||
found = rows if params["startDate"] >= "2026-09-09" else [old] if params["startDate"] <= "2026-08-20" <= params["endDate"] else []
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
|
||||
|
||||
orig = (httpx.get, ts.CALL_INTERVAL_SEC)
|
||||
httpx.get, ts.CALL_INTERVAL_SEC = get, 0
|
||||
try:
|
||||
rec = ts.TossAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10))
|
||||
finally:
|
||||
httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||
allp = rec["probes"][0]
|
||||
assert allp["ok"] and allp["count"] == 2
|
||||
f = {x["name"]: x for x in allp["fields"]}
|
||||
assert f["price"]["sum"] == 29900
|
||||
for k in ("ordererName", "ordererPhone", "address", "zipCode", "shippingNote"):
|
||||
assert f[k]["personal"] and f[k]["sample"] == "", k
|
||||
assert not f["productName"]["personal"] and f["productName"]["sample"] == "밀폐용기"
|
||||
assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec) and "010-9999-8888" not in repr(rec)
|
||||
# 날짜별: 매출(주문일) · 환불(환불일, 적용 규칙) · 순 거래액 — 9/10 환불 = 반품 클레임 5,000 + 클레임 없는 결제취소 11,900
|
||||
assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 0, "ship": 29900},
|
||||
{"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 16900, "ship": -16900}]
|
||||
assert rec["day_cols"]["ship"].startswith("순 거래액")
|
||||
labels = [p["label"] for p in rec["probes"]]
|
||||
assert any("결제 뒤 취소·반품(매출 포함)" in x for x in labels) and any("정산 건별" in x for x in labels)
|
||||
# 환불 출처별 — 적용 규칙 · 클레임 · 취소 시각 · 정산(참고), 날짜별 합계 + 건별
|
||||
cand = {c["key"]: c for c in rec["refund_candidates"]}
|
||||
assert rec["refund_candidates"][0]["key"] == "rule" and cand["rule"]["days"] == {"2026-09-10": 16900}
|
||||
assert sorted(x["orderId"] for x in cand["rule"]["rows"]) == ["7", "8"]
|
||||
assert cand["settlement"]["days"] == {"2026-09-10": 9900}
|
||||
assert cand["canceled"]["days"] == {"2026-09-10": 11900} and cand["canceled"]["rows"][0]["orderId"] == "7"
|
||||
assert cand["canceled"]["rows"][0]["orderDate"] == "2026-08-20" # 주문일은 따로 열로(메모 X)
|
||||
assert {x["orderId"]: x["orderDate"] for x in cand["rule"]["rows"]} == {"7": "2026-08-20", "8": "2026-08-25"}
|
||||
assert cand["claims"]["days"] == {"2026-09-10": 5000} and len(cand["claims"]["rows"]) == 1 # 환불 안 된 클레임 제외
|
||||
cf = {x["name"]: x for x in next(p for p in rec["probes"] if p["key"] == "claims")["fields"]}
|
||||
assert cf["requestReason"]["personal"] and cf["returnAddress"]["personal"] and cf["order.ordererPhoneNumber"]["personal"]
|
||||
assert "010-5555-6666" not in repr(rec) and "반품동" not in repr(rec)
|
||||
|
||||
|
||||
def test_not_implemented_and_mock():
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
@@ -1385,6 +1658,68 @@ def test_sync_job_cancel():
|
||||
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
|
||||
|
||||
|
||||
|
||||
def test_sync_job_stop_shop():
|
||||
"""쇼핑몰별 [중지]: 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, "중지됨") 다음 쇼핑몰로 넘어간다.
|
||||
차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 끝난 쇼핑몰·없는 쇼핑몰은 중지 못 함."""
|
||||
import bcrypt
|
||||
import httpx
|
||||
|
||||
from app.modules.performance import jobs
|
||||
from app.modules.performance.adapters import naver as nv
|
||||
from app.modules.performance.adapters import toss as ts
|
||||
|
||||
job = jobs.create_job(user="king@x", start=None, end=None)
|
||||
naver_days = []
|
||||
|
||||
def get(url, params=None, headers=None, timeout=None):
|
||||
if "commerce.naver.com" in url:
|
||||
naver_days.append(params["from"][:10])
|
||||
if len(naver_days) == 1:
|
||||
assert job.stop_shop("gsshop") # 차례가 안 온 GS샵을 미리 중지
|
||||
if len(naver_days) == 2:
|
||||
assert job.stop_shop("naver") # 둘째 날을 받는 도중 네이버 중지
|
||||
rows = [_naver_item("A" + naver_days[-1], "P" + naver_days[-1], naver_days[-1], 10000)]
|
||||
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"hasNext": False}}})
|
||||
if url.endswith("/claims"):
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": [], "nextToken": None}})
|
||||
found = [_toss_item(1, 11, "2026-09-09T10:00:00", 12000)] if params["startDate"] == "2026-09-09" else []
|
||||
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
|
||||
|
||||
def post(url, data=None, timeout=None, headers=None):
|
||||
return httpx.Response(200, json={"access_token": "T", "expires_in": 10799})
|
||||
|
||||
st = FakeStore()
|
||||
st.markets = [m for m in st.markets if m["code"] in ("naver", "gsshop", "toss")]
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(next(a for a in all_adapters() if a.code == "naver"),
|
||||
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
|
||||
creds.save(next(a for a in all_adapters() if a.code == "gsshop"),
|
||||
{"vendor_code": "1047142", "api_key": "0123456789abcdef0123456789ABCDEF"})
|
||||
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
|
||||
st.events[("naver", "SALE", "naver:OLD")] = {"amount": 5000, "is_sample": False, "sales_date": date(2026, 9, 10)}
|
||||
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC)
|
||||
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = post, get, 0, 0
|
||||
try:
|
||||
res = SyncService(st, creds).sync_all(start=date(2026, 9, 9), end=date(2026, 9, 12), user="king@x", job=job)
|
||||
finally:
|
||||
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = orig
|
||||
job.finish()
|
||||
by = {r["code"]: r for r in res}
|
||||
assert naver_days == ["2026-09-09", "2026-09-10"] # 중지 뒤 네이버는 더 부르지 않음
|
||||
assert by["naver"]["cancelled"] and by["naver"]["message"] == "중지됨"
|
||||
assert by["gsshop"]["cancelled"] and by["gsshop"]["message"] == "중지됨" # 미리 중지 → 차례에 건너뜀
|
||||
assert by["toss"]["ok"] and by["toss"]["upserted"] == 1 # 다음 쇼핑몰은 계속
|
||||
assert ("naver", "SALE", "naver:OLD") in st.events and not any(k[0] == "naver" and k[2] != "naver:OLD" for k in st.events)
|
||||
assert ("toss", "SALE", "toss:1") in st.events
|
||||
snap = job.snapshot()
|
||||
shops = {s["code"]: s for s in snap["shops"]}
|
||||
assert shops["naver"]["state"] == "cancelled" and shops["naver"]["message"] == "중지됨" and shops["naver"]["stop_requested"]
|
||||
assert shops["toss"]["state"] == "done" and not snap["cancel_requested"]
|
||||
assert "naver" not in st.status # 연결 상태 안 바뀜
|
||||
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
||||
n = 0
|
||||
|
||||
+786
-26
@@ -13,8 +13,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta
|
||||
from datetime import time as dtime
|
||||
from typing import Any
|
||||
|
||||
@@ -1840,6 +1842,20 @@ class ProjectStore:
|
||||
with self._pool.connection() as conn:
|
||||
return self._table_exists(conn, "goal_years")
|
||||
|
||||
@staticmethod
|
||||
def _goal_quarters(conn: Any) -> bool:
|
||||
"""마이그레이션 017(분기) 적용 여부 — goal_cells 월 칸 CHECK 가 16(4분기)까지 받는가."""
|
||||
row = conn.execute(
|
||||
"SELECT pg_get_constraintdef(c.oid) AS d FROM pg_constraint c "
|
||||
"WHERE c.conname = 'goal_cells_month_check' AND c.conrelid = 'goal_cells'::regclass"
|
||||
).fetchone()
|
||||
return bool(row) and "16" in str(row["d"])
|
||||
|
||||
def goals_halves_enabled(self) -> bool:
|
||||
"""상·하반기 글 칸·월 칸 병합(마이그레이션 014) 적용 여부."""
|
||||
with self._pool.connection() as conn:
|
||||
return self._table_exists(conn, "goal_cell_merges")
|
||||
|
||||
def list_goal_years(self) -> list[int]:
|
||||
"""목표를 만든 연도(최근 연도 먼저). 013 미적용이면 UndefinedTable."""
|
||||
with self._pool.connection() as conn:
|
||||
@@ -1871,25 +1887,35 @@ class ProjectStore:
|
||||
(src["year"],),
|
||||
).fetchall()
|
||||
plan = []
|
||||
groups = self._column_exists(conn, "goal_rows", "label_cont")
|
||||
for a in areas:
|
||||
labels = conn.execute(
|
||||
"SELECT label FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id",
|
||||
"SELECT label" + (", label_cont" if groups else "") + " FROM goal_rows "
|
||||
"WHERE area_id = %s ORDER BY sort_order, id",
|
||||
(a["id"],),
|
||||
).fetchall()
|
||||
plan.append((a["name"], a["color"], tuple(r["label"] for r in labels) or ("",)))
|
||||
plan.append((a["name"], a["color"],
|
||||
tuple((r["label"], bool(r.get("label_cont"))) for r in labels) or (("", False),)))
|
||||
else:
|
||||
plan = list(store.DEFAULT_GOAL_AREAS)
|
||||
plan = [(n, c, tuple((lb, False) for lb in labels)) for n, c, labels in store.DEFAULT_GOAL_AREAS]
|
||||
groups = self._column_exists(conn, "goal_rows", "label_cont")
|
||||
for i, (name, color, labels) in enumerate(plan):
|
||||
aid = conn.execute(
|
||||
"INSERT INTO goal_areas (year, name, color, sort_order) "
|
||||
"VALUES (%s, %s, %s, %s) RETURNING id",
|
||||
(y, name, color, i),
|
||||
).fetchone()["id"]
|
||||
for j, label in enumerate(labels):
|
||||
conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)",
|
||||
(aid, label, j),
|
||||
)
|
||||
for j, (label, cont) in enumerate(labels):
|
||||
if groups:
|
||||
conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, %s, %s)",
|
||||
(aid, label, cont and j > 0, j),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)",
|
||||
(aid, label, j),
|
||||
)
|
||||
|
||||
def delete_goal_year(self, *, year: int) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
@@ -1913,7 +1939,11 @@ class ProjectStore:
|
||||
"""한 해 목표 표 전체. 연도가 없으면 None.
|
||||
|
||||
metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}}
|
||||
areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", ...}}]}]
|
||||
areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", 13: "상반기 글", ...},
|
||||
merges: {시작 칸: (가로 칸 수, 세로 줄 수)}}]}]
|
||||
halves = 마이그레이션 014 적용 여부(기간 글 칸·병합 — 이름은 예전 그대로, 지금은 분기 칸)
|
||||
quarters = 마이그레이션 017 적용 여부(2·4분기 칸 15·16 저장)
|
||||
rect = 마이그레이션 015 적용 여부(세로 병합·연간/반기 칸 병합·주간 회의록)
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
head = conn.execute(
|
||||
@@ -1928,8 +1958,9 @@ class ProjectStore:
|
||||
"SELECT id, name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id",
|
||||
(year,),
|
||||
).fetchall()
|
||||
groups = self._column_exists(conn, "goal_rows", "label_cont")
|
||||
row_rows = conn.execute(
|
||||
"SELECT r.id, r.area_id, r.label FROM goal_rows r "
|
||||
"SELECT r.id, r.area_id, r.label" + (", r.label_cont" if groups else "") + " FROM goal_rows r "
|
||||
"JOIN goal_areas a ON a.id = r.area_id WHERE a.year = %s "
|
||||
"ORDER BY r.sort_order, r.id",
|
||||
(year,),
|
||||
@@ -1940,6 +1971,15 @@ class ProjectStore:
|
||||
"WHERE a.year = %s",
|
||||
(year,),
|
||||
).fetchall()
|
||||
halves = self._table_exists(conn, "goal_cell_merges")
|
||||
rect = halves and self._column_exists(conn, "goal_cell_merges", "row_span")
|
||||
quarters = halves and self._goal_quarters(conn)
|
||||
merge_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 JOIN goal_areas a ON a.id = r.area_id "
|
||||
"WHERE a.year = %s",
|
||||
(year,),
|
||||
).fetchall() if halves else []
|
||||
metrics: dict[str, dict[str, dict[int, float]]] = {
|
||||
m: {k: {} for k in store.GOAL_KINDS} for m in store.GOAL_METRICS
|
||||
}
|
||||
@@ -1948,10 +1988,16 @@ class ProjectStore:
|
||||
cells: dict[int, dict[int, str]] = {}
|
||||
for c in cell_rows:
|
||||
cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"]
|
||||
merges: dict[int, dict[int, tuple[int, int]]] = {}
|
||||
for g in merge_rows:
|
||||
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]]] = {}
|
||||
for r in row_rows:
|
||||
rid = int(r["id"])
|
||||
rows_by_area.setdefault(int(r["area_id"]), []).append(
|
||||
{"id": int(r["id"]), "label": r["label"], "cells": cells.get(int(r["id"]), {})}
|
||||
{"id": rid, "label": r["label"], "cells": cells.get(rid, {}),
|
||||
"merges": merges.get(rid, {}), "label_cont": bool(r.get("label_cont"))}
|
||||
)
|
||||
areas = [
|
||||
{"id": int(a["id"]), "name": a["name"], "color": a["color"],
|
||||
@@ -1959,7 +2005,8 @@ class ProjectStore:
|
||||
for a in area_rows
|
||||
]
|
||||
return {"year": int(head["year"]), "sales_unit": head["sales_unit"],
|
||||
"metrics": metrics, "areas": areas}
|
||||
"metrics": metrics, "areas": areas, "halves": halves, "rect": rect, "groups": groups,
|
||||
"quarters": quarters}
|
||||
|
||||
def set_goal_metric(
|
||||
self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = ""
|
||||
@@ -2050,20 +2097,103 @@ class ProjectStore:
|
||||
self._move_goal_item("goal_areas", "year", area_id, direction)
|
||||
|
||||
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("세로로 병합된 칸에 걸린 줄은 옮길 수 없습니다. 병합을 해제한 뒤 옮기세요.")
|
||||
if 0 <= j < len(ids):
|
||||
conts = self._label_conts(int(me["area_id"]), ids)
|
||||
in_group = lambda k: conts[k] or (k + 1 < len(ids) and conts[k + 1]) # noqa: E731
|
||||
if in_group(i) or in_group(j):
|
||||
raise ValueError("같은 항목 칸으로 묶인 줄은 옮길 수 없습니다. 항목 칸을 나눈 뒤 옮기세요.")
|
||||
self._move_goal_item("goal_rows", "area_id", row_id, direction)
|
||||
|
||||
def add_goal_row(self, *, area_id: int, label: str = "") -> int:
|
||||
lb = store.validate_goal_row_label(label)
|
||||
def _label_conts(self, area_id: int, ids: list[int]) -> list[bool]:
|
||||
"""영역 줄 순서(ids)대로 label_cont — 016 미적용이면 모두 False."""
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s", (area_id,)).fetchone():
|
||||
raise KeyError(area_id)
|
||||
rid = conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, "
|
||||
"(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_rows WHERE area_id = %s)) "
|
||||
"RETURNING id",
|
||||
(area_id, lb, area_id),
|
||||
).fetchone()["id"]
|
||||
return int(rid)
|
||||
if not self._column_exists(conn, "goal_rows", "label_cont"):
|
||||
return [False] * len(ids)
|
||||
got = {int(r["id"]): bool(r["label_cont"]) for r in conn.execute(
|
||||
"SELECT id, label_cont FROM goal_rows WHERE area_id = %s", (area_id,)).fetchall()}
|
||||
return [got.get(i, False) for i in ids]
|
||||
|
||||
def add_goal_row(
|
||||
self, *, area_id: int, label: str = "", ref_row_id: int | None = None, place: str = "below",
|
||||
same_label: bool = False,
|
||||
) -> int:
|
||||
"""줄 추가 — 기준 줄(ref_row_id)이 있으면 그 줄 위(place="above")/아래("below")에, 없으면 영역 맨 끝에.
|
||||
|
||||
same_label(3열에서 추가, 016) = 새 줄을 기준 줄과 **같은 항목 칸(2열)** 안에 넣는다: 아래면 새 줄이 묶음에 이어 붙고
|
||||
(label_cont), 위면 — 기준 줄이 묶음 첫 줄이면 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙는다."""
|
||||
lb = store.validate_goal_row_label(label)
|
||||
if place not in ("above", "below"):
|
||||
raise ValueError("place 는 above 또는 below 입니다.")
|
||||
if same_label and ref_row_id is None:
|
||||
raise ValueError("같은 항목 칸에 추가하려면 기준 줄이 필요합니다.")
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
if not conn.execute(
|
||||
"SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,)
|
||||
).fetchone():
|
||||
raise KeyError(area_id)
|
||||
if ref_row_id is None:
|
||||
rid = conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, "
|
||||
"(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_rows WHERE area_id = %s)) "
|
||||
"RETURNING id",
|
||||
(area_id, lb, area_id),
|
||||
).fetchone()["id"]
|
||||
return int(rid)
|
||||
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 ref_row_id not in ids:
|
||||
raise KeyError(ref_row_id)
|
||||
if same_label:
|
||||
if not self._column_exists(conn, "goal_rows", "label_cont"):
|
||||
raise store.GoalMigration016Needed()
|
||||
ref = conn.execute("SELECT label, label_cont FROM goal_rows WHERE id = %s", (ref_row_id,)).fetchone()
|
||||
if place == "above" and not ref["label_cont"]:
|
||||
# 묶음 첫 줄 위 — 새 줄이 첫 줄(이름을 넘겨받음), 기준 줄은 이어 붙는다
|
||||
rid = int(conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, false, 0) "
|
||||
"RETURNING id", (area_id, ref["label"]),
|
||||
).fetchone()["id"])
|
||||
conn.execute("UPDATE goal_rows SET label = '', label_cont = true WHERE id = %s", (ref_row_id,))
|
||||
else:
|
||||
rid = int(conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, '', true, 0) "
|
||||
"RETURNING id", (area_id,),
|
||||
).fetchone()["id"])
|
||||
else:
|
||||
rid = int(conn.execute(
|
||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, 0) RETURNING id",
|
||||
(area_id, lb),
|
||||
).fetchone()["id"])
|
||||
i = ids.index(ref_row_id) + (1 if place == "below" else 0)
|
||||
# 따로 추가(2열 메뉴·+)는 화면이 묶음의 맨 위(위에)·맨 아래(아래) 줄을 기준으로 보내 묶음 밖에 들어간다
|
||||
# 세로 병합 안쪽(시작 줄 아래 ~ 마지막 줄)에 끼우면 엑셀처럼 그 병합이 한 줄 늘어난다
|
||||
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)
|
||||
for n, x in enumerate(ids):
|
||||
conn.execute("UPDATE goal_rows SET sort_order = %s WHERE id = %s", (n, x))
|
||||
return rid
|
||||
|
||||
def update_goal_row(self, *, row_id: int, label: str) -> None:
|
||||
lb = store.validate_goal_row_label(label)
|
||||
@@ -2086,14 +2216,84 @@ class ProjectStore:
|
||||
).fetchone()["n"]
|
||||
if n <= 1:
|
||||
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"]),
|
||||
)
|
||||
if self._column_exists(conn, "goal_rows", "label_cont"):
|
||||
# 묶음 첫 줄을 지우면 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름을 넘겨받는다(비어 있으면)
|
||||
me2 = conn.execute("SELECT label, label_cont, sort_order FROM goal_rows WHERE id = %s",
|
||||
(row_id,)).fetchone()
|
||||
if not me2["label_cont"]:
|
||||
nxt = conn.execute(
|
||||
"SELECT id, label, label_cont FROM goal_rows WHERE area_id = %s AND id <> %s "
|
||||
"AND (sort_order, id) > (%s, %s) ORDER BY sort_order, id LIMIT 1",
|
||||
(me["area_id"], row_id, me2["sort_order"], row_id),
|
||||
).fetchone()
|
||||
if nxt and nxt["label_cont"]:
|
||||
conn.execute(
|
||||
"UPDATE goal_rows SET label_cont = false, label = CASE WHEN label = '' THEN %s ELSE label END "
|
||||
"WHERE id = %s", (me2["label"], nxt["id"]),
|
||||
)
|
||||
conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,))
|
||||
|
||||
def split_goal_label(self, *, row_id: int) -> int:
|
||||
"""항목 칸 나누기 — row_id(묶음 첫 줄) 아래 이어 붙은 줄들을 각자 항목 칸으로(이름은 빈 칸). 나눈 줄 수."""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
if not self._column_exists(conn, "goal_rows", "label_cont"):
|
||||
raise store.GoalMigration016Needed()
|
||||
me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s FOR UPDATE", (row_id,)).fetchone()
|
||||
if me is None:
|
||||
raise KeyError(row_id)
|
||||
rows = conn.execute(
|
||||
"SELECT id, label_cont FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (me["area_id"],)
|
||||
).fetchall()
|
||||
ids = [int(r["id"]) for r in rows]
|
||||
n = 0
|
||||
for r in rows[ids.index(row_id) + 1:]:
|
||||
if not r["label_cont"]:
|
||||
break
|
||||
conn.execute("UPDATE goal_rows SET label_cont = false WHERE id = %s", (r["id"],))
|
||||
n += 1
|
||||
return n
|
||||
|
||||
def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None:
|
||||
m = store.validate_goal_month(month, allow_year=True)
|
||||
text = store.validate_goal_text(body)
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone():
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
# 빈 대상 칸을 포함해 일반 저장·이동·병합이 같은 영역 잠금으로 직렬화된다.
|
||||
area = conn.execute(
|
||||
"SELECT a.id AS area_id FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id "
|
||||
"WHERE r.id = %s FOR UPDATE OF a", (row_id,),
|
||||
).fetchone()
|
||||
if not area:
|
||||
raise KeyError(row_id)
|
||||
halves = self._table_exists(conn, "goal_cell_merges")
|
||||
if m > 12 and not halves:
|
||||
raise store.GoalMigration014Needed()
|
||||
if m in store.GOAL_Q_NEW and not self._goal_quarters(conn):
|
||||
raise store.GoalMigration017Needed()
|
||||
if halves:
|
||||
# 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장
|
||||
area_id = area["area_id"]
|
||||
ids, merges, _ = self._area_geometry(conn, int(area_id))
|
||||
if self._covered_by(merges, ids.index(row_id), store.GOAL_COL_ORDER.index(m)):
|
||||
raise ValueError("병합된 칸입니다. 새로고침해 주세요.")
|
||||
if not text:
|
||||
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m))
|
||||
else:
|
||||
@@ -2104,6 +2304,566 @@ class ProjectStore:
|
||||
(row_id, m, text, store.norm_str(updated_by, lower=True)),
|
||||
)
|
||||
|
||||
def move_goal_cell(
|
||||
self, *, source_row: Any, source_month: Any, target_row: Any, target_month: Any,
|
||||
source_body: str, target_body: str, body: str, updated_by: str = "",
|
||||
) -> str:
|
||||
"""같은 연도 안에서 셀의 내용·서식을 이동한다. 두 값의 비교와 이동은 한 트랜잭션.
|
||||
|
||||
병합 시작 칸끼리도 내용만 이동하며 병합 배치·영역 색·열 너비는 유지한다.
|
||||
응답만 유실된 요청을 다시 보내면 이미 같은 이동이 완료된 상태는 성공으로 돌려준다.
|
||||
"""
|
||||
try:
|
||||
sr, tr = int(source_row), int(target_row)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("이동할 셀이 올바르지 않습니다.")
|
||||
sm = store.validate_goal_month(source_month, allow_year=True)
|
||||
tm = store.validate_goal_month(target_month, allow_year=True)
|
||||
if sr <= 0 or tr <= 0 or (sr, sm) == (tr, tm):
|
||||
raise ValueError("서로 다른 두 셀을 골라 주세요.")
|
||||
expected_source, expected_target = store.validate_goal_text(source_body), store.validate_goal_text(target_body)
|
||||
moved = store.validate_goal_text(body)
|
||||
if not expected_source or not moved or store.goal_text_plain(moved).strip() != store.goal_text_plain(expected_source).strip():
|
||||
raise ValueError("원본 내용과 이동할 내용이 일치하지 않습니다.")
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
rows = conn.execute(
|
||||
"SELECT r.id, r.area_id, a.year FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id "
|
||||
"WHERE r.id = ANY(%s)", ([sr, tr],),
|
||||
).fetchall()
|
||||
by_id = {int(r["id"]): r for r in rows}
|
||||
if sr not in by_id or tr not in by_id:
|
||||
raise KeyError(sr if sr not in by_id else tr)
|
||||
if by_id[sr]["year"] != by_id[tr]["year"]:
|
||||
raise ValueError("같은 연도의 셀로만 이동할 수 있습니다.")
|
||||
areas = sorted({int(r["area_id"]) for r in rows})
|
||||
# 교차 영역 이동도 같은 순서로 잠가 교착을 피하고, 행 삭제도 함께 차단한다.
|
||||
conn.execute("SELECT id FROM goal_areas WHERE id = ANY(%s) ORDER BY id FOR UPDATE", (areas,)).fetchall()
|
||||
locked = conn.execute(
|
||||
"SELECT id, area_id FROM goal_rows WHERE id = ANY(%s) ORDER BY id FOR UPDATE", ([sr, tr],),
|
||||
).fetchall()
|
||||
if len(locked) != len(by_id):
|
||||
raise KeyError("이동할 줄이 삭제되었습니다.")
|
||||
halves = self._table_exists(conn, "goal_cell_merges")
|
||||
if (sm > 12 or tm > 12) and not halves:
|
||||
raise store.GoalMigration014Needed()
|
||||
if (sm in store.GOAL_Q_NEW or tm in store.GOAL_Q_NEW) and not self._goal_quarters(conn):
|
||||
raise store.GoalMigration017Needed()
|
||||
geometry = {a: self._area_geometry(conn, a) for a in areas} if halves else {}
|
||||
for rid, month in ((sr, sm), (tr, tm)):
|
||||
if halves:
|
||||
ids, merges, _ = geometry[int(by_id[rid]["area_id"])]
|
||||
if rid not in ids or self._covered_by(merges, ids.index(rid), store.GOAL_COL_ORDER.index(month)):
|
||||
raise store.GoalCellConflict("병합 배치가 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.")
|
||||
cells = conn.execute(
|
||||
"SELECT row_id, month, body FROM goal_cells "
|
||||
"WHERE (row_id = %s AND month = %s) OR (row_id = %s AND month = %s) FOR UPDATE",
|
||||
(sr, sm, tr, tm),
|
||||
).fetchall()
|
||||
values = {(int(c["row_id"]), int(c["month"])): store.validate_goal_text(c["body"]) for c in cells}
|
||||
source, target = values.get((sr, sm), ""), values.get((tr, tm), "")
|
||||
if not source and target == moved:
|
||||
return moved
|
||||
if source != expected_source or target != expected_target:
|
||||
raise store.GoalCellConflict("원본 또는 대상 내용이 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.")
|
||||
conn.execute(
|
||||
"INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s) "
|
||||
"ON CONFLICT (row_id, month) DO UPDATE "
|
||||
"SET body = EXCLUDED.body, updated_by = EXCLUDED.updated_by, updated_at = now()",
|
||||
(tr, tm, moved, store.norm_str(updated_by, lower=True)),
|
||||
)
|
||||
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (sr, sm))
|
||||
return moved
|
||||
|
||||
# ── 엑셀식 사각형 병합 ─────────────────────────────────────────
|
||||
@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) 가능 여부).
|
||||
병합 = {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~3월·1분기·…·10~12월·4분기) — 가로는 같은 분기 월 칸끼리만.
|
||||
걸친 기존 병합은 통째로 흡수(엑셀이 선택을 넓히듯). 글은 범위 안 칸들의 글을 왼쪽 위부터 줄·칸 순서대로
|
||||
줄바꿈으로 이어 왼쪽 위 칸에 두고, 나머지 칸 글은 지운다(글을 잃지 않게)."""
|
||||
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 conn.transaction():
|
||||
if not self._table_exists(conn, "goal_cell_merges"):
|
||||
raise store.GoalMigration014Needed()
|
||||
if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,)).fetchone():
|
||||
raise KeyError(area_id)
|
||||
ids, merges, rect = self._area_geometry(conn, area_id)
|
||||
if rf not in ids or rt not in ids:
|
||||
raise KeyError(rf if rf not in ids else rt)
|
||||
r0, r1 = sorted((ids.index(rf), ids.index(rt)))
|
||||
c0, c1 = sorted((store.GOAL_COL_ORDER.index(int(col_from)), store.GOAL_COL_ORDER.index(int(col_to))))
|
||||
grown = True
|
||||
while grown: # 걸친 병합을 통째로 품을 때까지 넓힌다
|
||||
grown = False
|
||||
for g in merges:
|
||||
if g["r0"] <= r1 and g["r1"] >= r0 and g["c0"] <= c1 and g["c1"] >= c0:
|
||||
n = (min(r0, g["r0"]), max(r1, g["r1"]), min(c0, g["c0"]), max(c1, g["c1"]))
|
||||
if n != (r0, r1, c0, c1):
|
||||
r0, r1, c0, c1 = n
|
||||
grown = True
|
||||
start, span = store.validate_goal_rect_cols(store.GOAL_COL_ORDER[c0], store.GOAL_COL_ORDER[c1])
|
||||
row_span = r1 - r0 + 1
|
||||
if span * row_span < 2:
|
||||
raise ValueError("두 칸 이상 골라야 병합할 수 있습니다.")
|
||||
if (row_span > 1 or start == store.GOAL_YEAR or start in store.GOAL_COL_QUARTER) and not rect:
|
||||
raise store.GoalMigration015Needed()
|
||||
if start in store.GOAL_Q_NEW and not self._goal_quarters(conn):
|
||||
raise store.GoalMigration017Needed()
|
||||
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.merge_goal_texts([
|
||||
bodies[(r, m)] for r in rows_in for m in cols_in if bodies.get((r, m))
|
||||
])
|
||||
conn.execute(
|
||||
"DELETE FROM goal_cell_merges WHERE row_id = ANY(%s) AND start_month = ANY(%s)",
|
||||
(rows_in, cols_in),
|
||||
)
|
||||
conn.execute(
|
||||
"DELETE FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)", (rows_in, cols_in),
|
||||
)
|
||||
anchor = rows_in[0]
|
||||
if text:
|
||||
conn.execute(
|
||||
"INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s)",
|
||||
(anchor, start, text, who),
|
||||
)
|
||||
if rect:
|
||||
conn.execute(
|
||||
"INSERT INTO goal_cell_merges (row_id, start_month, span, row_span, updated_by) "
|
||||
"VALUES (%s, %s, %s, %s, %s)",
|
||||
(anchor, start, span, row_span, who),
|
||||
)
|
||||
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:
|
||||
"""병합 해제 — 글은 시작 월 칸에 그대로 남는다."""
|
||||
with self._pool.connection() as conn:
|
||||
if not self._table_exists(conn, "goal_cell_merges"):
|
||||
raise store.GoalMigration014Needed()
|
||||
row = conn.execute(
|
||||
"DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s RETURNING row_id",
|
||||
(row_id, start),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
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()
|
||||
|
||||
def _meeting_keys(self, conn: Any) -> bool:
|
||||
"""마이그레이션 018 — goal_meeting_items.line_key(주가 바뀌어도 같은 줄을 가리키는 연결키) 적용 여부.
|
||||
적용되면 한 번만 확인한다(되돌리는 마이그레이션은 없다)."""
|
||||
if getattr(self, "_meeting_keys_ok", False):
|
||||
return True
|
||||
ok = self._column_exists(conn, "goal_meeting_items", "line_key")
|
||||
if ok:
|
||||
self._meeting_keys_ok = True
|
||||
return ok
|
||||
|
||||
def _meeting_cols(self, conn: Any) -> str:
|
||||
return self._MEETING_ITEM_COLS + (", line_key" if self._meeting_keys(conn) else "")
|
||||
|
||||
@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
|
||||
if out.get("line_key") is not None:
|
||||
out["line_key"] = str(out["line_key"])
|
||||
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.
|
||||
|
||||
"지난주"는 **정확히 7일 전 주(week_start − 7)** 만이다(몇 주 전 회의록을 지난주로 보이지 않게).
|
||||
· prev_meeting = 그 주 회의록 머리(전주 목표), 그 주 회의록이 없으면 None.
|
||||
· 줄의 prev = 그 주 회의록에서 **같은 연결키(line_key, 마이그레이션 018)** 의 줄 — 생성 순서·이름 변경·
|
||||
순서 이동과 무관하다. 018 미적용이면 예전 carry_from 을 쓰되 가리키는 줄이 정확히 7일 전 주일 때만.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
self._require_meetings(conn)
|
||||
cols = self._meeting_cols(conn)
|
||||
keyed = self._meeting_keys(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
|
||||
prev_week = week_start - timedelta(days=7)
|
||||
items = conn.execute(
|
||||
f"SELECT {cols} FROM goal_meeting_items WHERE week_start = %s "
|
||||
"ORDER BY sort_order, id", (week_start,),
|
||||
).fetchall()
|
||||
prev_head = conn.execute(
|
||||
"SELECT week_start, week_target FROM goal_meetings WHERE week_start = %s", (prev_week,),
|
||||
).fetchone()
|
||||
prev_rows = conn.execute(
|
||||
f"SELECT {cols} FROM goal_meeting_items WHERE week_start = %s", (prev_week,),
|
||||
).fetchall() if prev_head else []
|
||||
by_key = {str(r["line_key"]): r for r in prev_rows if r.get("line_key") is not None} if keyed else {}
|
||||
by_id = {int(r["id"]): r for r in prev_rows}
|
||||
out_items = []
|
||||
for r in items:
|
||||
it = self._meeting_item(r)
|
||||
if keyed:
|
||||
p = by_key.get(it.get("line_key") or "")
|
||||
else:
|
||||
p = by_id.get(it["carry_from"]) if it["carry_from"] is not None else None
|
||||
it["prev"] = self._meeting_item(p) if p 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,
|
||||
"line_keys": keyed,
|
||||
}
|
||||
|
||||
def create_meeting(self, *, week_start: date, sections: list[tuple[str, str]], created_by: str = "") -> bool:
|
||||
"""회의록 만들기 — 이미 있으면 False. 줄(구역·이름·색·쇼핑몰 연결·순서)을 글 없이 이어받을 원본:
|
||||
① 앞선 가장 가까운 회의록(평소 순서), ② 앞선 회의록이 없으면 뒤에 있는 가장 가까운 회의록
|
||||
(다음 주를 먼저 만들고 앞 주를 나중에 만든 경우 — 다음 주 줄이 이 주 줄을 "지난주"로 찾게),
|
||||
③ 둘 다 없으면 sections(목표 표 업무 영역 이름·색)마다 기본 양식 줄(store.MEETING_TEMPLATE).
|
||||
이어받은 줄은 원본 줄의 연결키(line_key, 018)를 그대로 갖는다 → 생성 순서와 무관하게 7일 전 주의 같은 키 줄이
|
||||
"지난주"가 된다. 새 줄(양식·줄 추가)은 새 키. carry_from 은 앞선 원본 줄일 때만 기록(이력, 화면 연결에는 안 씀)."""
|
||||
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)
|
||||
keyed = self._meeting_keys(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
|
||||
src_cols = "id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "")
|
||||
src_items: list[dict[str, Any]] = []
|
||||
src_is_prev = True
|
||||
for cmp_, order, is_prev in (("<", "DESC", True), (">", "ASC", False)):
|
||||
# 줄이 하나라도 있는 가장 가까운 회의록(빈 회의록은 건너뜀)
|
||||
src = conn.execute(
|
||||
f"SELECT m.week_start FROM goal_meetings m WHERE m.week_start {cmp_} %s "
|
||||
"AND EXISTS (SELECT 1 FROM goal_meeting_items i WHERE i.week_start = m.week_start) "
|
||||
f"ORDER BY m.week_start {order} LIMIT 1",
|
||||
(ws,),
|
||||
).fetchone()
|
||||
if src:
|
||||
src_items = conn.execute(
|
||||
f"SELECT {src_cols} FROM goal_meeting_items WHERE week_start = %s ORDER BY sort_order, id",
|
||||
(src["week_start"],),
|
||||
).fetchall()
|
||||
src_is_prev = is_prev
|
||||
break
|
||||
if src_items:
|
||||
for n, r in enumerate(src_items):
|
||||
key = str(r["line_key"]) if keyed and r.get("line_key") is not None else str(uuid.uuid4())
|
||||
carry = r["id"] if src_is_prev else None
|
||||
if keyed:
|
||||
conn.execute(
|
||||
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
|
||||
"marketplace_code, carry_from, sort_order, updated_by, line_key) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n,
|
||||
who, key),
|
||||
)
|
||||
else:
|
||||
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"], carry, 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, ("",)):
|
||||
if keyed:
|
||||
conn.execute(
|
||||
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
|
||||
"marketplace_code, sort_order, updated_by, line_key) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(ws, name, color, label, store.guess_meeting_market(name, label), n, who,
|
||||
str(uuid.uuid4())),
|
||||
)
|
||||
else:
|
||||
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=3000, 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)
|
||||
# 새 줄 = 새 연결키(018) — 이름이 같은 다른 줄과 섞이지 않는다
|
||||
keyed = self._meeting_keys(conn)
|
||||
new_id = int(conn.execute(
|
||||
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, "
|
||||
"sort_order, updated_by" + (", line_key" if keyed else "") + ") VALUES (%s,%s,%s,%s,%s,0,%s"
|
||||
+ (",%s" if keyed else "") + ") RETURNING id",
|
||||
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
|
||||
store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ())),
|
||||
).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]
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 직렬화
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -24,7 +24,7 @@ import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import date
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -2514,6 +2514,10 @@ def inbox_page(request: Request) -> HTMLResponse:
|
||||
# 조회: project 권한자 전원 · 입력/구조 변경: 관리자(is_admin) 전용
|
||||
# ────────────────────────────────────────────────────────────
|
||||
_GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)."
|
||||
_GOALS_014_MSG = "분기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다."
|
||||
_GOALS_017_MSG = "2·4분기 칸은 DB 마이그레이션 017 이 필요합니다."
|
||||
_GOALS_015_MSG = "세로 병합·연간/반기 칸 병합과 주간 회의록은 DB 마이그레이션 015 가 필요합니다."
|
||||
_GOALS_016_MSG = "같은 항목 칸 안에 줄 추가(3열)는 DB 마이그레이션 016 이 필요합니다."
|
||||
|
||||
|
||||
def _fmt_goal_num(v: float | None) -> str:
|
||||
@@ -2525,10 +2529,77 @@ def _fmt_goal_num(v: float | None) -> str:
|
||||
return f"{v:,.2f}".rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def _goal_label(metric: str, v: float | None) -> str:
|
||||
"""지표 칸 표기 — 로아스는 % 단위(499 → "499%"). 입력칸도 이 표기로 보이고, 저장 때 % 는 떼고 읽는다."""
|
||||
s = _fmt_goal_num(v)
|
||||
return f"{s}%" if s and metric == "roas" else s
|
||||
|
||||
|
||||
def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None:
|
||||
"""업무 영역 줄마다 칸 배치(row["layout"]) — 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 … 4분기 순서, 엑셀식 사각형 병합.
|
||||
|
||||
병합(row["merges"] = {시작 칸: (가로 칸 수, 세로 줄 수)})의 시작 칸은 {"span", "rspan"}(colspan/rowspan),
|
||||
병합에 가려진 칸은 빼고 그린다. 칸 = {"m", "kind": year|month|quarter, "h"(분기 1~4), "span", "rspan", "now"}.
|
||||
가로는 같은 분기 월 칸 안(예전 반기 병합이 분기를 넘으면 여기서 잘림), 세로는 영역 끝까지로 자른다.
|
||||
겹치는 병합(있을 수 없지만)은 나중 것을 무시."""
|
||||
order = store.GOAL_COL_ORDER
|
||||
covered: set[tuple[int, int]] = set()
|
||||
anchors: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
for ri, row in enumerate(rows):
|
||||
for start, (span, rspan) in sorted((row.get("merges") or {}).items()):
|
||||
if start not in order:
|
||||
continue
|
||||
ci = order.index(start)
|
||||
cols = [c for c in range(ci, min(len(order), ci + span))
|
||||
if store.goal_col_group(order[c]) == store.goal_col_group(start)]
|
||||
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 "quarter" if m in store.GOAL_COL_QUARTER else "month"
|
||||
h = 0 if kind == "year" else store.GOAL_COL_QUARTER[m] if kind == "quarter" else store.goal_quarter_of(m)
|
||||
out.append({"m": m, "kind": kind, "h": h, "span": span, "rspan": rspan,
|
||||
"now": kind == "month" and m <= this_month <= m + span - 1,
|
||||
"html": store.goal_text_html(row.get("cells", {}).get(m, ""))})
|
||||
row["layout"] = out
|
||||
|
||||
|
||||
def _goal_label_spans(rows: list[dict[str, Any]]) -> None:
|
||||
"""항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음).
|
||||
영역 첫 줄은 늘 묶음 첫 줄."""
|
||||
for k, row in enumerate(rows):
|
||||
if k == 0 or not row.get("label_cont"):
|
||||
row["label_cont"] = False
|
||||
n = 1
|
||||
while k + n < len(rows) and rows[k + n].get("label_cont"):
|
||||
n += 1
|
||||
row["label_span"] = n
|
||||
else:
|
||||
row["label_span"] = 0
|
||||
|
||||
|
||||
def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
||||
"""목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400."""
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except store.GoalMigration014Needed:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_014_MSG)
|
||||
except store.GoalMigration015Needed:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_015_MSG)
|
||||
except store.GoalMigration016Needed:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_016_MSG)
|
||||
except store.GoalMigration017Needed:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_017_MSG)
|
||||
except store.GoalCellConflict as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
except UndefinedTable:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
|
||||
except KeyError:
|
||||
@@ -2562,11 +2633,15 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
||||
admin = is_admin(user)
|
||||
enabled = st.goals_enabled()
|
||||
board = st.get_goal_board(year=year) if enabled else None
|
||||
if board:
|
||||
for m in board["metrics"].values():
|
||||
for kind in list(m):
|
||||
m[kind + "_label"] = {mo: _fmt_goal_num(v) for mo, v in m[kind].items()}
|
||||
today = today_kst()
|
||||
this_month = today.month if today.year == year else 0
|
||||
if board:
|
||||
for metric, m in board["metrics"].items():
|
||||
for kind in list(m):
|
||||
m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()}
|
||||
for area in board["areas"]:
|
||||
_goal_area_layout(area["rows"], this_month)
|
||||
_goal_label_spans(area["rows"])
|
||||
return render_template(
|
||||
request,
|
||||
"project/goals.html",
|
||||
@@ -2588,7 +2663,10 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
||||
"goal_year": year,
|
||||
"board": board,
|
||||
"months": list(range(1, 13)),
|
||||
"this_month": today.month if today.year == year else 0,
|
||||
# 분기 — (분기, 그 분기 월, 분기 글 칸 번호, 이름). 분기 칸은 그 분기 월 바로 오른쪽
|
||||
"quarters": [(q, list(range(q * 3 - 2, q * 3 + 1)), store.GOAL_QUARTER_COL[q], f"{q}분기")
|
||||
for q in (1, 2, 3, 4)],
|
||||
"this_month": this_month,
|
||||
"goal_area_colors": list(store.GOAL_AREA_COLORS),
|
||||
},
|
||||
)
|
||||
@@ -2631,7 +2709,7 @@ def api_set_goal_metric(request: Request, year: int, payload: dict[str, Any] = B
|
||||
kind=str(payload.get("kind") or ""), month=payload.get("month"),
|
||||
value=value, updated_by=user["email"],
|
||||
)
|
||||
return JSONResponse({"ok": True, "value": value, "label": _fmt_goal_num(value)})
|
||||
return JSONResponse({"ok": True, "value": value, "label": _goal_label(str(payload.get("metric") or ""), value)})
|
||||
|
||||
|
||||
@router.post("/api/goals/{year}/areas")
|
||||
@@ -2671,7 +2749,15 @@ def api_move_goal_area(request: Request, area_id: int, payload: dict[str, Any] =
|
||||
def api_add_goal_row(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
_require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", ""))
|
||||
# ref_row_id + place(above|below) 가 있으면 그 줄 위/아래에, 없으면 영역 맨 끝에
|
||||
ref = payload.get("ref_row_id")
|
||||
try:
|
||||
ref_id = int(ref) if ref not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="ref_row_id 가 올바르지 않습니다.")
|
||||
rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", ""),
|
||||
ref_row_id=ref_id, place=payload.get("place") or "below",
|
||||
same_label=bool(payload.get("same_label")))
|
||||
return JSONResponse({"ok": True, "id": rid}, status_code=201)
|
||||
|
||||
|
||||
@@ -2691,6 +2777,15 @@ def api_delete_goal_row(request: Request, row_id: int) -> JSONResponse:
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/api/goals/rows/{row_id}/split-label")
|
||||
def api_split_goal_label(request: Request, row_id: int) -> JSONResponse:
|
||||
"""항목 칸 나누기 — 묶음 첫 줄 아래 이어 붙은 줄들을 각자 항목 칸으로(016)."""
|
||||
_require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
n = _goal_call(st.split_goal_label, row_id=row_id)
|
||||
return JSONResponse({"ok": True, "split": n})
|
||||
|
||||
|
||||
@router.post("/api/goals/rows/{row_id}/move")
|
||||
def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
_require_admin(request)
|
||||
@@ -2703,7 +2798,8 @@ def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = B
|
||||
def api_set_goal_cell(
|
||||
request: Request, row_id: int, month: int, payload: dict[str, Any] = Body(...)
|
||||
) -> JSONResponse:
|
||||
"""업무 영역 칸 글 — month 0 = 연간, 1~12 = 월. 빈 글 = 지움."""
|
||||
"""업무 영역 칸 글 — month 0 = 연간, 1~12 = 월, 분기 칸 13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기
|
||||
(014, 15·16 은 017). 빈 글 = 지움."""
|
||||
user = _require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
_goal_call(
|
||||
@@ -2711,3 +2807,498 @@ def api_set_goal_cell(
|
||||
body=payload.get("body", ""), updated_by=user["email"],
|
||||
)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/api/goals/cells/move")
|
||||
def api_move_goal_cell(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""내용·글자 서식만 원자적으로 이동. 원본·대상의 예상값이 바뀌면 409, 병합 배치는 유지."""
|
||||
user = _require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
if any(not isinstance(payload.get(k), str) for k in ("source_body", "target_body", "body")):
|
||||
raise HTTPException(status_code=400, detail="이동할 내용과 두 칸의 현재 내용을 보내 주세요.")
|
||||
body = _goal_call(
|
||||
st.move_goal_cell, source_row=payload.get("source_row"), source_month=payload.get("source_month"),
|
||||
target_row=payload.get("target_row"), target_month=payload.get("target_month"),
|
||||
source_body=payload["source_body"], target_body=payload["target_body"], body=payload["body"],
|
||||
updated_by=user["email"],
|
||||
)
|
||||
return JSONResponse({"ok": True, "body": body})
|
||||
|
||||
|
||||
@router.post("/api/goals/areas/{area_id}/merge")
|
||||
def api_merge_goal_rect(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""엑셀식 병합 {row_from, row_to(줄 id), col_from, col_to(칸 번호 0·1~12·13~16)} — 같은 영역 안 사각형,
|
||||
가로는 같은 분기 월 칸끼리. 걸친 병합은 흡수, 글은 왼쪽 위부터 이어서 왼쪽 위 칸에."""
|
||||
user = _require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
res = _goal_call(
|
||||
st.merge_goal_rect, area_id=area_id, row_from=payload.get("row_from"), row_to=payload.get("row_to"),
|
||||
col_from=payload.get("col_from"), col_to=payload.get("col_to"), updated_by=user["email"],
|
||||
)
|
||||
return JSONResponse({"ok": True, **res})
|
||||
|
||||
|
||||
@router.delete("/api/goals/rows/{row_id}/merge/{start}")
|
||||
def api_unmerge_goal_cells(request: Request, row_id: int, start: int) -> JSONResponse:
|
||||
"""병합 해제 — 글은 왼쪽 위(시작) 칸에 남는다(엑셀과 같음)."""
|
||||
_require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
_goal_call(st.unmerge_goal_cells, row_id=row_id, start=start)
|
||||
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)
|
||||
|
||||
|
||||
class _MeetingPerf:
|
||||
"""회의록이 읽는 실적(읽기 전용) — 값과 상태를 따로 둔다. 조회 장애를 0 원으로 바꾸지 않는다.
|
||||
|
||||
state: ``off``(실적 모듈 미연결) · ``error``(쇼핑몰 목록 조회 실패) · ``empty``(매출 집계 쇼핑몰 없음) · ``ok``.
|
||||
``sum``/``total`` 은 알 수 없으면 None(목록 장애·매출 조회 실패), 정상 조회 결과 0 건이면 0.
|
||||
매출 조회가 실패할 때마다 ``failures`` 가 늘어난다(부분 실패 — 머리 숫자마다 따로 미확인)."""
|
||||
|
||||
def __init__(self, perf: Any) -> None:
|
||||
self.perf = perf
|
||||
self.markets: list[dict[str, Any]] = []
|
||||
self.failures = 0
|
||||
if perf is None:
|
||||
self.state = "off"
|
||||
else:
|
||||
try:
|
||||
self.markets = [m for m in perf.list_marketplaces() if m.get("enabled")]
|
||||
self.state = "ok"
|
||||
except Exception: # noqa: BLE001 — 실적 DB 장애가 회의록을 막지 않게
|
||||
logger.warning("performance marketplaces unavailable for meeting", exc_info=True)
|
||||
self.state = "error"
|
||||
self.names = {m["code"]: m["name"] for m in self.markets}
|
||||
self.sales_codes = [m["code"] for m in self.markets if m.get("include_in_sales")]
|
||||
if self.state == "ok" and not self.sales_codes:
|
||||
self.state = "empty"
|
||||
|
||||
@property
|
||||
def readable(self) -> bool:
|
||||
"""쇼핑몰 목록을 읽었는가(ok·empty) — 연결 쇼핑몰이 "사용 중이 아님"을 판단할 수 있는가."""
|
||||
return self.state in ("ok", "empty")
|
||||
|
||||
def sum(self, start: date, end: date, codes: list[str]) -> dict[str, int] | None:
|
||||
"""기간 쇼핑몰별 매출 합(원, 취소·반품 차감 = 대시보드 총매출과 같은 값). 알 수 없으면 None."""
|
||||
if not self.readable:
|
||||
return None
|
||||
if not codes or end < start:
|
||||
return {}
|
||||
try:
|
||||
out: dict[str, int] = {}
|
||||
for (_, code), amount in self.perf.daily_amounts(start, end, codes).items():
|
||||
out[code] = out.get(code, 0) + int(amount)
|
||||
return out
|
||||
except Exception: # noqa: BLE001
|
||||
self.failures += 1
|
||||
logger.warning("performance sales unavailable for meeting", exc_info=True)
|
||||
return None
|
||||
|
||||
def total(self, start: date, end: date) -> int | None:
|
||||
"""매출 집계 쇼핑몰 합계. 매출 집계 쇼핑몰이 없으면(empty) None — 0 원으로 보이지 않게."""
|
||||
if self.state != "ok":
|
||||
return None
|
||||
r = self.sum(start, end, self.sales_codes)
|
||||
return None if r is None else sum(r.values())
|
||||
|
||||
def freshness(self) -> dict[str, Any] | None:
|
||||
"""매출 집계 쇼핑몰별 마지막 갱신 성공 시각(실적 모듈 perf_connection_status — 서버가 기록한 값만).
|
||||
oldest = 가장 오래된 쇼핑몰 기준(자료가 적어도 이 시각까지는 갱신됨), never = 한 번도 성공 못 한 쇼핑몰."""
|
||||
if self.state != "ok" or not hasattr(self.perf, "statuses"):
|
||||
return None
|
||||
try:
|
||||
stats = self.perf.statuses() or {}
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("performance statuses unavailable for meeting", exc_info=True)
|
||||
return None
|
||||
shops, never = [], []
|
||||
for code in self.sales_codes:
|
||||
t = (stats.get(code) or {}).get("last_success_sync_at")
|
||||
if t:
|
||||
shops.append({"name": self.names.get(code, code), "at": str(t)})
|
||||
else:
|
||||
never.append(self.names.get(code, code))
|
||||
oldest = min((s["at"] for s in shops), default="")
|
||||
return {"shops": shops, "never": never, "oldest": oldest}
|
||||
|
||||
|
||||
def _kst_short(iso: str) -> str:
|
||||
"""'2026-10-01T14:20:00+09:00' → '10/01 14:20'(서버가 준 시각을 한국시간으로)."""
|
||||
if not iso:
|
||||
return ""
|
||||
try:
|
||||
from datetime import datetime # noqa: WPS433
|
||||
|
||||
d = datetime.fromisoformat(str(iso))
|
||||
if d.tzinfo is not None:
|
||||
d = d.astimezone(KST)
|
||||
return d.strftime("%m/%d %H:%M")
|
||||
except ValueError:
|
||||
return str(iso)[:16]
|
||||
|
||||
|
||||
def _meeting_view(request: Request, st: Any, *, year: int, month: int, week: date) -> dict[str, Any]:
|
||||
"""회의록 화면 데이터 — 머리(월 목표·누적·남은 주 필요 매출·전주/금주 목표·결과) + 줄(지난주 리뷰 포함).
|
||||
|
||||
"지난주"는 정확히 7일 전 주(prev_week)만 — 머리 전주 목표·전주 결과·줄의 지난주 칸·결과·달성률이 같은 주다
|
||||
(db.get_meeting 이 7일 전 주 회의록에서 같은 연결키 줄만 prev 로 준다). 실적은 _MeetingPerf — 알 수 없는 값은
|
||||
None + head.unknown 에 이름(0 원·0% 로 보이지 않게, 그 값에 기대는 달성률·필요 매출도 계산하지 않는다)."""
|
||||
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 = _MeetingPerf(_perf_sales(request))
|
||||
names = perf.names
|
||||
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)
|
||||
unknown: list[str] = []
|
||||
|
||||
def total(key: str, a: date, b: date) -> int | None:
|
||||
v = perf.total(a, min(b, today))
|
||||
if v is None and perf.state in ("error", "ok"):
|
||||
unknown.append(key) # 목록 장애(error) 또는 이 기간 매출 조회 실패(ok 인데 None)
|
||||
return v
|
||||
|
||||
# 월 누적 = 이 주 앞까지(지난주 일요일까지) — 남은 목표를 이번 주 포함 남은 주로 나눠 "주당 필요 매출"
|
||||
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("mtd", first, mtd_end) if mtd_end >= first else 0 # 1주차 앞에는 지난 날이 없다(정말 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 # 정확히 7일 전 주 회의록이어야 "전주 목표"
|
||||
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
|
||||
fresh = perf.freshness()
|
||||
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_exists": bool(pm and pm["week_start"] == prev_start.isoformat()),
|
||||
"prev_result": total("prev_result", prev_start, prev_end) if prev_start <= today else None,
|
||||
"week_result": total("week_result", week, week_end) if week <= today else None,
|
||||
# perf = 실적 모듈 연결 여부(예전 뜻 그대로 — 갱신 상자·안내 문구 조건), 조회 성공 여부는 perf_state·unknown
|
||||
"perf": perf.state != "off",
|
||||
"perf_state": perf.state,
|
||||
"unknown": unknown,
|
||||
"fresh_oldest": _kst_short(fresh["oldest"]) if fresh else "",
|
||||
"fresh_tip": ("매출 자료(실적 모듈) 쇼핑몰별 마지막 갱신 성공 — " +
|
||||
" · ".join(f"{s['name']} {_kst_short(s['at'])}" for s in fresh["shops"]) +
|
||||
(f" · 갱신 성공 기록 없음: {', '.join(fresh['never'])}" if fresh["never"] else "")) if fresh else "",
|
||||
}
|
||||
if meeting:
|
||||
# 줄마다 지난주 결과 — 쇼핑몰 연결이면 그 주 실적(자동), 아니면 직접 입력한 결과(지난주 줄에 저장)
|
||||
all_codes = [m["code"] for m in perf.markets]
|
||||
by_week: dict[str, dict[str, int] | None] = {}
|
||||
|
||||
def week_sales(ws: str) -> dict[str, int] | None:
|
||||
"""그 주(월~일, 오늘까지) 쇼핑몰별 실적 — 조회 실패면 None(시작 전 주는 부르지 않는다)."""
|
||||
if ws not in by_week:
|
||||
a = date.fromisoformat(ws)
|
||||
by_week[ws] = perf.sum(a, min(a + timedelta(days=6), today), all_codes)
|
||||
return by_week[ws]
|
||||
|
||||
for it in meeting["items"]:
|
||||
prev = it.get("prev")
|
||||
if not prev:
|
||||
continue
|
||||
auto = None
|
||||
code = prev.get("marketplace_code") or ""
|
||||
a = date.fromisoformat(prev["week_start"])
|
||||
prev["period"] = f"{a.month}/{a.day}~{(a + timedelta(days=6)).month}/{(a + timedelta(days=6)).day}"
|
||||
prev["not_started"] = bool(code) and a > today
|
||||
# 쇼핑몰 목록을 못 읽었으면 연결 쇼핑몰이 사용 중인지 알 수 없다 → 결과 미확인(직접 입력 칸·0 으로 바꾸지 않음)
|
||||
prev["auto_error"] = bool(code) and not prev["not_started"] and perf.state == "error"
|
||||
# 실적 모듈에서 사용 중이 아닌 쇼핑몰(설정에서 사용 OFF·없는 코드)은 늘 0 이라 자동으로 보지 않고 직접 입력
|
||||
prev["market_off"] = bool(code) and perf.state != "error" and code not in names
|
||||
if code and perf.readable and not prev["not_started"] and not prev["market_off"]:
|
||||
got = week_sales(prev["week_start"])
|
||||
if got is None:
|
||||
prev["auto_error"] = True
|
||||
else:
|
||||
auto = got.get(code, 0)
|
||||
prev["auto_result"] = auto
|
||||
prev["result"] = auto if auto is not None else (None if prev["auto_error"] else prev.get("result_amount"))
|
||||
prev["market_name"] = names.get(code, code)
|
||||
for it in meeting["items"]:
|
||||
code = it["marketplace_code"]
|
||||
it["market_name"] = names.get(code, code) if code else ""
|
||||
it["market_off"] = bool(code) and perf.state != "error" and code not in names
|
||||
it["market_unknown"] = bool(code) and perf.state == "error"
|
||||
# 이번 주 진행 중 실적(쇼핑몰 연결 줄) — 정량 목표 칸 아래에 "이번주 실적"
|
||||
it["week_auto"], it["week_error"] = None, False
|
||||
if code and week <= today and not it["market_off"]:
|
||||
got = week_sales(meeting["week_start"]) if perf.readable else None
|
||||
if got is None:
|
||||
it["week_error"] = perf.state != "off"
|
||||
else:
|
||||
it["week_auto"] = got.get(code, 0)
|
||||
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 perf.markets]}
|
||||
|
||||
|
||||
def _month_plan(st: Any, year: int, month: int) -> list[dict[str, Any]] | None:
|
||||
"""회의록 위 "N월 계획" — 연간 목표 표의 그 달 열 글을 업무 영역별로(빈 칸은 뺌). 목표 표가 없으면 None.
|
||||
가로 병합(예: 9~10월 칸)에 적은 글도 그 달 계획으로, 세로 병합은 한 번만. 항목 이름이 묶인 줄(016)은 묶음 이름."""
|
||||
try:
|
||||
board = st.get_goal_board(year=year) if st.goals_enabled() else None
|
||||
except Exception: # noqa: BLE001 — 목표 표를 못 읽어도 회의록은 열린다
|
||||
logger.warning("goal board unavailable for meeting plan", exc_info=True)
|
||||
return None
|
||||
if not board:
|
||||
return None
|
||||
out = []
|
||||
for area in board["areas"]:
|
||||
rows = area["rows"]
|
||||
_goal_area_layout(rows, 0)
|
||||
_goal_label_spans(rows)
|
||||
items, label = [], ""
|
||||
for row in rows:
|
||||
if not row.get("label_cont"):
|
||||
label = row.get("label") or ""
|
||||
cell = next((c for c in row["layout"] if c["kind"] == "month" and c["m"] <= month <= c["m"] + c["span"] - 1), None)
|
||||
text = store.goal_text_plain(row["cells"].get(cell["m"], "") if cell else "").strip()
|
||||
if not text:
|
||||
continue
|
||||
rng = f"{cell['m']}~{cell['m'] + cell['span'] - 1}월" if cell["span"] > 1 else ""
|
||||
items.append({"label": label, "text": text, "range": rng})
|
||||
if items:
|
||||
out.append({"name": area["name"], "color": area["color"], "lines": items}) # 키 lines — 템플릿의 a.items 는 dict.items 메서드
|
||||
return out
|
||||
|
||||
|
||||
def _meet_members() -> list[dict[str, str]]:
|
||||
"""회의 참석자 후보 = 전체 멤버(project 모듈 권한 보유 등록 사용자) — 이름·이메일·사진."""
|
||||
try:
|
||||
from app.main import user_store # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
out = [{"email": u["email"], "name": u.get("name") or u["email"].split("@")[0], "avatar": u.get("picture") or ""}
|
||||
for u in user_store.list_all() if has_module(u, "project")]
|
||||
except Exception: # noqa: BLE001 — 사용자 목록이 없어도 회의록은 열린다
|
||||
logger.warning("meeting members unavailable", exc_info=True)
|
||||
return []
|
||||
return sorted(out, key=lambda m: m["name"])
|
||||
|
||||
|
||||
def _parse_attendees(text: str, members: list[dict[str, str]]) -> list[dict[str, str]]:
|
||||
"""참석자 칸(쉼표로 이은 이메일 — 예전엔 자유 입력 글자) → 칩 목록. 멤버 이메일이면 이름·사진, 아니면 글자 그대로."""
|
||||
by_email = {m["email"].lower(): m for m in members}
|
||||
out, seen = [], set()
|
||||
for tok in str(text or "").replace("\n", ",").split(","):
|
||||
t = tok.strip()
|
||||
if not t or t.lower() in seen:
|
||||
continue
|
||||
seen.add(t.lower())
|
||||
m = by_email.get(t.lower())
|
||||
out.append({"key": m["email"] if m else t, "email": m["email"] if m else "", "name": m["name"] if m else t,
|
||||
"avatar": m["avatar"] if m else ""})
|
||||
return out
|
||||
|
||||
|
||||
@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 has_module, 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 not None and (sel.year, sel.month) != (year, month):
|
||||
# 다른 달의 주(주는 월요일이 속한 달의 것) — 그 달 회의록 주소로
|
||||
return RedirectResponse(url=f"/project/goals/{sel.year}/meetings/{sel.month}?week={sel.isoformat()}",
|
||||
status_code=303)
|
||||
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()
|
||||
cal = store.calendar_weeks(year, month)
|
||||
existing = set(st.meeting_weeks(start=cal[0][0], end=cal[-1][0])) if enabled else set()
|
||||
view = _meeting_view(request, st, year=year, month=month, week=sel) if enabled else {}
|
||||
members = _meet_members()
|
||||
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,
|
||||
# 작은 달력(월요일 시작) 한 줄 — 날짜·그 달 여부·오늘·요일(5 토, 6 일)·공휴일
|
||||
"days": [{"d": (w + timedelta(days=k)).day, "iso": (w + timedelta(days=k)).isoformat(),
|
||||
"in": (w + timedelta(days=k)).month == month, "today": w + timedelta(days=k) == today,
|
||||
"wd": k, "hol": store.KR_HOLIDAYS.get((w + timedelta(days=k)).isoformat(), "")}
|
||||
for k in range(7)]}
|
||||
for i, (w, e) in enumerate(weeks)],
|
||||
# 작은 달력 — 그 달 날짜가 든 주 전부(앞뒤 달에 속한 주는 흐리게, 누르면 그 달 회의록)
|
||||
"cal_weeks": [{"start": w.isoformat(), "own": (w.year, w.month) == (year, month),
|
||||
"href": (f"?week={w.isoformat()}" if (w.year, w.month) == (year, month)
|
||||
else f"/project/goals/{w.year}/meetings/{w.month}?week={w.isoformat()}"),
|
||||
"title": (f"{next(i + 1 for i, (x, _) in enumerate(weeks) if x == w)}주차"
|
||||
if (w.year, w.month) == (year, month) else f"{w.month}월 주")
|
||||
+ f" ({w.month}/{w.day}~{e.month}/{e.day})",
|
||||
"has": w.isoformat() in existing,
|
||||
"days": [{"d": (w + timedelta(days=k)).day, "in": (w + timedelta(days=k)).month == month,
|
||||
"today": w + timedelta(days=k) == today, "wd": k,
|
||||
"hol": store.KR_HOLIDAYS.get((w + timedelta(days=k)).isoformat(), "")}
|
||||
for k in range(7)]}
|
||||
for w, e in store.calendar_weeks(year, month)],
|
||||
"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(),
|
||||
"prev_week_end": (sel - timedelta(days=1)).isoformat(),
|
||||
# 주차를 열면 다시 받을 매출 기간(실적 모듈 매출 업데이트) — 지난주 월요일 ~ 이번 주 일요일(오늘까지)
|
||||
"sync_from": (sel - timedelta(days=7)).isoformat() if sel - timedelta(days=7) <= today else "",
|
||||
"sync_to": min(sel + timedelta(days=6), today).isoformat(),
|
||||
# 쇼핑몰 매출 갱신(실적 모듈 POST /performance/api/sync)은 실적 모듈 권한자만 — 없으면 화면이 부르지 않는다
|
||||
"can_sync": has_module(user, "performance"),
|
||||
"meeting_status": store.MEETING_STATUS,
|
||||
"meet_members": members,
|
||||
"month_plan": _month_plan(st, year, month),
|
||||
"attendee_list": _parse_attendees((view.get("meeting") or {}).get("attendees", ""), members),
|
||||
**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"])
|
||||
out: dict[str, Any] = {"ok": True}
|
||||
if "week_target" in fields: # 화면이 서버 확정값(원 정수)으로 칸을 맞춘다
|
||||
out["week_target"] = store.validate_meeting_amount(fields["week_target"])
|
||||
return JSONResponse(out)
|
||||
|
||||
|
||||
@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})
|
||||
|
||||
@@ -6,7 +6,10 @@ DB 없이 단위 테스트 가능한 순수 함수만 둔다(malaysia.store 패
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from html import escape
|
||||
from html.parser import HTMLParser
|
||||
from typing import Any
|
||||
|
||||
@@ -356,7 +359,7 @@ def validate_time(t: Any) -> str | None:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
||||
# ════════════════════════════════════════════════════════════
|
||||
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스
|
||||
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스(단위 %)
|
||||
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
|
||||
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
|
||||
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
|
||||
@@ -386,17 +389,58 @@ def validate_goal_year(y: Any) -> int:
|
||||
return v
|
||||
|
||||
|
||||
class GoalMigration014Needed(RuntimeError):
|
||||
"""기간(분기) 글 칸·월 칸 병합은 마이그레이션 014(goal_cell_merges) 뒤에만 된다."""
|
||||
|
||||
|
||||
class GoalMigration017Needed(RuntimeError):
|
||||
"""2·4분기 글 칸(15·16)은 마이그레이션 017(분기) 뒤에만 된다."""
|
||||
|
||||
|
||||
class GoalCellConflict(RuntimeError):
|
||||
"""셀 이동 전에 다른 창에서 원본 또는 대상 내용이 바뀜."""
|
||||
|
||||
|
||||
GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간
|
||||
# 분기 글 칸(2026-10-01 상·하반기 → 1~4분기). 칸 번호는 예전 반기 칸을 그대로 이어 쓴다 — 데이터 옮기기 없이
|
||||
# 예전 상반기 글(13)은 1분기, 하반기 글(14)은 3분기에 보인다. 2분기(15)·4분기(16)는 마이그레이션 017 뒤에 저장.
|
||||
GOAL_QUARTER_COL: dict[int, int] = {1: 13, 2: 15, 3: 14, 4: 16}
|
||||
GOAL_COL_QUARTER: dict[int, int] = {c: q for q, c in GOAL_QUARTER_COL.items()}
|
||||
GOAL_Q_NEW: tuple[int, ...] = (15, 16) # 017 이 있어야 저장되는 분기 칸
|
||||
GOAL_MAX_COL = 16
|
||||
|
||||
|
||||
def goal_quarter_of(month: int) -> int:
|
||||
"""1~3월 → 1분기, 4~6월 → 2분기, 7~9월 → 3분기, 10~12월 → 4분기."""
|
||||
return (int(month) - 1) // 3 + 1
|
||||
|
||||
|
||||
def validate_goal_month(m: Any, *, allow_year: bool = False) -> int:
|
||||
"""1~12월. allow_year 이면 0(연간)도 허용."""
|
||||
"""1~12월. allow_year 이면 업무 영역 글 칸 — 0(연간)·13~16(분기 칸, GOAL_QUARTER_COL)도 허용."""
|
||||
try:
|
||||
v = int(m)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("월이 올바르지 않습니다.")
|
||||
if not ((0 if allow_year else 1) <= v <= 12):
|
||||
if not ((0 if allow_year else 1) <= v <= (GOAL_MAX_COL if allow_year else 12)):
|
||||
raise ValueError("월이 올바르지 않습니다.")
|
||||
return v
|
||||
|
||||
|
||||
def validate_goal_merge(start: Any, end: Any) -> tuple[int, int]:
|
||||
"""월 칸 병합 범위(start~end 월, 2칸 이상) — 분기를 넘지 않는다."""
|
||||
try:
|
||||
s, e = int(start), int(end)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("병합할 월이 올바르지 않습니다.")
|
||||
if s > e:
|
||||
s, e = e, s
|
||||
if not (1 <= s and e <= 12) or s == e:
|
||||
raise ValueError("병합은 1~12월 안에서 2칸 이상 골라야 합니다.")
|
||||
if goal_quarter_of(s) != goal_quarter_of(e):
|
||||
raise ValueError("분기(1~3·4~6·7~9·10~12월)를 넘어 병합할 수 없습니다.")
|
||||
return s, e
|
||||
|
||||
|
||||
def validate_goal_value(v: Any) -> float | None:
|
||||
"""지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움)."""
|
||||
s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "")
|
||||
@@ -437,11 +481,253 @@ def validate_goal_color(color: Any) -> str:
|
||||
|
||||
def validate_goal_text(body: Any) -> str:
|
||||
v = str(body or "").replace("\r\n", "\n").strip()
|
||||
if v.startswith(GOAL_RICH_PREFIX):
|
||||
runs = goal_text_runs(v, strict=True)
|
||||
if not "".join(r["text"] for r in runs).strip():
|
||||
return ""
|
||||
return GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False, separators=(",", ":"))
|
||||
if len(v) > GOAL_TEXT_MAX:
|
||||
raise ValueError(f"칸 하나에 {GOAL_TEXT_MAX}자까지 쓸 수 있습니다.")
|
||||
return v
|
||||
|
||||
|
||||
# 기존 TEXT 칸에 버전이 있는 텍스트 조각을 저장한다. 예전 평문은 그대로 유지한다.
|
||||
GOAL_RICH_PREFIX = "pj-rich:v1:"
|
||||
|
||||
|
||||
def goal_text_runs(body: Any, *, strict: bool = False) -> list[dict[str, Any]]:
|
||||
value = str(body or "")
|
||||
if not value.startswith(GOAL_RICH_PREFIX):
|
||||
return [{"text": value}]
|
||||
try:
|
||||
raw = json.loads(value[len(GOAL_RICH_PREFIX):])
|
||||
if not isinstance(raw, list) or len(raw) > GOAL_TEXT_MAX:
|
||||
raise ValueError("서식 데이터가 올바르지 않습니다.")
|
||||
runs = []
|
||||
for item in raw:
|
||||
if not isinstance(item, dict) or not isinstance(item.get("text"), str):
|
||||
raise ValueError("서식 데이터가 올바르지 않습니다.")
|
||||
run: dict[str, Any] = {"text": item["text"]}
|
||||
for key in ("bold", "italic", "underline"):
|
||||
if isinstance(item.get(key), bool):
|
||||
run[key] = item[key]
|
||||
if re.fullmatch(r"#[0-9a-fA-F]{6}", str(item.get("color", ""))):
|
||||
run["color"] = item["color"].lower()
|
||||
size = item.get("size")
|
||||
if isinstance(size, int) and not isinstance(size, bool) and 10 <= size <= 32:
|
||||
run["size"] = size
|
||||
if run["text"]:
|
||||
runs.append(run)
|
||||
if sum(len(r["text"]) for r in runs) > GOAL_TEXT_MAX:
|
||||
raise ValueError(f"칸 하나에 {GOAL_TEXT_MAX}자까지 쓸 수 있습니다.")
|
||||
return runs
|
||||
except (ValueError, TypeError) as err:
|
||||
if strict:
|
||||
raise ValueError("칸의 서식 데이터가 올바르지 않습니다.") from err
|
||||
return [{"text": value}]
|
||||
|
||||
|
||||
def goal_text_plain(body: Any) -> str:
|
||||
return "".join(r["text"] for r in goal_text_runs(body))
|
||||
|
||||
|
||||
def goal_text_html(body: Any) -> str:
|
||||
"""허용한 글자 서식만 HTML로 만든다. 사용자 텍스트는 항상 escape한다."""
|
||||
out = []
|
||||
for run in goal_text_runs(body):
|
||||
style = []
|
||||
if "bold" in run:
|
||||
style.append("font-weight:" + ("700" if run["bold"] else "400"))
|
||||
if "italic" in run:
|
||||
style.append("font-style:" + ("italic" if run["italic"] else "normal"))
|
||||
if "underline" in run:
|
||||
style.append("text-decoration:" + ("underline" if run["underline"] else "none"))
|
||||
if "color" in run:
|
||||
style.append("color:" + run["color"])
|
||||
if "size" in run:
|
||||
style.append(f'font-size:{run["size"]}px')
|
||||
text = escape(run["text"])
|
||||
out.append(f'<span style="{";".join(style)}">{text}</span>' if style else text)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def merge_goal_texts(bodies: list[str]) -> str:
|
||||
values = [v for v in bodies if goal_text_plain(v).strip()]
|
||||
if not any(v.startswith(GOAL_RICH_PREFIX) for v in values):
|
||||
return validate_goal_text("\n".join(values))
|
||||
runs = []
|
||||
for value in values:
|
||||
if runs:
|
||||
runs.append({"text": "\n"})
|
||||
runs.extend(goal_text_runs(value))
|
||||
return validate_goal_text(GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False))
|
||||
|
||||
|
||||
# ── 엑셀식 사각형 병합(마이그레이션 015) ──────────────────────────────
|
||||
class GoalMigration015Needed(RuntimeError):
|
||||
"""세로 병합·주간 회의록은 마이그레이션 015 뒤에만 된다."""
|
||||
|
||||
|
||||
class GoalMigration016Needed(RuntimeError):
|
||||
"""항목 칸(2열) 묶음(같은 항목 칸 안에 줄 추가)은 마이그레이션 016 뒤에만 된다."""
|
||||
|
||||
|
||||
# 업무 영역 글 칸의 화면 순서 — 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 · 7~9월 · 3분기 · 10~12월 · 4분기
|
||||
GOAL_COL_ORDER: tuple[int, ...] = (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)
|
||||
|
||||
|
||||
def goal_col_group(m: int) -> str:
|
||||
"""병합 가능 묶음 — 가로 병합은 같은 묶음 안에서만(연간·분기 칸은 혼자, 월은 같은 분기끼리)."""
|
||||
if m == GOAL_YEAR:
|
||||
return "year"
|
||||
if m in GOAL_COL_QUARTER:
|
||||
return f"q{GOAL_COL_QUARTER[m]}"
|
||||
return f"months{goal_quarter_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_last_day(year: int, month: int) -> date:
|
||||
return date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1)
|
||||
|
||||
|
||||
def month_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||
"""그 달의 주(월요일~일요일) 목록 — **1주차 = 그 달 첫 월요일이 있는 주**, 주는 월요일이 속한 달의 것
|
||||
(2026-10-01 사용자 기준). 예: 2026년 10월 = 10/5·12·19·26 주, 9/28~10/4 주는 9월 마지막 주.
|
||||
월간 목표·누적은 이와 따로 늘 1일~말일."""
|
||||
first = date(year, month, 1)
|
||||
last = month_last_day(year, month)
|
||||
out, mon = [], first + timedelta(days=(7 - first.weekday()) % 7)
|
||||
while mon <= last:
|
||||
out.append((mon, mon + timedelta(days=6)))
|
||||
mon += timedelta(days=7)
|
||||
return out
|
||||
|
||||
|
||||
def calendar_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||
"""작은 달력용 — 그 달 날짜가 하나라도 든 주(월요일 시작) 전부(1일이 든 주부터 말일이 든 주까지)."""
|
||||
first, last = date(year, month, 1), month_last_day(year, month)
|
||||
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:
|
||||
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
|
||||
|
||||
|
||||
@@ -34,3 +34,4 @@
|
||||
title="프로젝트 관리 도움말" aria-label="프로젝트 관리 도움말">
|
||||
<span class="material-symbols-outlined">help</span>
|
||||
</a>
|
||||
{% include "project/_options.html" %}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션">
|
||||
<span class="material-symbols-outlined">settings</span>
|
||||
</button>
|
||||
<dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title">
|
||||
<form id="pj-options-form">
|
||||
<h2 id="pj-options-title">Project 옵션</h2>
|
||||
<label for="pj-options-font">폰트</label>
|
||||
<select id="pj-options-font" name="font">
|
||||
<option value="system">기본 시스템 폰트</option>
|
||||
<option value="pretendard">프리텐다드</option>
|
||||
<option value="nanum-square">나눔 스퀘어</option>
|
||||
<option value="nanum-square-neo">나눔 스퀘어 네오</option>
|
||||
<option value="nanum-square-round">나눔 스퀘어 라운드</option>
|
||||
</select>
|
||||
<div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div>
|
||||
<p>이 브라우저의 모든 Project 화면에 적용됩니다.</p>
|
||||
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
|
||||
<div class="pj-options-actions">
|
||||
<button type="button" class="pj-btn" id="pj-options-cancel">취소</button>
|
||||
<button type="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
<script>
|
||||
try {
|
||||
var pf = localStorage.getItem("pj_font") || "system";
|
||||
if (["system", "pretendard", "nanum-square", "nanum-square-neo", "nanum-square-round"].indexOf(pf) >= 0)
|
||||
document.documentElement.dataset.pjFont = pf;
|
||||
} catch (_) {}
|
||||
</script>
|
||||
<script src="/static/project-options.js?v=20261002g" defer></script>
|
||||
@@ -0,0 +1,300 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<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" data-me="{{ (user.email if user else '') | lower }}">
|
||||
<div class="pj-layout">
|
||||
{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}
|
||||
|
||||
<section class="pj-main">
|
||||
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력 #}
|
||||
<div class="pj-meet-headgrid">
|
||||
<div class="pj-meet-headleft">
|
||||
<div class="pj-meet-title">
|
||||
{# 연간 목표로 — 눈에 잘 띄는 큰 버튼(예전 ← 화살표 대신) #}
|
||||
<a class="pj-meet-goalbtn" href="/project/goals/{{ goal_year }}" title="{{ goal_year }}년 연간 목표로"><span class="material-symbols-outlined">flag</span><span>{{ goal_year }}년 목표</span></a>
|
||||
<h2 class="pj-goal-title">{{ 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>
|
||||
{% if meeting %}
|
||||
<span class="pj-meet-title-acts">
|
||||
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
|
||||
{% if is_admin %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>
|
||||
{% else %}<span class="pj-goal-note">회의록은 관리자만 입력할 수 있습니다.</span>{% endif %}
|
||||
</span>
|
||||
{% endif %}
|
||||
{# 주차 탭 — 주 = 월요일~일요일, 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 }}" title="{{ w.n }}주차 {{ w.label }}">
|
||||
{# 날짜는 짧게 — 같은 달이면 끝 월 생략(10/5~11), 달이 넘어가면 10/26~11/1 #}
|
||||
{% set ws = w.start.split('-') %}{% set we = w.end.split('-') %}
|
||||
<b>{{ w.n }}주차</b><span>{{ ws[1] | int }}/{{ ws[2] | int }}~{% if we[1] != ws[1] %}{{ we[1] | int }}/{% endif %}{{ we[2] | int }}</span>
|
||||
{% if w.has %}<i class="pj-meet-dot" title="회의록 있음"></i>{% endif %}
|
||||
{% if w.now %}<em>이번 주</em>{% endif %}
|
||||
</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
</div>
|
||||
{# 이 달 계획 — 연간 목표 표의 그 달 열 글(업무 영역별, router._month_plan) #}
|
||||
{% if month_plan is not none %}
|
||||
<section class="pj-meet-plan">
|
||||
<div class="pj-meet-plan-head"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</div>
|
||||
{% if month_plan %}
|
||||
<div class="pj-meet-plan-grid">
|
||||
{% for a in month_plan %}
|
||||
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
|
||||
<b class="pj-meet-plan-name">{{ a.name }}</b>
|
||||
{% for it in a.lines %}
|
||||
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
</div>
|
||||
{# 작은 달력 — 월요일 시작(주 = 월~일), 보고 있는 주는 영역 표시, 줄을 누르면 그 주 회의록. 점 = 회의록 있음.
|
||||
1주차 = 그 달 첫 월요일이 있는 주 — 1일 앞쪽 날짜가 든 주는 앞 달 주(흐리게, 누르면 앞 달 회의록). #}
|
||||
<div class="pj-meet-cal" aria-label="{{ goal_month }}월 달력">
|
||||
<div class="pj-meet-cal-head">{{ goal_year }}년 {{ goal_month }}월</div>
|
||||
<div class="pj-meet-cal-wd"><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span><span class="is-sun">일</span></div>
|
||||
{% for w in cal_weeks %}
|
||||
<a class="pj-meet-cal-row{% if w.start == week %} is-on{% endif %}{% if not w.own %} is-other{% endif %}" href="{{ w.href }}"
|
||||
title="{{ w.title }}{% if w.has %} · 회의록 있음{% endif %}{% if not w.own %} — 이 주는 {{ w.title.split('월')[0] }}월 회의록{% endif %}">
|
||||
{% for d in w.days %}<span class="pj-meet-cal-d{% if not d.in %} is-out{% endif %}{% if d.today %} is-today{% endif %}{% if d.wd == 5 %} is-sat{% endif %}{% if d.wd == 6 or d.hol %} is-sun{% endif %}"{% if d.hol %} title="{{ d.hol }}"{% endif %}>{{ d.d }}</span>{% endfor %}
|
||||
{% if w.has %}<i class="pj-meet-cal-dot"></i>{% endif %}
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</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' }}">
|
||||
|
||||
{% 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 %}
|
||||
{% set unk = h.unknown or [] %}
|
||||
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
|
||||
{# ── 숫자 — 한 줄 막대(월 목표 대비 누적·남은 주 필요 매출 | 전주 리뷰 | 금주 목표) ── #}
|
||||
<div class="pj-meet-kpibar">
|
||||
<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"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||
<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>{% elif 'mtd' in unk %}{{ unknown_val() }}{% 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" title="월 목표 − 누적을 이번 주 포함 남은 주로 나눈 값">
|
||||
<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>{% elif 'mtd' in unk and h.month_target_won is not none %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</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"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||
<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>{% elif 'prev_result' in unk %}{{ unknown_val() }}{% 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>
|
||||
{% elif h.prev_target and 'prev_result' in unk %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</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 %}
|
||||
<span class="pj-meet-sub-slot">{% if h.need_per_week is not none %}<span class="pj-meet-kpi-sub">필요 {{ won(h.need_per_week) }}원</span>{% endif %}</span>
|
||||
</div>
|
||||
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||
<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>{% elif 'week_result' in unk %}{{ unknown_val() }}{% 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>
|
||||
</div>
|
||||
{# 매출 자료 갱신 — 주차를 열면 실적 모듈 매출 업데이트(지난주 월요일 ~ 이번 주 오늘)를 한 번 더 돌리고 숫자 칸만 다시 그린다
|
||||
(project.js initMeetingSync, 같은 주는 10분에 한 번). 정상이면 아무것도 보이지 않는다(2026-10-01 요청 — 큰 상태 줄 없음).
|
||||
실패·일부 실패면 이 작은 안내 + [다시 시도], 실적 권한이 없으면 부르지 않고 한 줄 설명. 마지막 갱신 성공 시각은 서버 기록(data-fresh). #}
|
||||
{% if h.perf and sync_from %}<div id="pj-meet-sync" class="pj-meet-syncnote" hidden role="status" aria-live="polite"
|
||||
data-from="{{ sync_from }}" data-to="{{ sync_to }}" data-can="{{ '1' if can_sync else '0' }}" data-fresh="{{ h.fresh_oldest }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">sync_problem</span><span class="pj-meet-sync-text"></span>
|
||||
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-sync-btn" hidden>다시 시도</button>
|
||||
</div>{% endif %}
|
||||
{% if not h.perf %}<p class="pj-goal-note">실적 모듈이 연결되지 않아 실적·누적·쇼핑몰 자동 결과는 비어 있습니다(결과는 직접 입력).</p>
|
||||
{% elif h.perf_state == 'error' %}<p class="pj-goal-note pj-meet-perf-warn">실적 모듈 쇼핑몰 목록을 읽지 못해 실적·누적·쇼핑몰 자동 결과를 <b>미확인</b>으로 표시합니다(0 원이 아님). 회의록 입력은 그대로 됩니다.</p>
|
||||
{% elif h.perf_state == 'empty' %}<p class="pj-goal-note">실적 모듈에 매출 집계 쇼핑몰이 없어 실적·누적은 비어 있습니다.</p>
|
||||
{% elif unk %}<p class="pj-goal-note pj-meet-perf-warn">일부 실적을 읽지 못했습니다 — <b>미확인</b> 칸은 0 원이 아니라 알 수 없는 값입니다.</p>{% endif %}
|
||||
|
||||
{# 참석자 — 전체 멤버에서 고른다(칩, [참석자] = 고르기 창). 저장은 이메일을 쉼표로 이어서, 예전 자유 입력 글자도 칩으로 #}
|
||||
<div class="pj-meet-attend">
|
||||
<span class="pj-meet-attend-label">참석자</span>
|
||||
<div class="pj-meet-attend-chips" id="pj-meet-attend"{% if edit %} data-edit="1"{% endif %}>
|
||||
{% for a in attendee_list %}<span class="pj-meet-chip" data-key="{{ a.key }}" data-name="{{ a.name }}" data-avatar="{{ a.avatar }}"{% if not a.email %} title="멤버가 아닌 글자(예전 입력)"{% endif %}>
|
||||
{%- if a.avatar %}<img class="pj-avatar" src="{{ a.avatar }}" alt="" referrerpolicy="no-referrer">{% else %}<span class="pj-meet-chip-ini">{{ a.name[:1] }}</span>{% endif %}<span>{{ a.name }}</span>
|
||||
{%- if edit %}<button type="button" class="pj-meet-chip-x" title="빼기" aria-label="{{ a.name }} 빼기">×</button>{% endif %}</span>{% endfor %}
|
||||
{% if edit %}<button type="button" class="pj-meet-attend-add" id="pj-meet-attend-add"><span class="material-symbols-outlined">person_add</span>참석자</button>
|
||||
{% elif not attendee_list %}<span class="pj-muted">—</span>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
|
||||
<table class="pj-meet-table" id="pj-meet-table">
|
||||
{# table-layout: fixed 는 첫 줄(묶음 머리, colspan)로 너비를 정하므로 열 너비는 colgroup 으로 #}
|
||||
<colgroup>
|
||||
{# is-this / is-prev — 순서 바꾸기(project.js initMeetOrder)가 이 묶음으로 열을 옮긴다 #}
|
||||
<col class="pj-meet-w-sec" /><col class="pj-meet-w-label" /><col class="is-this" /><col class="pj-meet-w-amt is-this" />
|
||||
<col class="is-prev" /><col class="pj-meet-w-amt is-prev" /><col class="pj-meet-w-amt is-prev" /><col class="pj-meet-w-rate is-prev" /><col class="pj-meet-w-eval is-prev" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr class="pj-meet-group">
|
||||
{# 이번주 ↔ 지난주 리뷰 순서 바꾸기 — 보는 사람마다 브라우저에 기억(localStorage pj_meet_order:{이메일}) #}
|
||||
<th colspan="2" class="pj-meet-order-cell"><button type="button" class="pj-meet-order-btn" id="pj-meet-order"
|
||||
title="이번주와 지난주 리뷰의 순서 바꾸기(내 화면에 기억)"><span class="material-symbols-outlined">swap_horiz</span>순서 바꾸기</button></th>
|
||||
<th colspan="2" class="is-this">이번주 ({{ week[5:] | replace('-', '/') }} ~ {{ week_end[5:] | replace('-', '/') }})</th>
|
||||
{# 지난주 = 정확히 7일 전 주 — 줄의 지난주 칸·결과·달성률도 이 주 회의록의 같은 줄(연결키)만 #}
|
||||
<th colspan="5" class="is-prev">지난주 리뷰 ({{ prev_week[5:] | replace('-', '/') }} ~ {{ prev_week_end[5:] | replace('-', '/') }}){% if not h.prev_exists %} <span class="pj-meet-noprev">— 이 주 회의록 없음</span>{% endif %}</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 }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% 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_unknown %}<span class="pj-meet-market is-unknown" title="실적 모듈 쇼핑몰 목록을 읽지 못해 이 연결의 실적을 확인할 수 없습니다">{{ it.market_name }} · 미확인</span>
|
||||
{% elif it.market_off %}<span class="pj-meet-market is-off" title="실적 모듈에서 사용 중인 쇼핑몰이 아닙니다(실적 설정에서 사용 OFF 이거나 없는 쇼핑몰) — 결과는 직접 입력">{{ it.market_name }} · 실적 미사용</span>
|
||||
{% elif 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 %}
|
||||
{# 이번주 실적 — data-auto = 실적(서버), % 는 화면이 서버 확정 정량 목표(tr data-target-amount)로 다시 계산(project.js paintMeetWeek) #}
|
||||
<span class="pj-meet-week-slot" data-auto="{{ it.week_auto if it.week_auto is not none else '' }}"{% if it.week_error %} data-err="1"{% endif %} data-name="{{ it.market_name }}">{% if it.week_auto is not none %}<span class="pj-meet-week-auto" title="실적 모듈 {{ it.market_name }} 이번 주({{ week[5:] | replace('-', '/') }}~ 오늘까지) 매출">이번주 실적 {{ won(it.week_auto) }}{% if it.target_amount %} · {{ "%.0f" | format(it.week_auto / it.target_amount * 100) }}%{% endif %}</span>{% elif it.week_error %}<span class="pj-meet-week-auto is-unknown" title="실적 조회 실패">이번주 실적 미확인</span>{% endif %}</span>
|
||||
</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 pj-meet-c-result">
|
||||
{% if p.not_started %}
|
||||
<span class="pj-muted" title="지난 회의록의 주({{ p.period }})가 아직 시작되지 않았습니다">진행 전</span>
|
||||
{% elif p.auto_error %}
|
||||
<span class="pj-meet-unknown" title="실적 모듈 {{ p.market_name }} {{ p.period }} 매출을 읽지 못했습니다 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>
|
||||
{% elif p.auto_result is not none %}
|
||||
<span class="pj-meet-auto" title="실적 모듈 {{ p.market_name }} {{ p.period }} 매출(자동){% if not p.auto_result %} — 0 이면 그 기간 실적이 아직 없습니다(실적 화면 [매출 업데이트]){% endif %}">{{ 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">{% if h.prev_exists %}지난주 회의록에 없는 줄{% else %}지난주({{ prev_week[5:] | replace('-', '/') }}~) 회의록 없음{% endif %}</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 %}
|
||||
<script>window.PJ_MEET_MEMBERS = {{ (meet_members or []) | tojson }};</script>
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
<section class="pj-main">
|
||||
<div class="pj-section-head">
|
||||
<h2>{{ goal_year }}년 목표</h2>
|
||||
<h2 class="pj-goal-title">{{ goal_year }}년 목표</h2>
|
||||
{% if board %}
|
||||
<div class="pj-goal-head-acts">
|
||||
{% if is_admin %}
|
||||
@@ -37,6 +37,31 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if is_admin and goals_enabled and board %}
|
||||
<div class="pj-goal-format" id="pj-goal-format" role="toolbar" aria-label="선택한 글자 서식" hidden>
|
||||
<div class="pj-goal-format-group pj-goal-color-picker">
|
||||
<button type="button" class="pj-goal-format-btn pj-goal-color-toggle" data-goal-format="color" aria-label="글자 색상" title="글자 색상" aria-expanded="false" aria-controls="pj-goal-color-grid" disabled><span class="pj-goal-color-letter" aria-hidden="true">가<span class="pj-goal-color-preview"></span></span><svg class="pj-goal-format-chevron" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><path d="m2 4 3 3 3-3"/></svg></button>
|
||||
<div class="pj-goal-color-grid" id="pj-goal-color-grid" role="group" aria-label="글자 색상 선택" hidden>
|
||||
{% for color in ('#000000', '#4B5563', '#9CA3AF', '#DC2626', '#EA580C', '#CA8A04', '#16A34A', '#0891B2', '#2563EB', '#7C3AED', '#DB2777', '#FFFFFF') %}
|
||||
<button type="button" class="pj-goal-text-swatch" data-goal-color="{{ color }}" style="--swatch: {{ color }}" title="{{ color }}" aria-label="{{ color }}" aria-pressed="false" disabled></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="글자 크기">
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="size-up" aria-label="글자 크기 2px 키우기" title="글자 크기 2px 키우기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 9V2M2 5l3-3 3 3"/></svg></button>
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="size-down" aria-label="글자 크기 2px 줄이기" title="글자 크기 2px 줄이기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 2v7M2 6l3 3 3-3"/></svg></button>
|
||||
<output class="pj-goal-size-value" data-goal-format="size" aria-label="선택한 글자 크기">14px</output>
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="글자 모양">
|
||||
{% for key, label in (('bold', '굵게'), ('italic', '기울임'), ('underline', '밑줄')) %}
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="{{ key }}" aria-label="{{ label }}" title="{{ label }}" aria-pressed="false" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="서식 초기화">
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="reset" aria-label="서식 초기화" title="서식 초기화" disabled><svg class="pj-goal-reset-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16 3 5 5a2 2 0 0 1 0 3L11 21H7l-4-4a2 2 0 0 1 0-3L13 3a2 2 0 0 1 3 0Z"/><path d="m8 9 7 7M11 21h10"/></svg></button>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="pj-view pj-goal-pane" id="pj-goal-pane">
|
||||
{% if not goals_enabled %}
|
||||
<div class="pj-empty">연간 목표가 아직 준비되지 않았습니다(DB 마이그레이션 013 필요).</div>
|
||||
@@ -51,8 +76,10 @@
|
||||
{% else %}
|
||||
{% set sm = board.metrics.sales %}
|
||||
{% set rm = board.metrics.roas %}
|
||||
{# 월 칸은 pj-goal-m + data-h(분기 1~4) — 분기 접기(initGoals)가 이걸로 숨긴다.
|
||||
분기 칸 클래스는 예전 이름 pj-goal-half-col 그대로(연간 칸처럼 굵게·회색 합계) #}
|
||||
{% macro num_cell(metric, kind, labels, mo) -%}
|
||||
<td class="pj-goal-numtd{% if mo == this_month %} is-now{% endif %}">
|
||||
<td class="pj-goal-numtd pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ (mo - 1) // 3 + 1 }}">
|
||||
{%- if is_admin -%}
|
||||
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
|
||||
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
||||
@@ -63,88 +90,112 @@
|
||||
</td>
|
||||
{%- endmacro %}
|
||||
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
|
||||
data-admin="{{ 'true' if is_admin else 'false' }}">
|
||||
data-admin="{{ 'true' if is_admin else 'false' }}"
|
||||
data-halves="{{ 'true' if board.halves else 'false' }}">
|
||||
<thead>
|
||||
<tr>
|
||||
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #}
|
||||
<th class="pj-goal-c1"><span class="pj-goal-colresize" data-col="c1" title="끌어서 너비 조절"></span></th>
|
||||
<th class="pj-goal-c2"><span class="pj-goal-colresize" data-col="c2" title="끌어서 너비 조절"></span></th>
|
||||
<th class="pj-goal-year-col">연간</th>
|
||||
{% for mo in months %}<th class="{% if mo == this_month %}is-now{% endif %}">{{ mo }}월</th>{% endfor %}
|
||||
{# 연간·월·분기 칸도 머리 칸 오른쪽 끝을 끌어 너비 조절(data-col: y · m1~m12 · q1~q4) #}
|
||||
<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 quarters %}
|
||||
{# 월 이름을 누르면 그 달 주간 회의록(/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_q).
|
||||
아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘, 누르면 펼침).
|
||||
분기 색(data-h → --qc)은 머리 위 색 띠(월 가늘게·분기 두껍게)와 분기 열 옅은 음영 #}
|
||||
<th class="pj-goal-half-col pj-goal-fold-th" data-h="{{ h }}" data-col="q{{ h }}">
|
||||
<button type="button" class="pj-goal-fold" data-h="{{ h }}" aria-expanded="true"
|
||||
data-label="{{ hmonths[0] }}~{{ hmonths[-1] }}월"
|
||||
title="{{ hmonths[0] }}~{{ hmonths[-1] }}월 접기"><svg class="pj-goal-fold-ic" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><rect x="1.75" y="1.75" width="12.5" height="12.5" rx="3"/><path d="M5 8h6"/><path class="pj-goal-fold-v" d="M8 5v6"/></svg></button>{{ hname }}
|
||||
<span class="pj-goal-colresize" data-col="q{{ h }}" title="끌어서 너비 조절"></span>
|
||||
</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
{# ── 숫자 지표 ── #}
|
||||
{# ── 숫자 지표 — 연간·분기 칸은 화면에서 계산(매출 합계·달성률, 로아스 매출 가중 평균), 로아스는 % 단위 ── #}
|
||||
<tbody class="pj-goal-kpi">
|
||||
<tr>
|
||||
<th class="pj-goal-c1" rowspan="3">매출</th>
|
||||
<th class="pj-goal-c2">목표</th>
|
||||
<td class="pj-goal-sum" data-metric="sales" data-kind="target"></td>
|
||||
{% for mo in months %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-year-col" data-metric="sales" data-kind="target" data-scope="0"></td>
|
||||
{% for h, hmonths, hm, hname in quarters %}
|
||||
{% for mo in hmonths %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-half-col" data-metric="sales" data-kind="target" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
<tr>
|
||||
<th class="pj-goal-c2">실적</th>
|
||||
<td class="pj-goal-sum" data-metric="sales" data-kind="actual"></td>
|
||||
{% for mo in months %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-year-col" data-metric="sales" data-kind="actual" data-scope="0"></td>
|
||||
{% for h, hmonths, hm, hname in quarters %}
|
||||
{% for mo in hmonths %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-half-col" data-metric="sales" data-kind="actual" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
<tr class="pj-goal-rate-row">
|
||||
<th class="pj-goal-c2">달성</th>
|
||||
<td class="pj-goal-rate" data-month="0"></td>
|
||||
{% for mo in months %}<td class="pj-goal-rate{% if mo == this_month %} is-now{% endif %}" data-month="{{ mo }}"></td>{% endfor %}
|
||||
<td class="pj-goal-rate pj-goal-year-col" data-month="0"></td>
|
||||
{% for h, hmonths, hm, hname in quarters %}
|
||||
{% for mo in hmonths %}<td class="pj-goal-rate pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-month="{{ mo }}"></td>{% endfor %}
|
||||
<td class="pj-goal-rate pj-goal-half-col" data-month="{{ hm }}" data-h="{{ h }}"></td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
<tr>
|
||||
<th class="pj-goal-c1" rowspan="2">로아스</th>
|
||||
<th class="pj-goal-c2">목표</th>
|
||||
<td class="pj-goal-sum pj-goal-sum-na"></td>
|
||||
{% for mo in months %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
|
||||
{# 로아스 연간·분기 = 월 매출로 가중한 평균(광고비 = 매출 ÷ 로아스로 환산) — project.js recompute #}
|
||||
<td class="pj-goal-sum pj-goal-year-col" data-metric="roas" data-kind="target" data-scope="0"></td>
|
||||
{% for h, hmonths, hm, hname in quarters %}
|
||||
{% for mo in hmonths %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-half-col" data-metric="roas" data-kind="target" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
<tr>
|
||||
<th class="pj-goal-c2">실적</th>
|
||||
<td class="pj-goal-sum pj-goal-sum-na"></td>
|
||||
{% for mo in months %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-year-col" data-metric="roas" data-kind="actual" data-scope="0"></td>
|
||||
{% for h, hmonths, hm, hname in quarters %}
|
||||
{% for mo in hmonths %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
|
||||
<td class="pj-goal-sum pj-goal-half-col" data-metric="roas" data-kind="actual" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #}
|
||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(관리자) ── #}
|
||||
{% for area in board.areas %}
|
||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" data-color="{{ area.color }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
||||
{% for row in area.rows %}
|
||||
<tr data-row-id="{{ row.id }}">
|
||||
{% if loop.first %}
|
||||
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
|
||||
<span class="pj-goal-area-text">{{ area.name }}</span>
|
||||
{% if is_admin %}
|
||||
<span class="pj-goal-tools">
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="area-rename" data-name="{{ area.name }}" title="이름 바꾸기">✎</button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="area-color" data-color="{{ area.color }}" title="색 바꾸기"><span class="material-symbols-outlined">palette</span></button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="area-up" title="위로">↑</button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="area-down" title="아래로">↓</button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="row-add" title="줄 추가">+</button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="area-del" data-name="{{ area.name }}" title="영역 삭제">×</button>
|
||||
</span>
|
||||
{% endif %}
|
||||
{# 구역 메뉴(색·위로·아래로·줄 추가·영역 삭제) — 우클릭 또는 ⋮ 버튼(키보드 Tab → Enter/Space, 터치 탭). project.js areaMenuItems #}
|
||||
<span class="pj-goal-area-text"{% if is_admin %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
|
||||
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
|
||||
aria-label="{{ area.name }} 구역 메뉴" title="구역 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||
</th>
|
||||
{% endif %}
|
||||
<th class="pj-goal-c2 pj-goal-row-label">
|
||||
<span class="pj-goal-row-text">{{ row.label }}</span>
|
||||
{% if is_admin %}
|
||||
<span class="pj-goal-tools">
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="row-rename" data-label="{{ row.label }}" title="줄 이름 바꾸기">✎</button>
|
||||
{% if area.rows | length > 1 %}
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="row-up" title="위로">↑</button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="row-down" title="아래로">↓</button>
|
||||
<button type="button" class="pj-icon-btn" data-goal-act="row-del" data-label="{{ row.label }}" title="줄 삭제">×</button>
|
||||
{% endif %}
|
||||
</span>
|
||||
{% endif %}
|
||||
{# 항목 칸(2열) — 같은 항목 칸으로 묶인 줄(016 label_cont)은 묶음 첫 줄이 rowspan 으로 덮는다 #}
|
||||
{% if not row.label_cont %}
|
||||
<th class="pj-goal-c2 pj-goal-row-label"{% if (row.label_span or 1) > 1 %} rowspan="{{ row.label_span }}"{% endif %} data-label-span="{{ row.label_span or 1 }}">
|
||||
<span class="pj-goal-row-text"{% if is_admin %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
|
||||
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
|
||||
aria-label="{{ (row.label or '이름 없는') }} 줄 메뉴" title="줄 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||
</th>
|
||||
{% for mo in [0] + months %}
|
||||
<td class="pj-goal-texttd{% if mo == 0 %} pj-goal-year-col{% endif %}{% if mo == this_month %} is-now{% endif %}">
|
||||
{%- if is_admin -%}
|
||||
<textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ mo }}"
|
||||
placeholder="{{ '연간 목표' if mo == 0 else '' }}">{{ row.cells.get(mo, '') }}</textarea>
|
||||
{% endif %}
|
||||
{# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #}
|
||||
{% for c in row.layout %}
|
||||
{% set editable = is_admin and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
|
||||
{% set merged = c.span > 1 or c.rspan > 1 %}
|
||||
<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 %}"
|
||||
{% if c.kind in ('month', 'quarter') %}data-h="{{ c.h }}" {% endif %}data-month="{{ c.m }}" data-span="{{ c.span }}" data-rspan="{{ c.rspan }}"
|
||||
{%- if c.span > 1 %} colspan="{{ c.span }}" style="--span: {{ c.span }}"{% endif %}{% if c.rspan > 1 %} rowspan="{{ c.rspan }}"{% endif %}>
|
||||
{%- if editable -%}
|
||||
<div class="pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="목표 내용"
|
||||
data-row="{{ row.id }}" data-month="{{ c.m }}"
|
||||
data-placeholder="{{ '연간 목표' if c.m == 0 else ((c.h ~ '분기 목표') if c.kind == 'quarter' else '') }}">{{ c.html|safe }}</div>
|
||||
{%- else -%}
|
||||
<div class="pj-goal-text-ro">{{ row.cells.get(mo, '') }}</div>
|
||||
<div class="pj-goal-text-ro">{{ c.html|safe }}</div>
|
||||
{%- endif -%}
|
||||
</td>
|
||||
{% endfor %}
|
||||
@@ -156,7 +207,10 @@
|
||||
{% if is_admin %}
|
||||
<div class="pj-goal-foot">
|
||||
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다.</span>
|
||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 글자를 드래그해 선택하면 선택한 셀 상단에서 12색 견본·크기 2px 증감·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다. 모든 행의 셀 오른쪽 경계를 끌어 열 너비를 조절하고, 더블클릭하면 그 열의 가장 긴 문단에 맞춥니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
|
||||
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함). 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 끌면 내용과 서식이 함께 이동합니다(대상에 글이 있으면 덮어쓰기 확인, Esc로 취소).
|
||||
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
|
||||
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
@@ -169,5 +223,6 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
<script src="/static/project-goal-text.js?v=20261003c" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
{% block content %}
|
||||
{# ── 프로젝트 관리 도움말 — 처음 쓰는 사람을 위한 기능 안내(정적 페이지, DB 불필요).
|
||||
기능이 바뀌면 이 페이지도 같이 고친다(docs/PROJECT_MODULE.md 와 짝). ── #}
|
||||
<div class="pjh">
|
||||
<div class="pjh" id="top">
|
||||
<nav class="pjh-toc" aria-label="도움말 목차">
|
||||
<p class="pjh-toc-title">목차</p>
|
||||
<ol>
|
||||
@@ -34,13 +34,29 @@
|
||||
<li><a href="#inbox">수신함과 알림</a></li>
|
||||
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
||||
<li><a href="#trash">휴지통 (관리자)</a></li>
|
||||
<li><a href="#goals">연간 목표</a></li>
|
||||
<li><a href="#meetings">주간 회의록</a></li>
|
||||
<li><a href="#tips">단축키와 자주 묻는 질문</a></li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
<div class="pjh-body">
|
||||
<div class="pjh-search" id="pjh-search" hidden>
|
||||
<form id="pjh-search-form" role="search" aria-label="도움말 검색">
|
||||
<label for="pjh-query">도움말 검색</label>
|
||||
<div class="pjh-search-field">
|
||||
<input type="search" id="pjh-query" name="q" placeholder="예: 회의록, 셀 병합, 쇼핑몰 연결" autocomplete="off"
|
||||
aria-describedby="pjh-search-hint pjh-search-status" aria-controls="pjh-results" />
|
||||
<button type="submit">검색</button>
|
||||
<button type="button" id="pjh-search-clear" hidden>지우기</button>
|
||||
</div>
|
||||
<p class="pjh-search-hint" id="pjh-search-hint">한 글자부터 제목·본문을 검색합니다. 결과를 누르면 해당 설명으로 바로 이동합니다. 여러 단어는 띄어 쓰세요.</p>
|
||||
</form>
|
||||
<p class="pjh-search-status" id="pjh-search-status" role="status" aria-live="polite" aria-atomic="true"></p>
|
||||
<ol class="pjh-results" id="pjh-results" aria-label="도움말 검색 결과" hidden></ol>
|
||||
</div>
|
||||
<!-- 머리말 + 빠른 시작 -->
|
||||
<header class="pjh-hero" id="top">
|
||||
<header class="pjh-hero">
|
||||
<h1>프로젝트 관리 도움말</h1>
|
||||
<p>프로젝트 관리는 <b>아사나(Asana) 방식</b>으로 팀의 일을 정리하는 도구입니다.
|
||||
프로젝트 안에 할 일(작업)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
||||
@@ -52,6 +68,7 @@
|
||||
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
||||
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
||||
</div>
|
||||
<p class="pjh-quick-links">계획과 회의를 준비한다면 <a href="#goals">연간 목표</a> · <a href="#meetings">주간 회의록</a> 설명부터 읽어 보세요.</p>
|
||||
</header>
|
||||
|
||||
<!-- 1. 용어 -->
|
||||
@@ -78,7 +95,7 @@
|
||||
<section class="pjh-sec" id="layout">
|
||||
<h2><span class="pjh-num">2</span>화면 구성</h2>
|
||||
<div class="pjh-map" aria-hidden="true">
|
||||
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말</span></div>
|
||||
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
|
||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>오른쪽 위: 범위(이 프로젝트 / 전체 프로젝트)<br>필터 바<br>작업들</div>
|
||||
</div>
|
||||
@@ -88,11 +105,9 @@
|
||||
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
||||
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||
<li><b>목표</b> — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 —
|
||||
맨 위에 <b>매출</b>(목표·실적·달성률)과 <b>로아스</b>(목표·실적)를 달마다, 그 아래에 <b>업무 영역</b>(상품·마케팅·컨텐츠·유통 등)별로
|
||||
연간·월별 계획을 적습니다. 매출의 <b>연간</b> 칸은 월 합계, <b>달성</b>은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다.
|
||||
<b>입력은 관리자만</b> 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 <b>+ 연도 추가</b>로 새해 목표를
|
||||
만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역 이름 칸에 마우스를 올려 이름·색·순서·줄 추가·삭제를 합니다.</li>
|
||||
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
|
||||
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
|
||||
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
|
||||
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
||||
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
||||
</ul>
|
||||
@@ -101,6 +116,8 @@
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 폰트를 고르고 미리 본 뒤 <span class="pjh-ui">저장</span>을 누르면 Project 화면에 적용되고 창이 닫힙니다.
|
||||
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||
</ul>
|
||||
<h3>프로젝트 제목</h3>
|
||||
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버·관리자만)</p>
|
||||
@@ -114,16 +131,17 @@
|
||||
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.</p>
|
||||
<table class="pjh-table">
|
||||
<tr><th>할 수 있는 일</th><th>누가</th></tr>
|
||||
<tr><td>프로젝트 보기</td><td>그 프로젝트의 <b>멤버</b>(또는 관리자). 멤버가 아니면 주소를 알아도 열리지 않습니다.</td></tr>
|
||||
<tr><td>작업·하위 작업·댓글</td><td>그 프로젝트 멤버 누구나 만들고 고칠 수 있습니다.</td></tr>
|
||||
<tr><td>프로젝트 보기</td><td>그 프로젝트의 <b>멤버·소유자</b>(또는 관리자). 멤버가 아니면 주소를 알아도 열리지 않습니다.</td></tr>
|
||||
<tr><td>작업·하위 작업·댓글</td><td>그 프로젝트의 멤버·소유자·관리자가 만들고 고칠 수 있습니다.</td></tr>
|
||||
<tr><td>작업·섹션·프로젝트 삭제</td><td><b>만든 사람만</b> 지울 수 있습니다(최고 관리자는 예외).</td></tr>
|
||||
<tr><td>댓글 고치기·지우기</td><td>댓글을 쓴 사람(또는 관리자)만.</td></tr>
|
||||
<tr><td>새 프로젝트, 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
|
||||
<tr><td>새 프로젝트, 사이드바의 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
|
||||
<tr><td>멤버 배정·제외, 프로젝트 소유자 바꾸기</td><td>관리자</td></tr>
|
||||
<tr><td>다른 프로젝트에서 연결돼 온 작업</td><td>원래 프로젝트 멤버가 아니면 <b>읽기만</b> — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다).</td></tr>
|
||||
<tr><td>멤버에서 빠졌을 때</td><td>그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다.</td></tr>
|
||||
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
|
||||
<tr><td>목표 보기</td><td>누구나 · <b>목표 입력·연도 추가·업무 영역 편집</b>은 관리자</td></tr>
|
||||
<tr><td>목표·주간 회의록 보기</td><td>프로젝트 관리 권한이 있는 직원 누구나 · <b>입력·생성·삭제·구조 편집</b>은 관리자</td></tr>
|
||||
<tr><td>프로젝트 제목 바로 고치기</td><td>그 프로젝트 멤버·소유자·관리자</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
@@ -200,6 +218,7 @@
|
||||
<p class="pjh-lead">보드는 섹션(세로 칸)이 옆으로 늘어선 화면입니다. 섹션이 많으면 가로로 스크롤되고, 한 섹션에 카드가 많으면 그 섹션 안에서만 세로로 스크롤됩니다.</p>
|
||||
<h3>섹션 다루기</h3>
|
||||
<ul>
|
||||
<li><b>그룹 축소</b> — 섹션 머리의 왼쪽 화살표를 누르면 카드가 숨겨지고 제목·작업 수가 세로로 표시됩니다. 반대 방향 화살표를 누르면 펼쳐집니다. 축소 상태는 내 브라우저에 기억됩니다.</li>
|
||||
<li><b>섹션 추가</b> — 마지막 섹션 바로 오른쪽의 <span class="pjh-ui">+ 섹션 추가</span>.</li>
|
||||
<li><b>이름 바꾸기</b> — 섹션 이름을 누르면 그 자리에서 고칩니다. <kbd>Enter</kbd> 저장, <kbd>Esc</kbd> 취소.</li>
|
||||
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
||||
@@ -217,8 +236,10 @@
|
||||
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 작업을 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
||||
<h3>작업 카드 다루기</h3>
|
||||
<ul>
|
||||
<li><b>작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span> 또는 섹션 맨 아래 <span class="pjh-ui">+ 작업 추가</span>. 오른쪽에 작업 편집 창이 열립니다.</li>
|
||||
<li><b>상단 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||
<li><b>하단 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||
<li><b>열기</b> — 카드를 누르면 오른쪽에 작업 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
||||
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 작업은 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 작업은 상태만 표시합니다.</li>
|
||||
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
||||
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.</li>
|
||||
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 작업 링크 복사 · 완료로 표시 · 삭제</span></li>
|
||||
@@ -242,6 +263,7 @@
|
||||
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
||||
<li><b>열기</b> — 줄을 누르면 그 하위 작업이 작업처럼 편집 창으로 열립니다.</li>
|
||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 하위 작업 삭제</span></li>
|
||||
<li><b>순서 바꾸기</b> — 펼친 하위 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||
<li><b>다른 작업으로 옮기기</b> — 하위 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 하위 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||
</ul>
|
||||
<h3>+ 하위 작업 추가</h3>
|
||||
@@ -301,7 +323,7 @@
|
||||
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
||||
<li><span class="pjh-ui">다른 프로젝트에 추가</span>를 누릅니다. 빼려면 이름 옆 <span class="pjh-ui">×</span>(연결 해제).</li>
|
||||
</ol>
|
||||
<p>작업은 하나라서 어느 보드에서 고쳐도 모두 같이 바뀝니다.</p>
|
||||
<p>작업은 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 작업의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.</p>
|
||||
<h3>댓글</h3>
|
||||
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
|
||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||
@@ -409,7 +431,7 @@
|
||||
<h3>댓글 대화창</h3>
|
||||
<p>카드·목록·캘린더·내 작업에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
||||
<ul>
|
||||
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>.</li>
|
||||
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>. <kbd>Shift</kbd>+<kbd>Enter</kbd>로 줄바꿈합니다. 입력칸은 높이 70px로 고정되며 긴 글은 칸 안에서 스크롤됩니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">attach_file</span></span>로 파일을 붙이거나, 캡처한 이미지를 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여 넣습니다. 이미지는 작은 그림으로 보입니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 작업 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
||||
<li>웹 주소를 붙여 넣으면 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||
@@ -463,7 +485,7 @@
|
||||
<ul>
|
||||
<li>작업 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">작업 링크 복사</span>로 주소를 복사합니다.</li>
|
||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 하위 작업 링크는 하위 작업 자체가 열립니다.</li>
|
||||
<li>그 프로젝트의 <b>멤버만</b> 열 수 있어 밖으로 새지 않습니다.</li>
|
||||
<li>현재 그 작업을 볼 수 있는 멤버·소유자·관리자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -480,13 +502,161 @@
|
||||
<div>하위 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
|
||||
</section>
|
||||
|
||||
<!-- 20. 단축키와 FAQ -->
|
||||
<!-- 20. 연간 목표 -->
|
||||
<section class="pjh-sec" id="goals">
|
||||
<h2><span class="pjh-num">20</span>연간 목표</h2>
|
||||
<p class="pjh-lead">한 해의 매출 목표·실적과 업무 계획을 한 표에서 관리합니다. 숫자는 위쪽 지표에, 실행 계획은 아래쪽 업무 영역에 적습니다. 프로젝트 관리 권한이 있는 직원은 볼 수 있고, 입력·구조 변경은 관리자만 할 수 있습니다.</p>
|
||||
|
||||
<h3 id="goals-start">목표 열기와 연도 만들기</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>왼쪽 사이드바 <span class="pjh-ui">목표</span>를 눌러 연도 목록을 펼친 뒤 원하는 연도를 누릅니다. 올해는 목표가 아직 없어도 목록에 보입니다.</li>
|
||||
<li>관리자는 빈 연도 화면에서 <span class="pjh-ui">해당 연도 목표 만들기</span>, 또는 사이드바의 <span class="pjh-ui">+ 연도 추가</span>로 새 표를 만듭니다.</li>
|
||||
<li>가장 가까운 이전 연도의 업무 영역·줄 구성을 가져옵니다. 이전 연도가 없으면 다음 연도의 구성을 사용하고, 처음이면 상품·마케팅·컨텐츠·유통으로 시작합니다. 이전 숫자와 계획 글은 복사하지 않습니다.</li>
|
||||
<li>위쪽 <span class="pjh-ui">매출 단위</span>를 확인한 뒤 월별 숫자와 계획을 입력합니다.</li>
|
||||
</ol>
|
||||
|
||||
<h3 id="goals-metrics">매출·로아스 입력과 달성률 계산</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>칸</th><th>입력·계산 방법</th></tr>
|
||||
<tr><td>매출 목표·실적</td><td>관리자가 월별 숫자를 직접 입력합니다. 목표 표의 실적은 회의록의 자동 매출과 별도로 관리하므로 실적 모듈에서 자동으로 채워지지 않습니다.</td></tr>
|
||||
<tr><td>매출 단위</td><td>예를 들어 단위가 <b>백만원</b>이면 30은 30,000,000원입니다. 단위를 바꿔도 이미 적은 숫자는 자동 환산되지 않으므로 숫자와 단위를 함께 확인하세요.</td></tr>
|
||||
<tr><td>연간·분기 매출</td><td>해당 기간에 입력한 월 숫자의 합계입니다. 합계 칸에 따로 입력하지 않습니다.</td></tr>
|
||||
<tr><td>달성</td><td>실적 ÷ 목표 × 100입니다. 월별로 계산하며, 연간·분기는 <b>기간 전체 목표 합계</b> 대비 입력된 실적 합계로 계산합니다. 목표가 없거나 0이면 달성률을 표시하지 않습니다. 100% 이상은 초록으로 표시됩니다.</td></tr>
|
||||
<tr><td>로아스(ROAS)</td><td>광고비 대비 매출 비율을 <b>% 단위</b>로 적습니다. 예: 300은 300%입니다. 연간·분기는 월 매출과 ROAS로 환산한 광고비를 합쳐 계산하고, 필요한 월 매출이 빠져 있으면 입력된 ROAS의 단순 평균을 사용합니다.</td></tr>
|
||||
</table>
|
||||
<p>숫자는 <kbd>Enter</kbd> 또는 칸을 떠날 때 저장됩니다. 숫자 칸을 비우면 값을 지우며, <kbd>Esc</kbd>를 누르면 마지막 저장값으로 돌아갑니다.</p>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>1~3월 목표가 각각 100이고 1월 실적만 50이면 1분기 달성은 50 ÷ 300 = 약 16.7%입니다. 아직 실적을 넣지 않은 달의 목표도 분기 목표 합계에 포함됩니다.</div></div>
|
||||
|
||||
<h3 id="goals-plan">업무 영역·항목·연간·분기·월 계획</h3>
|
||||
<p>업무 영역은 상품·마케팅처럼 큰 분류, 항목은 그 안의 세부 주제입니다. 한 항목의 연간 칸에는 큰 방향, 분기 칸에는 중간 목표, 월 칸에는 구체적인 실행 계획을 적으면 주간 회의에서 확인하기 쉽습니다.</p>
|
||||
<ul>
|
||||
<li><span class="pjh-ui">+ 업무 영역 추가</span>를 누르면 새 영역이 생기고 이름을 바로 고칠 수 있습니다.</li>
|
||||
<li>영역·항목 이름을 클릭해 고칩니다. <kbd>Enter</kbd>는 저장, <kbd>Esc</kbd>는 취소입니다.</li>
|
||||
<li>이름 칸을 우클릭하거나 <span class="pjh-ui">⋮</span>를 누르면 영역 색·위아래 순서·줄 추가·삭제 메뉴가 나옵니다. 항목 메뉴에서는 해당 줄 위·아래에 줄을 추가할 수 있습니다. 영역의 마지막 줄은 지울 수 없습니다.</li>
|
||||
<li>연간 글 칸에서 우클릭해 줄을 추가하면 같은 항목 이름 아래에 여러 줄로 나눠 계획을 적을 수 있습니다.</li>
|
||||
<li>키보드는 <kbd>Tab</kbd>으로 이름이나 ⋮ 버튼에 이동해 <kbd>Enter</kbd>로 열고, 메뉴에서 <kbd>↑</kbd><kbd>↓</kbd>·<kbd>Enter</kbd>로 선택합니다. <kbd>Esc</kbd>로 닫습니다. 터치 화면에서는 ⋮를 누릅니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="goals-format">글자 서식 바꾸기</h3>
|
||||
<p>글 칸에서 글자를 드래그해 선택하면 해당 셀 상단에 서식 도구가 나타납니다. <b>선택한 글자에만</b> 12색 견본·크기·굵게·기울임·밑줄을 적용합니다. 크기 버튼은 2px씩 조절하며 범위는 10~32px입니다.</p>
|
||||
<p>굵게·기울임·밑줄은 다시 누르면 해제됩니다. <span class="pjh-ui">서식 초기화</span>는 선택한 글자의 서식만 되돌리고 내용은 유지합니다. 글과 서식은 입력을 약 0.8초 멈추거나 칸을 떠날 때 자동 저장됩니다.</p>
|
||||
|
||||
<h3 id="goals-table">분기 접기·열 너비·행 높이</h3>
|
||||
<ul>
|
||||
<li>열은 연간 → 1~3월 → 1분기 → 4~6월 → 2분기 → 7~9월 → 3분기 → 10~12월 → 4분기 순서입니다. <b>분기 머리 칸</b>을 누르면 해당 월 3개가 접힙니다. 네모 안 <b>−</b>는 접기, <b>+</b>는 펼치기입니다.</li>
|
||||
<li>어느 행에서든 셀의 <b>오른쪽 경계</b>를 끌어 열 너비를 조절합니다. 경계를 더블클릭하면 가장 긴 문단에 맞춥니다. 직접 넣은 줄바꿈·글자 크기·굵기도 반영합니다.</li>
|
||||
<li>셀 우클릭의 <span class="pjh-ui">현재 열 너비 자동 맞춤</span>·<span class="pjh-ui">전체 열 너비 자동 맞춤</span>도 사용할 수 있습니다. 전체 맞춤은 접힌 월 열까지 포함합니다. 병합 칸은 다른 열을 유지하며 오른쪽 끝 열 너비를 조절합니다.</li>
|
||||
<li>접힘·열 너비는 내 브라우저에 기억됩니다. 행 높이는 가장 높은 글 칸에 맞춰 늘고, 글이 줄면 함께 줄어듭니다. 글은 상단 정렬입니다.</li>
|
||||
<li>가로 스크롤에서는 구분·항목·연간 칸이, 세로 스크롤에서는 머리와 매출·로아스 지표가 고정됩니다.</li>
|
||||
<li><b>월 이름</b>을 누르면 그 달의 <a href="#meetings">주간 회의록</a>으로 이동합니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="goals-merge">셀 병합·병합 해제·내용 이동</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>관리자는 업무 영역의 글 칸을 마우스로 끌어 여러 칸을 선택한 뒤 우클릭 → <span class="pjh-ui">셀 병합</span>을 누릅니다.</li>
|
||||
<li>가로 병합은 <b>같은 분기의 월 칸끼리</b> 가능합니다. 연간·분기 칸은 세로로만 병합합니다. 선택한 칸들의 글은 순서대로 첫 칸에 모입니다.</li>
|
||||
<li>병합된 칸을 우클릭 → <span class="pjh-ui">병합 해제</span>하면 다시 나뉩니다. 글은 왼쪽 위 칸에 남습니다.</li>
|
||||
<li>글 칸 하나를 클릭한 뒤 <b>위·아래·왼쪽 테두리</b>를 잡아 다른 글 칸으로 끌면 내용과 글자 서식이 함께 이동합니다. 오른쪽 경계는 너비 조절용입니다. 대상에 글이 있으면 덮어쓰기를 확인하고, <kbd>Esc</kbd>로 이동을 취소합니다.</li>
|
||||
</ol>
|
||||
|
||||
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
|
||||
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합, 내용 이동을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
|
||||
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
|
||||
<p>관리자의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 21. 주간 회의록 -->
|
||||
<section class="pjh-sec" id="meetings">
|
||||
<h2><span class="pjh-num">21</span>주간 회의록</h2>
|
||||
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 할 일과 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 직원은 조회할 수 있고, 생성·입력·삭제는 관리자만 할 수 있습니다.</p>
|
||||
|
||||
<h3 id="meetings-week">회의록 열기와 주차 기준</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>왼쪽 <span class="pjh-ui">목표</span>에서 연도를 선택하고 표 머리의 <b>월 이름</b>을 누릅니다.</li>
|
||||
<li>위쪽 주차 탭 또는 오른쪽 작은 달력의 주 한 줄을 눌러 주를 고릅니다. 점은 회의록이 있는 주, <span class="pjh-ui">이번 주</span>는 현재 주입니다. 이전·다음 달 버튼으로 달을 바꿉니다.</li>
|
||||
<li>한 주는 <b>월요일~일요일</b>이고, 월요일이 속한 달의 회의록입니다. 1주차는 그 달 첫 월요일이 있는 주입니다. 예: 2026년 10월 1주차는 10/5~10/11이며, 9/28~10/4는 9월 회의록입니다.</li>
|
||||
<li>작은 달력의 흐린 앞 달 주를 누르면 그 달 회의록으로 갑니다. <span class="pjh-ui">해당 연도 목표</span> 버튼은 연간 목표 표로 돌아갑니다.</li>
|
||||
</ol>
|
||||
|
||||
<h3 id="meetings-create">회의록 만들기와 이어받는 항목</h3>
|
||||
<p>선택한 주에 회의록이 없으면 관리자에게 <span class="pjh-ui">해당 주차 회의록 만들기</span>가 보입니다. 화면을 열기만 해서는 회의록이 만들어지지 않습니다.</p>
|
||||
<ul>
|
||||
<li>줄이 있는 가장 가까운 앞선 회의록에서 <b>구역·항목 이름·색·쇼핑몰 연결·순서</b>를 이어받습니다. 앞선 회의록이 없으면 가장 가까운 다음 회의록의 구성을 가져옵니다.</li>
|
||||
<li>어느 쪽에도 회의록이 없으면 해당 연도 목표 표의 업무 영역과 기본 양식으로 시작합니다.</li>
|
||||
<li>이번주 할 일·금액·메모는 새로 적습니다. 구성을 이어받는 것과 <b>지난주 리뷰</b>는 다릅니다. 리뷰에는 정확히 7일 전 주의 같은 항목만 표시됩니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
|
||||
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
||||
|
||||
<h3 id="meetings-kpis">월 목표·누적·주당 필요 매출 읽기</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>지표</th><th>뜻과 출처</th></tr>
|
||||
<tr><td>월 목표 매출·목표 ROAS</td><td>연간 목표 표의 해당 월 숫자입니다. 매출 단위가 원·천원·만원·십만원·백만원·천만원·억원이면 원으로 환산합니다. 모르는 단위는 원 환산을 못 하므로 주당 필요 매출도 계산하지 못합니다.</td></tr>
|
||||
<tr><td>월 누적 실적(지난주까지)</td><td>실적 모듈의 매출 집계 쇼핑몰 매출을 <b>그 달 1일부터 선택한 주의 직전 일요일까지</b> 합칩니다. 현재 날짜·월말을 넘기지 않습니다. 이번주 매출은 이 누적에 포함하지 않습니다.</td></tr>
|
||||
<tr><td>주당 필요</td><td>(월 목표 매출 − 월 누적 실적) ÷ <b>이번주를 포함한 그 달 남은 주 수</b>입니다. 원 단위 정수로 계산하고, 이미 월 목표를 달성했다면 0원입니다.</td></tr>
|
||||
<tr><td>전주 목표</td><td>정확히 7일 전 회의록에 적은 금주 목표입니다. 그 주 회의록이 없으면 비어 있습니다.</td></tr>
|
||||
<tr><td>전주 결과·달성률</td><td>실적 모듈의 전주 월~일 매출과 그 값 ÷ 전주 목표 × 100입니다. 전주 결과는 매출 자료이므로 전주 회의록이 없어도 조회될 수 있습니다. 목표가 없거나 0이면 달성률은 없습니다.</td></tr>
|
||||
<tr><td>금주 목표·현재 실적</td><td>금주 목표는 관리자가 정하는 원 단위 금액입니다. 현재 실적은 선택한 주 월요일부터 일요일 또는 오늘 중 이른 날까지의 매출입니다. 아직 시작하지 않은 미래 주의 실적은 비어 있습니다.</td></tr>
|
||||
</table>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>월 목표가 1억원이고 지난주까지 누적이 4천만원, 남은 주가 이번주 포함 3주이면 주당 필요는 2천만원입니다. 이 숫자는 계획 참고값이며 금주 목표로 자동 저장되지는 않습니다.</div></div>
|
||||
<p>월 목표·누적은 달의 1일~말일 기준이고, 주간 결과는 월요일~일요일 기준입니다. 달을 넘는 마지막 주의 주간 결과에는 다음 달 날짜가 포함될 수 있습니다.</p>
|
||||
|
||||
<h3 id="meetings-edit">이번주 할 일·정량 목표·참석자·메모 입력</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li><b>금주 목표</b>에 전체 매출 목표를 적습니다. 줄별 <b>정량 목표</b>는 각 항목의 목표 금액이며, 현재는 원 단위입니다. 금주 목표와 줄별 목표 합계는 자동으로 맞춰지지 않습니다.</li>
|
||||
<li>각 항목의 <b>이번주 할 일 · 행사</b>에 실행할 일과 일정을 적습니다.</li>
|
||||
<li><span class="pjh-ui">참석자</span>를 눌러 프로젝트 관리 권한이 있는 등록 직원 중 선택합니다. 찾기·전원 선택·모두 해제를 사용할 수 있으며, 칩의 <span class="pjh-ui">×</span>로 참석자를 뺍니다.</li>
|
||||
<li>아래 <b>결정 사항 · 메모</b>에 회의 결론과 다음주까지 확인할 일을 적습니다.</li>
|
||||
</ol>
|
||||
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자·평가는 바꾸는 즉시 저장됩니다.</p>
|
||||
|
||||
<h3 id="meetings-review">지난주 리뷰·결과·평가</h3>
|
||||
<p>지난주 할 일과 목표는 <b>정확히 7일 전 주의 같은 항목</b>에서 가져옵니다. 이름 변경·순서 이동·회의록 생성 순서와 관계없이 이어진 같은 줄을 찾습니다. 그 주 회의록이 없으면 “회의록 없음”, 회의록은 있지만 항목이 없으면 “지난주 회의록에 없는 줄”로 표시합니다. 몇 주 전 기록을 지난주로 대신 보여 주지 않습니다.</p>
|
||||
<ul>
|
||||
<li><b>결과</b> — 쇼핑몰 연결 항목은 해당 쇼핑몰의 전주 매출이 자동 표시됩니다. 연결하지 않은 항목은 관리자가 결과 금액을 직접 입력합니다.</li>
|
||||
<li><b>달성률</b> — 결과 ÷ 지난주 정량 목표 × 100입니다. 목표가 없거나 0이면 계산하지 않으며, 100% 이상은 초록으로 표시됩니다.</li>
|
||||
<li><b>평가</b> — <span class="pjh-ui">— · 완료 · 일부 · 미달</span> 중 선택합니다. 달성률과 별개로 회의에서 판단해 정합니다.</li>
|
||||
<li><b>저장 위치</b> — 이번 화면에서 입력한 지난주 결과·평가는 <b>지난주 회의록의 줄</b>에 저장됩니다. 이번주 할 일·정량 목표는 이번주 회의록에 저장됩니다.</li>
|
||||
<li><span class="pjh-ui">순서 바꾸기</span>는 이번주와 지난주 리뷰의 좌우 배치만 바꿉니다. 선택은 로그인한 사람별로 내 브라우저에 기억됩니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-markets">쇼핑몰 연결·자동 실적·매출 갱신</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>항목을 우클릭하거나 <span class="pjh-ui">⋯</span> → <span class="pjh-ui">쇼핑몰 연결(결과 자동)…</span>에서 실적 모듈의 사용 중인 쇼핑몰을 고릅니다. 자동 결과를 쓰지 않으려면 <span class="pjh-ui">연결 안 함</span>을 선택합니다.</li>
|
||||
<li>연결된 항목의 정량 목표 아래에 이번주 실적과 목표 대비 비율이 나옵니다. 지난주 리뷰의 자동 결과는 <b>지난주 항목의 쇼핑몰 연결</b>을 기준으로 계산합니다. 이번주 연결을 바꿔도 지난주 연결은 바뀌지 않습니다.</li>
|
||||
<li>유통 구역은 항목 이름으로 일부 쇼핑몰을 추측해 연결하므로 생성 후 연결 배지를 확인하세요. 마케팅의 “네이버” 같은 광고 항목은 자동 연결하지 않습니다.</li>
|
||||
</ol>
|
||||
<p>실적 갱신 권한이 있으면 주차를 열 때 지난주부터 선택한 주의 오늘까지 매출을 자동 갱신합니다. 같은 주의 자동 갱신은 브라우저에서 10분 간격으로 제한하며, 성공 시에는 별도 큰 안내 없이 숫자가 바뀝니다. 실패·일부 쇼핑몰 실패 시 작은 안내와 <span class="pjh-ui">다시 시도</span>가 나옵니다. 마지막 갱신 성공 시각은 실적 모듈 기록이며 숫자에 마우스를 올려 확인할 수 있습니다.</p>
|
||||
<table class="pjh-table">
|
||||
<tr><th>표시·상태</th><th>확인할 내용</th></tr>
|
||||
<tr><td>미확인</td><td>조회에 실패해 값을 알 수 없습니다. <b>0원과 다릅니다.</b> 이에 의존하는 달성률·주당 필요 매출도 계산하지 않습니다. 안내의 다시 시도를 사용하거나 실적 연결 상태를 확인하세요.</td></tr>
|
||||
<tr><td>0원</td><td>매출 조회는 성공했지만 해당 기간에 저장된 실적이 없거나 합계가 0원입니다. 필요하면 실적 화면에서 매출 자료를 갱신하세요.</td></tr>
|
||||
<tr><td>실적 미사용</td><td>연결 쇼핑몰이 사용 중이 아니거나 목록에 없습니다. 해당 항목의 결과는 직접 입력합니다.</td></tr>
|
||||
<tr><td>실적 미연결·집계 대상 없음</td><td>자동 실적·누적이 비어 있습니다. 회의록 계획·메모는 계속 입력할 수 있습니다.</td></tr>
|
||||
<tr><td>실적 갱신 권한 없음</td><td>새 매출을 요청하지 않고 저장된 실적을 보여 줍니다. 회의록 조회 권한과 매출 갱신 권한은 별개입니다.</td></tr>
|
||||
</table>
|
||||
|
||||
<h3 id="meetings-rows">구역·줄 추가·순서·삭제</h3>
|
||||
<ul>
|
||||
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
|
||||
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
|
||||
<li>줄을 삭제하면 이번주 할 일·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
|
||||
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 금주 목표를 저장하거나 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동·쇼핑몰 연결 같은 작업에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
|
||||
<p>관리자의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 22. 단축키와 FAQ -->
|
||||
<section class="pjh-sec" id="tips">
|
||||
<h2><span class="pjh-num">20</span>단축키와 자주 묻는 질문</h2>
|
||||
<h2><span class="pjh-num">22</span>단축키와 자주 묻는 질문</h2>
|
||||
<h3>단축키</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>키</th><th>하는 일</th></tr>
|
||||
<tr><td><kbd>/</kbd></td><td>전체 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||
<tr><td><kbd>/</kbd></td><td>작업 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||
<tr><td><kbd>Esc</kbd></td><td>작업 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
||||
<tr><td><kbd>Enter</kbd></td><td>하위 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
||||
@@ -500,26 +670,14 @@
|
||||
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
||||
<p><b>Q. 하위 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>하위 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
|
||||
<p><b>Q. 작업을 두 프로젝트에 같이 두고 싶어요.</b><br>작업 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
|
||||
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 정확히 7일 전 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
||||
<p><b>Q. 도움말에서 필요한 설명을 빠르게 찾고 싶어요.</b><br>이 페이지 위쪽 검색창에 단어를 입력하고 결과를 누르세요. 제목·본문의 일치 단어가 강조되고 해당 소제목으로 이동합니다. <kbd>Enter</kbd>는 첫 결과로 이동, <kbd>Esc</kbd>나 <span class="pjh-ui">지우기</span>는 검색을 초기화합니다.</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a class="pjh-top" href="#top" title="맨 위로" aria-label="맨 위로"><span class="material-symbols-outlined">arrow_upward</span></a>
|
||||
|
||||
<script>
|
||||
// 목차 — 지금 읽고 있는 장을 강조한다(스크롤 위치 기준).
|
||||
(function () {
|
||||
var links = Array.prototype.slice.call(document.querySelectorAll(".pjh-toc a"));
|
||||
var secs = links.map(function (a) { return document.querySelector(a.getAttribute("href")); });
|
||||
if (!("IntersectionObserver" in window)) return;
|
||||
var io = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (en) {
|
||||
if (!en.isIntersecting) return;
|
||||
var i = secs.indexOf(en.target);
|
||||
links.forEach(function (a, k) { a.classList.toggle("is-active", k === i); });
|
||||
});
|
||||
}, { rootMargin: "-10% 0px -75% 0px" });
|
||||
secs.forEach(function (s) { if (s) io.observe(s); });
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project-help.js?v=20261003a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -104,5 +104,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -84,7 +84,7 @@
|
||||
<span class="material-symbols-outlined">attach_file</span>
|
||||
<input type="file" id="pj-cm-file-input" multiple hidden />
|
||||
</label>
|
||||
<input type="text" id="pj-cm-input" placeholder="댓글 입력… (이미지는 붙여넣기 가능)" autocomplete="off" />
|
||||
<textarea id="pj-cm-input" class="pj-composer-ta" rows="1" placeholder="댓글 입력… (Shift+Enter 줄바꿈, 이미지는 붙여넣기 가능)" autocomplete="off"></textarea>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -420,7 +420,7 @@
|
||||
바깥이라 끝까지 내려도 마지막 내용은 이 칸 바로 위에서 멈추고 가리지 않는다. -->
|
||||
<div class="pj-comment-dock" id="pj-comment-dock" hidden>
|
||||
<div class="pj-comment-form">
|
||||
<input type="text" id="pj-comment-input" placeholder="댓글을 추가하거나 @로 멤버를 태그하세요" autocomplete="off" />
|
||||
<textarea id="pj-comment-input" class="pj-composer-ta" rows="1" placeholder="댓글을 추가하거나 @로 멤버를 태그하세요 (Shift+Enter 줄바꿈)" autocomplete="off"></textarea>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-comment-send">등록</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -466,7 +466,7 @@
|
||||
<span class="material-symbols-outlined">attach_file</span>
|
||||
<input type="file" id="pj-cm-file-input" multiple hidden />
|
||||
</label>
|
||||
<input type="text" id="pj-cm-input" placeholder="댓글 입력… (이미지는 붙여넣기 가능)" autocomplete="off" />
|
||||
<textarea id="pj-cm-input" class="pj-composer-ta" rows="1" placeholder="댓글 입력… (Shift+Enter 줄바꿈, 이미지는 붙여넣기 가능)" autocomplete="off"></textarea>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -496,5 +496,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
+22
-6
@@ -534,6 +534,7 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.cpg-prod-manual-row .erp-field { flex: 1 1 160px; min-width: 0; }
|
||||
.cpg-prod-manual-row .cpg-weight-field { flex: 0 1 120px; }
|
||||
.cpg-prod-manual-row .erp-input { min-width: 0; width: 100%; }
|
||||
|
||||
/* 상자 그림 안 박스 호수 라벨 (예: 2호) */
|
||||
@@ -1009,16 +1010,21 @@ body.cpg-dragging { cursor: grabbing; user-select: none; }
|
||||
text-overflow: ellipsis;
|
||||
vertical-align: middle;
|
||||
}
|
||||
/* 열 폭: 제품명 160 / 제품코드 96 / 상태 72 / 동작 104 고정,
|
||||
쿠팡상품코드는 남는 폭을 흡수 → 다른 열이 지정 폭 그대로 유지된다. */
|
||||
/* 열 폭: 제품명 160 / 제품코드 96 / (포장무게 84) / 상태 72 / 동작 104 고정,
|
||||
쿠팡상품코드는 남는 폭을 흡수 → 다른 열이 지정 폭 그대로 유지된다.
|
||||
상태·동작은 끝에서부터 센다(포장무게 열이 있든 없든 — 마이그레이션 007 전이면 없음). */
|
||||
.cpg-prod-right .erp-table th:nth-child(1),
|
||||
.cpg-prod-right .erp-table td:nth-child(1) { width: 160px; }
|
||||
.cpg-prod-right .erp-table th:nth-child(2),
|
||||
.cpg-prod-right .erp-table td:nth-child(2) { width: 96px; }
|
||||
.cpg-prod-right .erp-table th:nth-child(4),
|
||||
.cpg-prod-right .erp-table td:nth-child(4) { width: 72px; }
|
||||
.cpg-prod-right .erp-table th:nth-child(5),
|
||||
.cpg-prod-right .erp-table td:nth-child(5) { width: 104px; }
|
||||
.cpg-prod-right .erp-table th.cpg-weight-col,
|
||||
.cpg-prod-right .erp-table td.cpg-weight-col { width: 84px; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.cpg-prod-right .erp-table th.cpg-weight-col .cpg-sort { margin-left: auto; }
|
||||
.cpg-weight-unit { margin-left: 2px; font-size: 11px; color: var(--erp-muted, #8a8f98); }
|
||||
.cpg-prod-right .erp-table th:nth-last-child(2),
|
||||
.cpg-prod-right .erp-table td:nth-last-child(2) { width: 72px; }
|
||||
.cpg-prod-right .erp-table th:nth-last-child(1),
|
||||
.cpg-prod-right .erp-table td:nth-last-child(1) { width: 104px; }
|
||||
/* 제품코드·쿠팡상품코드는 mono 라 조금 더 좁게 */
|
||||
.cpg-prod-right .erp-table td:nth-child(2),
|
||||
.cpg-prod-right .erp-table td:nth-child(3) { font-size: 12px; }
|
||||
@@ -1339,6 +1345,16 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
||||
.cpg-boxno-c-name { width: auto; }
|
||||
.cpg-boxno-c-code { width: 100px; }
|
||||
.cpg-boxno-c-qty { width: 62px; }
|
||||
.cpg-boxno-c-weight { width: 92px; }
|
||||
/* 상자 무게 합계(g) — 상자 단위 한 칸(rowspan), 오른쪽 정렬 숫자. 무게 없는 제품이 있으면 작은 표시 */
|
||||
.cpg-boxno-weight {
|
||||
text-align: right; vertical-align: middle; font-variant-numeric: tabular-nums; font-weight: 600;
|
||||
border-left: 1px solid var(--color-cloud-gray);
|
||||
}
|
||||
.cpg-boxno-weight .cpg-weight-unit { font-weight: 400; }
|
||||
.cpg-boxno-wmiss {
|
||||
display: block; margin-top: 1px; font-size: 10.5px; font-weight: 600; color: #b45309; white-space: nowrap;
|
||||
}
|
||||
.cpg-boxno-cell {
|
||||
text-align: center; font-weight: 700;
|
||||
font-family: var(--font-geist-mono);
|
||||
|
||||
@@ -157,6 +157,7 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-modal { position: fixed; inset: 0; z-index: 1000; background: rgba(0, 0, 0, .35); display: flex; align-items: center; justify-content: center; padding: 20px; }
|
||||
.perf-modal-card { background: #fff; border-radius: 14px; width: min(1100px, 100%); max-height: 88vh; display: flex; flex-direction: column; box-shadow: 0 20px 60px rgba(0, 0, 0, .25); }
|
||||
.perf-modal-card.is-narrow { width: min(560px, 100%); }
|
||||
.perf-modal-card.is-wide { width: min(1640px, 100%); } /* 주문 내역 — 열이 많아 넓게 */
|
||||
.perf-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--perf-line); }
|
||||
.perf-modal-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
|
||||
.perf-modal-body { padding: 12px 16px; overflow: auto; }
|
||||
@@ -229,6 +230,8 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-ev-table thead th { background: var(--perf-soft, #fafafa); box-shadow: 0 1px 0 var(--perf-line, #e5e5e5); }
|
||||
/* 취소 행 — 행 전체를 기울임 + 취소선 + 회색 */
|
||||
.perf-ev-table tr.is-cancel td { font-style: italic; text-decoration: line-through; color: #9a9a9a; }
|
||||
/* 상품명만 줄바꿈 — 긴 상품명 때문에 표가 창보다 넓어져 가로 스크롤이 생기지 않게(나머지 열은 한 줄) */
|
||||
.perf-ev-table .perf-ev-name { white-space: normal; min-width: 220px; overflow-wrap: anywhere; }
|
||||
|
||||
/* ── 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대(runSyncWithProgress) ── */
|
||||
.perf-prog-card { width: min(640px, 100%); }
|
||||
@@ -262,6 +265,15 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
@media (max-width: 560px) { .perf-prog-row { grid-template-columns: 1fr 44px; } .perf-prog-name { grid-column: 1 / -1; } .perf-prog-text { grid-column: 1 / -1; } }
|
||||
|
||||
/* [업데이트 취소] — 창 아래 왼쪽, 빨간 글자. 끝나면 숨김 */
|
||||
/* 쇼핑몰별 [중지] — 이름 옆 작은 버튼(이 쇼핑몰만 멈추고 다음 쇼핑몰로) */
|
||||
.perf-prog-name { display: flex; align-items: center; gap: 6px; }
|
||||
.perf-prog-name > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.perf-prog-stop {
|
||||
flex: none; margin-left: auto; padding: 1px 8px; border: 1px solid var(--perf-line); border-radius: 999px;
|
||||
background: #fff; color: var(--perf-down); font-size: 11.5px; font-weight: 600; line-height: 1.6; cursor: pointer;
|
||||
}
|
||||
.perf-prog-stop:hover { border-color: var(--perf-down); background: #fff5f5; }
|
||||
.perf-prog-stop:disabled { opacity: .6; cursor: default; }
|
||||
.perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; }
|
||||
.perf-prog-cancel[hidden] { display: none; }
|
||||
.perf-prog-cancel:disabled { opacity: .6; cursor: default; }
|
||||
|
||||
+71
-17
@@ -54,7 +54,8 @@
|
||||
function openModal(title, opts) {
|
||||
opts = opts || {};
|
||||
const back = el("div", { class: "perf-modal" });
|
||||
const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : ""), role: "dialog", "aria-modal": "true" });
|
||||
const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : opts.wide ? " is-wide" : ""),
|
||||
role: "dialog", "aria-modal": "true" });
|
||||
const head = el("div", { class: "perf-modal-head" });
|
||||
head.appendChild(el("h3", { text: title }));
|
||||
const x = el("button", { type: "button", class: "perf-modal-x", "aria-label": "닫기" }, "×");
|
||||
@@ -85,10 +86,10 @@
|
||||
sec = Math.max(0, Math.round(sec || 0));
|
||||
return Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
|
||||
}
|
||||
function progressRow(name, fraction, text, cls) {
|
||||
function progressRow(name, fraction, text, cls, action) {
|
||||
const pct = Math.round((fraction || 0) * 100);
|
||||
return '<div class="perf-prog-row' + (cls ? " " + cls : "") + '">' +
|
||||
'<div class="perf-prog-name">' + esc(name) + "</div>" +
|
||||
'<div class="perf-prog-name"><span>' + esc(name) + "</span>" + (action || "") + "</div>" +
|
||||
'<div class="perf-prog-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + pct + '">' +
|
||||
'<span style="width:' + pct + '%"></span></div>' +
|
||||
'<div class="perf-prog-pct">' + pct + "%</div>" +
|
||||
@@ -101,8 +102,10 @@
|
||||
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
|
||||
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
|
||||
if (s.state === "skipped") t += " · " + (s.message || "");
|
||||
if (s.state === "cancelled") t += " · 저장하지 않음(기존 매출 그대로)";
|
||||
if (s.state === "cancelled") t = (s.message === "중지됨" ? "중지됨" : t) + " · 저장하지 않음(기존 매출 그대로)";
|
||||
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
|
||||
else if (s.state === "running" && s.stop_requested) t += " · 중지하는 중…";
|
||||
if (s.state === "waiting" && s.stop_requested) t += " · 중지 — 차례가 오면 건너뜀";
|
||||
let html = esc(t);
|
||||
if (s.elapsed && s.state !== "waiting") html += ' <span class="perf-muted">(' + fmtSec(s.elapsed) + ")</span>";
|
||||
return html;
|
||||
@@ -118,7 +121,12 @@
|
||||
const cls = s.state === "error" ? "is-error" : s.state === "done" ? "is-done" :
|
||||
(s.state === "skipped" || s.state === "cancelled") ? "is-skip" : "";
|
||||
if (job.cancel_requested) s.cancel_pending = true;
|
||||
return progressRow(s.name, s.fraction, shopText(s), cls);
|
||||
// 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로(대기·수집 중일 때만, 저장 중엔 못 멈춤)
|
||||
const stoppable = !job.finished && !job.cancel_requested && !s.stop_requested &&
|
||||
(s.state === "waiting" || s.state === "running");
|
||||
const stopBtn = stoppable ? '<button type="button" class="perf-prog-stop" data-stop="' + esc(s.code) + '" title="' +
|
||||
esc(s.name) + ' 업데이트만 멈추고 다음 쇼핑몰로 넘어갑니다(이 쇼핑몰은 저장하지 않음)">중지</button>' : "";
|
||||
return progressRow(s.name, s.fraction, shopText(s), cls, stopBtn);
|
||||
}).join("");
|
||||
html += progressRow("전체", o.fraction,
|
||||
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
|
||||
@@ -147,6 +155,23 @@
|
||||
m.foot.appendChild(cancelBtn);
|
||||
m.foot.appendChild(closeBtn);
|
||||
let jobId = null;
|
||||
// 쇼핑몰별 [중지] — 진행 창은 0.8초마다 다시 그려지므로 위임으로 받는다
|
||||
m.body.addEventListener("click", async function (e) {
|
||||
const b = e.target.closest("[data-stop]");
|
||||
if (!b || !jobId) return;
|
||||
b.disabled = true;
|
||||
b.textContent = "중지하는 중…";
|
||||
try {
|
||||
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
|
||||
encodeURIComponent(b.dataset.stop) + "/stop");
|
||||
last = r.job;
|
||||
renderSyncJob(m.body, r.job, false);
|
||||
} catch (err) {
|
||||
b.disabled = false;
|
||||
b.textContent = "중지";
|
||||
alertMsg("중지 실패: " + err.message);
|
||||
}
|
||||
});
|
||||
cancelBtn.addEventListener("click", async function () {
|
||||
if (!jobId) return;
|
||||
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
|
||||
@@ -199,7 +224,7 @@
|
||||
function jobResults(job) {
|
||||
return (job && job.shops || []).map(function (s) {
|
||||
return { code: s.code, name: s.name, ok: s.state === "done", skipped: s.state === "skipped",
|
||||
cancelled: s.state === "cancelled",
|
||||
cancelled: s.state === "cancelled", stopped: s.state === "cancelled" && s.message === "중지됨",
|
||||
upserted: s.upserted, status: s.status, label: s.label, message: s.message, finished: s.state !== "waiting" && s.state !== "running" && s.state !== "saving" };
|
||||
});
|
||||
}
|
||||
@@ -263,11 +288,12 @@
|
||||
const running = job && !job.finished;
|
||||
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
|
||||
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
|
||||
const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [];
|
||||
const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [], stopped = [];
|
||||
let changed = 0;
|
||||
(res.results || []).forEach(function (r) {
|
||||
const name = (data.names || {})[r.code] || r.name || r.code;
|
||||
if (r.cancelled) cancelled.push(name);
|
||||
if (r.stopped) stopped.push(name);
|
||||
else if (r.cancelled) cancelled.push(name);
|
||||
else if (r.skipped) busy.push(name);
|
||||
else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
|
||||
else if (r.status === "not_implemented") pending.push(name);
|
||||
@@ -278,6 +304,7 @@
|
||||
if (ok.length) parts.push("<b>반영</b> " + esc(ok.join(", ")));
|
||||
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
|
||||
if (busy.length) parts.push("<b>이미 진행 중</b> " + esc(busy.join(", ")));
|
||||
if (stopped.length) parts.push("<b>중지됨</b>(기존 매출 그대로) " + esc(stopped.join(", ")));
|
||||
if (cancelled.length) parts.push("<b>취소됨</b>(기존 매출 그대로) " + esc(cancelled.join(", ")));
|
||||
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
|
||||
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
|
||||
@@ -309,7 +336,7 @@
|
||||
async function openEvents(code, from, to) {
|
||||
const name = (data.names || {})[code] || code;
|
||||
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
||||
const m = openModal(title);
|
||||
const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
try {
|
||||
const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) +
|
||||
@@ -325,7 +352,7 @@
|
||||
"<td>" + esc(r.sales_date) + "</td><td>" + esc(KIND[r.event_type] || r.event_type) +
|
||||
(r.is_sample ? ' <span class="perf-pill">테스트</span>' : "") + "</td>" +
|
||||
"<td>" + esc(r.external_order_id) + "</td>" +
|
||||
"<td>" + esc(r.product_name) + (r.option_name ? " <span class='perf-muted'>" + esc(r.option_name) + "</span>" : "") + "</td>" +
|
||||
'<td class="perf-ev-name">' + esc(r.product_name) + (r.option_name ? " <span class='perf-muted'>" + esc(r.option_name) + "</span>" : "") + "</td>" +
|
||||
'<td class="perf-num">' + esc(r.quantity) + "</td>" +
|
||||
'<td class="perf-num">' + fmt(r.amount) + "</td>" +
|
||||
"<td>" + esc(r.order_date || "") + "</td><td>" + esc(r.payment_date || "") + "</td>" +
|
||||
@@ -334,7 +361,7 @@
|
||||
m.body.innerHTML =
|
||||
'<div class="perf-ev-wrap"><table class="perf-table perf-ev-table"><thead><tr>' +
|
||||
'<th class="perf-th-label">매출일</th><th class="perf-th-label">구분</th><th class="perf-th-label">주문번호</th>' +
|
||||
'<th class="perf-th-label">상품명</th><th>수량</th><th>금액</th><th class="perf-th-label">주문일</th>' +
|
||||
'<th class="perf-th-label perf-ev-name">상품명</th><th>수량</th><th>금액</th><th class="perf-th-label">주문일</th>' +
|
||||
'<th class="perf-th-label">결제일</th><th class="perf-th-label">상태</th></tr></thead><tbody>' + body +
|
||||
'</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" colspan="5">결제 ' + fmt(sales) +
|
||||
" / 취소·반품 " + fmt(minus) + '</th><td class="perf-num">' + fmt(sum) + '</td><td colspan="3"></td></tr></tfoot></table></div>' +
|
||||
@@ -960,7 +987,7 @@
|
||||
}
|
||||
});
|
||||
|
||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||
const probe = document.getElementById("perf-probe");
|
||||
if (probe) probe.addEventListener("click", async function () {
|
||||
const day = document.getElementById("perf-probe-date").value;
|
||||
@@ -970,7 +997,7 @@
|
||||
const codeSel = document.getElementById("perf-probe-code");
|
||||
const code = codeSel ? codeSel.value : "elevenst";
|
||||
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
|
||||
gsshop: "GS샵에서 불러오는 중… (10일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||||
gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||||
out.innerHTML = '<p class="perf-muted">' + loading + "</p>";
|
||||
try {
|
||||
const to = document.getElementById("perf-probe-to").value || day;
|
||||
@@ -993,10 +1020,11 @@
|
||||
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
|
||||
}).join("") + "</tbody></table>";
|
||||
}).join("");
|
||||
// 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교
|
||||
// 날짜별 현재 규칙 매출(네이버·토스쇼핑) — 쇼핑몰 관리자 화면 매출과 나란히 비교
|
||||
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
|
||||
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>매출</th>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>' +
|
||||
esc((r.day_cols || {}).amount || "매출") + "</th>" +
|
||||
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
|
||||
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
|
||||
r.days.map(function (d) {
|
||||
@@ -1007,7 +1035,33 @@
|
||||
["orders", "amount", "claimed", "ship"].map(function (k) {
|
||||
return '<td class="perf-num"><b>' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "</b></td>";
|
||||
}).join("") + "</tr></tbody></table>" : "";
|
||||
out.innerHTML = summary + days + (details || '<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
|
||||
// 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모)
|
||||
const rc = r.refund_candidates || [];
|
||||
const candDays = (r.days || []).map(function (d) { return d.date; });
|
||||
const cands = rc.length ? '<h4 class="perf-h" style="margin:14px 0 6px">환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||||
rc.map(function (c) { return "<th>" + esc(c.label) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||||
candDays.map(function (dt) {
|
||||
return '<tr><td class="perf-td-label">' + esc(dt) + "</td>" + rc.map(function (c) {
|
||||
return '<td class="perf-num">' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + "</td>";
|
||||
}).join("") + "</tr>";
|
||||
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' + rc.map(function (c) {
|
||||
if (c.error) return '<td><span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(c.error) + "</span></td>";
|
||||
const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0);
|
||||
return '<td class="perf-num"><b>' + fmt(t) + "</b></td>";
|
||||
}).join("") + "</tr></tbody></table>" +
|
||||
rc.filter(function (c) { return !c.error && (c.rows || []).length; }).map(function (c) {
|
||||
return '<p class="perf-muted" style="margin:10px 0 4px">' + esc(c.label) + " — " + fmt(c.rows.length) + "건</p>" +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불일</th><th class="perf-th-label">주문일</th>' +
|
||||
'<th class="perf-th-label">주문번호</th>' +
|
||||
'<th class="perf-th-label">주문상품</th><th>금액</th><th class="perf-th-label">메모</th></tr></thead><tbody>' +
|
||||
c.rows.map(function (x) {
|
||||
return '<tr><td class="perf-td-label">' + esc(x.date) + "</td><td>" + esc(x.orderDate || "") + "</td><td>" +
|
||||
esc(x.orderId) + "</td><td>" + esc(x.orderProductId) +
|
||||
'</td><td class="perf-num">' + fmt(x.amount) + '</td><td class="perf-muted">' + esc(x.note) + "</td></tr>";
|
||||
}).join("") + "</tbody></table>";
|
||||
}).join("") : "";
|
||||
out.innerHTML = summary + days + cands + (details ||'<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
} finally { probe.disabled = false; }
|
||||
@@ -1033,7 +1087,7 @@
|
||||
if (job && !job.finished) rest.push("(아직 진행 중 — 창을 닫았습니다. 끝나면 대시보드에 반영됩니다)");
|
||||
(res.results || []).forEach(function (r) {
|
||||
const name = names[r.code] || r.name || r.code;
|
||||
if (r.cancelled) rest.push(name + "(취소됨)");
|
||||
if (r.cancelled) rest.push(name + (r.stopped ? "(중지됨)" : "(취소됨)"));
|
||||
else if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
|
||||
else if (r.skipped) rest.push(name + "(이미 진행 중)");
|
||||
else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
@font-face { font-family: "Pretendard Variable"; src: url("vendor/project-fonts/PretendardVariable.woff2") format("woff2"); font-weight: 100 900; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquare"; src: url("vendor/project-fonts/NanumSquareR.woff") format("woff"); font-weight: 100 599; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquare"; src: url("vendor/project-fonts/NanumSquareB.woff") format("woff"); font-weight: 600 749; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquare"; src: url("vendor/project-fonts/NanumSquareEB.woff") format("woff"); font-weight: 750 900; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquareNeo"; src: url("vendor/project-fonts/NanumSquareNeoR.woff") format("woff"); font-weight: 100 599; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquareNeo"; src: url("vendor/project-fonts/NanumSquareNeoB.woff") format("woff"); font-weight: 600 749; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquareNeo"; src: url("vendor/project-fonts/NanumSquareNeoEB.woff") format("woff"); font-weight: 750 900; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquareRound"; src: url("vendor/project-fonts/NanumSquareRoundR.woff2") format("woff2"); font-weight: 100 599; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquareRound"; src: url("vendor/project-fonts/NanumSquareRoundB.woff2") format("woff2"); font-weight: 600 749; font-style: normal; font-display: swap; }
|
||||
@font-face { font-family: "NanumSquareRound"; src: url("vendor/project-fonts/NanumSquareRoundEB.woff2") format("woff2"); font-weight: 750 900; font-style: normal; font-display: swap; }
|
||||
@@ -0,0 +1,242 @@
|
||||
/* 목표 셀의 선택한 글자 서식. 서버와 같은 버전 있는 텍스트 조각을 사용한다. */
|
||||
(function () {
|
||||
"use strict";
|
||||
const PREFIX = "pj-rich:v1:";
|
||||
const STYLE_KEYS = ["bold", "italic", "underline", "color", "size"];
|
||||
const TOGGLES = ["bold", "italic", "underline"];
|
||||
function styles(node, inherited) {
|
||||
const s = Object.assign({}, inherited);
|
||||
if (node.nodeType !== 1) return s;
|
||||
const css = node.style;
|
||||
if (node.tagName === "B" || node.tagName === "STRONG") s.bold = true;
|
||||
if (css.fontWeight) s.bold = css.fontWeight === "bold" || Number(css.fontWeight) >= 600;
|
||||
if (node.tagName === "I" || node.tagName === "EM") s.italic = true;
|
||||
if (css.fontStyle) s.italic = css.fontStyle === "italic" || css.fontStyle === "oblique";
|
||||
if (node.tagName === "U") s.underline = true;
|
||||
const decoration = css.textDecorationLine || css.textDecoration;
|
||||
if (decoration) s.underline = decoration.includes("underline");
|
||||
const size = parseInt(css.fontSize, 10);
|
||||
if (size >= 10 && size <= 32) s.size = size;
|
||||
if (css.color) {
|
||||
const rgb = css.color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
|
||||
const hex = rgb ? "#" + rgb.slice(1).map(function (v) { return Number(v).toString(16).padStart(2, "0"); }).join("") : css.color;
|
||||
if (/^#[\da-f]{6}$/i.test(hex)) s.color = hex.toLowerCase();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
function readRuns(editor) {
|
||||
const runs = [];
|
||||
function add(text, style) { if (text) runs.push(Object.assign({ text: text }, style)); }
|
||||
function walk(node, inherited) {
|
||||
if (node.nodeType === 3) { add(node.nodeValue, inherited); return; }
|
||||
if (node.nodeType !== 1) return;
|
||||
if (node.tagName === "BR") { add("\n", inherited); return; }
|
||||
if (/^(SCRIPT|STYLE|IMG|IFRAME)$/.test(node.tagName)) return;
|
||||
const style = styles(node, inherited);
|
||||
const block = /^(DIV|P)$/.test(node.tagName);
|
||||
if (block && runs.length && !runs[runs.length - 1].text.endsWith("\n")) add("\n", inherited);
|
||||
Array.from(node.childNodes).forEach(function (child) { walk(child, style); });
|
||||
}
|
||||
Array.from(editor.childNodes).forEach(function (child) { walk(child, {}); });
|
||||
return compact(runs);
|
||||
}
|
||||
function compact(runs) {
|
||||
const out = [];
|
||||
runs.forEach(function (run) {
|
||||
if (!run.text) return;
|
||||
const prev = out[out.length - 1];
|
||||
if (prev && STYLE_KEYS.every(function (key) { return prev[key] === run[key]; })) prev.text += run.text;
|
||||
else out.push(Object.assign({}, run));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
function encode(runs) {
|
||||
runs = compact(runs);
|
||||
return runs.some(function (r) { return Object.keys(r).length > 1; }) ? PREFIX + JSON.stringify(runs) : runs.map(function (r) { return r.text; }).join("");
|
||||
}
|
||||
function decode(value) {
|
||||
if (value.startsWith(PREFIX)) {
|
||||
try { const runs = JSON.parse(value.slice(PREFIX.length)); if (Array.isArray(runs)) return runs; } catch (_) {}
|
||||
}
|
||||
return [{ text: value }];
|
||||
}
|
||||
function paint(editor, runs) {
|
||||
editor.replaceChildren();
|
||||
runs.forEach(function (r) {
|
||||
if (typeof r.text !== "string") return;
|
||||
const span = document.createElement("span");
|
||||
span.textContent = r.text;
|
||||
if (typeof r.bold === "boolean") span.style.fontWeight = r.bold ? "700" : "400";
|
||||
if (typeof r.italic === "boolean") span.style.fontStyle = r.italic ? "italic" : "normal";
|
||||
if (typeof r.underline === "boolean") span.style.textDecoration = r.underline ? "underline" : "none";
|
||||
if (/^#[\da-f]{6}$/i.test(r.color || "")) span.style.color = r.color;
|
||||
if (Number.isInteger(r.size) && r.size >= 10 && r.size <= 32) span.style.fontSize = r.size + "px";
|
||||
editor.appendChild(span.style.cssText ? span : document.createTextNode(r.text));
|
||||
});
|
||||
}
|
||||
function restore(editor, start, end) {
|
||||
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);
|
||||
const points = [], range = document.createRange();
|
||||
let node, offset = 0;
|
||||
while ((node = walker.nextNode())) {
|
||||
points.push({ node: node, start: offset, end: offset + node.length }); offset += node.length;
|
||||
}
|
||||
function point(n) { return points.find(function (p) { return n <= p.end; }) || points[points.length - 1]; }
|
||||
const a = point(start), b = point(end);
|
||||
if (!a || !b) { range.selectNodeContents(editor); range.collapse(false); }
|
||||
else { range.setStart(a.node, Math.max(0, start - a.start)); range.setEnd(b.node, Math.max(0, end - b.start)); }
|
||||
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
|
||||
return range;
|
||||
}
|
||||
function attach(editor) {
|
||||
// 기존 자동 저장·병합·초안 복구와 같은 value 인터페이스를 제공한다.
|
||||
Object.defineProperty(editor, "value", { configurable: true,
|
||||
get: function () { return encode(readRuns(editor)); },
|
||||
set: function (v) { paint(editor, decode(String(v || ""))); },
|
||||
});
|
||||
editor.addEventListener("keydown", function (e) {
|
||||
if (e.isComposing || e.keyCode === 229) return;
|
||||
if (e.key === "Enter") { e.preventDefault(); insert(editor, "\n"); }
|
||||
});
|
||||
editor.addEventListener("paste", function (e) {
|
||||
e.preventDefault(); insert(editor, e.clipboardData.getData("text/plain"));
|
||||
});
|
||||
}
|
||||
function insert(editor, text) {
|
||||
const sel = window.getSelection();
|
||||
if (!sel.rangeCount || !editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
|
||||
const range = sel.getRangeAt(0); range.deleteContents();
|
||||
const node = document.createTextNode(text); range.insertNode(node);
|
||||
range.setStartAfter(node); range.collapse(true); sel.removeAllRanges(); sel.addRange(range);
|
||||
editor.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
function init(table, toolbar) {
|
||||
if (!toolbar) return;
|
||||
let saved = null;
|
||||
// body 에 두어 표 스크롤과 화면 zoom 에 잘리지 않는 선택 셀 위 팝업으로 표시한다.
|
||||
document.body.appendChild(toolbar);
|
||||
const colorButton = toolbar.querySelector("[data-goal-format='color']");
|
||||
const colorGrid = toolbar.querySelector(".pj-goal-color-grid");
|
||||
function closeColors() { colorGrid.hidden = true; colorButton.setAttribute("aria-expanded", "false"); }
|
||||
function showColor(value) {
|
||||
colorButton.querySelector(".pj-goal-color-preview").style.backgroundColor = value;
|
||||
colorGrid.querySelectorAll("[data-goal-color]").forEach(function (btn) {
|
||||
btn.setAttribute("aria-pressed", String(btn.dataset.goalColor.toLowerCase() === value.toLowerCase()));
|
||||
});
|
||||
}
|
||||
function place() {
|
||||
if (!saved || !saved.editor.isConnected) { clear(); return; }
|
||||
const sel = window.getSelection();
|
||||
if (!sel.rangeCount || sel.isCollapsed || !saved.editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
|
||||
const cell = saved.editor.closest("td");
|
||||
if (!cell) { clear(); return; }
|
||||
// 같은 셀의 어느 줄을 선택해도 셀 상단·가운데를 기준으로 같은 위치에 둔다.
|
||||
const rect = cell.getBoundingClientRect();
|
||||
const paneRect = table.parentElement.getBoundingClientRect();
|
||||
if (rect.bottom < paneRect.top || rect.top > paneRect.bottom || rect.right < paneRect.left || rect.left > paneRect.right) {
|
||||
toolbar.hidden = true; closeColors(); return;
|
||||
}
|
||||
toolbar.hidden = false;
|
||||
const w = toolbar.offsetWidth, h = toolbar.offsetHeight;
|
||||
toolbar.style.left = Math.max(8, Math.min(rect.left + rect.width / 2 - w / 2, window.innerWidth - w - 8)) + "px";
|
||||
toolbar.style.top = Math.max(8, rect.top - h - 8) + "px";
|
||||
colorGrid.classList.toggle("is-below", rect.top - h - 88 < 8);
|
||||
}
|
||||
function clear() {
|
||||
saved = null;
|
||||
toolbar.hidden = true; closeColors();
|
||||
toolbar.querySelectorAll("button, input, select").forEach(function (el) { el.disabled = true; });
|
||||
}
|
||||
function capture() {
|
||||
// 서식 도구에 포커스를 옮길 때는 직전 글자 선택을 유지한다.
|
||||
if (toolbar.contains(document.activeElement)) return;
|
||||
const sel = window.getSelection();
|
||||
if (!sel.rangeCount || sel.isCollapsed) { clear(); return; }
|
||||
const range = sel.getRangeAt(0);
|
||||
const root = range.startContainer.nodeType === 1 ? range.startContainer : range.startContainer.parentElement;
|
||||
const editor = root.closest(".pj-goal-text[contenteditable='true']");
|
||||
if (!editor || !table.contains(editor) || !editor.contains(range.endContainer)) { clear(); return; }
|
||||
const pre = document.createRange(); pre.selectNodeContents(editor); pre.setEnd(range.startContainer, range.startOffset);
|
||||
saved = { editor: editor, start: pre.toString().length, end: pre.toString().length + range.toString().length };
|
||||
toolbar.querySelectorAll("button, input, select").forEach(function (el) { el.disabled = false; });
|
||||
let pos = 0;
|
||||
const chosen = readRuns(editor).filter(function (run) {
|
||||
const end = pos + run.text.length, intersects = end > saved.start && pos < saved.end;
|
||||
pos = end; return intersects;
|
||||
});
|
||||
function uniform(key, fallback) {
|
||||
const value = chosen[0] && chosen[0][key];
|
||||
return chosen.every(function (r) { return r[key] === value; }) && value !== undefined ? value : fallback;
|
||||
}
|
||||
TOGGLES.forEach(function (key) {
|
||||
const all = chosen.every(function (r) { return r[key] === true; });
|
||||
const some = chosen.some(function (r) { return r[key] === true; });
|
||||
toolbar.querySelector("[data-goal-format='" + key + "']").setAttribute("aria-pressed", all ? "true" : some ? "mixed" : "false");
|
||||
});
|
||||
showColor(uniform("color", "#000000"));
|
||||
const sizes = chosen.map(function (r) { return r.size || 14; });
|
||||
toolbar.querySelector("[data-goal-format='size']").textContent = sizes.every(function (n) { return n === sizes[0]; }) ? sizes[0] + "px" : "혼합";
|
||||
toolbar.querySelector("[data-goal-format='size-up']").disabled = sizes.every(function (n) { return n >= 32; });
|
||||
toolbar.querySelector("[data-goal-format='size-down']").disabled = sizes.every(function (n) { return n <= 10; });
|
||||
toolbar.hidden = false;
|
||||
place();
|
||||
}
|
||||
document.addEventListener("selectionchange", capture);
|
||||
table.addEventListener("mouseup", capture);
|
||||
table.addEventListener("keyup", capture);
|
||||
toolbar.addEventListener("mousedown", function (e) { if (e.target.closest("button")) e.preventDefault(); });
|
||||
function apply(key, value) {
|
||||
if (!saved || !saved.editor.isConnected) return;
|
||||
const editor = saved.editor, out = []; let pos = 0;
|
||||
readRuns(editor).forEach(function (run) {
|
||||
const end = pos + run.text.length;
|
||||
const a = Math.max(pos, saved.start), b = Math.min(end, saved.end);
|
||||
if (b <= a) out.push(run);
|
||||
else {
|
||||
if (a > pos) out.push(Object.assign({}, run, { text: run.text.slice(0, a - pos) }));
|
||||
const middle = Object.assign({}, run, { text: run.text.slice(a - pos, b - pos) });
|
||||
if (key === "reset") STYLE_KEYS.forEach(function (style) { delete middle[style]; });
|
||||
else if (key === "size-delta") middle.size = Math.max(10, Math.min(32, (middle.size || 14) + value));
|
||||
else middle[key] = value;
|
||||
out.push(middle);
|
||||
if (b < end) out.push(Object.assign({}, run, { text: run.text.slice(b - pos) }));
|
||||
}
|
||||
pos = end;
|
||||
});
|
||||
paint(editor, compact(out)); editor.focus(); restore(editor, saved.start, saved.end);
|
||||
editor.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
capture();
|
||||
}
|
||||
colorButton.addEventListener("click", function () {
|
||||
colorGrid.hidden = !colorGrid.hidden;
|
||||
colorButton.setAttribute("aria-expanded", String(!colorGrid.hidden));
|
||||
});
|
||||
colorGrid.addEventListener("click", function (e) {
|
||||
const btn = e.target.closest("[data-goal-color]");
|
||||
if (!btn) return;
|
||||
apply("color", btn.dataset.goalColor.toLowerCase()); closeColors();
|
||||
});
|
||||
TOGGLES.forEach(function (key) {
|
||||
const btn = toolbar.querySelector("[data-goal-format='" + key + "']");
|
||||
btn.addEventListener("click", function () { apply(key, btn.getAttribute("aria-pressed") !== "true"); });
|
||||
});
|
||||
toolbar.querySelector("[data-goal-format='size-up']").addEventListener("click", function () { apply("size-delta", 2); });
|
||||
toolbar.querySelector("[data-goal-format='size-down']").addEventListener("click", function () { apply("size-delta", -2); });
|
||||
toolbar.querySelector("[data-goal-format='reset']").addEventListener("click", function () { apply("reset"); });
|
||||
document.addEventListener("mousedown", function (e) {
|
||||
if (toolbar.contains(e.target) || (saved && saved.editor.contains(e.target))) return;
|
||||
clear();
|
||||
}, true);
|
||||
toolbar.addEventListener("keydown", function (e) {
|
||||
if (e.key !== "Escape") return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
if (!colorGrid.hidden) { closeColors(); colorButton.focus(); }
|
||||
else { if (saved) saved.editor.focus(); clear(); }
|
||||
});
|
||||
window.addEventListener("resize", place);
|
||||
window.addEventListener("scroll", function (e) { if (!toolbar.contains(e.target)) place(); }, true);
|
||||
new MutationObserver(function () { if (saved && !saved.editor.isConnected) clear(); }).observe(table, { childList: true, subtree: true });
|
||||
clear();
|
||||
}
|
||||
window.PJGoalText = { attach: attach, init: init, readRuns: readRuns, paint: paint, encode: encode };
|
||||
})();
|
||||
+59
-15
@@ -2,11 +2,11 @@
|
||||
왼쪽 목차(스크롤을 따라 현재 위치 강조) + 오른쪽 본문 카드. 처음 쓰는 사람이
|
||||
읽기 쉽게 — 단계는 번호 동그라미, 화면의 버튼·메뉴 이름은 .pjh-ui 칩으로 표시. */
|
||||
.pjh {
|
||||
--pjh-ink: #1e1f21; --pjh-soft: #6d6e6f; --pjh-line: #e8eaee;
|
||||
--pjh-ink: var(--pj-ink); --pjh-soft: var(--pj-ink-soft); --pjh-line: #e8eaee;
|
||||
--pjh-accent: var(--pj-accent, #7b68ee); --pjh-tint: var(--pj-accent-tint, #f1eeff);
|
||||
display: grid; grid-template-columns: 230px minmax(0, 1fr); gap: 28px;
|
||||
max-width: 1180px; margin: 0 auto; padding: 4px 0 60px; color: var(--pjh-ink);
|
||||
font-size: 14.5px; line-height: 1.7;
|
||||
font-size: var(--pj-text-size); line-height: var(--pj-text-leading);
|
||||
}
|
||||
@media (max-width: 1000px) {
|
||||
.pjh { grid-template-columns: minmax(0, 1fr); }
|
||||
@@ -15,26 +15,26 @@
|
||||
|
||||
/* 목차 */
|
||||
.pjh-toc { position: sticky; top: 12px; align-self: start; max-height: calc(100vh - 110px); overflow-y: auto; }
|
||||
.pjh-toc-title { font-size: 12px; font-weight: 800; color: var(--pjh-soft); letter-spacing: .04em; margin: 0 0 8px 10px; }
|
||||
.pjh-toc-title { font-size: 12px; font-weight: 500; color: var(--pjh-soft); letter-spacing: normal; margin: 0 0 8px 10px; }
|
||||
.pjh-toc ol { list-style: none; margin: 0; padding: 0; counter-reset: toc; }
|
||||
.pjh-toc li { counter-increment: toc; }
|
||||
.pjh-toc a {
|
||||
display: flex; gap: 8px; padding: 5px 10px; border-radius: 8px; color: #3d4046;
|
||||
text-decoration: none; font-size: 13.5px; line-height: 1.45;
|
||||
text-decoration: none; font-size: var(--pj-text-size); line-height: var(--pj-text-leading);
|
||||
}
|
||||
.pjh-toc a::before { content: counter(toc) "."; color: #9aa1a9; min-width: 18px; }
|
||||
.pjh-toc a:hover { background: #f1f2f4; }
|
||||
.pjh-toc a.is-active { background: var(--pjh-tint); color: var(--pjh-accent); font-weight: 700; }
|
||||
.pjh-toc a.is-active { background: var(--pjh-tint); color: var(--pjh-accent); font-weight: 500; }
|
||||
|
||||
/* 머리말 */
|
||||
.pjh-hero {
|
||||
background: linear-gradient(135deg, #f4f1ff 0%, #eef5ff 100%); border: 1px solid #e4defd;
|
||||
border-radius: 16px; padding: 26px 30px; margin-bottom: 18px;
|
||||
}
|
||||
.pjh-hero h1 { margin: 0 0 6px; font-size: 24px; font-weight: 800; }
|
||||
.pjh-hero h1 { margin: 0 0 6px; font-size: var(--pj-title-size); line-height: var(--pj-title-leading); font-weight: 500; }
|
||||
.pjh-hero p { margin: 0; color: #3d4046; }
|
||||
.pjh-quick { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; margin-top: 18px; }
|
||||
.pjh-quick-step { background: #fff; border: 1px solid #e4defd; border-radius: 12px; padding: 12px 14px; font-size: 13.5px; line-height: 1.5; }
|
||||
.pjh-quick-step { background: #fff; border: 1px solid #e4defd; border-radius: 12px; padding: 12px 14px; font-size: var(--pj-text-size); line-height: var(--pj-text-leading); }
|
||||
.pjh-quick-step b { display: block; color: var(--pjh-accent); font-size: 12px; margin-bottom: 2px; }
|
||||
|
||||
/* 본문 카드 */
|
||||
@@ -42,12 +42,12 @@
|
||||
background: #fff; border: 1px solid var(--pjh-line); border-radius: 14px;
|
||||
padding: 24px 30px; margin-bottom: 18px; scroll-margin-top: 16px;
|
||||
}
|
||||
.pjh-sec h2 { display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 20px; font-weight: 800; }
|
||||
.pjh-sec h2 { display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: var(--pj-heading-size); line-height: var(--pj-heading-leading); font-weight: 500; }
|
||||
.pjh-sec h2 .pjh-num {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px;
|
||||
border-radius: 9px; background: var(--pjh-tint); color: var(--pjh-accent); font-size: 15px; flex: none;
|
||||
}
|
||||
.pjh-sec h3 { margin: 22px 0 6px; font-size: 16px; font-weight: 800; }
|
||||
.pjh-sec h3 { margin: 22px 0 6px; font-size: var(--pj-section-size); line-height: var(--pj-section-leading); font-weight: 500; }
|
||||
.pjh-sec h3:first-of-type { margin-top: 8px; }
|
||||
.pjh-sec p { margin: 6px 0; }
|
||||
.pjh-sec ul { margin: 6px 0; padding-left: 20px; }
|
||||
@@ -59,14 +59,14 @@
|
||||
.pjh-steps li { counter-increment: step; position: relative; padding: 2px 0 6px 36px; margin: 0; }
|
||||
.pjh-steps li::before {
|
||||
content: counter(step); position: absolute; left: 0; top: 3px; width: 24px; height: 24px;
|
||||
border-radius: 50%; background: var(--pjh-accent); color: #fff; font-size: 12.5px; font-weight: 800;
|
||||
border-radius: 50%; background: var(--pjh-accent); color: #fff; font-size: 12.5px; font-weight: 500;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
|
||||
/* 화면 요소 이름(버튼·메뉴) 칩, 키보드 키 */
|
||||
.pjh-ui {
|
||||
display: inline-flex; align-items: center; gap: 3px; padding: 0 7px; border-radius: 6px;
|
||||
background: #f1f2f4; border: 1px solid #e2e4e8; font-size: 13px; font-weight: 700; line-height: 22px;
|
||||
background: #f1f2f4; border: 1px solid #e2e4e8; font-size: 13px; font-weight: 500; line-height: 22px;
|
||||
white-space: nowrap; vertical-align: 1px;
|
||||
}
|
||||
.pjh-ui .material-symbols-outlined { font-size: 16px; }
|
||||
@@ -79,7 +79,7 @@
|
||||
|
||||
/* 팁·주의 */
|
||||
.pjh-tip, .pjh-note, .pjh-warn {
|
||||
display: flex; gap: 10px; border-radius: 10px; padding: 10px 14px; margin: 10px 0; font-size: 13.5px; line-height: 1.6;
|
||||
display: flex; gap: 10px; border-radius: 10px; padding: 10px 14px; margin: 10px 0; font-size: var(--pj-text-size); line-height: var(--pj-text-leading);
|
||||
}
|
||||
.pjh-tip { background: #f2faf5; border: 1px solid #cfe9da; }
|
||||
.pjh-note { background: #f3f6ff; border: 1px solid #d6e0fb; }
|
||||
@@ -91,10 +91,10 @@
|
||||
.pjh-warn > .material-symbols-outlined { font-size: 20px; flex: none; margin-top: 1px; }
|
||||
|
||||
/* 표 */
|
||||
.pjh-table { width: 100%; border-collapse: collapse; margin: 8px 0; font-size: 13.5px; line-height: 1.55; }
|
||||
.pjh-table { width: 100%; border-collapse: collapse; margin: 8px 0; font-size: var(--pj-text-size); line-height: var(--pj-text-leading); }
|
||||
.pjh-table th, .pjh-table td { border-bottom: 1px solid var(--pjh-line); padding: 8px 10px; text-align: left; vertical-align: top; }
|
||||
.pjh-table th { background: #f7f8fa; font-weight: 800; color: #3d4046; white-space: nowrap; }
|
||||
.pjh-table td:first-child { font-weight: 700; white-space: nowrap; }
|
||||
.pjh-table th { background: #f7f8fa; font-weight: 500; color: #3d4046; white-space: nowrap; }
|
||||
.pjh-table td:first-child { font-weight: 500; white-space: nowrap; }
|
||||
|
||||
/* 화면 구성 그림(아주 단순한 모형) */
|
||||
.pjh-map {
|
||||
@@ -114,3 +114,47 @@
|
||||
background: var(--pjh-accent); color: #fff; box-shadow: 0 6px 18px rgba(123, 104, 238, .35);
|
||||
}
|
||||
.pjh-top:hover { filter: brightness(1.08); }
|
||||
|
||||
/* 검색 — 결과는 소제목 단위로 이동하며 본문은 계속 읽을 수 있다. */
|
||||
.erp-page:has(> .pjh) { box-sizing: border-box; }
|
||||
.pjh-body { min-width: 0; }
|
||||
.pjh [hidden] { display: none !important; }
|
||||
.pjh-search { background: #fff; border: 1px solid var(--pjh-line); border-radius: 14px; padding: 18px 22px; margin-bottom: 18px; }
|
||||
.pjh-search label { display: block; font-weight: 600; margin-bottom: 8px; }
|
||||
.pjh-search-field { display: flex; gap: 8px; }
|
||||
.pjh-search-field input { flex: 1; min-width: 0; border: 1px solid #cfd3d9; border-radius: 8px; padding: 10px 12px; font: inherit; }
|
||||
.pjh-search-field button { border: 1px solid #d7d0f7; border-radius: 8px; background: var(--pjh-tint); color: #493790; padding: 8px 12px; font: inherit; cursor: pointer; }
|
||||
.pjh-search-field button:hover { background: #e8e1ff; }
|
||||
.pjh-search-hint, .pjh-search-status { font-size: 13px; margin: 8px 0 0; color: var(--pjh-soft); }
|
||||
.pjh-search-status:empty { display: none; }
|
||||
.pjh-results { list-style: none; margin: 12px 0 0; padding: 0; max-height: 340px; overflow-y: auto; }
|
||||
.pjh-results li + li { border-top: 1px solid var(--pjh-line); }
|
||||
.pjh-results a { display: block; padding: 10px; color: var(--pjh-ink); text-decoration: none; border-radius: 8px; }
|
||||
.pjh-results a:hover { background: #f7f5ff; }
|
||||
.pjh-results strong, .pjh-results span { display: block; overflow-wrap: anywhere; }
|
||||
.pjh-results strong { color: #493790; font-weight: 600; }
|
||||
.pjh-results span { margin-top: 4px; font-size: 13px; }
|
||||
.pjh mark.pjh-match { background: #fff0a6; color: #423309; border-radius: 2px; padding: 0; }
|
||||
.pjh-quick-links { margin-top: 16px !important; }
|
||||
.pjh-sec h3 { scroll-margin-top: 20px; }
|
||||
.pjh :focus-visible { outline: 2px solid var(--pjh-accent); outline-offset: 3px; }
|
||||
.pjh-sec { overflow-wrap: anywhere; }
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.erp-app:has(.pjh) .erp-topbar { flex-wrap: wrap; height: auto; padding: 8px 12px; gap: 8px; }
|
||||
.erp-app:has(.pjh) .erp-topbar-left { flex-basis: 100%; }
|
||||
.erp-app:has(.pjh) .erp-topbar-right { width: 100%; gap: 6px; }
|
||||
.erp-app:has(.pjh) .erp-user-chip { margin-right: auto; }
|
||||
.erp-app:has(.pjh) .erp-user-email { display: none; }
|
||||
.pjh { gap: 12px; }
|
||||
.pjh-hero, .pjh-sec { padding: 18px 16px; }
|
||||
.pjh-search { padding: 16px; }
|
||||
.pjh-search-field { flex-wrap: wrap; }
|
||||
.pjh-search-field input { flex-basis: 100%; }
|
||||
.pjh-table td:first-child, .pjh-table th { white-space: normal; }
|
||||
.pjh-table th, .pjh-table td { padding: 7px 5px; }
|
||||
.pjh-map { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto; }
|
||||
.pjh-map-top { flex-wrap: wrap; gap: 6px; }
|
||||
.pjh-map-side, .pjh-map-main { grid-row: auto; }
|
||||
.pjh-top { right: 12px; bottom: 12px; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
/* 도움말의 제목·본문에서 검색하고 해당 소제목으로 이동한다. DB/API 불필요. */
|
||||
(function () {
|
||||
"use strict";
|
||||
const root = document.querySelector(".pjh");
|
||||
if (!root) return;
|
||||
const input = document.getElementById("pjh-query");
|
||||
const form = document.getElementById("pjh-search-form");
|
||||
const results = document.getElementById("pjh-results");
|
||||
const status = document.getElementById("pjh-search-status");
|
||||
const clear = document.getElementById("pjh-search-clear");
|
||||
const chapters = Array.from(root.querySelectorAll(".pjh-sec"));
|
||||
const index = [];
|
||||
let composing = false;
|
||||
|
||||
function plain(node) {
|
||||
const copy = node.cloneNode(true);
|
||||
copy.querySelectorAll(".pjh-num, .material-symbols-outlined").forEach(function (n) { n.remove(); });
|
||||
return copy.textContent.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
// 본문 자체에서 색인을 만든다. 도움말을 고치면 검색 결과도 함께 바뀐다.
|
||||
chapters.forEach(function (chapter) {
|
||||
const title = plain(chapter.querySelector("h2"));
|
||||
let block = { chapter: chapter, title: title, heading: chapter.querySelector("h2"), nodes: [], order: index.length };
|
||||
block.heading.id = block.heading.id || chapter.id + "-intro";
|
||||
let ordinal = 0;
|
||||
function finish() {
|
||||
block.text = block.nodes.map(plain).join(" ");
|
||||
block.search = (block.title + " " + block.text).toLowerCase();
|
||||
index.push(block);
|
||||
}
|
||||
Array.from(chapter.children).forEach(function (node) {
|
||||
if (node.tagName === "H2") return;
|
||||
if (node.tagName === "H3") {
|
||||
finish();
|
||||
ordinal++;
|
||||
node.id = node.id || chapter.id + "-" + ordinal;
|
||||
block = { chapter: chapter, title: title + " › " + plain(node), heading: node, nodes: [], order: index.length };
|
||||
} else block.nodes.push(node);
|
||||
});
|
||||
finish();
|
||||
});
|
||||
|
||||
function words(query) {
|
||||
return Array.from(new Set(query.trim().toLowerCase().split(/\s+/).filter(Boolean)));
|
||||
}
|
||||
|
||||
// 검색어는 HTML이나 정규식으로 해석하지 않는다.
|
||||
function marked(text, terms) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const lower = text.toLowerCase();
|
||||
let pos = 0;
|
||||
while (pos < text.length) {
|
||||
let start = -1, length = 0;
|
||||
terms.forEach(function (term) {
|
||||
const found = lower.indexOf(term, pos);
|
||||
if (found !== -1 && (start === -1 || found < start || (found === start && term.length > length))) {
|
||||
start = found; length = term.length;
|
||||
}
|
||||
});
|
||||
if (start === -1) { fragment.appendChild(document.createTextNode(text.slice(pos))); break; }
|
||||
fragment.appendChild(document.createTextNode(text.slice(pos, start)));
|
||||
const mark = document.createElement("mark");
|
||||
mark.className = "pjh-match";
|
||||
mark.textContent = text.slice(start, start + length);
|
||||
fragment.appendChild(mark);
|
||||
pos = start + length;
|
||||
}
|
||||
return fragment;
|
||||
}
|
||||
|
||||
function highlight(terms) {
|
||||
chapters.forEach(function (chapter) {
|
||||
chapter.querySelectorAll("mark.pjh-match").forEach(function (mark) {
|
||||
mark.replaceWith(document.createTextNode(mark.textContent));
|
||||
});
|
||||
chapter.normalize();
|
||||
if (!terms.length) return;
|
||||
const walker = document.createTreeWalker(chapter, NodeFilter.SHOW_TEXT);
|
||||
const nodes = [];
|
||||
let node;
|
||||
while ((node = walker.nextNode())) {
|
||||
if (!node.parentElement.closest(".material-symbols-outlined, .pjh-num") &&
|
||||
terms.some(function (term) { return node.nodeValue.toLowerCase().includes(term); })) nodes.push(node);
|
||||
}
|
||||
nodes.forEach(function (n) { n.replaceWith(marked(n.nodeValue, terms)); });
|
||||
});
|
||||
}
|
||||
|
||||
function snippet(text, terms) {
|
||||
const lower = text.toLowerCase();
|
||||
const hits = terms.map(function (term) { return lower.indexOf(term); }).filter(function (n) { return n >= 0; });
|
||||
const start = hits.length ? Math.max(0, Math.min.apply(null, hits) - 35) : 0;
|
||||
return (start ? "…" : "") + text.slice(start, start + 155) + (text.length > start + 155 ? "…" : "");
|
||||
}
|
||||
|
||||
function saveQuery(query) {
|
||||
const url = new URL(window.location.href);
|
||||
if (query.trim()) url.searchParams.set("q", query.trim());
|
||||
else url.searchParams.delete("q");
|
||||
window.history.replaceState(null, "", url);
|
||||
}
|
||||
|
||||
function search(updateUrl) {
|
||||
const query = input.value.slice(0, 160);
|
||||
const terms = words(query);
|
||||
results.replaceChildren();
|
||||
clear.hidden = !query;
|
||||
results.hidden = !terms.length;
|
||||
highlight(terms);
|
||||
if (updateUrl) saveQuery(query);
|
||||
if (!terms.length) { status.textContent = ""; return; }
|
||||
const matches = index.filter(function (entry) {
|
||||
return terms.every(function (term) { return entry.search.includes(term); });
|
||||
});
|
||||
// 제목에 모든 단어가 있으면 먼저, 나머지는 문서 순서대로.
|
||||
matches.sort(function (a, b) {
|
||||
function score(entry) { return terms.every(function (term) { return entry.title.toLowerCase().includes(term); }) ? 1 : 0; }
|
||||
return score(b) - score(a) || a.order - b.order;
|
||||
});
|
||||
status.textContent = matches.length
|
||||
? "검색 결과 " + matches.length + "개 · 결과를 누르거나 Enter로 첫 설명에 이동하세요."
|
||||
: "검색 결과가 없습니다. 다른 단어를 쓰거나 검색어를 줄여 보세요.";
|
||||
matches.forEach(function (entry) {
|
||||
const li = document.createElement("li");
|
||||
const link = document.createElement("a");
|
||||
link.href = "#" + entry.heading.id;
|
||||
const title = document.createElement("strong");
|
||||
title.appendChild(marked(entry.title, terms));
|
||||
const preview = document.createElement("span");
|
||||
preview.appendChild(marked(snippet(entry.text, terms), terms));
|
||||
link.append(title, preview);
|
||||
li.appendChild(link);
|
||||
results.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
const tocLinks = Array.from(root.querySelectorAll(".pjh-toc a"));
|
||||
function activate(chapter) {
|
||||
tocLinks.forEach(function (link) {
|
||||
const active = link.getAttribute("href") === "#" + chapter.id;
|
||||
link.classList.toggle("is-active", active);
|
||||
if (active) link.setAttribute("aria-current", "location");
|
||||
else link.removeAttribute("aria-current");
|
||||
});
|
||||
}
|
||||
function jump(id) {
|
||||
const target = document.getElementById(id);
|
||||
if (!target || !root.contains(target)) return;
|
||||
target.setAttribute("tabindex", "-1");
|
||||
target.focus({ preventScroll: true });
|
||||
target.scrollIntoView({ block: "start" });
|
||||
const chapter = target.closest(".pjh-sec");
|
||||
if (chapter) activate(chapter);
|
||||
}
|
||||
root.addEventListener("click", function (event) {
|
||||
const link = event.target.closest('a[href^="#"]');
|
||||
if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
const id = link.getAttribute("href").slice(1);
|
||||
if (!document.getElementById(id)) return;
|
||||
event.preventDefault();
|
||||
if (window.location.hash !== "#" + id) window.history.pushState(null, "", "#" + id);
|
||||
jump(id);
|
||||
});
|
||||
input.maxLength = 160;
|
||||
input.addEventListener("compositionstart", function () { composing = true; });
|
||||
input.addEventListener("compositionend", function () { composing = false; search(true); });
|
||||
input.addEventListener("input", function () { if (!composing) search(true); });
|
||||
form.addEventListener("submit", function (event) {
|
||||
event.preventDefault();
|
||||
if (composing) return;
|
||||
search(true);
|
||||
const first = results.querySelector("a");
|
||||
if (first) first.click();
|
||||
});
|
||||
function reset() { input.value = ""; search(true); input.focus(); }
|
||||
clear.addEventListener("click", reset);
|
||||
input.addEventListener("keydown", function (event) {
|
||||
if (composing || event.isComposing || event.keyCode === 229) return;
|
||||
if (event.key === "Escape") { event.preventDefault(); reset(); }
|
||||
});
|
||||
document.addEventListener("keydown", function (event) {
|
||||
if (event.key !== "/" || event.isComposing || event.ctrlKey || event.metaKey || event.altKey ||
|
||||
event.target.closest("input, textarea, select, [contenteditable='true']")) return;
|
||||
event.preventDefault();
|
||||
input.focus();
|
||||
input.scrollIntoView({ block: "center" });
|
||||
});
|
||||
function restore() {
|
||||
input.value = (new URL(window.location.href).searchParams.get("q") || "").slice(0, 160);
|
||||
search(false);
|
||||
if (window.location.hash) jump(window.location.hash.slice(1));
|
||||
}
|
||||
window.addEventListener("popstate", restore);
|
||||
window.addEventListener("hashchange", function () { if (window.location.hash) jump(window.location.hash.slice(1)); });
|
||||
document.getElementById("pjh-search").hidden = false;
|
||||
restore();
|
||||
|
||||
if ("IntersectionObserver" in window) {
|
||||
const observer = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (entry) { if (entry.isIntersecting) activate(entry.target); });
|
||||
}, { rootMargin: "-10% 0px -75% 0px" });
|
||||
chapters.forEach(function (chapter) { observer.observe(chapter); });
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
const button = document.getElementById("pj-options-btn"), dialog = document.getElementById("pj-options-dialog");
|
||||
if (!button || !dialog || button.dataset.bound) return;
|
||||
button.dataset.bound = "1";
|
||||
const names = { system: null, pretendard: "Pretendard Variable", "nanum-square": "NanumSquare",
|
||||
"nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" };
|
||||
const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview");
|
||||
const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save");
|
||||
const cancel = document.getElementById("pj-options-cancel");
|
||||
function current() { const v = document.documentElement.dataset.pjFont; return Object.hasOwn(names, v) ? v : "system"; }
|
||||
function paint() {
|
||||
const font = names[select.value];
|
||||
preview.style.fontFamily = font ? '"' + font + '", sans-serif' : "var(--pj-system-font)";
|
||||
}
|
||||
button.addEventListener("click", function () {
|
||||
select.value = current(); error.hidden = true; paint(); dialog.showModal(); select.focus();
|
||||
});
|
||||
select.addEventListener("change", paint);
|
||||
cancel.addEventListener("click", function () { if (!save.disabled) dialog.close(); });
|
||||
dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); });
|
||||
dialog.addEventListener("close", function () { button.focus(); });
|
||||
document.getElementById("pj-options-form").addEventListener("submit", async function (e) {
|
||||
e.preventDefault(); if (save.disabled) return;
|
||||
const value = select.value, font = names[value];
|
||||
if (!Object.hasOwn(names, value)) return;
|
||||
save.disabled = select.disabled = cancel.disabled = true; error.hidden = true;
|
||||
try {
|
||||
if (font && document.fonts) {
|
||||
const loaded = await Promise.all([document.fonts.load('400 14px "' + font + '"', "가나다 Project"), document.fonts.load('700 14px "' + font + '"', "가나다 Project")]);
|
||||
if (loaded.some(function (list) { return !list.length; })) throw new Error("폰트를 불러오지 못했습니다. 다시 시도해 주세요.");
|
||||
}
|
||||
localStorage.setItem("pj_font", value);
|
||||
document.documentElement.dataset.pjFont = value;
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
dialog.close();
|
||||
} catch (err) { error.textContent = "설정을 저장하지 못했습니다. " + err.message; error.hidden = false; }
|
||||
finally { save.disabled = select.disabled = cancel.disabled = false; }
|
||||
});
|
||||
})();
|
||||
+735
-127
File diff suppressed because it is too large
Load Diff
+2314
-166
File diff suppressed because it is too large
Load Diff
+98
@@ -0,0 +1,98 @@
|
||||
NanumSquare — Copyright 2016 NAVER Corporation. Font designed by Sandoll Communications Inc.
|
||||
|
||||
NanumSquareNeo — Copyright 2022 NAVER Corp. Font Designed by Sandoll Inc.
|
||||
|
||||
NanumSquareRound — Copyright 2017 NAVER Corporation. Font designed by Sandoll Communications Inc.
|
||||
|
||||
Original copyright notices embedded in the unmodified fonts are reproduced in the accompanying *.LICENSE.txt files.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
## SIL OPEN FONT LICENSE
|
||||
Version 1.1 - 26 February 2007
|
||||
|
||||
## PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
## DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
## PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
##TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
##DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
Copyright © 2022 NAVER Corp. All rights reserved. Font Designed by Sandoll Inc.
|
||||
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
Copyright ®œ 2016 NAVER Corporation. All rights reserved. Font designed by Sandoll Communications Inc.
|
||||
|
||||
NAVER Corporation
|
||||
|
||||
www.navercorp.com
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
Copyright ®œ 2017 NAVER Corporation. All rights reserved. Font designed by Sandoll Communications Inc.
|
||||
|
||||
NAVER Corporation
|
||||
|
||||
http://www.navercorp.com
|
||||
@@ -0,0 +1,94 @@
|
||||
Copyright (c) 2021, Kil Hyung-jin (https://github.com/orioncactus/pretendard),
|
||||
with Reserved Font Name Pretendard.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
+12
@@ -0,0 +1,12 @@
|
||||
# Project 웹폰트
|
||||
|
||||
Project 옵션에서 선택한 폰트만 브라우저가 불러옵니다. 외부 CDN 요청은 없으며 파일을 수정하지 않았습니다.
|
||||
|
||||
- Pretendard Variable 1.3.9: https://github.com/orioncactus/pretendard (SIL OFL 1.1, `Pretendard-LICENSE.txt`)
|
||||
- NanumSquare / NanumSquareNeo / NanumSquareRound: https://campaign.naver.com/nanumsquare_neo/
|
||||
네이버 공식 웹폰트 `https://hangeul.pstatic.net/hangeul_static/webfont/`에서 배포하는 원본.
|
||||
각 폰트에 내장된 저작권 표기는 `*.LICENSE.txt`, OFL 1.1 전문은 `Nanum-OFL.md`에 포함했습니다.
|
||||
OFL 본문 출처: https://github.com/naver/nanumfont/wiki/Open-Font-License
|
||||
원본 문서의 NanumGothicCoding 저작권 머리글은 이 폴더에 포함된 세 폰트의 내장 저작권 정보로 바꾸고, 라이선스 본문은 그대로 두었습니다.
|
||||
|
||||
Regular / Bold / ExtraBold를 각각 제공하고, Pretendard는 100~900 가변 굵기를 제공합니다.
|
||||
@@ -208,6 +208,8 @@ DDL: `scripts/sql/cupang_db_init.sql` (멱등). DB·역할(`cupang_app`)·테이
|
||||
|
||||
박스 계산은 서버(`store.compute_boxes`)에서 재계산: `required_boxes = ceil(quantity / units_per_box)`. 클라이언트 계산은 미리보기용.
|
||||
|
||||
제품 카탈로그 `cupang_products`(제품코드 UNIQUE·제품명·쿠팡상품코드·활성) — **포장무게 `weight_g`**(INTEGER g, NULL = 미입력, 0~1,000,000 CHECK)는 마이그레이션 `scripts/sql/cupang_db_007_product_weight.sql`, 초기 값 시드 `scripts/sql/cupang_products_weight_seed.sql`(무게가 비어 있는 행만 채움, 실행 전 값은 `_cpg_weight_seed_backup` 에 남김). 007 미적용이면 화면은 무게 칸을 숨기고 그대로 동작. 출고 상세의 상자별 무게 합계는 저장하지 않고 화면·엑셀을 만들 때 지금 무게로 계산한다.
|
||||
|
||||
임시 저장(`cupang_box_calc_drafts`)은 화면 상태 스냅샷만 담는다. 불러올 때 박스 수는 저장값을 쓰지 않고 서버에서 다시 계산하고, 그 위에 분배 내역을 얹는다(사라진 항목은 제외). 마이그레이션: `scripts/sql/cupang_db_003_box_calc_drafts.sql`.
|
||||
|
||||
상품은 `cupang_db` 에 복제 저장하지 않는다. 라인에는 `product_code` + `product_name_snapshot` 만 보존(과거 명칭 보존). 상품 검색은 `itemcode_db` **읽기 전용**(`ITEMCODE_DB_URL`, 미설정 시 수동 입력).
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
|
||||
|
||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑 = **구현됨**, 나머지 5개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 단계에서 공식 API 문서로 확정**한다.
|
||||
|
||||
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
||||
@@ -147,6 +147,42 @@
|
||||
**GS샵 수수료율은 0%**. 배송비 제외, `ordType` 이 SALE 이 아니면 RETURN 음수. `replace_range`.
|
||||
원본 데이터 확인에 날짜별 현재 규칙 매출·취소/반품·배송비(참고).
|
||||
|
||||
### 토스쇼핑 (`adapters/toss.py`, 구현됨)
|
||||
|
||||
- 문서: `https://shopping-docs.toss.im/dev` (공개, 전체 목록 `llms.txt`, 쪽 주소 뒤 `.md` = 원문). 문의는 문서의 디스코드.
|
||||
- 인증: 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > **자체 개발** → [키 발급](**호출 IP 입력 — 운영 서버 외부 IP**, 등록된
|
||||
IP 만 호출 가능) → Access Key·Secret Key. `POST https://oauth2.cert.toss.im/token`(form: `grant_type=client_credentials`·
|
||||
`client_id`=Access Key·`client_secret`=Secret Key·`scope=toss-shopping-fep:write`). 토큰 `expires_in` 약 1년 — 문서가 매번 발급하면
|
||||
이용이 제한될 수 있다고 해서 `access_token`·`access_token_expires_at`(internal, 암호화)으로 저장해 재사용, 만료 1시간 전·401 이면 새로.
|
||||
[연결 테스트]는 입력값으로 시험하므로 항상 새 토큰. 입력칸 키는 처음 만든 `api_key`(Access Key)·`api_secret`(Secret Key) 그대로
|
||||
(라벨만 변경 — 예전 "판매자 ID" 칸은 없앰).
|
||||
- API: `https://shopping-fep.toss.im`, `Authorization: Bearer {token}`. 오류가 **HTTP 200 + `resultType: "FAIL"`**(`error.errorCode`·
|
||||
`reason`)로도 온다. 읽기 초당 50회(넘으면 `TOO_MANY_REQUEST`) → 호출 간격 0.1초, 제한이면 1·2·4초 쉬고 다시.
|
||||
- 수집: 주문 내역 조회 `GET /api/v3/shopping-fep/orders/v2?startDate&endDate&limit=50&nextCursor` — 한 번에 **31일**, 상태 생략 =
|
||||
전체, 커서(`nextCursor` null = 끝). 줄 = 주문상품(`orderProductId`), 주문 = `orderId`. 금액 항목: `price`(판매가 × 수량)·
|
||||
`originPrice`(정상가 × 수량)·`totalDiscountPrice`(= `tossShoppingDiscount` + `tossPayDiscount`)·`tossPayPoint`·`deliveryFee`
|
||||
(묶음 `deliveryFeeGroupId` 마다). 결제일 필드는 따로 없고 `orderedAt`(주문 = 결제) · `canceledAt` · `confirmedAt`.
|
||||
- **매출 규칙 = 파트너스 "순 거래액" = 매출 − 환불**(2026-10-01 사용자 지정, 9/6 화면: 매출 29,600 − 환불 11,900 = 순 거래액 17,700).
|
||||
- 매출 SALE = 주문 하나(`toss:{orderId}`), 날짜 = `orderedAt` 의 한국 날짜, 금액 = `price` 합(할인 전, 배송비 제외), 할인은
|
||||
`discount_amount` 로만. 결제 전(`BEFORE_PAYMENT`)만 빼고 나중에 취소·반품된 주문도 주문일 매출에 둔다(화면 "매출"도 환불 전).
|
||||
- 환불 = **환불일**에 뺀다, 주문상품마다 한 번(사건 ID `toss:R{orderProductId}`), `merge_refunds`:
|
||||
① 클레임 목록 `GET /api/v3/shopping-fep/claims?size=100&nextToken`(유형·상태 조건 없음 = 전체 — 이 API 는 그 밖엔 날짜로 못 거른다,
|
||||
최대 1만 건)의 **환불 완료**(`isRefunded`) `CANCEL`·`RETURN` — 날짜 = `refundedDt`. 반품은 이것뿐(주문 내역엔 반품 완료 날짜 없음).
|
||||
사건 종류 CANCEL / RETURN.
|
||||
② 클레임이 **없는** 결제취소(`CANCELED_PAYMENT`) — 날짜 = 주문 내역 `canceledAt`(결제완료 단계 고객 취소는 클레임이 안 생김).
|
||||
클레임이 있는 주문상품은 클레임 날짜만 쓴다(그 날짜가 기간 밖이어도 취소 시각으로 다시 넣지 않음 — 날짜가 흔들리지 않게).
|
||||
금액 = 그 주문상품의 `price`(판매가 × 수량 — 매출과 같은 기준), 주문 내역에 없으면 클레임 `order.price`. 다른 날 주문의 환불을 잡으려고
|
||||
수집 때 **기간 앞 90일**(`CANCEL_LOOKBACK_DAYS`) 주문 내역도 부른다. 교환·미환불 클레임은 제외.
|
||||
- 수집은 `collect` 를 직접 구현(주문 내역을 매출·환불 금액·취소 시각에 함께 쓰려고). 진행 막대 = 기간 주문 구간 + 앞 90일 구간 + 클레임 1.
|
||||
`replace_range`(접두어 `toss:` — 매출·환불 함께 교체). 개인정보(주문자·수령인·주소·요청사항·수거 주소·요청 사유·송장)는 저장 안 함.
|
||||
- **실데이터 대조(2026-10-01, 9/6)**: 매출 29,600 = 주문 2건 `price` 합 **일치**(`orderedAt` 은 시간대 없이 한국 시간 — 17:57 주문도 9/6).
|
||||
환불 11,900 = 9/5 주문(276435356)을 9/6 취소 — 클레임 `CANCEL/COMPLETED` `refundedDt` 9/6 과 `canceledAt` 9/6 **둘 다 일치**,
|
||||
정산 건별 REFUND 에는 **없다**(9/6 거래일 정산 = PAY 2줄 + 배송비 2줄뿐 — 구매확정 전 취소는 정산에 안 올라옴) → 정산은 환불에 쓰지 않는다.
|
||||
- 원본 데이터 확인(토스쇼핑): 날짜별 **매출(주문일)·환불(환불일)·순 거래액**(`day_cols`, = 저장되는 값) + **환불 출처별 비교**
|
||||
(`refund_candidates`: 적용 규칙 · 클레임 환불 완료 · 주문 취소 시각 · 정산 REFUND(참고), 날짜별 합계 + 건별 주문번호·금액·메모)
|
||||
+ 주문 상태별·클레임·정산 항목 합계. 화면 숫자와 다르면 출처별 열로 어느 쪽이 빠졌는지 본다.
|
||||
- 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`.
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||
@@ -198,9 +234,11 @@
|
||||
| 기능 | 권한 |
|
||||
|---|---|
|
||||
| 대시보드 · 매출 업데이트 · 금액 상세 | `performance` (admin 자동) |
|
||||
| 설정 화면 · 수수료 · 인증정보 · 연결 테스트 · 테스트 데이터 · 재암호화 | `is_admin` |
|
||||
| 설정 화면 진입 · **수수료율 조회·변경·이력 삭제**(`/api/marketplaces/{code}/rates`) | `performance` (2026-10-01부터 일반 사용자도) |
|
||||
| 사용·매출 집계 토글 · 인증정보 · 연결 테스트 · 원본 데이터 확인·대조 · 과거 매출 가져오기(92일 초과) · 테스트 데이터 · 재암호화 | `is_admin` |
|
||||
|
||||
화면에서 설정 탭을 숨기는 것과 별개로 모든 설정 API 가 `common.require_store(admin=True)` 로 403 을 낸다.
|
||||
일반 사용자의 설정 화면(탭 이름 "수수료 설정")은 쇼핑몰 표에 쇼핑몰·수수료율·마지막 동기화만, 다른 칸·카드는 템플릿이 관리자에게만
|
||||
그린다. 화면과 별개로 수수료 API 를 뺀 설정 API 는 모두 `common.require_store(admin=True)` 로 403 을 낸다.
|
||||
|
||||
## 6. 동기화 (`sync.py`)
|
||||
|
||||
@@ -220,6 +258,10 @@
|
||||
직전(`ctx.progress.check()` → `Cancelled`)에 멈추고 **저장하지 않는다**(저장은 수집이 끝난 뒤 한 트랜잭션이라 기존 매출 그대로),
|
||||
차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 남고, 저장 중이던 쇼핑몰은 그 저장을 끝낸다.
|
||||
취소된 실행은 `perf_sync_runs` 에 failed + "업데이트 취소", 연결 상태(`perf_connection_status`)는 바꾸지 않는다.
|
||||
- **쇼핑몰별 [중지]**(진행 창 쇼핑몰 이름 옆, 대기·수집 중일 때만, 시작한 사람·관리자,
|
||||
`POST /api/sync/jobs/{id}/shops/{code}/stop`): 그 쇼핑몰만 위와 같은 방식으로 멈추고(저장 안 함, 기존 매출 그대로) **다음 쇼핑몰로
|
||||
넘어간다**. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. `ShopProgress.stop_requested` → `cancel_requested`/`check()`,
|
||||
상태 "중지됨"(`stopped_only`), `perf_sync_runs` 는 failed + "쇼핑몰 중지". 저장 중·끝난 쇼핑몰은 409.
|
||||
- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
|
||||
+ 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
|
||||
9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·
|
||||
|
||||
+350
-9
@@ -9,9 +9,22 @@
|
||||
목록(보기 탭, 예전 "리스트") · 캘린더(예전 "달력") · 수신함 · 첨부 파일 · 작업 링크 복사 ·
|
||||
프로젝트 칸 + "다른 프로젝트에 추가"(예전 "연결된 프로젝트") · 담당자 없음(예전 "(미지정)").
|
||||
"@태그"는 그대로 쓴다. 코드 식별자·DB 컬럼(`tasks`, `stage_id`, `task_followers` 등)과 코드 주석은 예전 이름 그대로다.
|
||||
**도움말** — `/project/help`(`project/help.html` + `static/project-help.css`), 프로젝트 관리 화면 상단 바 로그아웃
|
||||
**도움말** — `/project/help`(`project/help.html` + `static/project-help.css`·`static/project-help.js`), 프로젝트 관리 화면 상단 바 로그아웃
|
||||
오른쪽 **?** 아이콘(`_help_btn.html`, `erp_base.html` 의 `topbar_after_logout` 블록)으로 새 탭에서 연다. 처음 쓰는 사람용
|
||||
기능 설명 20장 — **화면 기능을 바꾸면 도움말도 같이 고친다.**
|
||||
기능 설명 22장 — 목표·주간 회의록은 별도 장으로 진입·입력·지표 계산·쇼핑몰 연결·저장·삭제까지 설명한다.
|
||||
도움말 검색은 실제 본문의 장·소제목으로 색인을 만들어 제목·본문을 한 글자부터 검색한다(띄어 쓴 단어는 모두 포함).
|
||||
결과에 소제목·본문 일부와 일치 단어를 강조하고, 클릭 또는 Enter로 해당 소제목에 스크롤·포커스를 옮긴다.
|
||||
`/`는 도움말 검색창, Esc·지우기는 초기화. 한글 조합 중에는 검색 이동을 하지 않는다.
|
||||
검색어는 `?q=`, 읽는 위치는 `#소제목`으로 유지해 새로고침·공유·뒤로 가기에서도 복원한다. DB/API 호출 없이 동작한다.
|
||||
검증: `python tests/js/render_help.py` 후 `node tests/js/help_ui.test.js`(jsdom),
|
||||
`node tests/js/help.browser.test.js`(Playwright/Chromium — 실제 ERP 셸·390px 모바일·검색 이동·URL 복원).
|
||||
**화면 기능을 바꾸면 도움말도 같이 고친다.**
|
||||
**Project 옵션**(2026-10-02) — 도움말 오른쪽 톱니 버튼(`_options.html` 공통 include)이 native dialog를 연다.
|
||||
현재 시스템 폰트(기본)·Pretendard Variable·NanumSquare·NanumSquareNeo·NanumSquareRound 중 선택하고 미리보기 → 저장 후 닫기.
|
||||
`localStorage.pj_font`에 이 브라우저의 선택을 기억하며 모든 Project 화면에서 복원한다. 취소는 적용하지 않는다.
|
||||
`project.css`의 `--pj-font`만 변경하므로 다른 ERP 화면은 영향을 받지 않으며 아이콘·코드 고정폭 폰트는 유지한다.
|
||||
폰트는 `static/vendor/project-fonts/`에 원본·저작권/OFL을 함께 보관하고 `project-fonts.css`에서 선언한다(외부 CDN 없음).
|
||||
저장 시 400/700 글꼴 로딩을 확인하고, 실패하면 이전 설정과 열린 창을 유지해 재시도할 수 있다.
|
||||
**멤버 이름 표기** — 이메일 아이디의 첫 글자만 대문자(king → King). JS 는 `idOf(email)`/`capName(s)`,
|
||||
템플릿은 `{{ nm[:1]|upper }}{{ nm[1:] }}` 로 화면에 그릴 때만 바꾼다(API `id`·DB 값은 그대로 — 멘션·검색은 이메일 기준).
|
||||
**프로젝트 색상·아이콘(아사나식)** — 색상표는 32색(`store.COLOR_PALETTE`, 8칸×4줄 — 위 2줄은 아사나 프로젝트 16색, 아래 2줄은 같은 열의 진한 색. 진한 칸은 체크를 흰색 `.is-dark`. 새 프로젝트
|
||||
@@ -45,6 +58,26 @@
|
||||
|
||||
## 1-1. 프로젝트 → 섹션 → 작업 (하위 작업 포함) 3단계 구조
|
||||
|
||||
**화면 조정(2026-10-03)** — 본문 좌우 여백 8px. 공용 왼쪽 메뉴 오른쪽 경계를 드래그해
|
||||
170~500px로 조절(방향키도 지원, 더블클릭 기본값), `localStorage.pj_side_w`에 기억한다.
|
||||
드래그 중에는 최신 마우스 위치를 화면 프레임당 한 번 반영하고, 목표 표 글 높이 등 전체 화면 재계산은
|
||||
놓는 순간에 한 번만 실행한다. 창 포커스를 잃을 때도 마지막 위치를 저장하고 드래그를 종료한다.
|
||||
수신함·내 작업 배지는 메뉴 이름 바로 옆에 표시. 댓글·답글 입력칸은 70px 고정 높이, 긴 글은 내부 스크롤.
|
||||
전체 멤버는 메뉴 내부 폭 207px 이하에서는 3열, 그보다 넓으면 4열로 자동 재배치한다(container query).
|
||||
각 멤버 칸은 최소 너비를 강제하지 않고 스크롤바용 여백 안에 맞추므로 오른쪽 멤버가 가려지지 않는다.
|
||||
보드 그룹 머리의 왼쪽 화살표+세로선 아이콘은 그룹 축소, 축소 후 반대 방향 아이콘으로 펼치기.
|
||||
축소 시 카드·추가 버튼을 숨기고 섹션 제목·작업 수를 세로로 표시하며
|
||||
`localStorage['pj_board_fold:'+projectId]`에 섹션 id(전체 프로젝트 보기에서는 이름)별로 기억한다.
|
||||
이 설정은 화면 표시만 바꾸므로 읽기 전용 사용자도 조절 가능하며 서버 작업·섹션 데이터는 변경하지 않는다.
|
||||
목표 표 열 너비는 모든 행의 셀 오른쪽 경계에서 조절(병합 셀은 오른쪽 끝 열), 새 줄·병합·합계 재계산 뒤에도 유지.
|
||||
경계를 더블클릭하면 그 열의 가장 긴 문단에 자동으로 맞춘다. 직접 넣은 줄바꿈은 유지하고 글꼴·크기·굵기·여백을
|
||||
반영하며, 병합 칸은 다른 열 너비를 유지한 채 선택한 열만 맞춘다. 긴 문단은 드래그 최대 너비(600px)를 넘어도
|
||||
맞추고 브라우저에 기억한다(이름 열도 자동 맞춤 가능). 현재 편집 중인 글·숫자도 내용 변경 없이 측정한다.
|
||||
목표 업무 행 높이는 가장 높은 글 칸의 자연 높이에 맞춘다. 글·이름 칸 모두 위·아래 6px 여백과 상단 정렬을
|
||||
사용하며, 글이 짧아지면 행도 줄어든다. 글이 한 줄이거나 비어 있으면 한 줄 높이만 확보하고 보기 전용도 같은 규칙이다.
|
||||
목표 글자를 선택하면 해당 셀 상단 중앙을 기준으로 셀 위에 서식 도구가 표시되며, 색상은 지정된 12색 견본으로만 선택한다.
|
||||
기존 글의 다른 색상은 보존. 글자 선택 해제·외부 클릭·편집 셀 제거 시 도구를 닫고 기존 부분 서식·자동 저장을 재사용한다.
|
||||
|
||||
**"섹션"은 새 개념이 아니라 기존 "단계"(칸반 컬럼)를 그대로 재사용한다** —
|
||||
아사나도 보드 뷰의 컬럼과 목록 뷰의 구분선이 같은 "섹션" 하나다. DB
|
||||
컬럼/테이블 이름(`project_stages`, `stage_id`)은 그대로 두고, 사용자에게
|
||||
@@ -57,15 +90,33 @@
|
||||
HTML5 DnD, `PUT /api/projects/{id}/stages/order` 재사용). "전체 프로젝트"
|
||||
스코프(여러 프로젝트를 섹션 '이름'으로 합쳐 보는 예전 방식)에서는 섹션을
|
||||
하나로 특정할 수 없어 관리 UI가 없다.
|
||||
- **보드 빠른 작업 추가**(2026-10-02) — 하단 `+ 작업 추가`·섹션 메뉴에서
|
||||
상세창 대신 보드 안에 이름·담당자·마감일 입력 카드가 열린다. Enter는 저장 후 연속 입력,
|
||||
카드 밖 클릭은 저장 후 닫기, Esc·빈 카드 밖 클릭은 취소. 섹션 기본 담당자를 적용하고,
|
||||
저장 실패 시 입력을 유지하며 저장 중 반복 제출을 막는다. 기존 작업 생성 API를 재사용한다.
|
||||
**섹션 머리 `+`는 기존 오른쪽 작업 상세창**(`openTaskModal`)을 열어 제목·설명·담당자·우선순위·마감일을 설정한다.
|
||||
- **하위 작업(subtask)** — 새 테이블이 아니라 `tasks.parent_task_id` 재사용
|
||||
(부모 삭제 시 CASCADE). 작업 편집 팝업 안에 인라인으로 표시되며(체크박스+
|
||||
제목+담당자+마감일, 한 줄에서 바로 저장), 보드/캘린더/목록에는 최상위
|
||||
작업만 카드로 뜬다(하위 작업은 부모 카드의 "N ⤷ ▾" 토글로 — 누르면 아사나처럼 카드 아래로
|
||||
하위 작업 목록(완료 체크·제목·마감·담당자)이 펼쳐진다. 펼친 상태는 페이지에 머무는 동안 유지).
|
||||
섹션을 갖지 않는다(칸반에 안 보이므로).
|
||||
펼친 하위 작업 한 줄을 다른 카드로 드래그하면 그 작업의 하위 작업으로 옮겨진다
|
||||
펼친 하위 작업 한 줄을 같은 카드 안에서 위아래로 드래그하면 순서가 저장된다
|
||||
(`PUT /api/tasks/{parent_id}/subtasks/order` `{ordered_ids}` — 작업 팝업과 같은 API).
|
||||
보라색 선으로 삽입 위치를 표시하며 실패 시 기존 순서를 유지한다.
|
||||
다른 카드로 드래그하면 그 작업의 하위 작업으로 옮겨진다
|
||||
(`POST /api/tasks/{id}/move-parent` `{parent_task_id}` → `db.move_subtask`, 활동 `subtask_moved`).
|
||||
받는 쪽은 **같은 프로젝트의 최상위 작업만**(순환 방지), 하위 작업의 하위 작업은 함께 따라간다.
|
||||
**카드 크기·표지**(2026-10-02): 카드 높이 100px 고정(`.pj-card-head` height 86px = 100 − 아래 여백 12 − 테두리 2, 제목 2줄·
|
||||
프로젝트 배지가 있으면 1줄까지, 담당자·날짜 줄은 맨 아래), 담당자 13.2px·아바타 20px·날짜 12.1px(기존 +10%).
|
||||
**카드 완료 표시**: 제목 왼쪽 원형 체크 버튼(`.pj-card-check`, role=checkbox·aria-checked).
|
||||
완료된 카드는 녹색 원 안 흰 체크 + 회색 제목으로 표시하며 취소선은 없다. 클릭하면 기존 작업 PUT `{completed}`로 완료/취소.
|
||||
저장 중 중복 클릭을 막고 응답 후 카드·내 작업 개수를 갱신한다. 실패하면 상태를 유지해 재시도할 수 있다.
|
||||
읽기 전용 작업은 비활성 체크로 상태만 표시하며 카드 높이·표지·하위 작업 펼침과 드래그 구조는 유지한다.
|
||||
설명에 이미지가 있으면 **첫 이미지를 카드 위 표지**로(아사나, `cardCoverSrc` — template 로 읽어 이미지를 불러오지 않음,
|
||||
우리 첨부·http(s)·data:image 만, 높이 140px object-fit cover). 표지·펼친 하위 작업은 100px 위·아래에 더해진다.
|
||||
**하위 작업이 없는 카드**도 같은 모양의 빈 토글(⤷ ▾, `.pj-card-subtoggle.is-empty` — 카드에 마우스를 올리면 보임, 편집 권한자만)이
|
||||
있어 누르면 카드 아래가 펼쳐지며 곧바로 새 하위 작업 이름 입력 줄이 열린다(빈 목록엔 "하위 작업 없음" 대신 추가 줄).
|
||||
펼친 하위 작업 목록 맨 아래 **"+ 하위 작업 추가"**(아사나, `renderSubAdd`) — 누르면 그 자리에 새 줄
|
||||
(✓ · "작업 이름 입력" · 점선 달력 · 점선 사람)이 열려 Enter 로 바로 만들고, 줄은 열린 채 다음 입력으로.
|
||||
이름을 쓴 채 다른 곳을 누르면 Enter 와 같이 만들고 줄은 닫힘(`onOutsideDown` — 문서 pointerdown, 한글 조합 중인
|
||||
@@ -293,6 +344,17 @@ docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_012_comment_replies_reactions.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_013_goals.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< 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
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_016_goal_row_label_groups.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_017_goal_quarters.sql
|
||||
# 018 = 주간 회의록 줄 연결키(line_key) — 적용 전 백업, 적용·확인 방법은 6-9-3
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_018_meeting_line_keys.sql
|
||||
|
||||
# 4) 재배포 (git pull 후 반드시 --build)
|
||||
cd /opt/www/main && docker compose up -d --build web
|
||||
@@ -347,6 +409,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
(`.pj-modal-actions-top`) — 카드가 flex column 이고 `.pj-modal-body` 만 스크롤하므로 sticky 없이 고정된다(sticky 는 카드 padding 안쪽에 붙어 바가 밀려 내려오고 제목을 덮었다). 저장 버튼은 없다 — 실시간 저장(§6-6).
|
||||
댓글 입력칸은 아사나처럼 **창 맨 아래 고정**(`#pj-comment-dock`) — `.pj-modal-body` 바깥 형제라서
|
||||
끝까지 스크롤해도 마지막 내용이 입력칸 위에서 멈춘다(sticky 아님). 새 작업(id 없음)이면 숨긴다.
|
||||
댓글·댓글 대화창(`#pj-cm-input`)·답글 입력칸은 여러 줄 입력칸(`textarea.pj-composer-ta`) — **Enter = 등록, Shift+Enter = 줄바꿈**,
|
||||
입력칸 높이는 70px로 고정된다(`fitComposer`, 긴 글은 내부 스크롤). 댓글 본문은 `white-space: pre-wrap` 이라 줄바꿈이 그대로 보인다.
|
||||
**설명란 이미지 더블클릭 → 별도 브라우저 창**(`openImageWindow`, 페이지 안 팝업 아님) — 창 크기 = 원본 크기(화면보다 크면 95%),
|
||||
처음 원본 100%(창보다 크면 맞춤), 휠 = 커서 기준 확대·축소, 끌기 = 이동, 아래 막대 − / % / + · 1:1 · 맞춤, 더블클릭 = 원본↔맞춤,
|
||||
키 + − 0 1 Esc. 팝업이 막히면 허용 안내 토스트.
|
||||
그 아래 메타(담당자·섹션·우선순위·마감일 한 줄 — 마감일은 캘린더 아이콘 버튼, 좁으면 2×2 | 협업자), 다시 그 아래 **설명란**과
|
||||
**하위 작업**가 각각 팝업 너비 전체를 쓰는 별도 행(`.pj-desc-block` / `.pj-subtask-full`,
|
||||
그리드 `1 / -1`). 하위 작업은 제목 왼쪽 체크박스로 완료를 토글하고, 완료된 줄은
|
||||
@@ -478,6 +545,8 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
프로젝트 화면을 `?task={id}&embed=1` 로 iframe 에 열고, `html.pj-embed` 가 작업 창 외에는 숨긴다.
|
||||
작업 창을 닫으면 iframe 이 `postMessage({type:"pj-embed-close"})` → 패널 닫힘.
|
||||
embed 에서만 작업 창 맨 위에 "프로젝트로 이동"(`#pj-goto-project`) — `window.top` 을 그 프로젝트 화면(`?task=`)으로. Ctrl+클릭은 새 탭(예전처럼 이동).
|
||||
- **위쪽 여백 줄임**(2026-10-01): 프로젝트 관리 모든 화면(`.erp-page` 안이 `.pj-wrap`·`.pjh` 일 때만, `:has`)은 공통 본문 위 여백
|
||||
24px → 6px, 화면 위 여백·제목 줄 위 여백 0 — 상단 바와 제목 사이 36px → 6px. 다른 모듈은 그대로.
|
||||
- 화면 배율 토글(상단 바 `fit_screen`, `_help_btn.html`) — `html.pj-ui-scale` 이면 `.erp-app` 에 `zoom: .75`
|
||||
(2880×1620·200% = CSS 폭 1440px 에서 1920 기준 화면처럼). zoom 안에서 줄어드는 `vh` 높이는 배율로 나눠
|
||||
되돌린다. 팝업은 전부 `body` 에 붙어 배율 밖이라 좌표 보정 불필요(전체 검색 결과창도 body 로 옮김),
|
||||
@@ -489,9 +558,18 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
(`initGoalSide`, localStorage `pj_goal_open`, 목표 화면에선 항상 펼침). 연도 목록은 `router._goal_years_nav`
|
||||
(`goal_years` 최근 연도 먼저 + **올해는 항상**, 013 미적용이면 올해만) — 사이드바를 그리는 모든 화면 컨텍스트에 `goal_years`.
|
||||
- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정,
|
||||
이번 달 열 강조. 월 칸 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`), 머리·왼쪽 이름 가운데 정렬(왼쪽 이름은 세로도 가운데 — 관리자 도구는 칸 아래에 떠 있는 막대라 자리를 차지하지 않음). 왼쪽 이름 두 칸(구분·항목)은 머리 칸 오른쪽 끝을 끌어 너비 조절(48~320px, 더블클릭 = 72px) — 브라우저별 localStorage `pj_goal_col_w`, CSS 변수 `--goal-c1-w`·`--goal-c2-w`.
|
||||
이번 달 열 강조. **가로 스크롤 때 3열(구분·항목·연간)까지 고정** — 연간 열 `position: sticky; left: 1열+2열 너비`, 경계 그림자.
|
||||
월 칸 기본 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`). 머리·왼쪽 이름은 가로 가운데 정렬이며,
|
||||
업무 영역의 이름·글은 세로 상단 정렬, 위·아래 여백 각 6px이다. 행 높이는 가장 높은 글 칸에 맞추고 글이 줄면 함께 줄어든다.
|
||||
**모든 열**(구분·항목·연간·1~12월·분기)은 모든 행의 셀 오른쪽 끝에서 끌어 너비 조절(더블클릭 = 가장 긴 문단에 맞춤).
|
||||
브라우저별 localStorage `pj_goal_col_w`(키 `c1`·`c2`·`y`·`m1`~`m12`·`q1`~`q4`, 기본값과 다른 칸만 저장).
|
||||
드래그는 이름 두 칸 48~320px·CSS 변수 `--goal-c1-w`·`--goal-c2-w`, 나머지 40~600px·머리 칸의 `--cw`로 조절한다.
|
||||
자동 맞춤은 긴 문단에 맞게 최대 너비를 넘어도 저장·복원한다. 접기 애니메이션의 월 칸 안쪽 고정 폭은
|
||||
`--fold-w`(병합 칸 = 걸친 월 너비 합)로 JS가 넣는다.
|
||||
- **틀 고정** — 세로 스크롤에도 머리 줄 + 숫자 지표(매출·로아스) 줄까지 위에 붙어 있다. 지표 칸 `position: sticky` + 줄마다 `--kpi-top`(머리 줄 높이 + 앞 지표 줄 높이 합, `stickKpi`, 창 크기 바뀌면 다시 잼). z-index: 영역 이름 칸 2(마우스 올림 6) < 지표 칸 7 < 지표 이름 칸 8 < 머리 줄 9 < 머리 이름 칸 10.
|
||||
- **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) —
|
||||
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, 연간은 실적이 있는 달의 목표 합계 대비)는
|
||||
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, **연간·반기는 그 기간 목표 합계 전체 대비 입력된
|
||||
실적 합계** — 2026-10-01 사용자 기준, 예전엔 실적이 있는 달의 목표만)는
|
||||
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
|
||||
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
|
||||
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
|
||||
@@ -501,14 +579,277 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
관리자에게 "목표 만들기" 버튼(GET 에서 자동 생성하지 않는다). 연도 삭제는 연도를 직접 입력해야 진행(CASCADE 전부 삭제).
|
||||
- API(전부 관리자): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
|
||||
`{metric,kind,month,value}`(빈값 = 지움, 응답 `label` 은 쉼표 표기) · `POST /api/goals/{y}/areas` `{name,color}` ·
|
||||
`PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` ·
|
||||
`PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` `{label, ref_row_id?, place?: above|below}`(기준 줄 위/아래, 없으면 맨 끝) ·
|
||||
`PUT|DELETE /api/goals/rows/{id}` · `POST /api/goals/rows/{id}/move` · `PUT /api/goals/rows/{id}/cells/{month}` `{body}`.
|
||||
013 미적용 503, 없는 대상 404, 입력 오류 400(`_goal_call`).
|
||||
- 화면 동작(`initGoals`): 숫자 칸은 Enter/칸 떠남에 저장(Esc 취소), 글 칸은 0.8초 멈춤·칸 떠남·페이지 떠남(keepalive)에 저장,
|
||||
저장되면 칸 테두리가 잠깐 초록. 영역/줄 추가·이름·순서·삭제는 저장 뒤 새로고침(스크롤 위치 sessionStorage 로 되살림),
|
||||
영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지).
|
||||
- 화면 동작(`initGoals`): 숫자 칸은 Enter/칸 떠남에 저장(Esc = 저장된 값으로), 글 칸은 0.8초 멈춤·칸 떠남에 저장,
|
||||
저장되면 칸 테두리가 잠깐 초록, 실패하면 빨간 테두리(입력값 유지). 저장은 공용 `createFieldSaver`(6-9-3 — 같은 칸 요청 직렬화,
|
||||
보낸 값만 저장됨으로, 실패 시 초안 유지·localStorage 초안 백업, 페이지 떠남 보호). 영역/줄 추가·순서·삭제·병합은 먼저 저장 안 된
|
||||
글을 저장하고(실패하면 작업 중단) 그 자리에서 다시 그림(`refreshTable`), 영역 색은 팝업(body 에 붙임)에서 바로 바뀜.
|
||||
목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지).
|
||||
- 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기.
|
||||
|
||||
### 6-9-0. 1~4분기 칸 (마이그레이션 017, 2026-10-01 — 상·하반기 대신)
|
||||
|
||||
- **열 순서** — 연간 · 1~3월 · **1분기** · 4~6월 · **2분기** · 7~9월 · **3분기** · 10~12월 · **4분기**
|
||||
(`store.GOAL_COL_ORDER = (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)`). 템플릿 컨텍스트 `quarters`
|
||||
(`(분기, 월 목록, 글 칸 번호, "N분기")`), 월 칸 `data-h` = 분기 1~4, 분기 칸 클래스는 예전 이름 `pj-goal-half-col` 그대로.
|
||||
- **분기 글 칸 번호**(`store.GOAL_QUARTER_COL`) = 1분기 13 · 2분기 15 · 3분기 14 · 4분기 16 — 예전 반기 칸 번호를 그대로 이어 써서
|
||||
글을 옮기지 않는다(예전 상반기 글 → 1분기, 하반기 글 → 3분기에 보임). 15·16 은 017 이 `goal_cells` CHECK 를 0~16 으로 넓힌 뒤에만
|
||||
저장(미적용이면 읽기 전용 칸 + API 503 `GoalMigration017Needed`, 적용 여부 = `db._goal_quarters` → `board.quarters`).
|
||||
- **병합** — 가로는 **같은 분기 월 칸끼리만**, 연간·분기 칸은 세로로만(`goal_col_group`: year · q1~q4 · months1~4).
|
||||
017 은 분기를 넘던 예전 반기 병합(예: 2~4월)을 그 분기 끝 월까지로 줄이고(글은 시작 칸 그대로), 한 칸짜리가 된 병합 행은 지운다.
|
||||
화면(`_goal_area_layout`)도 분기를 넘는 병합은 잘라 그린다(017 전에도 안전).
|
||||
- **숫자 지표** — 분기 칸 = 그 분기 월 합계, 달성률 = 분기 실적 합계 ÷ 분기 목표 합계(`SUM_SCOPES` 연간 + 4분기),
|
||||
로아스 분기 = 매출 가중 평균(연간과 같은 규칙).
|
||||
- **업무 영역 추가 · 줄 추가는 묻지 않고 바로**(2026-10-02) — 영역은 "새 업무 영역", 줄은 빈 이름으로 만들고 표를 다시 그린 뒤
|
||||
그 이름 칸을 바로 입력 상태로(`editNewName` → `startNameEdit`, Enter 저장 · Esc 그대로).
|
||||
- **분기 접기** — 분기 **머리 칸 아무 곳이나** 누르면(`.pj-goal-fold-th`, 너비 조절 손잡이를 끈 직후 0.3초 클릭은 무시) 그 분기 월 칸을
|
||||
접었다 편다. 아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘) — 바뀔 때 90° 돌며 세로 막대가 자라거나 줄어든다.
|
||||
- **분기 색(monday.com 그룹 색 띠 방식)** — 분기마다 차분한 색 하나(1 파랑 · 2 청록 · 3 보라 · 4 남색, 달성률 빨강·초록과 안 겹치게).
|
||||
`data-h` 가 있는 칸에 `--qc`·`--qt`·`--qt2`. 머리 위 색 띠 = 월 칸 3px · 분기 칸 6px(`th::before`, 월 링크가 덮어도 보임),
|
||||
분기 열 전체 옅은 음영(`td.pj-goal-half-col[data-h]` background-image — 영역 색 위에도), 분기 칸 오른쪽 2px 경계,
|
||||
분기 머리 글자·아이콘은 분기 색, 접힌 분기 머리는 진한 음영.
|
||||
열 너비 키는 `q1`~`q4`(기본 80px).
|
||||
- 아래 6-9-1 의 상·하반기 설명은 014 당시 기록 — 칸 번호·접기·병합 규칙은 이 절이 우선.
|
||||
|
||||
### 6-9-1. 상·하반기 칸 · 반기 접기 · 이름 바로 수정 · 월 칸 병합 · 로아스 % (마이그레이션 014) — 017 에서 분기로 바뀜(6-9-0)
|
||||
|
||||
- **열 순서** — 연간 · 1~6월 · **상반기** · 7~12월 · **하반기**. 템플릿 컨텍스트 `halves`
|
||||
(`(반기, 월 목록, 글 칸 번호 13|14, 이름)`), 월 칸은 `pj-goal-m` + `data-h="1|2"`, 반기 칸은 `pj-goal-half-col`.
|
||||
- 숫자 지표: 매출 목표·실적의 반기 칸 = 그 반기 월 합계(`data-scope="13|14"`, 연간은 `0`), 달성률은 연간과 같은 규칙
|
||||
(그 반기 목표 합계 대비 실적, `SUM_SCOPES`). **로아스 연간·반기**(목표·실적) = 기간 매출 ÷ 기간 광고비 — 광고비를 따로 적지 않아
|
||||
월마다 매출 ÷ 로아스로 환산해 합친 **매출 가중 평균**(같은 목표/실적 매출 사용), 로아스가 있는 달 중 매출이 없는 달이 있으면 단순 평균
|
||||
(말풍선에 방식·개월 수). 화면 계산(저장 안 함), 숫자 칸을 고치면 바로 다시 계산.
|
||||
- 업무 영역 글: `goal_cells.month` **13 = 상반기, 14 = 하반기**(014 가 CHECK 를 0~14 로 넓힘). 014 미적용이면 반기 글 칸은
|
||||
보기 전용 빈 칸이고, 저장 API 는 503 "마이그레이션 014 필요"(`store.GoalMigration014Needed`).
|
||||
- **반기 접기** — 반기 칸 머리의 버튼(`.pj-goal-fold`, 펼침 ‹ / 접힘 뒤집힌 › + 강조색)이 그 반기 월 칸을 접었다 편다.
|
||||
보기 전용 사용자도 쓸 수 있고 상태는 브라우저별 localStorage `pj_goal_fold`(`{"1":bool,"2":bool}`).
|
||||
애니메이션(`applyFold`): 접기 = `.is-shrunk`(칸 width·padding·테두리 → 0, `.is-folding` 동안만 transition .32s) 뒤
|
||||
`.is-gone`(display:none), 펴기 = 거꾸로. 줄어드는 동안 칸 안 내용은 원래 폭(`85px × --span`)으로 고정해 잘라 내서 줄 높이가
|
||||
출렁이지 않는다. **표는 `width: 1px` + `table-layout: fixed`** — fixed 는 표 너비가 auto 가 아닐 때만 먹는다(auto 면 칸 너비가
|
||||
내용을 따라가 펼칠 때 애니메이션 없이 한 번에 튄다). 표는 칸 너비 합만큼 늘어난다. contenteditable 글 칸은 고정 높이 없이
|
||||
펼쳤을 때의 내용·너비로 자연 높이가 정해진다(예전 textarea는 숨겨져 있으면 측정을 건너뛰고 펼친 뒤 다시 잼).
|
||||
`prefers-reduced-motion` 이면 애니메이션 없이.
|
||||
- **영역·줄 이름 바로 수정**(관리자) — 이름(`[data-goal-edit="area|row"]`)을 누르면 contenteditable(`startNameEdit`) —
|
||||
Enter·칸 떠남 = 저장, Esc = 취소, 붙여넣기는 글자만. 영역 이름 빈 값은 되돌림(서버도 400), 줄 이름은 빈 값 허용(빈 줄 이름은
|
||||
마우스를 올리면 "줄 이름" 자리 표시). 예전 ✎(prompt) 버튼은 없앴다. 색·순서·줄 추가·삭제는 우클릭 메뉴(아래).
|
||||
- **구역·항목 칸 메뉴 = 우클릭 + ⋮ 버튼**(2026-10-01) — 마우스 오버 도구 막대(색·↑·↓·+·×)는 뺐다(옆 칸으로 갈 때 걸리거나 고정되는 문제).
|
||||
대신(점검 UX 8) 칸 오른쪽 위 작은 ⋮ 버튼(`.pj-goal-menu-btn`, 관리자만, `data-goal-menu="area|row"`) — absolute 라 자리를 차지하지 않고
|
||||
평소 투명, 칸에 마우스·포커스가 오면 보임, 터치 화면(`hover: none`)은 늘 옅게(0.7). 우클릭과 **같은 메뉴**(`openAreaMenu`·`openRowLabelMenu`).
|
||||
접근성: 버튼 `aria-label="{이름} 구역 메뉴|줄 메뉴"`·`aria-haspopup="menu"`·`aria-expanded`, Tab → Enter/Space 로 열면 첫 항목 포커스,
|
||||
메뉴(`showContextMenu` 공용, `role=menu`/`menuitem`) 안 ↑↓·Home·End·Enter, Esc·Tab = 닫고 버튼으로 포커스 복귀, 같은 버튼 다시 누르면 닫힘.
|
||||
이름 칸(`[data-goal-edit]`)도 `tabindex=0` — Enter·F2 = 이름 수정(한글 조합 중 Enter 무시).
|
||||
1열(구역 칸) 우클릭(`areaMenuItems` → `goalAct`): 색 바꾸기(색 창은 우클릭한 자리, 현재 색은 `tbody[data-color]`) · 위로 · 아래로
|
||||
(맨 위·맨 아래면 없음) · 줄 추가(구역 맨 아래) · 영역 삭제. 2열(항목 칸) 우클릭(`rowMenuItems`): 위/아래에 줄 추가 · **위로 · 아래로**
|
||||
(묶이지 않은 칸만) · 항목 칸 나누기(묶인 칸) · 줄 삭제. 이름은 눌러서 바로 수정(그대로).
|
||||
- **줄 추가·삭제(항목 칸)**(관리자) — 줄 이름 칸 도구 막대: ↑·↓(줄 2개 이상)·**+ = 이 줄 아래에 줄 추가**·×(줄 2개 이상). 항목 칸 **우클릭 메뉴**: 위에 줄 추가 / 아래에 줄 추가 / 줄 삭제(영역의 마지막 한 줄이면 없음). 추가는 이름을 묻고(비워도 됨) `db.add_goal_row(ref_row_id, place)` 가 영역 줄 순서를 다시 매긴다(영역 FOR UPDATE). 영역 이름 칸의 + 는 예전처럼 맨 끝에 추가.
|
||||
- **칸 병합 — 엑셀식**(관리자, 014 + 015, 2026-10-01에 예전 Shift+클릭·떠 있는 병합 버튼·오른쪽/왼쪽 칸과 병합 메뉴를 대체)
|
||||
— `goal_cell_merges(row_id, start_month, span, row_span)`. 시작 칸 = **왼쪽 위**(row_id = 맨 위 줄, start_month = 왼쪽 칸 번호).
|
||||
- 범위: **같은 업무 영역 안 연속된 줄**(세로, `row_span` — 015) × 화면 순서(연간 · 1~6월 · 상반기 · 7~12월 · 하반기 =
|
||||
`store.GOAL_COL_ORDER`)의 연속된 칸. 가로는 **같은 반기 월 칸끼리만**, 연간(0)·상반기(13)·하반기(14) 칸은 **세로로만**
|
||||
(`store.validate_goal_rect_cols`, DB CHECK). 015 미적용이면 예전처럼 한 줄 월 칸 가로 병합만(세로·연간/반기는 503).
|
||||
- 고르기: 글 칸을 **마우스로 끌기**(다른 칸으로 넘어가는 순간부터 범위 선택, 글 선택·포커스는 막음 — `html.pj-goal-selecting`)
|
||||
또는 **Shift+클릭**(마지막으로 누른 칸부터). 범위가 병합된 칸에 걸치면 **엑셀처럼 그 칸 전체로 넓힌다**(`expand`). 칸 한 번 클릭은
|
||||
그대로 입력. 다른 곳 누름·Esc = 해제.
|
||||
- **우클릭**: "셀 병합 (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**(해제 뒤 이동).
|
||||
- 새 연도 만들기(구조 복사)는 병합을 복사하지 않는다(줄 이름만).
|
||||
- **구조 변경 뒤 제자리 다시 그리기**(`refreshTable`, 2026-10-01) — 줄·영역 추가/삭제/이동, 병합/해제 뒤 페이지를 새로고침하지
|
||||
않고 이 페이지를 다시 받아 **업무 영역 tbody 만** 바꿔 끼운다(열 너비·반기 접기 다시 적용, 새 글 칸 연결 `bindTexts`). 새로고침 때
|
||||
저장된 열 너비가 늦게 적용돼 표가 줄었다 늘어나고 깜박이던 것을 없앴다. 애니메이션: 지운 줄은 흐려지며 사라지고, 남은 줄은 예전
|
||||
자리에서 미끄러져 오고(FLIP, 0.28초), 새 줄은 위에서 내려오며 보라색으로 잠깐 강조(`is-new-row`), 병합·해제한 칸은 테두리 강조
|
||||
(`is-merge-flash`). 동작 줄이기 설정이면 애니메이션 없이. 받아 오기 실패하면 예전처럼 새로고침.
|
||||
- **3열(연간 칸) 우클릭 → 줄 메뉴**: 위에 줄 추가 · 아래에 줄 추가 · 줄 삭제. **3열에서 추가한 줄은 같은 항목 칸(2열) 안에** 들어간다
|
||||
(2열은 하나, 3열부터 줄이 늘어남 — 이름을 묻지 않음, `same_label`, 마이그레이션 016). 세로로 병합된 연간 칸이면 아래 추가는 병합의
|
||||
맨 아래 줄 기준, 삭제는 없음. 병합 메뉴(셀 병합·해제)가 있으면 그 아래에 붙는다.
|
||||
- **항목 칸(2열) 묶음**(016 `goal_rows.label_cont` = 바로 위 줄 항목 칸에 묶임, 이름은 묶음 첫 줄에): 화면은 `router._goal_label_spans`
|
||||
가 묶음 첫 줄에 `label_span`(2열 rowspan), 이어 붙은 줄은 2열을 그리지 않는다.
|
||||
- `POST /api/goals/areas/{id}/rows {ref_row_id, place, same_label: true}` → 아래 = 새 줄이 이어 붙음, 위 = 기준 줄이 묶음 첫 줄이면
|
||||
새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙음(이어 붙은 줄 위면 그냥 이어 붙음). 016 미적용이면 503.
|
||||
- 2열 메뉴·+ 의 줄 추가는 **묶음 밖**(위 = 묶음 첫 줄 위, 아래 = 묶음 맨 아래 줄 아래, 이름 물음). 묶인 2열 우클릭 → **항목 칸 나누기**
|
||||
(`POST /api/goals/rows/{첫 줄}/split-label` — 이어 붙은 줄들이 각자 빈 이름 항목 칸으로).
|
||||
- 묶음 첫 줄 삭제 → 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름이 비어 있으면 넘겨받음. 묶인 줄(첫 줄·이어 붙은 줄)과 바꾸는 ↑↓ 이동은 400
|
||||
(나눈 뒤 이동), 묶음 첫 줄 도구 막대엔 ↑↓ 없음. 새 연도 만들기는 묶음도 복사한다.
|
||||
- **선택한 글자 서식**(관리자, 2026-10-02) — 목표 업무 영역 글 칸은 `.pj-goal-text[contenteditable]`.
|
||||
같은 칸의 글자를 드래그해 선택하면 셀 상단 중앙을 기준으로 셀 위에 엑셀 형태 도구가 나타난다(여러 줄 글의 어느 줄을 선택해도 동일 위치).
|
||||
아이콘은 처음 엑셀 형태 도구 크기의 80%이다. 밑에 현재 색상 선을 둔 `가`+드롭다운은 기존 12색 견본,
|
||||
`가`+위/아래 화살표는 크기 2px 증감(10~32px, 혼합 크기는 조각마다 증감), 굵게·기울임·밑줄은 적용 상태가 보이는 토글 버튼.
|
||||
서식 초기화는 구분선 뒤의 지우개 아이콘(14.4px)으로 표시하며 접근성 이름·도움말은 `서식 초기화`이다.
|
||||
모든 버튼은 24px 높이, 서식 바는 위아래 여백 4px로 한 줄에서 34px 높이. 서식 초기화는 선택 범위의 모든 서식만 제거하며 글은 유지한다.
|
||||
기존 `createFieldSaver`의 자동 저장·실패 재시도·임시 복구를 재사용한다.
|
||||
`goal_cells.body` TEXT에 `pj-rich:v1:` + JSON 텍스트 조각 배열 `{text,bold?,italic?,underline?,color?,size?}`를 저장한다(추가 마이그레이션 없음).
|
||||
평문은 기존 형식 그대로, `store.validate_goal_text`가 허용 서식과 보이는 글자 길이를 검사하고 `goal_text_html`이 글을 escape한 안전한 span만 만든다.
|
||||
셀 병합은 각 조각 서식을 보존하고, 회의록 월간 계획 추출은 `goal_text_plain`으로 글만 읽는다.
|
||||
- **칸 아무 곳이나 눌러 입력**(엑셀처럼) — 글 입력칸은 글 높이만큼이라, 옆 칸 글이 길거나 세로 병합으로 칸이 길면 아래쪽을 눌러도
|
||||
입력이 안 됐다. 이제 업무 영역 글 칸(`td.pj-goal-texttd`)·회의록 글/금액 칸 아무 곳이나 누르면 그 칸 입력으로 들어가고 커서는 글 끝.
|
||||
칸 전체가 글 입력 마우스 모양. Shift+클릭(범위 고르기)·끌기(병합 선택)는 그대로.
|
||||
입력 중 테두리·밝은 배경도 입력칸이 아니라 **칸 전체**(`td:focus-within`, 회의록 표도 같음).
|
||||
- **고른 칸 내용 지우기(엑셀 Del)** — 끌기·Shift+클릭으로 고른 범위에서 Del → 범위 안 글 칸을 비우고 칸마다 바로 저장, 안내 토스트.
|
||||
바로 직전 지우기는 **Ctrl+Z** 로 되돌림(되돌린 값도 저장). 입력 중(글 칸에 커서)일 때의 Del·Ctrl+Z 는 평소 글자 편집.
|
||||
우클릭 메뉴에도 "내용 지우기 (Del)"(`ink_eraser`, 고른 범위에 글이 있을 때).
|
||||
- **우클릭 너비 자동 맞춤**(2026-10-03) — 목표 표의 이름·글·숫자·머리 칸 모두 "현재 열 너비 자동 맞춤" / "전체 열 너비 자동 맞춤"을 표시한다.
|
||||
보기 전용 사용자도 사용 가능하며 너비는 브라우저에 저장한다. 현재 열은 경계 더블클릭과 같고, 병합 칸은 오른쪽 끝 열을 맞춘다.
|
||||
전체 맞춤은 접힌 월 열도 포함해 각 열의 가장 긴 문단에 맞추고, 병합 글에 부족한 폭은 그 병합의 마지막 열에 더한다.
|
||||
- **셀 테두리로 내용 이동**(관리자, 2026-10-03) — 업무 영역의 연간·월·분기 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 잡아
|
||||
다른 글 칸에 놓으면 내용과 색·크기·굵게·기울임·밑줄을 옮긴다. 오른쪽 경계는 열 너비 조절용이다. 끄는 동안 대상 칸을 표시하고
|
||||
표 가장자리에서는 자동 스크롤한다. Esc·창 포커스 해제·원본에 놓기는 취소한다. 대상에 글이 있으면 덮어쓰기를 확인한다.
|
||||
병합 시작 칸의 글도 이동 가능하며 병합 배치·영역 색·열 너비는 유지한다. 연간·분기의 기본 글자 서식도 명시해 원본의 표시를 보존한다.
|
||||
미저장 글을 먼저 저장한 후 `POST /api/goals/cells/move`로 두 칸을 한 트랜잭션에서 이동한다(추가 마이그레이션 없음).
|
||||
일반 글 저장·병합과 영역 잠금을 공유하고 원본·대상 예상값을 비교한다. 다른 창의 수정·병합에 가려진 칸은 409로 중단한다.
|
||||
성공 응답 뒤 원본을 비우며, 실패하면 두 칸의 화면 내용을 유지한다. 응답이 유실된 동일 요청 재시도는 완료 상태를 확인해 성공으로 반환한다.
|
||||
- **우클릭 메뉴 아이콘** — `menuIcon(name)`(Material Symbols)을 `showContextMenu` 항목 `icon` 에: 위에 줄 추가 `add_row_above` ·
|
||||
아래에 줄 추가 `add_row_below` · 줄 삭제 `delete`(빨강) · 셀 병합 `cell_merge` · 병합 해제 `call_split` · 항목 칸 나누기
|
||||
`horizontal_split` · (회의록) 위로/아래로 `arrow_upward`/`arrow_downward` · 쇼핑몰 연결 `link` · 연결 안 함 `link_off` · 쇼핑몰 `storefront`.
|
||||
- **월 머리 → 주간 회의록** — 목표 표 머리의 월 칸을 누르면 `/project/goals/{연도}/meetings/{월}`(6-9-2). 링크(`a.pj-goal-mlink`)는
|
||||
글자만이 아니라 **칸 전체**(absolute inset 0), 오른쪽 끝 너비 조절 손잡이(z-index 5)는 링크 위라 그대로 끌 수 있다.
|
||||
- **로아스 단위 %** — 로아스 목표·실적 칸은 `499%` 처럼 보인다(`router._goal_label`, 저장 응답 `label` 도 같음). 입력은 `499`·`499%`
|
||||
둘 다 되고 저장 값은 숫자(`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주차 = 그 달 첫 월요일이 있는 주**, 주는 월요일이 속한 달의 것
|
||||
(2026-10-01 사용자 기준. 예: 2026년 10월 = 10/5·12·19·26 주, 9/28~10/4 는 9월 마지막 주). 다른 달의 주를 `?week=` 로 열면
|
||||
그 달 회의록 주소로 303. 점 = 회의록 있음, "이번 주" 꼬리표. 기본 선택 = 이번 주(그 달 주면) 아니면 1주차.
|
||||
‹ 이전 달 · 다음 달 › 링크, ← 목표 표.
|
||||
- **월간 목표·누적은 늘 1일~말일**(주차와 따로): 월 누적 실적 = 1일 ~ 이 주 앞(지난주 일요일, 1주차면 첫 월요일 전날)까지,
|
||||
주당 필요 매출 = (월 목표 − 누적) ÷ 그 달 남은 주 수(이 주 포함).
|
||||
- 머리 배치: 왼쪽 = **[🚩 {연도}년 목표] 버튼**(연간 목표로, 큰 강조 버튼 `.pj-meet-goalbtn` — 예전 ← 화살표 대신)·제목·‹이전 달·다음 달›·
|
||||
인쇄·회의록 삭제·**주차 탭(제목 줄 오른쪽 끝 = 달력 바로 왼쪽에 붙음, 한 줄짜리 작은 탭 — `1주차 10/5~11`, 같은 달이면 끝 월 생략, 전체 기간은 말풍선)**,
|
||||
그 아래 **{월}월 계획**(달력 앞까지 너비), **오른쪽 위 = 작은 달력**(폭 174px, 날짜 10.5px·칸 높이 21px). 목표·회의록 제목은 32px 굵게(`h2.pj-goal-title`).
|
||||
- **작은 달력**(`.pj-meet-cal`, `store.calendar_weeks`): 그 달 날짜가 든 주 전부(월요일 시작) — 앞 달에 속한 주(1일 앞쪽,
|
||||
예: 10월 달력의 9/28 주)는 흐리게, 누르면 그 달(9월) 회의록. 줄 = 주(월~일) — 보고 있는 주는 영역 표시(테두리·배경),
|
||||
오늘 동그라미, 토 파랑·일/공휴일(`store.KR_HOLIDAYS`) 빨강, 다른 달 날짜 흐리게, 회의록 있는 주는 왼쪽 점. 줄을 누르면 그 주 회의록
|
||||
(`?week=`). 날짜 정보는 라우터가 주마다 `days`(d·in·today·wd·hol)로 넘긴다. 인쇄에선 숨김.
|
||||
- **머리 숫자**(`router._meeting_view`): 월 목표 매출(목표 표 숫자 + 단위, 단위가 원/천/만/십만/백만/천만/억이면 원 환산 —
|
||||
`store.sales_unit_multiplier`) · **월 누적 실적(지난주 일요일까지)** · **주당 필요 매출** = (월 목표 − 누적) ÷ 이번 주 포함 남은 주 수 ·
|
||||
목표 ROAS(목표 표) / 전주 목표(바로 앞 주 회의록의 금주 목표) · **전주 결과** · 전주 달성률 · **금주 목표**(입력, 칸 안내 = 필요 매출) ·
|
||||
금주 현재 실적. 실적·누적·결과는 **실적 모듈 `performance_store.daily_amounts`(대시보드 총매출과 같은 값, 매출 집계 쇼핑몰)** 에서
|
||||
읽기만 한다 — 실적 모듈이 없거나 오류면 빈칸("직접 입력" 안내), 회의록은 그대로 동작.
|
||||
숫자는 **한 줄 막대**(`.pj-meet-kpibar`, 칸 9개·값 15px, 좁은 화면 1300px 이하 두 줄) — 긴 설명은 말풍선(`title`).
|
||||
**실적을 알 수 없으면 0 원이 아니라 "⚠ 미확인"**(6-9-3 — `head.perf_state`·`head.unknown`), 그 값에 기대는 달성 %·주당 필요 매출도 미확인.
|
||||
실적 칸 말풍선 = 쇼핑몰별 마지막 갱신 성공 시각(실적 모듈 `perf_connection_status.last_success_sync_at`, `head.fresh_tip`).
|
||||
- **이번주 ↔ 지난주 리뷰 순서 바꾸기**(표 왼쪽 위 [⇄ 순서 바꾸기], `initMeetOrder`): 줄마다 is-this(2칸)·is-prev(5칸) 묶음과
|
||||
colgroup 을 통째로 옮긴다. 보는 사람마다 브라우저에 기억(localStorage `pj_meet_order:{로그인 이메일}`, `.pj-wrap[data-me]`).
|
||||
- 표 머리 "지난주 리뷰 (MM/DD ~ MM/DD)" = 지난주 월~일(`prev_week`·`prev_week_end`) — **줄의 지난주 칸·결과·달성률·머리 전주 목표도 정확히 이
|
||||
주(7일 전) 회의록만**(그 주 회의록이 없으면 머리에 "— 이 주 회의록 없음", 줄은 "지난주(MM/DD~) 회의록 없음", 회의록은 있는데 그 줄이 없으면
|
||||
"지난주 회의록에 없는 줄"). 예전엔 몇 주 전 회의록 줄이 지난주 날짜 아래 보였다(점검 버그 5).
|
||||
- 첫 회의록 기본 줄 마케팅 "메타"(예전 "메타(숫자)" — 017 이 그 이름 줄만 "메타"로 바꿈).
|
||||
- **{월}월 계획**(`router._month_plan`, `.pj-meet-plan`, 머리 왼쪽 `.pj-meet-headleft` 안 — 제목 줄 아래·달력 왼쪽): 연간 목표 표의 그 달 열 글을 업무 영역별 작은 카드로
|
||||
(영역 색, `항목: 글`, 빈 칸·글 없는 영역은 뺌). 가로 병합 칸(예: 9~10월)에 적은 글도 그 달 계획으로 보이고 범위를 오른쪽에 작게,
|
||||
세로 병합은 한 번만, 묶인 줄(016 `label_cont`)은 묶음 항목 이름. 목표 표가 없으면(013 미적용) 칸 자체를 숨김, 읽기만.
|
||||
- **줄**(구역 = 목표 표 업무 영역, 표의 구역 칸 rowspan): 항목 | **이번주 할 일·행사** | **정량 목표**(원, 예전 이름 "목표 금액") ‖ 지난주 리뷰: 지난주 할 일 |
|
||||
지난주 목표 | **결과** | 달성률 | **평가**(— · 완료 · 일부 · 미달). 지난주 칸 = **7일 전 주 회의록에서 같은 연결키(`line_key`, 018)의 줄**
|
||||
(예전 `carry_from` 은 이력으로만 — 6-9-3).
|
||||
결과는 그 줄이 **쇼핑몰 연결**(`marketplace_code`)이면 실적 모듈의 그 주(지난 회의록 주 월~일) 그 쇼핑몰 매출 **자동**("자동" 표시),
|
||||
아니면 직접 입력 — **지난 회의록 줄의 `result_amount`·`status` 에 저장**(그 주 결과는 그 주 줄에 남는다). 달성률은 저장 즉시 화면 계산.
|
||||
지난 회의록 주가 아직 시작 전이면 "진행 전"(0 으로 보이지 않게), 연결한 쇼핑몰이 실적 모듈에서 사용 중이 아니면(사용 OFF·없는 코드)
|
||||
"실적 미사용" 표시 + 직접 입력. 자동 결과 말풍선 = 쇼핑몰·기간, 0 이면 "그 기간 실적 없음 — [매출 업데이트]" 안내.
|
||||
쇼핑몰 연결 줄은 정량 목표 아래에 **이번주 실적**(이 주 월요일~오늘, 목표 대비 %)도 보인다 — % 는 화면이 실적(`slot data-auto`)과
|
||||
**서버 확정 정량 목표**(`tr data-target-amount`)로 계산(`paintMeetWeek`): 목표 저장 즉시 다시 계산(100→200 이면 100%→50%), 목표 0·빈칸이면
|
||||
% 없음, 실적 조회 실패면 "이번주 실적 미확인", 저장 실패면 확정값 그대로. 다시 그리기(`meetRepaint`)는 실적 값만 옮겨 와 같은 방식으로 계산하고
|
||||
차례 번호(`meetRepaintSeq`)로 늦게 온 옛 화면을 버린다 — 목표 저장과 엇갈려도 옛 비율이 들어오지 않는다(점검 버그 7).
|
||||
- **매출 자료 갱신**(`initMeetingSync`, **정상이면 화면 표시 없음** — 2026-10-01 상태 줄·[매출 갱신] 버튼은 요청으로 뺐다. 점검 UX 9 로
|
||||
실패·일부 실패·권한 없음일 때만 숫자 막대 아래 한 줄 안내 `#pj-meet-sync.pj-meet-syncnote`(`data-state=error|partial|noperm|running`) +
|
||||
[다시 시도] — 실패한 쇼핑몰 이름(상태), **서버가 기록한** 마지막 갱신 성공 시각(`data-fresh` = 매출 집계 쇼핑몰 중 가장 오래된 성공 시각,
|
||||
다시 그릴 때 서버 값으로 바뀜. 브라우저 시각은 10분 제한 계산에만 쓰고 보여 주지 않음). 기록 `sessionStorage pj_meet_sync:{월요일}` =
|
||||
`{at, state: ok|partial|error|noperm, bad}` — 일부 실패를 성공으로 기록하지 않고, 10분 안 다시 열면 부르지 않되 그 상태 안내는 유지.
|
||||
실적 모듈 권한은 서버가 미리 알려 줘(`can_sync` → `data-can`) 권한이 없으면 API 를 부르지 않고 "권한이 없어 저장된 실적" 설명, 그래도 403 이면
|
||||
noperm 으로 기억해 그 세션엔 다시 부르지 않음. 다른 업데이트에 합류(`joined`)했는데 그 작업 기간이 이 주 기간을 다 덮지 못하면 이 주 기간으로
|
||||
한 번 더. 아래는 예전 설명(동작은 같음): 주차를 열면 실적 모듈 `POST /performance/api/sync {from: 지난주 월요일, to: 이번 주 일요일·오늘 중 이른 날, background: true}` 로 쇼핑몰에서 매출을 한 번 더 받고(진행 n/m 쇼핑몰·받은 자료), 끝나면 이 화면을 서버에서 다시 받아 **숫자 칸만** 바꿔 끼운다(머리 카드·자동 결과·달성률·이번주 실적 — 입력 중인 칸·직접 입력 결과 칸·저장 안 된 글은 그대로). 같은 주는 브라우저별 10분에 한 번만 자동(sessionStorage `pj_meet_sync:{월요일}` — 줄 추가 등으로 새로고침해도 다시 부르지 않음), [매출 갱신] 버튼은 언제나. 이미 다른 매출 업데이트가 돌면 그 작업이 끝나길 기다린다. 실적 권한이 없으면 저장된 실적으로 보여 준다는 안내, 실패한 쇼핑몰은 이름·상태. 지난주가 아직 오지 않은 주(미래)는 갱신 줄이 없다.
|
||||
- **참석자 = 전체 멤버에서 고르기**(2026-10-01): 칩(사진·이름, × = 빼기) + [참석자] 고르기 창(찾기·전원 선택·모두 해제·체크) —
|
||||
후보는 `project` 모듈 권한 보유 등록 사용자(`router._meet_members`, 좌측 전체 멤버와 같음). 저장은 이메일을 쉼표로 이어 그대로
|
||||
`goal_meetings.attendees`(최대 3000자), 예전 자유 입력 글자는 칩으로 남는다(`_parse_attendees`). 바뀔 때마다 바로 저장.
|
||||
- **결정 사항·메모**. 인쇄 버튼(인쇄용 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 에서 자동 생성 안 함): 줄이 있는 앞선 가장 가까운 회의록, 없으면 **뒤에 있는
|
||||
가장 가까운 회의록**(다음 주를 먼저 만든 경우)의 줄(구역·이름·색·쇼핑몰 연결·순서)을 글 없이 이어받고 **원본 줄의 연결키(`line_key`)를 그대로**
|
||||
(앞선 원본이면 `carry_from` 도 이력으로 기록), 둘 다 없으면 그 해 목표 표 업무 영역마다 **기본 양식 줄**(`store.MEETING_TEMPLATE` —
|
||||
상품1~5 / 메타·구글·네이버·기타.신규 / 내용1~5 / 신규 인플루언서·콜라보·쿠팡·네이버·gs·토스·애터미·해외·오프라인·기타, 없는 구역은
|
||||
빈 줄 하나). **유통** 구역 줄 이름으로 쇼핑몰 연결 추측(`store.guess_meeting_market`: 쿠팡·네이버/스마트스토어·gs·토스·11번가·카페24/자사몰·
|
||||
롯데·지마켓·카카오·오늘의집 — 마케팅의 "네이버"는 광고라 연결 안 함). 줄 추가 때도 같은 추측.
|
||||
- 편집(관리자, 칸별 즉시 저장 — 목표 표와 같은 권한, 공용 `createFieldSaver` 6-9-3): 글 0.8초 멈춤·칸 떠남, 금액 Enter·칸 떠남(서버 확정값을
|
||||
쉼표 표기로 — 요청 뒤 다시 입력 중이면 그 초안 유지), 금주 목표 저장(`PUT` 응답에 확정 `week_target`) 뒤엔 **새로고침 없이** 머리 숫자만 서버
|
||||
계산으로 다시(`meetRepaint` — 다른 칸의 저장 안 된 글 보존). 줄 작업(추가·순서·쇼핑몰 연결·삭제)은 먼저 저장 안 된 칸을 저장하고, 실패하면
|
||||
작업하지 않는다(초안 유지). **항목 우클릭·⋯ 메뉴**: 위/아래에 줄 추가 · 위로/아래로(같은 구역 안) ·
|
||||
쇼핑몰 연결(결과 자동)…(연결 안 함 + 실적 모듈 사용 중 쇼핑몰, 현재 값 체크) · 줄 삭제. 구역 칸 + = 그 구역 끝에 줄, [+ 구역 추가].
|
||||
줄 이름은 눌러서 그 자리에서 수정. 회의록 삭제 = 그 주 줄 전부 삭제, 다음 주 회의록의 지난주 칸은 빈다 — 그 주를 다시 만들면 같은 연결키로
|
||||
다시 이어진다(새 회의록이라 글은 비어 있음, 018).
|
||||
- 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-9-3. 저장 안전장치 · 지난주 연결 · 실적 미확인 (2026-10-01 점검 반영 — `docs/reviews/GOALS_MEETINGS_REVIEW_2026-10-01.md`, 마이그레이션 018)
|
||||
|
||||
**칸별 자동 저장 `createFieldSaver`**(project.js 공용, 목표 표 글·숫자 + 회의록 글·메모·금액·금주 목표 — 버그 1·2·3)
|
||||
- 칸마다 `{saved, chain, busy, timer, failed}`. **saved = 성공한 요청에 실어 보낸 값**만(응답 때 바뀌어 있는 화면 값을 저장됨으로 보지 않음).
|
||||
- **같은 칸 요청은 직렬화** — 앞 요청이 끝나야 다음 요청을 보내므로 서버에 닿는 쓰기 순서 = 보낸 순서(늦은 옛 요청이 최신 값을 덮지 못함, 응답만
|
||||
버리는 방식이 아님). 다음 요청은 보낼 때의 최신 초안을 읽어 진행 중에 새로 쓴 값도 뒤이어 저장. 앞 요청이 없으면 그 자리에서(동기) 보낸다.
|
||||
- 응답 반영: 서버 표기(쉼표·원 정수)는 **요청 뒤 초안이 그대로일 때만** 칸에 넣는다(`onSaved(..., same)`). 실패하면 초안·dirty 유지 +
|
||||
빨간 테두리(`is-save-failed`, 말풍선) + 토스트 — 다음 입력·칸 떠남·Enter·`flushAll` 이 다시 보낸다. 숫자 Esc = 저장된 값.
|
||||
- `flushAll()` = 대기 타이머 + 진행 중 요청 + 실패했던 칸까지 기다리고 하나라도 실패하면 reject. 목표 표 구조 작업(영역·줄 추가/이동/삭제,
|
||||
병합/해제)과 회의록 줄 작업은 **먼저 flushAll — 실패하면 구조 요청·표 교체를 하지 않는다**. 목표 표 구조 작업은 한 번에 하나(`withStruct`).
|
||||
- 목표 표 `refreshTable`: 시작 전 flush(실패 = throw), 표를 받는 사이 새로 입력한 글이 있으면 저장 후 다시 받기(최대 3번, 바꿔 끼우기 직전 검사는
|
||||
동기라 그 사이 입력 불가), 계속 입력 중이면 바꿔 끼우지 않고 `pendingRefresh` — 저장이 끝나면 다시 그린다. 이름 고치는 중이어도 기다림.
|
||||
- **초안 백업** — 글 칸은 입력할 때마다 `localStorage pj_draft:goal:{줄}:{칸}` · `pj_draft:meet:item:{id}:content` · `pj_draft:meet:notes:{월요일}` =
|
||||
`{base(서버에 저장된 값), draft, at}`, 저장되면 지움(14일 지난 것은 열 때 정리). 다시 열 때 **서버 값 = base 면 되살려 다시 저장**, 서버 값이 바뀌었으면
|
||||
(다른 사람·다른 창) 되살리지 않고 안내.
|
||||
- **페이지 떠남**(`beforeunload`): 진행 중 요청이 없는 dirty 글 칸은 `keepalive` PUT 으로 한 번 더 보낸다 — **브라우저가 끝까지 보낸다는 보장은 없어서**
|
||||
초안 백업이 함께 남는다(keepalive 도 같은 칸 줄에 들어가 순서가 섞이지 않음). 실패했던 칸·진행 중 요청이 있는 칸·Enter 전 숫자 칸이 있으면 브라우저
|
||||
이탈 경고. 저장이 다 끝났으면 경고 없음.
|
||||
|
||||
**지난주 연결 — 연결키 `goal_meeting_items.line_key`(마이그레이션 018, 버그 4·5)**
|
||||
- 왜 키인가: 이름(label) 비교는 같은 이름 줄(기타·빈 이름)·다른 구역 같은 이름(마케팅/유통 "네이버")·이름 변경에서 다른 줄 결과가 섞인다.
|
||||
`carry_from`(앞선 회의록 줄 id)은 만들 때 한 방향으로만 생겨 역순 생성·앞 주 삭제/재생성(ON DELETE SET NULL)에서 끊긴다.
|
||||
키는 **회의록을 만들 때 원본 줄 키를 그대로 이어받고 새 줄은 새 키** → "지난주" = `week_start − 7` 회의록의 같은 키 줄(UNIQUE `(week_start, line_key)`),
|
||||
생성 순서·이름 변경·순서 이동과 무관, 한 줄이 두 줄에 붙지 않는다.
|
||||
- 만들기 원본: 앞선 가장 가까운(줄 있는) 회의록 → 없으면 뒤의 가장 가까운 회의록 → 둘 다 없으면 양식(새 키).
|
||||
- **018 적용 전**에도 코드는 동작 — `_meeting_keys` 가 칸 유무를 보고, 없으면 `carry_from` 을 쓰되 **가리키는 줄이 정확히 7일 전 주일 때만** 지난주로
|
||||
(버그 5 는 적용 전에도 고침, 역순 생성 연결(버그 4)은 018 필요). 018 은 `line_key` 기본값(랜덤 키)을 두어 **코드 배포 전에 적용해도** 예전 코드의
|
||||
줄 추가가 실패하지 않는다(그 줄은 연결 없이 새 키).
|
||||
- **018 의 기존 데이터 채우기(자동 복구 범위)**: `carry_from` 사슬을 따라 같은 키(뿌리 = 사슬 맨 앞 줄, `md5('goal_meeting_item:'||id)::uuid` 라 다시 돌려도
|
||||
같은 키). → 같은 원본(예: 9/14)에서 이어받은 9/28(먼저 만듦)·9/21(나중에 만듦) 줄은 자동으로 다시 이어진다. 이름 바꾼 줄도 사슬이면 이어진다.
|
||||
**자동으로 잇지 않는 것**: `carry_from` 이 없는 줄(첫 회의록 양식 줄·줄 추가·앞 주 삭제로 끊긴 줄) — 이름이 같아도 붙이지 않는다.
|
||||
예: 9/21·9/28 을 둘 다 앞선 회의록 없이 양식으로 만들었다면 연결 안 됨. 이런 쌍은 `scripts/sql/project_db_018b_meeting_line_link_candidates.sql`
|
||||
(**조회만**)로 "정확히 7일 차이 + 같은 구역·같은 이름이 양쪽 주에 각각 한 줄씩만 + 아직 연결 안 됨" 후보를 보고, 사람이 확인한 쌍만 그 파일 안
|
||||
주석의 UPDATE 로 따로 잇는다(운영 적용은 별도 승인·백업 후). 한 주 안 같은 키(정상 데이터엔 없음)는 순서가 뒤인 줄에 새 키.
|
||||
- 적용(운영은 백업·승인 후, 여러 번 돌려도 안전):
|
||||
```bash
|
||||
docker exec -i postgres-db psql -U postgres -d project_db < scripts/sql/project_db_018_meeting_line_keys.sql
|
||||
docker exec -i postgres-db psql -U postgres -d project_db -c \
|
||||
"SELECT count(*) AS total, count(line_key) AS keyed FROM goal_meeting_items;" # total = keyed
|
||||
docker exec -i postgres-db psql -U postgres -d project_db < scripts/sql/project_db_018b_meeting_line_link_candidates.sql # 후보 조회만
|
||||
```
|
||||
적용 전 확인(조회만): `SELECT week_start, count(*) FILTER (WHERE carry_from IS NULL) AS no_link, count(*) FROM goal_meeting_items GROUP BY 1 ORDER BY 1;`
|
||||
|
||||
**실적 미확인(버그 6)** — `router._MeetingPerf`: `state` = `off`(실적 모듈 미연결) · `error`(쇼핑몰 목록 조회 실패) · `empty`(매출 집계 쇼핑몰 없음) · `ok`.
|
||||
조회 실패한 값은 None + `head.unknown`(`mtd`·`prev_result`·`week_result`, 기간마다 따로 → 부분 실패), 화면 "⚠ 미확인", 그 값에 기대는 달성 %·주당 필요
|
||||
매출도 계산하지 않음. 정상 조회 0건만 0원. 목록 장애면 쇼핑몰 연결 줄 결과 = 미확인(직접 입력 칸으로 바꾸지 않음, "실적 미사용"으로 오인하지 않음),
|
||||
연결 배지 "· 미확인". `head.perf` 는 예전 뜻(실적 모듈 연결 여부) 그대로 — 갱신 상자·"연결되지 않아" 문구 조건. 회의록 열기·직접 입력은 그대로.
|
||||
|
||||
**테스트** — `tests/test_project_module.py`(`test_meeting_prev_week_links`: 역순 생성·같은 이름·다른 구역 같은 이름·이름 변경·이동·새 줄·삭제/재생성·
|
||||
건너뛴 주, 018 적용/미적용 둘 다 · `test_meeting_perf_unknown_vs_zero`: 미연결·목록 장애·매출 장애·부분 실패·정상 0·집계 쇼핑몰 없음),
|
||||
`tests/test_meeting_line_keys_migration.py`(018 백필·멱등·UNIQUE — 임시 스키마, 끝에 ROLLBACK), `tests/js/goals_meeting_ui.test.js`
|
||||
(`python tests/js/render_goals.py` 후 — 버그 1·2·3·5·6·7, UX 8·9, 분기 접기·열 너비·스크롤·참석자 회귀).
|
||||
|
||||
## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음)
|
||||
|
||||
**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
main-app 목표관리·주간회의록: 버그 7개와 UI·UX 문제 2개 수정 요청
|
||||
|
||||
아래 9개 항목을 실제 코드에서 확인하고 수정해 주세요. 분석이나 수정 계획만 제시하지 말고, 구현·회귀 테스트·관련 문서 갱신까지 완료해 주세요. 기존 변경 사항과 사용자 데이터를 보존하고, 수정 완료 여부는 재현 테스트 결과로 증명해 주세요.
|
||||
|
||||
1. 작업 맥락과 범위
|
||||
|
||||
프로젝트: DBX ERP main-app, FastAPI / PostgreSQL / Jinja / JavaScript.
|
||||
개발 PC 경로: G:\내 드라이브\프로젝트\Main-app
|
||||
운영 서버 main-app 경로: /opt/www/main
|
||||
|
||||
작업 전 AGENTS.md를 확인하고 다음 문서를 순서대로 읽어 주세요.
|
||||
- docs/PROJECT_OVERVIEW.md
|
||||
- docs/SERVER_ARCHITECTURE.md
|
||||
- docs/DATABASES.md
|
||||
- docs/DEPLOYMENT.md
|
||||
이어서 docs/PROJECT_MODULE.md와 관련 코드를 읽어 주세요.
|
||||
|
||||
기존 점검 보고서:
|
||||
docs/reviews/GOALS_MEETINGS_REVIEW_2026-10-01.md
|
||||
|
||||
보고서의 기준 커밋은 21981eb입니다. 아래 줄 번호는 당시 기준이므로 현재 코드의 함수·동작을 기준으로 위치를 다시 찾아 주세요. 이미 해결된 항목은 중복 수정하지 말고, 해당 재현 테스트가 통과함을 확인해 주세요.
|
||||
|
||||
주요 파일:
|
||||
- app/static/project.js
|
||||
- app/static/project.css
|
||||
- app/modules/project/router.py
|
||||
- app/modules/project/db.py
|
||||
- app/modules/project/store.py
|
||||
- app/modules/project/templates/project/goals.html
|
||||
- app/modules/project/templates/project/goal_meeting.html
|
||||
- tests/test_project_module.py
|
||||
- tests/js/project_ui.test.js 및 관련 테스트 도구
|
||||
|
||||
이번 작업은 9개 문제의 수정입니다. 무관한 전체 리팩터링이나 화면 재설계는 하지 마세요. 기존 자동 저장, 관리자 편집 권한, 분기 접기, 열 너비 조절, 스크롤 위치 유지, 셀 병합·해제, 항목 칸 묶음, 참석자 선택, 쇼핑몰 연결, 한글 입력을 유지해 주세요.
|
||||
|
||||
주차 규칙은 유지해 주세요: 1주차는 그 달 첫 월요일이 있는 주이며, 주는 월요일이 속한 달의 것입니다. 월간 목표·누적은 달의 1일~말일을 기준으로 합니다. 연간·분기 매출 달성률은 해당 기간 목표 합계 전체 대비 실적 합계입니다.
|
||||
|
||||
운영 DB나 운영 화면에서 재현을 위해 입력·생성·삭제하지 마세요. 로컬 테스트 대역 또는 운영과 분리된 테스트 DB를 사용하세요. 비밀값을 출력하거나 커밋하지 마세요. 파괴 명령·신규 DB 생성·운영 데이터 보정은 AGENTS.md의 승인 규칙을 따르세요. 이 요청에는 운영 배포나 운영 데이터 변경이 포함되지 않습니다.
|
||||
|
||||
2. 가장 먼저 수정할 저장 손실 버그 3개
|
||||
|
||||
[버그 1 / P1] 회의록 자동 저장이 아직 전송하지 않은 글을 저장 완료로 처리
|
||||
|
||||
위치: project.js의 initGoalMeeting() → queue(), flush(), flushAll(), beforeunload. 당시 약 9110행.
|
||||
|
||||
재현:
|
||||
1) 같은 글 칸에 draft A를 입력하고 blur로 PUT을 시작합니다.
|
||||
2) A 응답을 지연한 상태에서 draft B를 입력합니다.
|
||||
3) A 응답을 완료하고 B의 800ms 자동 저장 시간을 기다립니다.
|
||||
|
||||
실제 관찰: 화면은 B, data-saved도 B, 서버는 A, PUT은 1회뿐입니다.
|
||||
원인: await p.save(ta.value) 이후 바뀐 ta.value를 saved에 기록합니다.
|
||||
|
||||
수정 요구:
|
||||
- 요청에 보낸 값과 현재 초안을 분리하고, 성공한 요청값만 저장 완료 기준으로 기록하세요.
|
||||
- 같은 칸의 요청을 직렬화하거나 동등한 방법으로 오래된 요청이 최신 저장을 덮지 못하게 하세요. 클라이언트 응답만 무시하는 것으로 서버의 쓰기 순서 문제를 해결했다고 간주하지 마세요.
|
||||
- 진행 중 새 입력이 생기면 최신 값이 뒤이어 저장되도록 하세요.
|
||||
- 실패한 칸은 dirty 상태와 초안을 보존하고 재시도할 수 있어야 합니다.
|
||||
- pending 타이머뿐 아니라 진행 중 저장도 flushAll이 기다려야 합니다.
|
||||
- 페이지 이동·새로고침 과정에서도 미저장 상태를 잊지 마세요. beforeunload의 keepalive만으로 저장을 보장한다고 표현하지 마세요.
|
||||
|
||||
완료 기준:
|
||||
- A 응답 전 B를 입력해도 최종 서버 값이 B입니다.
|
||||
- 지연·중복 blur·빠른 연속 입력에도 최신 값이 남습니다.
|
||||
- 저장 실패 후 페이지 이탈 시도에서 미저장 초안이 조용히 사라지지 않으며, 가능한 재전송·이탈 경고·초안 복구 등 구현한 보호 동작을 검증합니다.
|
||||
|
||||
[버그 2 / P1] 숫자 저장의 늦은 응답이 최신 입력을 덮음
|
||||
|
||||
위치: initGoals()의 숫자 change 처리(약 8229행), initGoalMeeting()의 금액 change 처리(약 9179행).
|
||||
|
||||
재현: 200 저장 응답을 지연한 동안 같은 입력창에 300을 입력하고, 그 후 200 응답을 완료하면 화면 값이 200으로 되돌아갑니다.
|
||||
|
||||
수정 요구:
|
||||
- 응답이 도착해도 요청 이후 바뀐 최신 초안을 보존하세요.
|
||||
- 서버의 정규화 값·쉼표 표기는 현재 초안이 해당 요청 이후 변경되지 않았을 때만 적용하세요.
|
||||
- 실패 응답에서도 요청 이후 작성한 새 입력을 과거 saved 값으로 되돌리지 마세요.
|
||||
- 목표 표 숫자, 회의록 정량 목표·지난주 결과, 금주 목표를 확인하세요. 금주 목표 저장의 전체 새로고침이 다른 칸의 미저장 글을 잃게 만들지 않도록 함께 검증하세요.
|
||||
- 저장 순서와 초안 보호는 버그 1과 일관된 방식으로 처리하세요.
|
||||
|
||||
완료 기준: 늦은 200 응답 후에도 현재 초안 300이 유지되고, 사용자가 300을 확정하면 최종 서버 값도 300입니다. 응답 순서 역전·실패·빠른 재편집을 테스트하세요.
|
||||
|
||||
[버그 3 / P1] 글 저장 실패 후 표를 다시 그려 미저장 계획을 지움
|
||||
|
||||
위치: initGoals() → saveText(), flushTexts(), refreshTable(), 구조 변경·병합 호출부. 당시 약 8257 / 8386 / 8416행.
|
||||
|
||||
재현: 목표 칸에 unsaved important plan을 입력한 직후 업무 영역 추가를 실행합니다. 글 PUT은 503으로 실패하고 화면 GET은 기존 저장본을 반환하면, 새 글이 기존 original로 바뀝니다.
|
||||
원인: saveText가 실패를 삼켜 flushTexts가 성공한 것처럼 끝나고, DOM 교체가 계속됩니다.
|
||||
|
||||
수정 요구:
|
||||
- 실패를 상위 작업에 전달하고 초안을 유지하세요.
|
||||
- 구조 변경·병합·해제·표 교체 전에 dirty 칸과 진행 중 저장을 실제로 완료하세요.
|
||||
- 저장 실패 시 해당 구조 작업·DOM 교체를 중단하세요. 이미 시작된 구조 요청도 고려하여 순서를 조정하세요.
|
||||
- flush 중 새로 입력한 글도 잃지 않도록 하세요.
|
||||
- 목표 글 저장 역시 같은 칸의 오래된 요청이 최신 값을 덮는 문제를 방지하세요.
|
||||
|
||||
완료 기준: 글 PUT 실패 시 작성 내용이 남고 불필요한 표 교체가 발생하지 않습니다. 성공한 경우에만 영역·줄 추가/이동·병합 등이 정상 진행됩니다. 진행 중 저장과 실패를 각각 재현하세요.
|
||||
|
||||
3. 데이터 연결·표시 버그 4개
|
||||
|
||||
[버그 4 / P2] 회의록 생성 순서에 따라 지난주 연결이 빠짐
|
||||
|
||||
위치: ProjectStore.create_meeting(), get_meeting(), carry_from 처리. 당시 db.py 약 2524 / 2536행.
|
||||
|
||||
재현: 2026-09-28 주를 먼저 생성한 다음 2026-09-21 주를 생성합니다. 앞 주가 존재해도 9/28의 carry_from은 NULL로 남습니다.
|
||||
운영 화면 관찰: 9/21과 9/28 모두 회의록 존재 점이 있고, 9/28의 24개 줄 중 data-prev가 있는 줄은 0개였습니다. 실제 운영 생성·삭제 이력은 확인하지 않았으며, 생성 순서는 동일한 상태를 만드는 확인된 원인입니다.
|
||||
|
||||
수정 요구:
|
||||
- 회의록 생성 순서와 무관하게 대응 항목의 직전 주 리뷰를 연결할 수 있게 하세요.
|
||||
- 이름 변경·동일 이름의 여러 줄·순서 변경·다른 구역의 같은 이름을 고려하세요. label만 비교해 임의로 첫 줄에 연결하지 마세요.
|
||||
- 안정적인 항목 식별자 또는 기존 연결 구조를 안전하게 활용하는 방법을 선택하고 이유를 설명하세요.
|
||||
- 연결이 불확실한 과거 데이터는 추정으로 다른 항목에 붙이지 마세요. 안전한 처리 기준을 문서화하세요.
|
||||
- 필요하면 멱등 마이그레이션 파일을 작성하고 적용·검증 방법을 제공하세요. 운영 적용·운영 보정은 실행하지 마세요.
|
||||
|
||||
완료 기준: 정순 생성·역순 생성 모두 올바른 항목에 연결됩니다. 중복 이름·이름 변경·앞 주 삭제/재생성·새로 추가된 항목에서도 다른 줄의 결과가 섞이지 않습니다. 기존 데이터의 자동 복구 가능 범위와 제한을 명확히 보고하세요.
|
||||
|
||||
[버그 5 / P2] 다른 주의 결과를 지난주 날짜 아래 표시
|
||||
|
||||
위치: router.py의 _meeting_view() → it.prev 처리(약 2922행), goal_meeting.html의 지난주 리뷰 머리(약 190행).
|
||||
|
||||
재현: 9/28 회의록의 참조 줄이 9/7 회의록이면, 표 머리는 9/21~9/27이지만 결과와 달성률은 9/7~9/13 데이터를 사용합니다.
|
||||
|
||||
수정 요구:
|
||||
- 버그 4의 연결 정책과 일치하도록 실제 리뷰 데이터 기간과 표시 기간을 맞추세요.
|
||||
- 기본적으로 '지난주' 리뷰는 정확히 7일 전 주만 사용하세요. 직전 주가 없으면 지난주 자료 없음으로 표시하세요.
|
||||
- 이전 회의록 양식·항목을 이어받는 기능은 유지할 수 있지만, 몇 주 전 결과를 지난주로 표시하거나 잘못된 주에 결과·평가를 저장하지 마세요.
|
||||
- 더 이전 회의록 결과를 보여줄 필요가 있으면 별도 명칭과 실제 날짜를 명시하고 지난주 지표와 분리하세요.
|
||||
|
||||
완료 기준: 누락된 주·연말/연초·월 경계에서도 표 머리, 각 줄 결과·달성률, 머리 전주 목표가 모두 같은 실제 주를 의미합니다.
|
||||
|
||||
[버그 6 / P2] 실적 조회 장애를 매출 0원으로 표시
|
||||
|
||||
위치: router.py의 _perf_markets(), _perf_sum(), _meeting_view(). 당시 약 2849 / 2854 / 2901행.
|
||||
|
||||
재현: 실적 저장소 list_marketplaces()에서 예외를 발생시키면 월 누적·전주 결과·금주 결과가 모두 0이고 perf=true로 나옵니다.
|
||||
|
||||
수정 요구:
|
||||
- 정상 조회 결과 0건, 설정된 쇼핑몰 없음, 실적 모듈 미연결, 목록 조회 실패, 매출 조회 실패를 구분하세요.
|
||||
- 실적을 알 수 없을 때 0원·0%로 표시하거나 이를 이용해 주당 필요 매출을 계산하지 마세요.
|
||||
- head.perf의 기존 용도와 템플릿 조건을 확인하고 필요하면 연결 여부·조회 성공 여부를 별도 상태로 관리하세요.
|
||||
- 회의록은 계속 열리고 직접 입력도 사용할 수 있어야 합니다.
|
||||
|
||||
완료 기준: 실제 정상 무매출은 0으로 표시됩니다. 조회 장애는 미확인/조회 실패로 표시되고, 그 실적에 의존하는 달성률·필요 매출도 미확인입니다. 부분 실패 처리도 일관되게 테스트하세요.
|
||||
|
||||
[버그 7 / P2] 정량 목표 저장 후 이번주 달성률이 갱신되지 않음
|
||||
|
||||
위치: initGoalMeeting()의 금액 change 처리, .pj-meet-week-slot / .pj-meet-week-auto. 당시 약 9179행.
|
||||
|
||||
재현: 실적 100·목표 100·표시 100%인 행에서 목표를 200으로 저장하면 표시가 100%로 남습니다. 정상은 50%입니다.
|
||||
|
||||
수정 요구:
|
||||
- 서버가 확정한 현재 목표와 현재 실적으로 비율을 즉시 갱신하세요.
|
||||
- 0·빈 목표·실적 미확인·저장 실패를 구분하세요.
|
||||
- 목표 저장과 백그라운드 실적 repaint가 겹쳐도 이전 비율이 다시 들어오지 않도록 하세요.
|
||||
- 수정 중인 초안과 서버 확정값의 의미를 일관되게 표시하고, 다른 입력칸은 유지하세요.
|
||||
|
||||
완료 기준: 목표 100→200이면 100%→50%로 즉시 바뀝니다. 목표 0·삭제·실적 조회 실패·백그라운드 갱신과의 동시 실행을 테스트하세요.
|
||||
|
||||
4. UI·UX 문제 2개
|
||||
|
||||
[UX 8] 목표의 구역·항목 메뉴가 우클릭에만 있어 찾기·접근이 어려움
|
||||
|
||||
위치: project.js의 areaMenuItems(), rowMenuItems(), contextmenu 처리(약 8483 / 8560행), goals.html, project.css.
|
||||
|
||||
수정 요구:
|
||||
- 기존 우클릭 메뉴는 유지하세요.
|
||||
- 구역·항목에 작은 메뉴 진입점 또는 동등한 접근 수단을 제공하세요.
|
||||
- 기존 사용자 요구로 제거한 큰 마우스오버 도구 막대를 그대로 복원하지 마세요. 이름 편집·열 너비·병합·분기 접기를 방해하지 않는 간결한 방식으로 구현하세요.
|
||||
- Tab으로 접근, Enter/Space로 열기, Escape로 닫기, 닫은 뒤 포커스 복귀, 터치 클릭을 지원하세요.
|
||||
- 메뉴 버튼에 명확한 접근성 이름을 제공하고 관리자에게만 편집 기능을 노출하세요.
|
||||
|
||||
완료 기준: 마우스 우클릭·키보드·터치로 동일한 메뉴 작업을 실행할 수 있고 표 레이아웃·고정 열이 깨지지 않습니다. 터치 검증을 못 했다면 완료했다고 쓰지 말고 미검증 범위를 보고하세요.
|
||||
|
||||
[UX 9] 매출 자동 갱신 실패와 자료 시점을 알 수 없음
|
||||
|
||||
위치: initMeetingSync()의 say()·catch(약 8860 / 8926행), goal_meeting.html의 hidden #pj-meet-sync(약 109행).
|
||||
|
||||
수정 요구:
|
||||
- 기존 요구대로 정상 자동 갱신은 조용히 유지하세요. 항상 표시되는 큰 진행 상태 줄을 되살리지 마세요.
|
||||
- 실패 시 최소한의 오류 안내와 재시도 수단을 제공하세요.
|
||||
- 자료의 마지막 성공 갱신 시점 또는 확인 가능한 갱신 상태를 과장 없이 보여 주세요.
|
||||
- 일부 쇼핑몰만 실패한 경우 전체 성공처럼 표시하거나 성공 시점을 부정확하게 기록하지 마세요.
|
||||
- 권한 없음은 권한 없는 API를 반복 호출하지 않고 설명하며, 기존 10분 제한·중복 작업 합류 동작과 일관되게 처리하세요.
|
||||
- 저장된 실적을 읽은 시점과 쇼핑몰에서 실제로 갱신에 성공한 시점을 혼동하지 마세요. 서버가 확인해 주지 않는 최신성을 브라우저 시각으로 만들어 표시하지 마세요.
|
||||
|
||||
완료 기준: 정상 시 조용한 화면, 실패 시 식별 가능한 안내·재시도, 부분 실패 시 정확한 상태가 확인됩니다. 재시도·갱신 중에도 편집 중인 글과 숫자가 보존됩니다.
|
||||
|
||||
5. 검증과 완료 보고
|
||||
|
||||
각 버그는 먼저 원래 실패 조건을 재현하고 수정 후 동일 조건이 통과하는 테스트를 남겨 주세요. 지연 응답·순서 역전·503·빠른 연속 입력은 테스트 대역으로 결정적으로 만들고, 정상 즉시 응답만 시험하지 마세요.
|
||||
|
||||
반드시 포함할 검증:
|
||||
- 회의록 글 A→B 연속 입력과 늦은 A 응답
|
||||
- 숫자 200 저장 중 300 재입력, 오래된 성공/실패 응답
|
||||
- 저장 실패 후 dirty 초안 유지와 페이지 이탈 보호
|
||||
- 진행 중 저장이 있는 상태의 구조 변경·새로고침·병합
|
||||
- 역순 생성 회의록, 중복 이름, 이름 변경, 누락 주, 월·연도 경계
|
||||
- 실적 목록 조회 장애, 매출 조회 장애, 정상 매출 0건
|
||||
- 목표 변경 후 비율 및 백그라운드 repaint와의 동시 실행
|
||||
- 관리자/읽기 전용 권한, 우클릭·키보드 메뉴, 정상/실패/부분 실패 갱신 안내
|
||||
- 기존 분기 접기·고정 열·열 너비·병합·스크롤 유지·참석자·한글 입력에 대한 관련 회귀 확인
|
||||
|
||||
기존 테스트 실행 방식을 확인하고 이번 변경에 맞는 테스트를 실행하세요. 환경이 없어 실행하지 못한 통합 테스트를 통과했다고 보고하지 마세요. 관련 사용자 도움말과 docs/PROJECT_MODULE.md를 최종 구현에 맞게 갱신하세요. 환경변수를 추가한다면 예시 파일과 배포 문서도 갱신하세요.
|
||||
|
||||
완료 보고는 다음을 포함해 주세요.
|
||||
1) 9개 항목별 수정 위치·최종 동작·검증 결과
|
||||
2) 실제 실행한 테스트 명령과 결과, 실행하지 못한 검증
|
||||
3) 필요한 마이그레이션과 운영 적용 전 확인 사항(운영 적용은 별도)
|
||||
4) 과거 회의록 연결의 안전한 복구 가능 범위와 남은 제한
|
||||
5) 변경 파일 목록과 UI 확인 결과
|
||||
|
||||
근거가 달라진 항목은 실제 코드와 테스트 결과를 설명하세요. 계획만 남기거나 일부 항목을 조용히 누락하지 말고, 승인된 로컬 수정과 검증을 끝까지 완료해 주세요.
|
||||
@@ -0,0 +1,94 @@
|
||||
# 클로드 수정 재검증 — 목표관리·주간회의록
|
||||
|
||||
검증일: 2026-10-01. 대상 커밋: `e1006c63de3b56f698138cf3674f5fbdde726c48`. 비교 기준: 최초 점검 커밋 `21981eb`.
|
||||
|
||||
## 판정
|
||||
|
||||
기존 9개 항목의 기본 동작은 대부분 개선됐다. 그러나 **초안 복구에서 입력이 영구적으로 사라지는 P1 문제가 재현돼 완전 해결로 판정할 수 없다.** 지난주 연결은 마이그레이션 018 적용이 필요하며, 기존에 연결 사슬 없이 만들어진 회의록은 018 적용만으로 복구되지 않는다. 운영 DB의 적용·복구 완료 여부는 이번 검증에서 확인하지 않았다.
|
||||
|
||||
기능 소스와 운영 데이터는 수정하지 않았다. 실제 운영 화면의 배포 상태·실제 터치 기기·화면 배치까지 검증한 결과는 아니다.
|
||||
|
||||
## 재현한 추가 문제
|
||||
|
||||
### P1 — 초안의 기준값이 서버값과 다르면 최신 입력과 백업을 삭제
|
||||
|
||||
위치:
|
||||
|
||||
- `app/static/project.js:271`: `d.base !== initial`이면 `localStorage.removeItem(...)` 후 복구하지 않는다.
|
||||
- `app/static/project.js:304`: 요청에 보낸 원문을 저장 기준값으로 기록한다.
|
||||
- `app/static/project.js:9488`: 회의록 글 저장 성공 시 서버가 실제 저장한 `res.item.content`를 기준값에 반영하지 않는다.
|
||||
- `app/modules/project/store.py:627`: 실제 서버는 글의 앞뒤 공백을 `.strip()`으로 제거한다. 목표 글에도 같은 처리(`:476`)가 있다.
|
||||
|
||||
실제 `project.js`와 렌더된 회의록 템플릿을 jsdom에서 실행했다. 네트워크와 서버 저장만 대역으로 만들어 지연·장애를 주었으며, 서버의 공백 정규화와 같은 처리를 사용했다.
|
||||
|
||||
**재현 A — 정상 저장에서도 공백 때문에 충돌로 오판**
|
||||
|
||||
1. 기존 글 `original`에서 `A `를 입력하고 저장 요청을 보낸다(끝 공백 포함).
|
||||
2. 응답 전에 `B - latest unsaved work`로 계속 입력한다.
|
||||
3. 서버는 `A`를 저장하고 정상 응답한다. 브라우저 백업은 `{base: "A ", draft: "B - latest unsaved work"}`다.
|
||||
4. B가 저장되기 전에 페이지를 닫았다가 서버의 A로 다시 연다.
|
||||
5. 복구 코드가 `"A " !== "A"`를 충돌로 판단한다. 화면은 A만 남고 **B의 localStorage 백업도 삭제된다.**
|
||||
|
||||
관측 결과:
|
||||
|
||||
```json
|
||||
{"server":"A","base":"A ","draft":"B - latest unsaved work","restored":"A","backupAfter":null}
|
||||
```
|
||||
|
||||
**재현 B — 서버 저장 뒤 응답만 끊긴 경우**
|
||||
|
||||
1. A 저장 요청 중 B를 추가 입력한다.
|
||||
2. 서버에는 A가 저장됐지만 응답에서 네트워크 오류가 발생한다.
|
||||
3. 백업 기준값은 기존 `original`, 초안은 B다.
|
||||
4. 다시 열면 서버 A와 기준값 original이 달라 충돌 처리되고, **B 백업이 삭제된다.**
|
||||
|
||||
```json
|
||||
{"server":"A","base":"original","draft":"B - latest unsaved work","restored":"A","backupAfter":null}
|
||||
```
|
||||
|
||||
페이지 이탈 경고가 있더라도 사용자가 닫거나 브라우저가 종료되는 경우를 보호하지 못한다. 자동 덮어쓰기를 막는 것은 적절하지만, 유일한 미저장 사본까지 삭제하면 복구 수단이 없어지는 것이 문제다. 목표 글도 같은 `createFieldSaver`와 공백 정규화를 사용하므로 동일한 경로의 위험이 있다(이번 직접 재현은 회의록 글).
|
||||
|
||||
수정 요구:
|
||||
|
||||
- 저장 기준값은 서버의 실제 저장값과 일치시킨다. 회의록 줄은 응답의 `item.content`, 다른 글 저장 API는 확정값 반환 또는 일관된 정규화가 필요하다. 최신 입력 B는 보존한다.
|
||||
- 충돌한 초안은 지우지 말고 별도 복구 대상으로 남긴다. 현재 서버값과 초안을 확인하고 복사·복원할 수 있어야 한다.
|
||||
- 저장됐지만 응답을 잃은 경우에도 백업을 보존한다. 확인되지 않은 자동 덮어쓰기는 피한다.
|
||||
- 위 두 시나리오를 목표 글·회의록 글·메모에 추가한다. 서버값 유지와 최신 초안 복구 가능성을 각각 검증한다.
|
||||
|
||||
## 기존 9개 항목별 결과
|
||||
|
||||
| 번호 | 최초 문제 | 재검증 결과 |
|
||||
|---|---|---|
|
||||
| 1 | 저장 중 추가 입력을 저장 완료로 오판 | 기본 A→B 저장·같은 칸 직렬화·실패 표시·재시도는 통과. 다만 위 P1 초안 복구 유실을 추가 수정해야 한다. |
|
||||
| 2 | 숫자의 늦은 응답이 새 입력을 덮음 | 통과. 목표 숫자·회의록 목표·결과 입력 모두 새 초안 보존, 순차 저장 확인. |
|
||||
| 3 | 글 저장 실패 뒤 구조 변경으로 입력 유실 | 기본 시나리오 통과. 실패하면 영역 추가·병합·표 교체 중단, 표 GET 중 새 글도 보호. |
|
||||
| 4 | 회의록 역순 생성 시 지난주 미연결 | 조건부. 018 적용 상태의 새 데이터는 실제 저장소 메서드 대역 실행에서 연결 확인. 미적용 상태는 여전히 미연결. 기존 독립 사슬 데이터는 별도 복구가 필요하다. |
|
||||
| 5 | 몇 주 전 자료를 직전 주 자료로 표시 | 통과. 저장소가 정확히 7일 전 주만 조회하며, 그 주가 없으면 리뷰를 비운다. 중간 주를 만들면 해당 주 자료로 연결. |
|
||||
| 6 | 실적 조회 장애를 0원으로 표시 | 통과. 목록 장애·매출 장애에서는 None/미확인, 정상 0건만 0원. 의존하는 필요 매출·달성률도 구분. |
|
||||
| 7 | 정량 목표 변경 뒤 이번주 실적 % 미갱신 | 통과. 목표 100→200이면 실적 100 기준 100%→50%, 0·빈칸 처리, 실패 시 확정 목표 기준 유지. |
|
||||
| 8 | 목표 조작이 우클릭에만 존재 | DOM·이벤트 검증 통과. 메뉴 버튼·키보드 이동·Esc·포커스 복귀 확인. 실제 터치·배치·입력기는 별도 확인 필요. |
|
||||
| 9 | 매출 갱신 실패·자료 시점이 보이지 않음 | 기본 시나리오 통과. 전체/부분 실패 안내·재시도·서버 갱신 시각·권한 없는 경우 호출 차단 확인. |
|
||||
|
||||
### 4번 완료 조건
|
||||
|
||||
`scripts/sql/project_db_018_meeting_line_keys.sql`은 기존 `carry_from` 사슬을 공유하는 줄에 같은 키를 준다. 두 주가 각각 양식으로 만들어져 `carry_from=NULL`인 경우에는 각자 다른 키를 받으므로 **마이그레이션만으로 서로 연결되지 않는다.** 이는 SQL 주석과 프로젝트 문서에도 명시돼 있다.
|
||||
|
||||
`project_db_018b_meeting_line_link_candidates.sql`은 후보 조회만 수행한다. 사람이 같은 항목임을 확인하고 별도 연결해야 한다. 최초 운영 관찰에서 발견한 9/21·9/28 미연결 자료가 실제 복구됐는지까지 확인해야 4번을 완료로 볼 수 있다. 현재 검증에서 운영 데이터가 여전히 미연결이라고 단정하지는 않는다.
|
||||
|
||||
이름만으로 무조건 연결하는 방식은 중복 이름·새 항목의 결과를 섞을 수 있어 적절하지 않다. 검증된 쌍만 연결하고, 후속 주 연결까지 확인한다.
|
||||
|
||||
## 검증 기록과 한계
|
||||
|
||||
| 검증 | 결과 |
|
||||
|---|---|
|
||||
| `python tests/js/render_goals.py` + `node tests/js/goals_meeting_ui.test.js` | **106개 assertion 통과**, exit 0, ALL PASS |
|
||||
| `python tests/js/render_project.py` + `node tests/js/project_ui.test.js` | **51개 assertion 통과**, exit 0, ALL PASS |
|
||||
| 별도 경계 조건 스크립트 `verify_claude_edges.cjs` | 위 공백·응답 유실 상황에서 최신 초안과 백업 삭제 재현 |
|
||||
| 별도 저장소·라우터 대역 실행 `verify_claude_backend.py` | 역순 생성(018 적용/미적용), 날짜 공백, 중간 주 연결, 실적 장애/실제 0, 기존 독립 키 미연결 **8개 확인 통과** |
|
||||
| Python 변경 파일 문법 컴파일 | 통과 |
|
||||
| `python tests/test_project_module.py` | **SKIP** — 로컬 `PROJECT_TEST_DB_URL` 미설정 |
|
||||
| `python tests/test_meeting_line_keys_migration.py` | **SKIP** — 같은 이유. 실제 PostgreSQL에서 018 적용·멱등성·제약조건은 미검증 |
|
||||
|
||||
별도 재현 스크립트는 `%TEMP%/main-app-goals-review-20261001/`에 있다. 백엔드 대역 실행은 실제 `ProjectStore.create_meeting/get_meeting`과 `_meeting_view`를 실행하되 DB 연결·SQL 결과를 메모리로 대체했다. **SQL 자체의 실행 검증을 대신하지 않는다.** UI 테스트는 실제 프로젝트 JS·템플릿을 사용하지만 가짜 HTTP 응답 기반이며 실제 브라우저 렌더링 검증을 대신하지 않는다.
|
||||
|
||||
현재 판단: 수정 방향과 기본 검증은 타당하다. **초안 유실 P1을 고치고, 018 실DB 검증 및 기존 미연결 회의록 복구 확인을 마친 뒤 완료 판정**하는 것이 적절하다.
|
||||
@@ -0,0 +1,79 @@
|
||||
# 목표관리·주간회의록 점검 — 2026-10-01
|
||||
|
||||
대상: 로컬 HEAD `21981eb`, `app/modules/project/`의 목표·회의록 저장/조회, `app/static/project.js`, 두 화면 템플릿. 실제 Chrome 운영 화면은 읽기 전용으로 관찰했다. 기능 코드·운영 DB·환경변수는 수정하지 않았다.
|
||||
|
||||
확인 결과: **기능 버그 7개, UI·UX 문제 2개**. P1은 입력 손실 때문에 우선 수정, P2는 데이터 연결·표시 정확도 수정이다. UI·UX 항목은 개선 제안으로 구분한다.
|
||||
|
||||
| 번호 | 우선순위 | 위치 | 문제와 수정 방향 |
|
||||
|---|---|---|---|
|
||||
| 1 | P1 | `app/static/project.js:9110` | 회의록 자동 저장 응답에서 요청 당시 글 대신 현재 입력값을 `saved`로 기록한다. 미전송 글이 저장됐다고 간주되어 다음 저장을 생략한다. 요청값을 캡처하고 칸별 저장 순서·최신 입력을 관리한다. |
|
||||
| 2 | P1 | `app/static/project.js:8229`, `9179` | 숫자 저장의 늦은 응답이 사용자가 다시 입력 중인 값을 덮는다. 목표 표 숫자와 회의록 정량 목표·결과 입력에 같은 구조가 있다. 응답은 요청값이 현재 초안과 일치할 때만 입력창에 반영한다. |
|
||||
| 3 | P1 | `app/static/project.js:8257`, `8386`, `8416` | 목표 글 저장 실패를 함수 내부에서 삼켜 구조 변경이 계속된다. 표를 다시 그리면 미저장 글이 사라진다. 저장 실패를 상위 작업에 전달하고, 모든 변경·진행 중 저장을 완료하기 전 DOM 교체·병합을 막는다. |
|
||||
| 4 | P2 | `app/modules/project/db.py:2524`, `2536` | 다음 주 회의록을 먼저 만들고 앞 주를 나중에 만들면 기존 다음 주의 `carry_from`을 연결하지 않는다. 실제 운영 화면에도 앞 주 존재 표시와 다음 주 리뷰 미연결이 동시에 있다. 안정적인 항목 연결키를 두고 생성 순서와 무관하게 전주 연결을 처리한다. |
|
||||
| 5 | P2 | `app/modules/project/router.py:2922`, `app/modules/project/templates/project/goal_meeting.html:190` | 한 주 이상 건너뛰면 가장 가까운 과거 회의록의 줄을 읽으면서 표 머리는 무조건 직전 주 날짜를 표시한다. 다른 주의 목표·결과·달성률을 지난주 수치로 오인한다. 실제 참조 주를 표시하거나 직전 주가 없으면 리뷰를 비운다. |
|
||||
| 6 | P2 | `app/modules/project/router.py:2849`, `2854`, `2901` | 쇼핑몰 목록 조회 장애를 빈 목록으로 바꿔 매출 합계를 0원으로 표시한다. 저장소 객체만 있으면 연결 여부도 참이다. 조회 실패와 실제 0건을 구분해 장애 시 지표를 미확인으로 표시한다. |
|
||||
| 7 | P2 | `app/static/project.js:9179` | 이번주 정량 목표 저장 뒤 `pj-meet-week-slot`의 목표 대비 %를 갱신하지 않는다. 이번주 실적 표시를 보관해 목표 변경 후 즉시 재계산한다. |
|
||||
| 8 | UX | `app/static/project.js:8483`, `8560`, `app/modules/project/templates/project/goals.html` | 목표 구역·항목의 색·순서·줄 추가·삭제가 우클릭 메뉴에만 있다. 키보드로 이름 칸에 접근할 수 없고 터치 대안도 없어 기능을 찾고 실행하기 어렵다. 이름 칸에 포커스 가능한 메뉴 버튼이나 키보드·터치 진입점을 제공한다. |
|
||||
| 9 | UX | `app/static/project.js:8860`, `8926`, `app/modules/project/templates/project/goal_meeting.html:109` | 매출 자동 갱신 실패 메시지도 숨은 상태 요소에만 전달되어 사용자는 실패·자료 시점을 알 수 없다. 정상 갱신은 조용히 유지하되 실패 안내와 마지막 성공 시점·재시도 진입점을 제공한다. |
|
||||
|
||||
## 재현 근거
|
||||
|
||||
### 1. 회의록: 저장되지 않은 글을 저장됨으로 처리
|
||||
|
||||
실제 `project.js`를 jsdom에서 실행하고 PUT 응답만 지연했다.
|
||||
|
||||
1. `draft A`를 입력하고 칸을 떠나 저장 요청을 보낸다.
|
||||
2. 요청이 끝나기 전에 같은 칸에 `draft B`를 입력한다.
|
||||
3. A의 저장 응답을 완료하고 B의 자동 저장 대기 시간 800ms가 지나도록 기다린다.
|
||||
|
||||
관찰 결과: **화면 B, `data-saved` B, 서버 A, PUT 1회**. 두 번째 글은 서버에 보내지지 않았다. `flush()`가 `await p.save(ta.value)` 뒤 바뀐 `ta.value`를 저장 완료 값으로 기록하기 때문이다.
|
||||
|
||||
추가 실패 시나리오: 저장을 503으로 실패시킨 뒤 `beforeunload`를 발생시키면 요청은 실패한 PUT 한 번뿐이었다. `pending`에서 먼저 지운 칸은 페이지 이탈 저장에도 포함되지 않는다. 실패한 초안을 계속 dirty 상태로 보관해야 한다.
|
||||
|
||||
### 2. 숫자: 이전 저장 응답이 최신 입력을 덮음
|
||||
|
||||
목표 숫자 200의 저장 응답을 지연한 동안 같은 입력창을 300으로 바꾸고, 그 후 200 응답을 완료했다.
|
||||
|
||||
관찰 결과: **현재 입력 300 → 200**. 사용자 초안이 이전 요청 응답으로 바뀌었다. 회의록 금액 저장도 응답값을 무조건 입력창에 대입하는 동일한 방식이다.
|
||||
|
||||
### 3. 목표 표: 저장 실패 후 구조 새로 그리기로 글 손실
|
||||
|
||||
목표 칸에 `unsaved important plan`을 입력한 직후 업무 영역 추가를 실행했다. 글 PUT은 503으로 실패, 화면 GET은 기존 저장본을 반환하도록 했다.
|
||||
|
||||
관찰 요청 순서: 영역 POST → 글 PUT(503) → 화면 GET. 최종 textarea는 **미저장 계획 → 기존 `original`**로 돌아갔다. 오류 토스트가 떠도 편집 글 자체가 사라진다. `saveText()`가 실패를 다시 던지지 않아 `flushTexts()`가 성공한 것처럼 끝난다.
|
||||
|
||||
### 4. 회의록 생성 순서에 따른 전주 연결 누락
|
||||
|
||||
실제 `ProjectStore.create_meeting()`을 호출하되 SQL 실행만 메모리 대역으로 바꿨다. 실제 DB에는 접속하지 않았다.
|
||||
|
||||
재현: 9/28 주 생성 → 9/21 주 생성. 결과: 앞 주 회의록은 존재하지만 9/28 줄의 **`carry_from`은 NULL**로 남았다.
|
||||
|
||||
운영 화면 관찰: 2026년 9월 화면에서 **9/21·9/28 모두 회의록 존재 점이 있으며, 선택된 9/28 주의 24개 줄 중 `data-prev`가 있는 줄은 0개**였다. 실제 운영 데이터가 이 상태에 이른 생성·삭제 이력은 확인하지 않았다. 생성 순서는 같은 상태를 만드는 확인된 원인이다.
|
||||
|
||||
### 5. 주차를 건너뛰었을 때 리뷰 기간 불일치
|
||||
|
||||
실제 `_meeting_view()`에 9/28 회의록의 참조 줄이 9/7 회의록인 데이터를 전달했다.
|
||||
|
||||
관찰 결과: 표 머리에 사용할 지난주 날짜는 **9/21~9/27**, 실제 줄의 결과 기간은 **9/7~9/13**, 그 다른 주의 목표 100·결과 50을 사용한 달성률 **50%**가 나온다. 머리의 전주 목표는 정확히 직전 주인지 검사하지만 줄은 검사하지 않는다.
|
||||
|
||||
### 6. 조회 장애가 실제 매출 0원처럼 표시
|
||||
|
||||
실적 저장소 대역의 `list_marketplaces()`에서 예외를 발생시켰다.
|
||||
|
||||
관찰 결과: **월 누적 0, 전주 결과 0, 금주 결과 0, `perf=true`**. 월 목표 1,000원인 재현 데이터에서 필요 매출도 1,000원으로 계산됐다. 장애로 실적을 못 읽은 상태와 실제 무매출을 구분하지 못한다.
|
||||
|
||||
### 7. 목표 변경 뒤 이번주 달성률 미갱신
|
||||
|
||||
실제 회의록 JS에 현재 실적 100·목표 100·표시 100%인 행을 전달하고 목표를 200으로 저장했다.
|
||||
|
||||
관찰 결과: **목표 200, 이번주 실적 100, 표시 100% 유지**. 올바른 표시는 50%다. 입력 금액만 바꾸고 아래 실적 비율은 재계산하지 않는다.
|
||||
|
||||
## 검증 범위와 우선순위
|
||||
|
||||
- JS는 실제 전체 `app/static/project.js`를 실행했다. DOM·API는 로컬 테스트 대역이며 운영 화면에는 입력·생성·삭제를 실행하지 않았다.
|
||||
- Python은 실제 조회 함수·생성 메서드를 호출하고 DB·실적 저장소를 대역으로 바꿨다. 실제 PostgreSQL 통합 테스트는 실행하지 않았다.
|
||||
- 총 8개 재현 시나리오를 실행했다(위 7개 버그 + 저장 실패 후 페이지 이탈 시나리오). 레이아웃은 실제 Chrome 화면으로 확인했으며 모바일·인쇄는 미검증이다.
|
||||
- 재현 스크립트는 개발 PC `%TEMP%/main-app-goals-review-20261001/`에 `review_ui.cjs`, `review_backend.py`, `review_rate.cjs`로 보관했다. jsdom도 그 임시 폴더에 설치했다. 저장소 의존성 파일은 변경하지 않았다.
|
||||
- 수정 순서: **칸별 저장 큐·요청값/초안 분리 → 실패 시 초안 보존·구조 변경 중단 → 전주 연결/날짜 정합성 → 실적 장애 구분·달성률 갱신 → 메뉴 접근성과 갱신 실패 안내**.
|
||||
|
||||
이 보고서는 발견·재현 결과이며 수정 완료 보고서가 아니다.
|
||||
@@ -0,0 +1,33 @@
|
||||
-- =====================================================================
|
||||
-- cupang_db 마이그레이션 007 — 제품 포장무게(g)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). DROP TABLE/TRUNCATE/DELETE 없음 — 칸 하나와 CHECK 제약만 더한다.
|
||||
--
|
||||
-- cupang_products.weight_g INTEGER NULL — 포장무게(그램). NULL = 아직 모름.
|
||||
-- 설정(제품명) 화면의 수기 추가·수정 팝업에서 입력, 등록 목록에 표시.
|
||||
-- 초기 값은 별도 시드 scripts/sql/cupang_products_weight_seed.sql (이 파일 다음에 실행).
|
||||
--
|
||||
-- 미적용이어도 화면은 동작한다 — 무게 칸만 숨기고 저장하지 않는다(라우터/DB 가 칸 유무를 확인).
|
||||
--
|
||||
-- 적용 (1회, 여러 번 돌려도 안전, 적용 전 cupang_db 백업):
|
||||
-- docker exec -i postgres-db psql -U postgres -d cupang_db < scripts/sql/cupang_db_007_product_weight.sql
|
||||
-- 확인:
|
||||
-- docker exec -i postgres-db psql -U postgres -d cupang_db -c "\d cupang_products"
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect cupang_db
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE cupang_products ADD COLUMN IF NOT EXISTS weight_g INTEGER NULL;
|
||||
|
||||
ALTER TABLE cupang_products DROP CONSTRAINT IF EXISTS cupang_products_weight_g_check;
|
||||
ALTER TABLE cupang_products ADD CONSTRAINT cupang_products_weight_g_check
|
||||
CHECK (weight_g IS NULL OR (weight_g >= 0 AND weight_g <= 1000000));
|
||||
|
||||
COMMENT ON COLUMN cupang_products.weight_g IS '포장무게(g). NULL = 미입력';
|
||||
|
||||
COMMIT;
|
||||
|
||||
SELECT 'cupang_db 007 product weight ready' AS status;
|
||||
@@ -0,0 +1,98 @@
|
||||
-- =====================================================================
|
||||
-- cupang_db 시드 — 등록된 제품에 포장무게(g) 채우기
|
||||
-- =====================================================================
|
||||
-- 사유: 사용자가 전달한 (물류코드, 포장무게 g) 39건(2026-10-02)을 cupang_products.weight_g 에 반영한다.
|
||||
--
|
||||
-- 선행: scripts/sql/cupang_db_007_product_weight.sql 적용 필요.
|
||||
--
|
||||
-- 안전: product_code 가 정확히 일치하고 **무게가 아직 비어 있는(NULL) 행만** UPDATE 한다.
|
||||
-- (조건 없는 대량 UPDATE 아님. 삭제/DROP 없음. 화면에서 이미 입력·수정한 무게는 덮어쓰지 않는다)
|
||||
-- 실행 전 현재 값을 _cpg_weight_seed_backup 테이블에 남긴다. 목록에 없는 제품은 건드리지 않는다.
|
||||
-- 여러 번 실행해도 안전(두 번째부터는 비어 있는 행이 없어 바뀌지 않음).
|
||||
--
|
||||
-- 실행:
|
||||
-- docker exec -i postgres-db psql -U postgres -d cupang_db < scripts/sql/cupang_products_weight_seed.sql
|
||||
--
|
||||
-- 되돌리기(백업 테이블이 남아 있을 때):
|
||||
-- UPDATE cupang_products p SET weight_g = b.old_weight_g
|
||||
-- FROM _cpg_weight_seed_backup b WHERE b.id = p.id;
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect cupang_db
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE TEMP TABLE _cpg_wseed (product_code TEXT, weight_g INTEGER);
|
||||
|
||||
INSERT INTO _cpg_wseed (product_code, weight_g) VALUES
|
||||
('MT-0550', 265),
|
||||
('MS-9804', 450),
|
||||
('MS-9805', 580),
|
||||
('MS-9801', 200),
|
||||
('MS-9806', 650),
|
||||
('MS-9807', 870),
|
||||
('MT-1800', 340),
|
||||
('MS-9808', 780),
|
||||
('MS-9809', 1070),
|
||||
('MS-9810', 870),
|
||||
('MS-9811', 1200),
|
||||
('MT-3200', 400),
|
||||
('MS-9802', 1000),
|
||||
('MS-1001', 623),
|
||||
('MS-1002', 951),
|
||||
('MS-1003', 1124),
|
||||
('MS-1004', 866),
|
||||
('MS-1005', 730),
|
||||
('MS-1006', 1110),
|
||||
('MS-1007', 1190),
|
||||
('MS-9812', 645),
|
||||
('MS-9813', 713),
|
||||
('MS-9814', 835),
|
||||
('MS-9815', 1270),
|
||||
('MS-9816', 1845),
|
||||
('MS-9817', 2252),
|
||||
('MS-9818', 3000),
|
||||
('MT-4000', 410),
|
||||
('MT-4000_3', 830),
|
||||
('MT-4000_5', 1250),
|
||||
('MZ-0001', 450),
|
||||
('MZ-0002', 520),
|
||||
('MT-0001', 800),
|
||||
('MT-0001_3', 1900),
|
||||
('MT-0001_5', 3000),
|
||||
('MT-5000_2', 1000),
|
||||
('MT-5000_4', 1800),
|
||||
('MT-7000_2', 1060),
|
||||
('MW-7000_2', 1060);
|
||||
|
||||
-- 변경 전 값 백업 (되돌리기용, 남겨둔다)
|
||||
DROP TABLE IF EXISTS _cpg_weight_seed_backup;
|
||||
CREATE TABLE _cpg_weight_seed_backup AS
|
||||
SELECT p.id, p.product_code, p.weight_g AS old_weight_g, now() AS backed_up_at
|
||||
FROM cupang_products p
|
||||
JOIN _cpg_wseed s ON s.product_code = p.product_code;
|
||||
|
||||
UPDATE cupang_products p
|
||||
SET weight_g = s.weight_g
|
||||
FROM _cpg_wseed s
|
||||
WHERE p.product_code = s.product_code
|
||||
AND p.weight_g IS NULL;
|
||||
|
||||
-- 반영 결과
|
||||
SELECT count(*) AS "무게가 들어간 제품 수"
|
||||
FROM cupang_products p JOIN _cpg_wseed s ON s.product_code = p.product_code
|
||||
WHERE p.weight_g IS NOT NULL;
|
||||
|
||||
-- 이미 다른 무게가 들어 있어 건너뛴 제품(화면에서 입력한 값 유지)
|
||||
SELECT p.product_code AS "기존 무게 유지", p.weight_g AS "현재 무게", s.weight_g AS "시드 무게"
|
||||
FROM cupang_products p JOIN _cpg_wseed s ON s.product_code = p.product_code
|
||||
WHERE p.weight_g IS DISTINCT FROM s.weight_g;
|
||||
|
||||
-- cupang_products 에 없는 제품코드 (설정 화면에서 등록한 뒤 수정 팝업으로 무게 입력, 또는 등록 후 이 시드 다시 실행)
|
||||
SELECT s.product_code AS "미등록 제품코드", s.weight_g AS "포장무게(g)"
|
||||
FROM _cpg_wseed s
|
||||
WHERE NOT EXISTS (SELECT 1 FROM cupang_products p WHERE p.product_code = s.product_code)
|
||||
ORDER BY s.product_code;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,45 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 014 — 연간 목표: 상·하반기 칸 · 월 칸 병합
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — goal_cells 의 month CHECK 제약만 넓혀 다시 건다.
|
||||
--
|
||||
-- goal_cells.month 0 = 연간, 1~12 = 월, 13 = 상반기, 14 = 하반기
|
||||
-- goal_cell_merges 업무 영역 줄의 월 칸 가로 병합. start_month 부터 span 칸(2칸 이상).
|
||||
-- 상반기(1~6)·하반기(7~12)를 넘지 않는다(사이에 상반기 칸이 있고, 반기를 접을 수 있어서).
|
||||
-- 글은 start_month 칸(goal_cells)에 둔다.
|
||||
--
|
||||
-- 미적용이어도 목표 화면은 동작한다 — 상·하반기 글 칸과 병합만 "마이그레이션 014 필요".
|
||||
--
|
||||
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
-- < scripts/sql/project_db_014_goal_halves_merges.sql
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect project_db
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE goal_cells DROP CONSTRAINT IF EXISTS goal_cells_month_check;
|
||||
ALTER TABLE goal_cells ADD CONSTRAINT goal_cells_month_check CHECK (month BETWEEN 0 AND 14);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goal_cell_merges (
|
||||
row_id BIGINT NOT NULL REFERENCES goal_rows(id) ON DELETE CASCADE,
|
||||
start_month SMALLINT NOT NULL,
|
||||
span SMALLINT NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (row_id, start_month),
|
||||
CONSTRAINT goal_cell_merges_range CHECK (
|
||||
span >= 2 AND start_month >= 1 AND start_month + span - 1 <= 12
|
||||
AND (start_month <= 6) = (start_month + span - 1 <= 6)
|
||||
)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 줄의 월 칸 가로 병합(반기 안에서만)';
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON goal_cell_merges TO project_app;
|
||||
|
||||
COMMIT;
|
||||
|
||||
SELECT 'project_db 014 goal halves/merges ready' AS status;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 016 — 연간 목표: 항목 칸(2열) 묶음
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 칸 하나 추가뿐 — 기존 데이터는 그대로(모두 false = 지금과 같은 화면).
|
||||
--
|
||||
-- goal_rows.label_cont = true → 이 줄의 항목 칸(2열)은 바로 위 줄의 항목 칸에 묶인다(이름은 묶음 첫 줄에만).
|
||||
-- 3열(연간 칸)에서 "아래에 줄 추가"를 하면 새 줄이 같은 항목 칸 안에 들어간다(2열은 하나, 3열부터 줄이 늘어남).
|
||||
--
|
||||
-- 미적용이어도 목표 화면은 동작한다 — 3열 줄 추가만 "마이그레이션 016 필요".
|
||||
--
|
||||
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
-- < scripts/sql/project_db_016_goal_row_label_groups.sql
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect project_db
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE goal_rows ADD COLUMN IF NOT EXISTS label_cont BOOLEAN NOT NULL DEFAULT false;
|
||||
COMMENT ON COLUMN goal_rows.label_cont IS 'true = 항목 칸(2열)이 바로 위 줄 항목 칸에 묶임(이름은 묶음 첫 줄에)';
|
||||
|
||||
COMMIT;
|
||||
|
||||
SELECT 'project_db 016 goal row label groups ready' AS status;
|
||||
@@ -0,0 +1,56 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 017 — 연간 목표: 상·하반기 → 1~4분기
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — CHECK 제약만 바꿔 다시 걸고, 조건 있는 UPDATE/DELETE 만 한다.
|
||||
--
|
||||
-- 분기 글 칸 번호는 예전 반기 칸을 그대로 이어 쓴다(글 옮기기 없음):
|
||||
-- 13 = 1분기(예전 상반기 글이 여기 보임) · 15 = 2분기 · 14 = 3분기(예전 하반기 글) · 16 = 4분기
|
||||
-- 화면 순서: 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 · 7~9월 · 3분기 · 10~12월 · 4분기
|
||||
--
|
||||
-- ① goal_cells.month — 0~14 → 0~16 (2·4분기 칸 저장)
|
||||
-- ② goal_cell_merges — 가로 병합은 같은 분기 월 칸 안에서만. 예전 반기 병합이 분기를 넘으면(예: 2~4월)
|
||||
-- 그 분기 끝 월까지로 줄인다(글은 시작 칸에 그대로). 줄인 뒤 한 칸짜리(가로 1 · 세로 1)가 된 병합은 지운다
|
||||
-- — 병합이 아니게 된 것뿐이고 글(goal_cells)은 지우지 않는다. 분기 칸(13~16)은 세로로만.
|
||||
-- ③ 주간 회의록 기본 줄 이름 "메타(숫자)" → "메타"(store.MEETING_TEMPLATE 와 같게, 그 이름인 줄만)
|
||||
--
|
||||
-- 미적용이어도 목표 화면은 동작한다 — 2·4분기 칸 저장·병합만 "마이그레이션 017 필요".
|
||||
--
|
||||
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
-- < scripts/sql/project_db_017_goal_quarters.sql
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect project_db
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ① 분기 글 칸 ───────────────────────────────────────────────────────
|
||||
ALTER TABLE goal_cells DROP CONSTRAINT IF EXISTS goal_cells_month_check;
|
||||
ALTER TABLE goal_cells ADD CONSTRAINT goal_cells_month_check CHECK (month BETWEEN 0 AND 16);
|
||||
|
||||
-- ② 병합 — 분기 안으로 ──────────────────────────────────────────────
|
||||
ALTER TABLE goal_cell_merges DROP CONSTRAINT IF EXISTS goal_cell_merges_range;
|
||||
|
||||
UPDATE goal_cell_merges
|
||||
SET span = ((start_month - 1) / 3 + 1) * 3 - start_month + 1
|
||||
WHERE start_month BETWEEN 1 AND 12
|
||||
AND start_month + span - 1 > ((start_month - 1) / 3 + 1) * 3;
|
||||
|
||||
DELETE FROM goal_cell_merges WHERE span = 1 AND row_span = 1;
|
||||
|
||||
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, 15, 16) AND span = 1)
|
||||
OR (start_month BETWEEN 1 AND 12 AND (start_month - 1) / 3 = (start_month + span - 2) / 3)
|
||||
)
|
||||
);
|
||||
COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 칸 병합(가로: 분기 안 월 칸, 세로: 같은 영역 안 줄 row_span)';
|
||||
|
||||
-- ③ 회의록 줄 이름 ──────────────────────────────────────────────────
|
||||
UPDATE goal_meeting_items SET label = '메타' WHERE label = '메타(숫자)';
|
||||
|
||||
COMMIT;
|
||||
|
||||
SELECT 'project_db 017 goal quarters ready' AS status;
|
||||
@@ -0,0 +1,87 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 018 — 주간 회의록 줄 연결키(line_key)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). DROP TABLE/TRUNCATE/DELETE 없음 — 새 칸을 더하고 비어 있는 칸만 채운다.
|
||||
--
|
||||
-- 왜: 예전엔 "지난주" 줄을 carry_from(만들 때 앞선 회의록 줄 id)으로만 찾았다.
|
||||
-- · 다음 주(9/28)를 먼저 만들고 앞 주(9/21)를 나중에 만들면 9/28 의 carry_from 이 비어 지난주 리뷰가 빠졌다.
|
||||
-- · 한 주를 건너뛰면 몇 주 전 줄이 "지난주"로 보였다.
|
||||
-- · 앞 주를 지웠다 다시 만들면 ON DELETE SET NULL 로 끊긴 연결이 돌아오지 않았다.
|
||||
-- 이제: 줄마다 연결키(line_key) — 회의록을 만들 때 원본 줄의 키를 그대로 이어받고, 새 줄은 새 키.
|
||||
-- "지난주" = 정확히 7일 전 주 회의록에서 같은 키의 줄(생성 순서·이름 변경·순서 이동과 무관).
|
||||
--
|
||||
-- ① line_key UUID 칸 추가
|
||||
-- ② 기존 줄 채우기 — carry_from 사슬을 따라 같은 키를 준다(사슬의 맨 앞 줄 = 키의 뿌리).
|
||||
-- carry_from 이 없는 줄(첫 회의록·줄 추가·앞 주 삭제로 끊긴 줄)은 자기만의 새 키 → 다른 줄에 붙지 않는다.
|
||||
-- 이름(label)으로 추정해 붙이지 않는다(같은 이름 줄·이름 변경 때 다른 줄 결과가 섞일 수 있어서).
|
||||
-- → 9/14 를 원본으로 9/28 을 먼저, 9/21 을 나중에 만든 경우 두 주 줄이 모두 9/14 키를 받아 9/28 ↔ 9/21 이 다시 연결된다.
|
||||
-- → 둘 다 양식(앞선 회의록 없음)으로 만든 주끼리는 사슬이 없어 연결되지 않는다(자동 복구 범위 밖,
|
||||
-- project_db_018b_meeting_line_link_candidates.sql 로 후보를 조회해 사람이 확인 후 따로 연결).
|
||||
-- ③ 한 주 안에서 키가 겹치면(정상 데이터에선 없음) 순서가 뒤인 줄에 새 키 — 한 줄이 두 줄에 붙지 않게
|
||||
-- ④ 기본값(예전 코드 호환) + NOT NULL + (week_start, line_key) UNIQUE
|
||||
--
|
||||
-- 미적용이어도 회의록은 동작한다 — "지난주"는 carry_from 이 정확히 7일 전 주 줄을 가리킬 때만 보인다(역순 생성 연결은 안 됨).
|
||||
--
|
||||
-- 적용 (1회, 여러 번 돌려도 안전, 적용 전 project_db 백업):
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
-- < scripts/sql/project_db_018_meeting_line_keys.sql
|
||||
-- 확인:
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db -c \
|
||||
-- "SELECT count(*) AS total, count(line_key) AS keyed FROM goal_meeting_items;"
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect project_db
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ① 칸 ─────────────────────────────────────────────────────────────
|
||||
ALTER TABLE goal_meeting_items ADD COLUMN IF NOT EXISTS line_key UUID;
|
||||
|
||||
-- ② 기존 줄 — carry_from 사슬로 키 채우기(비어 있는 줄만). id 는 만든 순서라 자식 id > 부모 id(순환 방지).
|
||||
-- 뿌리 키 = md5('goal_meeting_item:' || 뿌리 id) — 같은 데이터면 몇 번 돌려도 같은 키.
|
||||
WITH RECURSIVE chain AS (
|
||||
SELECT i.id, COALESCE(i.line_key, md5('goal_meeting_item:' || i.id)::uuid) AS k
|
||||
FROM goal_meeting_items i
|
||||
WHERE i.line_key IS NOT NULL
|
||||
OR i.carry_from IS NULL
|
||||
OR NOT EXISTS (SELECT 1 FROM goal_meeting_items p WHERE p.id = i.carry_from)
|
||||
UNION ALL
|
||||
SELECT c.id, chain.k
|
||||
FROM goal_meeting_items c
|
||||
JOIN chain ON c.carry_from = chain.id
|
||||
WHERE c.line_key IS NULL AND c.id > chain.id
|
||||
)
|
||||
UPDATE goal_meeting_items g
|
||||
SET line_key = chain.k
|
||||
FROM chain
|
||||
WHERE g.id = chain.id AND g.line_key IS NULL;
|
||||
|
||||
-- 사슬에 닿지 않은 줄(있을 수 없지만 안전하게) — 자기만의 키
|
||||
UPDATE goal_meeting_items SET line_key = md5('goal_meeting_item:' || id)::uuid WHERE line_key IS NULL;
|
||||
|
||||
-- ③ 한 주 안 같은 키 — 순서가 뒤인 줄만 새 키(줄 내용·carry_from 은 그대로)
|
||||
UPDATE goal_meeting_items g
|
||||
SET line_key = md5('goal_meeting_item:dup:' || g.id)::uuid
|
||||
FROM (SELECT id, row_number() OVER (PARTITION BY week_start, line_key ORDER BY sort_order, id) AS rn
|
||||
FROM goal_meeting_items) d
|
||||
WHERE g.id = d.id AND d.rn > 1;
|
||||
|
||||
-- ④ 제약 ───────────────────────────────────────────────────────────
|
||||
-- 기본값 — 018 을 먼저 적용하고 코드를 나중에 배포해도(예전 코드는 line_key 를 넣지 않음) 줄 추가가 실패하지 않게 새 키.
|
||||
-- 새 코드는 늘 키를 직접 넣는다(이어받기 = 원본 키, 새 줄 = 새 키). pgcrypto 없이 되는 식(md5 → uuid).
|
||||
ALTER TABLE goal_meeting_items ALTER COLUMN line_key SET DEFAULT md5(random()::text || clock_timestamp()::text)::uuid;
|
||||
ALTER TABLE goal_meeting_items ALTER COLUMN line_key SET NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_goal_meeting_items_week_key ON goal_meeting_items (week_start, line_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_meeting_items_key ON goal_meeting_items (line_key);
|
||||
|
||||
COMMENT ON COLUMN goal_meeting_items.line_key IS
|
||||
'주가 바뀌어도 같은 줄을 가리키는 연결키 — 회의록을 만들 때 원본 줄 키를 이어받음. 지난주 = 7일 전 주의 같은 키 줄';
|
||||
COMMENT ON COLUMN goal_meeting_items.carry_from IS
|
||||
'만들 때 이어받은 앞선 회의록 줄(이력). 화면의 지난주 연결은 line_key(018) 로 찾는다';
|
||||
|
||||
COMMIT;
|
||||
|
||||
SELECT 'project_db 018 meeting line keys ready' AS status,
|
||||
(SELECT count(*) FROM goal_meeting_items) AS items,
|
||||
(SELECT count(*) FROM goal_meeting_items WHERE line_key IS NULL) AS missing_keys;
|
||||
@@ -0,0 +1,45 @@
|
||||
-- =====================================================================
|
||||
-- project_db 018b — 주간 회의록 "지난주" 연결 후보 조회 (읽기 전용, 자동 적용 없음)
|
||||
-- =====================================================================
|
||||
-- 018 은 carry_from 사슬이 있는 줄만 자동으로 이어 준다. 앞선 회의록 없이 양식으로 만든 주끼리
|
||||
-- (예: 9/28 을 먼저 양식으로 만들고 9/21 도 양식으로 만든 경우)는 사슬이 없어 연결되지 않는다.
|
||||
-- 이 조회는 그런 주 쌍(정확히 7일 차이)에서 **구역+줄 이름이 양쪽 주에 각각 한 줄씩만 있는** 줄만 후보로 보여 준다.
|
||||
-- 같은 구역에 같은 이름이 두 줄 이상이거나 이름이 빈 줄, 이미 연결된 줄은 후보에서 뺀다(추정 연결 금지).
|
||||
--
|
||||
-- 실행(조회만):
|
||||
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
-- < scripts/sql/project_db_018b_meeting_line_link_candidates.sql
|
||||
--
|
||||
-- 후보를 사람이 확인한 뒤에만, 한 쌍씩 아래처럼 연결한다(다음 주 줄이 앞 주 줄의 키를 받음). 운영 적용은 별도 승인·백업 후.
|
||||
-- BEGIN;
|
||||
-- UPDATE goal_meeting_items SET line_key = (SELECT line_key FROM goal_meeting_items WHERE id = <앞 주 줄 id>)
|
||||
-- WHERE id = <다음 주 줄 id>
|
||||
-- AND NOT EXISTS (SELECT 1 FROM goal_meeting_items x
|
||||
-- WHERE x.week_start = goal_meeting_items.week_start
|
||||
-- AND x.line_key = (SELECT line_key FROM goal_meeting_items WHERE id = <앞 주 줄 id>));
|
||||
-- -- 다음 주 다음(+14일) 회의록이 그 줄을 예전 키로 이어받았다면 그 줄도 같은 키로 맞춰야 사슬이 이어진다 — 결과 확인 후 COMMIT
|
||||
-- COMMIT;
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
\connect project_db
|
||||
|
||||
WITH items AS (
|
||||
SELECT i.*, count(*) OVER (PARTITION BY i.week_start, i.section, i.label) AS same_name
|
||||
FROM goal_meeting_items i
|
||||
WHERE btrim(i.label) <> ''
|
||||
),
|
||||
pairs AS (
|
||||
SELECT p.week_start AS prev_week, n.week_start AS week,
|
||||
n.section, n.label, p.id AS prev_item_id, n.id AS item_id
|
||||
FROM items n
|
||||
JOIN items p ON p.week_start = n.week_start - 7 AND p.section = n.section AND p.label = n.label
|
||||
WHERE n.same_name = 1 AND p.same_name = 1
|
||||
AND n.line_key <> p.line_key
|
||||
-- 이미 이 앞 주에 같은 키 줄이 있는 다음 주 줄(연결됨)은 빼고, 앞 주 줄이 다른 줄과 이미 이어진 것도 뺀다
|
||||
AND NOT EXISTS (SELECT 1 FROM goal_meeting_items x WHERE x.week_start = p.week_start AND x.line_key = n.line_key)
|
||||
AND NOT EXISTS (SELECT 1 FROM goal_meeting_items y WHERE y.week_start = n.week_start AND y.line_key = p.line_key)
|
||||
)
|
||||
SELECT prev_week, week, section, label, prev_item_id, item_id
|
||||
FROM pairs
|
||||
ORDER BY week, section, label;
|
||||
@@ -13,3 +13,39 @@ node tests/js/box_calc_ui.test.js
|
||||
```
|
||||
|
||||
성공하면 마지막 줄에 `ALL PASS`, 실패하면 실패한 항목명이 출력되고 종료코드 1.
|
||||
|
||||
# 연간 목표·주간 회의록 UI 테스트 (jsdom)
|
||||
|
||||
`goals.html`·`goal_meeting.html` + `static/project.js` — 칸 저장 직렬화·늦은 응답·503·초안 보호·구조 변경 중단·이번주 실적 %·
|
||||
실적 미확인 표시·⋮ 메뉴(키보드·터치 클릭)·매출 갱신 안내를 가짜 서버(지연·실패를 직접 만듦)로 검증한다.
|
||||
|
||||
```bash
|
||||
python tests/js/render_goals.py # → tests/js/.out/goals_*.html · meeting_*.html
|
||||
node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom 또는 NODE_PATH)
|
||||
```
|
||||
|
||||
실제 브라우저 레이아웃·입력기·터치 기기는 아니다(그건 헤드리스 크롬으로 따로 확인).
|
||||
|
||||
목표 열 자동 맞춤은 실제 Chromium에서도 검증한다. 로컬 테스트 HTML·프로젝트 CSS/폰트를 사용하며 운영 서버·DB에 연결하지 않는다.
|
||||
부분 서식과 셀 여백, 명시적 줄바꿈, 75% 배율, 600px를 넘는 긴 문단, 저장된 너비 복원을 확인한다.
|
||||
행 높이는 3줄/2줄 셀의 상단 정렬·같은 위아래 여백, 한 줄로 줄였을 때 높이 축소, 큰 글씨, 보기 전용 화면까지 확인한다.
|
||||
실제 마우스로 셀 테두리를 끌어 내용·부분 서식을 이동하고, 지연 응답 동안 원본을 유지하는지 확인한다.
|
||||
우클릭 현재/전체 열 자동 맞춤은 접힌 월 열의 측정·너비 저장도 검증한다. jsdom에서는 저장 실패·409 충돌·덮어쓰기 취소·Esc 취소를 추가로 확인한다.
|
||||
|
||||
```powershell
|
||||
python tests/js/render_goals.py
|
||||
# playwright 설치 또는 NODE_PATH로 기존 설치 지정
|
||||
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
node tests/js/goals_autofit.browser.test.js
|
||||
```
|
||||
|
||||
`PJ_TEST_BROWSER`를 생략하면 Playwright에 설치된 기본 Chromium을 사용한다.
|
||||
|
||||
셀 이동 API의 권한·예상값 충돌·트랜잭션 롤백·응답 유실 재시도는 DB 없이 실행할 수 있다.
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests -p test_project_goal_move.py
|
||||
```
|
||||
|
||||
실제 PostgreSQL 이동·동시 요청 검증은 `python tests/test_project_module.py`에 포함된다.
|
||||
`PROJECT_TEST_DB_URL`에 기존 로컬 테스트 DB를 지정해야 하며, 미설정 또는 로컬 주소가 아니면 건너뛴다.
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
// 실제 Chromium + 프로젝트 CSS/폰트로 열 자동 너비를 검증한다(운영 서버·DB 미사용).
|
||||
// python tests/js/render_goals.py
|
||||
// NODE_PATH=<playwright가 있는 node_modules> node tests/js/goals_autofit.browser.test.js
|
||||
// 설치된 Chrome 사용 시 PJ_TEST_BROWSER=<chrome 실행 파일 경로> 지정.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../..");
|
||||
const STATIC = path.join(ROOT, "app/static");
|
||||
const server = http.createServer(function (req, res) {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/project/goals/2026") {
|
||||
const fixture = url.searchParams.has("readonly") ? "goals_ro.html" : "goals_admin.html";
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", fixture), "utf8")
|
||||
.replace("<body>", '<body style="font-family:var(--pj-font)"><div class="erp-app">')
|
||||
.replace("</body>", "</div></body>");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
|
||||
}
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
res.setHeader("Content-Type", "application/json"); res.end("{}"); return;
|
||||
}
|
||||
const file = path.resolve(STATIC, "." + decodeURIComponent(url.pathname.slice(7)));
|
||||
if (!url.pathname.startsWith("/static/") || !file.startsWith(STATIC + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
||||
res.statusCode = 404; res.end(); return;
|
||||
}
|
||||
const types = { ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".woff": "font/woff" };
|
||||
res.setHeader("Content-Type", types[path.extname(file)] || "application/octet-stream");
|
||||
fs.createReadStream(file).pipe(res);
|
||||
});
|
||||
|
||||
(async function () {
|
||||
let browser;
|
||||
try {
|
||||
await new Promise(function (resolve) { server.listen(0, "127.0.0.1", resolve); });
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined });
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
const errors = [], writes = [];
|
||||
page.on("pageerror", function (e) { errors.push(e.message); });
|
||||
page.on("request", function (r) { if (r.method() !== "GET") writes.push(r.url()); });
|
||||
await page.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026");
|
||||
await page.evaluate(async function () {
|
||||
await document.fonts.ready;
|
||||
const a = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const b = document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]');
|
||||
a.value = "다담: 100 백만(김지통)\n주부콩: 20백만(김지통)";
|
||||
b.value = "pj-rich:v1:" + JSON.stringify([{ text: "가장 긴 문단: 글자 크기와 굵기도 반영", size: 32, bold: true }, { text: " 끝" }]);
|
||||
window.autofitDraft = b.value;
|
||||
document.getElementById("pj-goal-pane").scrollTop = 0;
|
||||
});
|
||||
async function fit(key) {
|
||||
await page.locator('thead .pj-goal-colresize[data-col="' + key + '"]').dblclick();
|
||||
}
|
||||
async function widths() {
|
||||
return page.evaluate(function () {
|
||||
const td = document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').closest("td");
|
||||
const head = document.querySelector('thead th[data-col="m1"]');
|
||||
return { logical: parseFloat(head.style.getPropertyValue("--cw")), cell: td.getBoundingClientRect().width,
|
||||
zoom: document.documentElement.classList.contains("pj-ui-scale") ? 0.75 : 1 };
|
||||
});
|
||||
}
|
||||
await fit("m1");
|
||||
const rich = await widths();
|
||||
const expected = await page.evaluate(function () {
|
||||
const td = document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').closest("td");
|
||||
const editor = td.querySelector(".pj-goal-text"), ctx = document.createElement("canvas").getContext("2d");
|
||||
let textWidth = 0;
|
||||
Array.from(editor.childNodes).forEach(function (node) {
|
||||
const style = getComputedStyle(node.nodeType === 1 ? node : editor);
|
||||
ctx.font = style.fontWeight + " " + style.fontSize + " " + style.fontFamily;
|
||||
textWidth += ctx.measureText(node.textContent).width;
|
||||
});
|
||||
const cellStyle = getComputedStyle(td), style = getComputedStyle(editor);
|
||||
return textWidth + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(cellStyle.borderRightWidth);
|
||||
});
|
||||
assert(rich.logical >= expected && rich.logical <= expected + 4, JSON.stringify({ rich, expected }));
|
||||
assert(Math.abs(rich.cell - rich.logical) < 1, "실제 셀 너비와 지정한 너비 일치");
|
||||
assert(await page.evaluate(function () { return document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').value === window.autofitDraft; }));
|
||||
console.log("PASS rich text, actual font geometry, preserved draft");
|
||||
|
||||
await page.evaluate(function () {
|
||||
document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').value = "짧음";
|
||||
});
|
||||
await fit("m1");
|
||||
const plain = await widths();
|
||||
assert(plain.logical < rich.logical, "짧은 문단으로 바꾸면 너비 축소");
|
||||
const lineRects = await page.evaluate(function () {
|
||||
const editor = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const range = document.createRange(); range.selectNodeContents(editor);
|
||||
return Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).map(function (r) { return r.top; });
|
||||
});
|
||||
assert.equal(new Set(lineRects).size, 2, "명시적 두 문단은 각각 한 줄로 표시");
|
||||
await page.evaluate(function () { document.documentElement.classList.add("pj-ui-scale"); });
|
||||
await fit("m1");
|
||||
const zoomed = await widths();
|
||||
assert(Math.abs(zoomed.logical - plain.logical) <= 1, JSON.stringify({ plain, zoomed }));
|
||||
assert(Math.abs(zoomed.cell / zoomed.zoom - zoomed.logical) < 1);
|
||||
console.log("PASS explicit paragraphs, shrink to fit, 75% zoom");
|
||||
|
||||
await page.evaluate(function () {
|
||||
document.documentElement.classList.remove("pj-ui-scale");
|
||||
document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]').value = "길이가 아주 긴 목표 문단 ".repeat(20);
|
||||
});
|
||||
await fit("m1");
|
||||
const large = await widths();
|
||||
assert(large.logical > 600);
|
||||
// 새로고침 때 기존 beforeunload 보호가 수정한 초안을 저장하는 것은 별도 동작이다.
|
||||
assert.deepEqual(writes, [], "자동 맞춤 자체는 쓰기 요청 없음");
|
||||
await page.reload();
|
||||
assert.equal((await widths()).logical, large.logical);
|
||||
assert.equal(await page.locator(".pj-goal-autofit-measure").count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS long paragraph beyond 600px, persisted width, no writes/errors");
|
||||
|
||||
const mergedPage = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await mergedPage.addInitScript(function () {
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
const editor = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const td = editor.closest("td");
|
||||
td.colSpan = 2; td.dataset.span = "2"; td.nextElementSibling.remove();
|
||||
editor.textContent = "병합한 셀에서도 다른 열은 그대로 유지하고 가장 긴 문단에 맞춰 줍니다";
|
||||
});
|
||||
});
|
||||
await mergedPage.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026");
|
||||
const before = await mergedPage.locator('thead th[data-col="m1"]').evaluate(function (th) { return th.style.getPropertyValue("--cw"); });
|
||||
await mergedPage.locator('tbody.pj-goal-area [data-row-id="10"] .pj-goal-colresize[data-col="m2"]').dblclick();
|
||||
const merged = await mergedPage.evaluate(function () {
|
||||
const a = document.querySelector('thead th[data-col="m1"]'), b = document.querySelector('thead th[data-col="m2"]');
|
||||
const editor = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const range = document.createRange(); range.selectNodeContents(editor);
|
||||
return { first: a.style.getPropertyValue("--cw"), last: parseFloat(b.style.getPropertyValue("--cw")),
|
||||
actual: editor.closest("td").getBoundingClientRect().width,
|
||||
lines: Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).length };
|
||||
});
|
||||
assert.equal(merged.first, before);
|
||||
assert.equal(merged.lines, 1, JSON.stringify(merged));
|
||||
assert(Math.abs(merged.actual - parseFloat(before) - merged.last) < 1, JSON.stringify(merged));
|
||||
console.log("PASS merged cell mapping, one unwrapped paragraph, other column unchanged");
|
||||
await mergedPage.close();
|
||||
|
||||
for (const readonly of [false, true]) {
|
||||
const heightPage = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await heightPage.addInitScript(function () {
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
const row = document.querySelector('tr[data-row-id="10"]');
|
||||
row.querySelector('td[data-month="0"] > div').textContent = "첫 번째 줄\n두 번째 줄\n세 번째 줄";
|
||||
row.querySelector('td[data-month="1"] > div').textContent = "첫 줄\n둘째 줄";
|
||||
});
|
||||
});
|
||||
await heightPage.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026" + (readonly ? "?readonly=1" : ""));
|
||||
await heightPage.evaluate(function () {
|
||||
// 세 줄은 열 폭에 의해 추가로 접히지 않도록 연간 열만 넓힌다.
|
||||
const h = document.querySelector('thead .pj-goal-colresize[data-col="y"]');
|
||||
h.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
async function rowMetrics() {
|
||||
return heightPage.evaluate(function () {
|
||||
const row = document.querySelector('tr[data-row-id="10"]');
|
||||
const long = row.querySelector('td[data-month="0"] > div'), short = row.querySelector('td[data-month="1"] > div');
|
||||
const cell = long.closest("td"), style = getComputedStyle(long), cellStyle = getComputedStyle(cell);
|
||||
const range = document.createRange(); range.selectNodeContents(long);
|
||||
return { row: row.getBoundingClientRect().height, editor: long.getBoundingClientRect().height,
|
||||
paddingTop: parseFloat(style.paddingTop), paddingBottom: parseFloat(style.paddingBottom),
|
||||
border: parseFloat(cellStyle.borderTopWidth) + parseFloat(cellStyle.borderBottomWidth),
|
||||
topDifference: short.getBoundingClientRect().top - long.getBoundingClientRect().top,
|
||||
lines: new Set(Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).map(function (r) { return r.top; })).size,
|
||||
namesAtTop: Array.from(row.querySelectorAll("th")).every(function (th) { return getComputedStyle(th).verticalAlign === "top"; }),
|
||||
oneLineRow: document.querySelector('tr[data-row-id="11"]').getBoundingClientRect().height };
|
||||
});
|
||||
}
|
||||
const initial = await rowMetrics();
|
||||
assert.equal(initial.lines, 3, JSON.stringify(initial));
|
||||
assert.equal(initial.paddingTop, initial.paddingBottom);
|
||||
assert(Math.abs(initial.row - initial.editor - initial.border) <= 1, JSON.stringify(initial));
|
||||
assert(Math.abs(initial.topDifference) <= 1, "짧은 셀도 긴 셀과 같은 위치에서 상단 정렬");
|
||||
assert(initial.namesAtTop, "구역·항목 이름도 상단 정렬");
|
||||
assert(initial.oneLineRow <= 36, "한 줄 셀은 불필요한 빈 줄 없이 내용에 맞는 높이: " + initial.oneLineRow);
|
||||
if (!readonly) {
|
||||
await heightPage.evaluate(function () {
|
||||
const row = document.querySelector('tr[data-row-id="10"]');
|
||||
const long = row.querySelector('td[data-month="0"] > div'), short = row.querySelector('td[data-month="1"] > div');
|
||||
long.value = "한 줄"; short.value = "한 줄";
|
||||
long.dispatchEvent(new Event("input", { bubbles: true })); short.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const smaller = await rowMetrics();
|
||||
assert(smaller.row < initial.row && smaller.row <= 36, JSON.stringify({ initial, smaller }));
|
||||
await heightPage.evaluate(function () {
|
||||
const editor = document.querySelector('tr[data-row-id="10"] td[data-month="1"] > div');
|
||||
editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "큰 글씨\n두 줄", size: 32, bold: true }]);
|
||||
editor.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const largeText = await heightPage.evaluate(function () {
|
||||
const editor = document.querySelector('tr[data-row-id="10"] td[data-month="1"] > div');
|
||||
return { row: editor.closest("tr").getBoundingClientRect().height, editor: editor.getBoundingClientRect().height,
|
||||
clipped: editor.scrollHeight > editor.clientHeight, border: parseFloat(getComputedStyle(editor.closest("td")).borderBottomWidth) };
|
||||
});
|
||||
assert(largeText.row > smaller.row && !largeText.clipped);
|
||||
assert(Math.abs(largeText.row - largeText.editor - largeText.border) <= 1, JSON.stringify(largeText));
|
||||
}
|
||||
console.log("PASS content row height, symmetric padding, top alignment" + (readonly ? " (read-only)" : ", shrink and large font"));
|
||||
await heightPage.close();
|
||||
}
|
||||
const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
let releaseMove, startedMove;
|
||||
const moveGate = new Promise(function (resolve) { releaseMove = resolve; });
|
||||
const moveStarted = new Promise(function (resolve) { startedMove = resolve; });
|
||||
const moveRequests = [];
|
||||
await interactive.route("**/project/api/**", async function (route) {
|
||||
const request = route.request();
|
||||
if (request.url().endsWith("/goals/cells/move")) {
|
||||
const payload = request.postDataJSON(); moveRequests.push(payload); startedMove();
|
||||
await moveGate;
|
||||
await route.fulfill({ json: { ok: true, body: payload.body } });
|
||||
} else await route.fulfill({ json: { ok: true } });
|
||||
});
|
||||
await interactive.addInitScript(function () {
|
||||
localStorage.setItem("pj_goal_col_w", JSON.stringify({ y: 240, m1: 240, m2: 240 }));
|
||||
});
|
||||
await interactive.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026");
|
||||
const sourceCell = interactive.locator('tr[data-row-id="10"] td[data-month="1"]');
|
||||
const targetCell = interactive.locator('tr[data-row-id="11"] td[data-month="2"]');
|
||||
await sourceCell.locator(".pj-goal-text").evaluate(function (editor) {
|
||||
editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "드래그 이동", bold: true, italic: true, underline: true, size: 24, color: "#ff0000" }]);
|
||||
});
|
||||
await sourceCell.locator(".pj-goal-text").click();
|
||||
const edge = await sourceCell.locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox();
|
||||
const dest = await targetCell.boundingBox();
|
||||
await interactive.mouse.move(edge.x + edge.width / 2, edge.y + edge.height / 2);
|
||||
await interactive.mouse.down();
|
||||
await interactive.mouse.move(dest.x + dest.width / 2, dest.y + dest.height / 2, { steps: 6 });
|
||||
assert(await targetCell.evaluate(function (td) { return td.classList.contains("is-goal-move-target"); }));
|
||||
await interactive.mouse.up(); await moveStarted;
|
||||
assert.equal(moveRequests.length, 1);
|
||||
assert.equal(await sourceCell.locator(".pj-goal-text").textContent(), "드래그 이동");
|
||||
assert.equal(await targetCell.locator(".pj-goal-text").textContent(), "");
|
||||
releaseMove();
|
||||
await interactive.waitForFunction(function () {
|
||||
return document.querySelector('tr[data-row-id="10"] .pj-goal-text[data-month="1"]').textContent === "";
|
||||
});
|
||||
const moved = await targetCell.locator(".pj-goal-text").evaluate(function (editor) { return JSON.parse(editor.value.slice(11))[0]; });
|
||||
assert.equal(moved.text, "드래그 이동"); assert.equal(moved.color, "#ff0000"); assert.equal(moved.size, 24);
|
||||
assert(moved.bold && moved.italic && moved.underline);
|
||||
assert.deepEqual(await targetCell.evaluate(function (td) { return [td.colSpan, td.rowSpan]; }), [1, 1]);
|
||||
console.log("PASS actual mouse border drag, delayed atomic response, all text formats, unchanged cell geometry");
|
||||
|
||||
await targetCell.click({ button: "right" });
|
||||
await interactive.getByRole("menuitem", { name: "현재 열 너비 자동 맞춤" }).click();
|
||||
const oneWidth = await interactive.locator('thead th[data-col="m2"]').evaluate(function (th) { return parseFloat(th.style.getPropertyValue("--cw")); });
|
||||
assert(oneWidth < 240 && oneWidth > 100);
|
||||
await interactive.evaluate(function () {
|
||||
// 접힌 열도 전체 너비 계산에 포함한다.
|
||||
const editor = document.querySelector('.pj-goal-text[data-row="20"][data-month="4"]');
|
||||
editor.value = "접힌 열도 길이가 아주 긴 문단을 반영합니다";
|
||||
document.querySelector('thead th[data-col="q2"]').click();
|
||||
});
|
||||
await interactive.waitForTimeout(400);
|
||||
await targetCell.click({ button: "right" });
|
||||
await interactive.getByRole("menuitem", { name: "전체 열 너비 자동 맞춤" }).click();
|
||||
const all = await interactive.evaluate(function () {
|
||||
const head = document.querySelector('thead th[data-col="m4"]');
|
||||
return { width: parseFloat(head.style.getPropertyValue("--cw")), folded: head.classList.contains("is-gone"),
|
||||
saved: JSON.parse(localStorage.getItem("pj_goal_col_w")).m4 };
|
||||
});
|
||||
assert(all.folded && all.width > 200 && all.saved === all.width, JSON.stringify(all));
|
||||
console.log("PASS context menu single/all column fitting including collapsed columns");
|
||||
await interactive.close();
|
||||
console.log("ALL PASS");
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
await new Promise(function (resolve) { server.close(resolve); });
|
||||
}
|
||||
})().catch(function (e) { console.error(e); process.exitCode = 1; });
|
||||
@@ -0,0 +1,921 @@
|
||||
// 연간 목표(goals.html)·주간 회의록(goal_meeting.html) + static/project.js UI 회귀 테스트 — jsdom.
|
||||
// 서버는 가짜(fetch 대체)로 두고 지연(deferred)·순서 역전·503·연속 입력을 직접 만든다. 실제 브라우저 레이아웃·입력기·터치 기기는 아니다.
|
||||
//
|
||||
// python tests/js/render_goals.py # 템플릿 렌더 → tests/js/.out/goals_*.html · meeting_*.html
|
||||
// npm install jsdom # (최초 1회, 또는 NODE_PATH 로 jsdom 이 있는 node_modules 지정)
|
||||
// node tests/js/goals_meeting_ui.test.js
|
||||
//
|
||||
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { JSDOM, VirtualConsole } = require("jsdom");
|
||||
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 180000);
|
||||
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
const PAGE = {};
|
||||
["goals_admin", "goals_ro", "meeting_admin", "meeting_err", "meeting_ro"].forEach(function (n) {
|
||||
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
|
||||
});
|
||||
const GOALS_URL = "http://localhost/project/goals/2026";
|
||||
const MEET_URL = "http://localhost/project/goals/2026/meetings/9?week=2026-09-28";
|
||||
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
const p = new Promise(function (a, b) { resolve = a; reject = b; });
|
||||
return { promise: p, resolve: resolve, reject: reject };
|
||||
}
|
||||
function settle(n) {
|
||||
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 40)) return r(); setImmediate(spin); })(); });
|
||||
}
|
||||
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
|
||||
const unhandled = [];
|
||||
process.on("unhandledRejection", function (e) { unhandled.push(String(e && e.message || e)); });
|
||||
|
||||
// env.route(method, re, fn(url, body, call)) — fn 이 {status, body, text} 또는 "NETWORK" 를 돌려준다(Promise 가능)
|
||||
function makeEnv(html, url, opts) {
|
||||
opts = opts || {};
|
||||
const vc = new VirtualConsole();
|
||||
const env = { calls: [], routes: [], navigations: 0, toasts: [], prompts: [], inflight: {}, maxInflight: {} };
|
||||
vc.on("jsdomError", function (e) { if (/navigation/i.test(String(e && e.message))) env.navigations++; });
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: url, virtualConsole: vc });
|
||||
const w = dom.window, d = w.document;
|
||||
env.w = w; env.d = d;
|
||||
w.__PJ_TEST__ = true;
|
||||
w.console.error = function () {};
|
||||
w.scrollTo = function () {};
|
||||
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
|
||||
w.erpConfirm = function () { return Promise.resolve(true); };
|
||||
w.erpPrompt = function (msg, def) { env.prompts.push(msg); return Promise.resolve(opts.promptAnswer != null ? opts.promptAnswer : "새 이름"); };
|
||||
w.erpAlert = function () {};
|
||||
if (opts.storage) Object.keys(opts.storage).forEach(function (k) { w.localStorage.setItem(k, opts.storage[k]); });
|
||||
if (opts.session) Object.keys(opts.session).forEach(function (k) { w.sessionStorage.setItem(k, opts.session[k]); });
|
||||
env.route = function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); };
|
||||
w.fetch = async function (u, o) {
|
||||
const method = (o && o.method) || "GET";
|
||||
let body = o && o.body;
|
||||
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
|
||||
const call = { method: method, url: String(u), body: body, keepalive: !!(o && o.keepalive), done: false };
|
||||
env.calls.push(call);
|
||||
const key = method + " " + String(u).replace(/^https?:\/\/[^/]+/, "");
|
||||
env.inflight[key] = (env.inflight[key] || 0) + 1;
|
||||
env.maxInflight[key] = Math.max(env.maxInflight[key] || 0, env.inflight[key]);
|
||||
try {
|
||||
for (const r of env.routes) {
|
||||
if (r.method === method && r.re.test(String(u))) {
|
||||
const out = await r.fn(String(u), body, call);
|
||||
if (out === "NETWORK") throw new TypeError("Failed to fetch");
|
||||
const status = out.status || 200;
|
||||
return { ok: status < 400, status: status, statusText: "x",
|
||||
json: async function () { return out.body || {}; }, text: async function () { return out.text || ""; } };
|
||||
}
|
||||
}
|
||||
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; }, text: async function () { return ""; } };
|
||||
} finally {
|
||||
env.inflight[key]--;
|
||||
call.done = true;
|
||||
}
|
||||
};
|
||||
env.puts = function (re) { return env.calls.filter(function (c) { return c.method === "PUT" && re.test(c.url); }); };
|
||||
env.toastText = function () { const t = d.querySelector(".erp-toast"); return t ? t.textContent : ""; };
|
||||
return env;
|
||||
}
|
||||
async function boot(env) {
|
||||
if (env.d.readyState === "loading") await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
|
||||
env.w.eval(fs.readFileSync(path.join(ROOT, "app", "static", "project-goal-text.js"), "utf8"));
|
||||
env.w.eval(JS);
|
||||
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
return env;
|
||||
}
|
||||
function type(env, node, value) {
|
||||
node.value = value;
|
||||
node.dispatchEvent(new env.w.Event("input", { bubbles: true }));
|
||||
}
|
||||
function fire(env, node, name) { node.dispatchEvent(new env.w.Event(name, { bubbles: name !== "blur" && name !== "focus" })); }
|
||||
function key(env, node, k, extra) {
|
||||
const e = new env.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}));
|
||||
node.dispatchEvent(e);
|
||||
return e;
|
||||
}
|
||||
// 블록 하나가 예외로 멈춰도 나머지 블록은 계속(예외는 FAIL 로)
|
||||
async function section(fn) {
|
||||
try { await fn(); } catch (e) { check("블록 예외 없음: " + String(e && e.message || e).slice(0, 120), false); }
|
||||
}
|
||||
function itemLabel(b) { return (b.querySelector(".pj-ctxmenu-label") || b).textContent.trim(); }
|
||||
function unload(env) {
|
||||
const e = new env.w.Event("beforeunload", { cancelable: true });
|
||||
env.w.dispatchEvent(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
// jsdom에는 글꼴·레이아웃 엔진이 없다. 숨은 복사본의 실제 DOM/서식을 확인하면서
|
||||
// 결정적인 글 너비를 제공한다. 실제 CSS·폰트 측정은 별도 브라우저 검증으로 확인한다.
|
||||
function mockAutoFitLayout(env) {
|
||||
const realRect = env.w.HTMLElement.prototype.getBoundingClientRect;
|
||||
const measured = [];
|
||||
env.w.HTMLElement.prototype.getBoundingClientRect = function () {
|
||||
if (!this.classList.contains("pj-goal-autofit-measure")) return realRect.call(this);
|
||||
measured.push(this);
|
||||
const content = this.querySelector(".pj-goal-text, .pj-goal-text-ro, .pj-goal-num, .pj-goal-area-text, .pj-goal-row-text") || this;
|
||||
let line = 0, longest = 0;
|
||||
function walk(node, size, bold) {
|
||||
if (node.nodeType === 3) {
|
||||
node.nodeValue.split("\n").forEach(function (text, i) {
|
||||
if (i) { longest = Math.max(longest, line); line = 0; }
|
||||
line += text.length * size * (bold ? 1.2 : 1);
|
||||
});
|
||||
} else if (node.nodeType === 1) {
|
||||
if (node.tagName === "BR") { longest = Math.max(longest, line); line = 0; return; }
|
||||
const nextSize = parseFloat(node.style.fontSize) || size;
|
||||
const nextBold = node.style.fontWeight ? Number(node.style.fontWeight) >= 600 : bold;
|
||||
Array.from(node.childNodes).forEach(function (child) { walk(child, nextSize, nextBold); });
|
||||
}
|
||||
}
|
||||
walk(content, 10, false);
|
||||
const zoom = env.d.documentElement.classList.contains("pj-ui-scale") ? 0.75 : 1;
|
||||
return { width: (Math.max(longest, line) + 13) * zoom };
|
||||
};
|
||||
return measured;
|
||||
}
|
||||
|
||||
function beginGoalMove(env, source, target) {
|
||||
const td = source.closest("td");
|
||||
td.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||
const edge = td.querySelector('.pj-goal-move-edge[data-edge="bottom"]');
|
||||
edge.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 20, clientY: 20 }));
|
||||
env.d.elementFromPoint = function () { return target; };
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 300, clientY: 200 }));
|
||||
return function () { env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true, clientX: 300, clientY: 200 })); };
|
||||
}
|
||||
|
||||
// ── 가짜 서버 — 목표 표(글 칸 상태를 기억해 화면 GET 에 반영) ───────────────
|
||||
function goalsServer(env, st) {
|
||||
st = Object.assign({ cells: {}, areaAdded: false, cellHook: null, metricHook: null, getHook: null }, st || {});
|
||||
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
|
||||
env.route("PUT", /\/project\/api\/goals\/rows\/\d+\/cells\/\d+$/, async function (u, body, call) {
|
||||
const m = u.match(/rows\/(\d+)\/cells\/(\d+)/);
|
||||
if (st.cellHook) { const r = await st.cellHook(u, body, call); if (r) return r; }
|
||||
st.cells[m[1] + ":" + m[2]] = body.body;
|
||||
return { body: { ok: true } };
|
||||
});
|
||||
env.route("PUT", /\/project\/api\/goals\/2026\/metrics$/, async function (u, body, call) {
|
||||
if (st.metricHook) { const r = await st.metricHook(u, body, call); if (r) return r; }
|
||||
const n = Number(String(body.value).replace(/[,\s]/g, ""));
|
||||
st.metric = String(body.value);
|
||||
return { body: { ok: true, label: body.value === "" ? "" : n.toLocaleString("en-US") } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/goals\/2026\/areas$/, function () { st.areaAdded = true; return { body: { ok: true } }; });
|
||||
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/rows$/, function () { return { status: 201, body: { ok: true } }; });
|
||||
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/move$/, function () { return { body: { ok: true } }; });
|
||||
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/merge$/, function () { st.merged = true; return { body: { ok: true, row_id: 10, start: 1 } }; });
|
||||
env.route("GET", /\/project\/goals\/2026$/, async function () {
|
||||
if (st.getHook) await st.getHook();
|
||||
st.gets = (st.gets || 0) + 1;
|
||||
let html = PAGE.goals_admin.replace(/(<div class="pj-goal-text"[^>]*data-row="(\d+)" data-month="(\d+)"[^>]*>)([\s\S]*?)(<\/div>)/g,
|
||||
function (all, open, row, month, text, close) {
|
||||
const k = row + ":" + month;
|
||||
return open + (k in st.cells ? renderGoalBody(env, st.cells[k]) : text) + close;
|
||||
});
|
||||
if (st.areaAdded) {
|
||||
html = html.replace(/(<\/tbody>\s*)(<\/table>)/, '$1<tbody class="pj-goal-area" data-area-id="3" data-color="" style="--goal-bg: #fff">' +
|
||||
'<tr data-row-id="30"><th class="pj-goal-c1 pj-goal-area-name" rowspan="1"><span class="pj-goal-area-text">새 영역</span></th>' +
|
||||
'<th class="pj-goal-c2 pj-goal-row-label"><span class="pj-goal-row-text"></span></th>' +
|
||||
'<td class="pj-goal-texttd pj-goal-year-col" data-month="0" data-span="1" data-rspan="1"><div class="pj-goal-text" contenteditable="true" data-row="30" data-month="0"></div></td>' +
|
||||
"</tr></tbody>$2");
|
||||
}
|
||||
return { text: html };
|
||||
});
|
||||
env.route("POST", new RegExp("/project/api/goals/cells/move$"), async function (u, body, call) {
|
||||
st.moves = (st.moves || 0) + 1;
|
||||
if (st.moveHook) { const result = await st.moveHook(body, call); if (result) return result; }
|
||||
st.cells[body.source_row + ":" + body.source_month] = "";
|
||||
st.cells[body.target_row + ":" + body.target_month] = body.body;
|
||||
return { body: { ok: true, body: body.body } };
|
||||
});
|
||||
return st;
|
||||
}
|
||||
|
||||
function renderGoalBody(env, value) {
|
||||
const div = env.d.createElement("div");
|
||||
const runs = value.startsWith("pj-rich:v1:") ? JSON.parse(value.slice(11)) : [{ text: value }];
|
||||
env.w.PJGoalText.paint(div, runs);
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// ── 가짜 서버 — 회의록 ────────────────────────────────────────────────
|
||||
function meetServer(env, st) {
|
||||
st = Object.assign({ items: {}, head: {}, itemHook: null, headHook: null, getHook: null, syncHook: null, page: PAGE.meeting_admin }, st || {});
|
||||
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
|
||||
const amount = function (v) { if (v === "" || v == null) return null; return Number(String(v).replace(/[,\s원]/g, "")); };
|
||||
env.route("PUT", /\/project\/api\/goals\/meeting-items\/\d+$/, async function (u, body, call) {
|
||||
const id = Number(u.match(/meeting-items\/(\d+)/)[1]);
|
||||
if (st.itemHook) { const r = await st.itemHook(id, body, call); if (r) return r; }
|
||||
const it = st.items[id] = Object.assign(st.items[id] || { id: id }, {});
|
||||
Object.keys(body).forEach(function (k) { it[k] = /amount$/.test(k) ? amount(body[k]) : body[k]; });
|
||||
return { body: { ok: true, item: Object.assign({ target_amount: null, result_amount: null }, it) } };
|
||||
});
|
||||
env.route("PUT", /\/project\/api\/goals\/meetings\/2026-09-28$/, async function (u, body, call) {
|
||||
if (st.headHook) { const r = await st.headHook(body, call); if (r) return r; }
|
||||
Object.assign(st.head, body);
|
||||
const out = { ok: true };
|
||||
if ("week_target" in body) { out.week_target = amount(body.week_target); st.head.week_target = out.week_target; }
|
||||
return { body: out };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/items$/, function () { return { status: 201, body: { ok: true, id: 9 } }; });
|
||||
env.route("POST", /\/project\/api\/goals\/meeting-items\/\d+\/move$/, function () { return { body: { ok: true } }; });
|
||||
env.route("GET", /\/project\/goals\/2026\/meetings\/9/, async function () {
|
||||
st.gets = (st.gets || 0) + 1;
|
||||
const page = st.page;
|
||||
if (st.getHook) { const r = await st.getHook(); if (r) return r; }
|
||||
return { text: page };
|
||||
});
|
||||
env.route("POST", /\/performance\/api\/sync$/, async function (u, body) {
|
||||
st.syncCalls = (st.syncCalls || 0) + 1;
|
||||
if (st.syncHook) return st.syncHook(body);
|
||||
return { body: { joined: false, job: { id: "j1", finished: true, from: body.from, to: body.to, shops: [{ name: "쿠팡", state: "done", active: true }], overall: {} } } };
|
||||
});
|
||||
return st;
|
||||
}
|
||||
|
||||
(async function () {
|
||||
// ════════════════════ [1] 회의록 글 — A→B 연속 입력과 늦은 A 응답 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const gate = deferred();
|
||||
const st = meetServer(env, { itemHook: async function (id, body, call) { if (body.content === "draft A") await gate.promise; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "draft A"); ta.blur();
|
||||
await settle();
|
||||
ta.focus(); type(env, ta, "draft B");
|
||||
await settle();
|
||||
check("[1] A 진행 중엔 같은 칸 두 번째 요청을 보내지 않음(직렬화)", env.puts(/meeting-items\/1$/).length === 1);
|
||||
gate.resolve();
|
||||
await wait(900); await settle();
|
||||
const puts = env.puts(/meeting-items\/1$/).map(function (c) { return c.body.content; });
|
||||
check("[1] A 응답 뒤 B 가 뒤이어 저장됨(PUT A→B)", JSON.stringify(puts) === JSON.stringify(["draft A", "draft B"]), puts);
|
||||
check("[1] 최종 서버 값 = B", st.items[1].content === "draft B", st.items[1]);
|
||||
check("[1] 화면 = B", ta.value === "draft B");
|
||||
check("[1] 같은 칸 동시 요청 최대 1", env.maxInflight["PUT /project/api/goals/meeting-items/1"] === 1, env.maxInflight);
|
||||
const e = unload(env);
|
||||
check("[1] 저장 끝난 뒤 페이지 떠남 = 경고 없음", !e.defaultPrevented);
|
||||
});
|
||||
// 지연·중복 blur·빠른 연속 입력 — 응답 순서와 무관하게 최신 값이 남는다
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const gates = [];
|
||||
const st = meetServer(env, { itemHook: async function () { const g = deferred(); gates.push(g); await g.promise; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "x1"); ta.blur(); fire(env, ta, "blur"); fire(env, ta, "blur");
|
||||
ta.focus(); type(env, ta, "x12"); type(env, ta, "x123"); ta.blur();
|
||||
await settle();
|
||||
check("[1b] 중복 blur·연속 입력에도 진행 중 요청 1개", env.puts(/meeting-items\/1$/).length === 1);
|
||||
gates[0].resolve(); await settle();
|
||||
check("[1b] 첫 응답 뒤 최신 값으로 한 번 더", env.puts(/meeting-items\/1$/).length === 2 && env.puts(/meeting-items\/1$/)[1].body.content === "x123",
|
||||
env.puts(/meeting-items\/1$/).map(function (c) { return c.body.content; }));
|
||||
gates[1].resolve(); await settle();
|
||||
await wait(50); await settle();
|
||||
check("[1b] 최종 서버 값 = 마지막 입력", st.items[1].content === "x123" && env.puts(/meeting-items\/1$/).length === 2, st.items[1]);
|
||||
});
|
||||
// 저장 실패 → dirty·초안 유지, 페이지 떠남 = keepalive 재전송 + 이탈 경고 + 초안 백업, 다음에 열면 되살림
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
let fail = true;
|
||||
const st = meetServer(env, { itemHook: function () { if (fail) return { status: 503, body: { detail: "temporary" } }; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "important"); ta.blur();
|
||||
await settle();
|
||||
check("[1c] 실패해도 글 그대로", ta.value === "important");
|
||||
check("[1c] 실패 표시(빨간 테두리)", ta.closest("td").classList.contains("is-save-failed"));
|
||||
check("[1c] 실패 안내 토스트", /저장 실패/.test(env.toastText()), env.toastText());
|
||||
const draft = JSON.parse(env.w.localStorage.getItem("pj_draft:meet:item:1:content") || "null");
|
||||
check("[1c] 초안 백업(localStorage)", draft && draft.draft === "important" && draft.base === "original", draft);
|
||||
const before = env.puts(/meeting-items\/1$/).length;
|
||||
const e = unload(env);
|
||||
await settle();
|
||||
const after = env.puts(/meeting-items\/1$/);
|
||||
check("[1c] 페이지 떠남 — 실패한 칸을 keepalive 로 다시 보냄", after.length === before + 1 && after[after.length - 1].keepalive && after[after.length - 1].body.content === "important",
|
||||
after.map(function (c) { return [c.body.content, c.keepalive]; }));
|
||||
check("[1c] 페이지 떠남 — 실패 칸이 있으면 이탈 경고", e.defaultPrevented === true);
|
||||
// 다음에 열기 — 서버엔 아직 original(keepalive 도 실패) → 초안을 되살려 다시 저장
|
||||
const env2 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": JSON.stringify(draft) } });
|
||||
const st2 = meetServer(env2);
|
||||
await boot(env2);
|
||||
const ta2 = env2.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
check("[1c] 다시 열면 초안 되살림", ta2.value === "important");
|
||||
await wait(900); await settle();
|
||||
check("[1c] 되살린 초안 자동 저장", st2.items[1] && st2.items[1].content === "important", st2.items[1]);
|
||||
check("[1c] 저장 뒤 초안 백업 지움", env2.w.localStorage.getItem("pj_draft:meet:item:1:content") === null);
|
||||
// 다른 곳에서 바뀐 칸(base ≠ 서버 값) — 되살리지 않는다
|
||||
const stale = JSON.stringify({ base: "someone else", draft: "old draft", at: Date.now() });
|
||||
const env3 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": stale } });
|
||||
meetServer(env3);
|
||||
await boot(env3);
|
||||
check("[1c] 서버 값이 바뀐 칸은 초안을 덮어쓰지 않음", env3.d.querySelector('tr[data-item="1"] textarea.pj-meet-text').value === "original");
|
||||
fail = false; void st;
|
||||
});
|
||||
// 진행 중 저장이 있으면 줄 작업(위로)은 그 저장이 끝난 뒤에, 저장 실패면 줄 작업을 하지 않는다
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const gate = deferred();
|
||||
let fail = false;
|
||||
meetServer(env, { itemHook: async function (id, body) { if ("content" in body) { await gate.promise; if (fail) return { status: 503, body: { detail: "x" } }; } } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "pending text"); ta.blur();
|
||||
await settle();
|
||||
fail = true;
|
||||
env.d.querySelector('tr[data-item="1"] th.pj-meet-c-label').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||
const up = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "위로"; });
|
||||
up.click();
|
||||
await settle();
|
||||
check("[1d] 저장 진행 중엔 줄 이동 요청을 보내지 않음", !env.calls.some(function (c) { return /\/move$/.test(c.url); }));
|
||||
gate.resolve();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[1d] 저장 실패 → 줄 이동 취소(글 유지, 새로고침 없음)", !env.calls.some(function (c) { return /\/move$/.test(c.url); }) && ta.value === "pending text" && env.navigations === 0,
|
||||
{ nav: env.navigations });
|
||||
});
|
||||
|
||||
// ════════════════════ [2] 숫자 — 늦은 응답이 최신 입력을 덮지 않음 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const gates = [];
|
||||
const st = goalsServer(env, { metricHook: async function (u, body) { if (body.value === "200") { const g = deferred(); gates.push(g); await g.promise; } } });
|
||||
await boot(env);
|
||||
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
|
||||
inp.focus(); inp.value = "200"; fire(env, inp, "change"); inp.blur();
|
||||
await settle();
|
||||
inp.focus(); type(env, inp, "300");
|
||||
gates[0].resolve();
|
||||
await settle();
|
||||
check("[2] 늦은 200 응답 뒤에도 입력 중인 300 유지", inp.value === "300", inp.value);
|
||||
inp.blur();
|
||||
await settle(); await wait(10); await settle();
|
||||
const vals = env.puts(/metrics$/).map(function (c) { return c.body.value; });
|
||||
check("[2] 300 확정 → 최종 서버 값 300(요청 순서 200→300)", st.metric === "300" && JSON.stringify(vals) === '["200","300"]', vals);
|
||||
check("[2] 같은 칸 동시 요청 최대 1(순서 역전 불가)", env.maxInflight["PUT /project/api/goals/2026/metrics"] === 1);
|
||||
check("[2] 확정 뒤 서버 표기", inp.value === "300");
|
||||
});
|
||||
await section(async function () { // 실패 응답 — 요청 뒤 새로 입력한 값을 예전 값으로 되돌리지 않는다 / 그대로면 입력 유지 + 실패 표시, Esc = 저장된 값
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const gate = deferred();
|
||||
goalsServer(env, { metricHook: async function (u, body) { if (body.value === "200") { await gate.promise; return { status: 503, body: { detail: "down" } }; } } });
|
||||
await boot(env);
|
||||
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
|
||||
inp.focus(); inp.value = "200"; inp.blur();
|
||||
await settle();
|
||||
inp.focus(); type(env, inp, "300");
|
||||
gate.resolve(); await settle();
|
||||
check("[2b] 200 실패 응답이 새 입력 300 을 되돌리지 않음", inp.value === "300", inp.value);
|
||||
type(env, inp, "200"); inp.blur(); await settle(); await wait(10); await settle();
|
||||
check("[2b] 실패한 값 그대로면 입력 유지 + 실패 표시", inp.value === "200" && inp.parentElement.classList.contains("is-save-failed"));
|
||||
const e = unload(env);
|
||||
check("[2b] 미저장 숫자 칸이 있으면 이탈 경고", e.defaultPrevented === true);
|
||||
inp.focus(); key(env, inp, "Escape");
|
||||
check("[2b] Esc = 저장된 값(100)으로", inp.value === "100", inp.value);
|
||||
});
|
||||
await section(async function () { // 회의록 정량 목표·지난주 결과 — 늦은 응답이 새 초안을 덮지 않음
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const gate = deferred();
|
||||
const st = meetServer(env, { itemHook: async function (id, body) { if (body.target_amount === "200" || body.result_amount === "70") await gate.promise; } });
|
||||
await boot(env);
|
||||
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
|
||||
tin.focus(); tin.value = "200"; tin.blur(); await settle();
|
||||
tin.focus(); type(env, tin, "300");
|
||||
const rin = env.d.querySelector('tr[data-item="2"] input[data-field="result_amount"]');
|
||||
rin.focus(); rin.value = "70"; rin.blur(); await settle();
|
||||
rin.focus(); type(env, rin, "75");
|
||||
gate.resolve(); await settle();
|
||||
check("[2c] 정량 목표 늦은 응답이 300 초안 유지", tin.value === "300", tin.value);
|
||||
check("[2c] 지난주 결과 늦은 응답이 75 초안 유지", rin.value === "75", rin.value);
|
||||
tin.blur(); rin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[2c] 최종 서버 정량 목표 300 · 지난주 결과(7일 전 주 줄 902) 75", st.items[1].target_amount === 300 && st.items[902].result_amount === 75, st.items);
|
||||
check("[2c] 지난주 달성률 = 75/200", env.d.querySelector('tr[data-item="2"] [data-rate]').textContent.trim() === "37.5%",
|
||||
env.d.querySelector('tr[data-item="2"] [data-rate]').textContent);
|
||||
});
|
||||
await section(async function () { // 금주 목표 저장 — 새로고침하지 않고 숫자 칸만 다시(다른 칸의 미저장 글 보존)
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env, { itemHook: function (id, body) { if ("content" in body) return { status: 503, body: { detail: "x" } }; } });
|
||||
await boot(env);
|
||||
const gets0 = st.gets || 0;
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "unsaved note");
|
||||
const tgt = env.d.getElementById("pj-meet-target");
|
||||
tgt.focus(); tgt.value = "2,000"; tgt.blur();
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2d] 금주 목표 저장 = 서버 확정값", st.head.week_target === 2000 && tgt.value === "2,000", st.head);
|
||||
check("[2d] 페이지 새로고침 없음", env.navigations === 0);
|
||||
check("[2d] 숫자 칸만 다시 받음(GET 1회 더)", (st.gets || 0) === gets0 + 1, st.gets);
|
||||
check("[2d] 다른 칸 미저장 글 유지", ta.value === "unsaved note");
|
||||
});
|
||||
|
||||
// ════════════════════ [3] 목표 표 — 글 저장 실패면 구조 변경·표 교체 중단 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||
const st = goalsServer(env, { cellHook: function () { return { status: 503, body: { detail: "temporary save failure" } }; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
ta.focus(); type(env, ta, "unsaved important plan");
|
||||
env.d.getElementById("pj-goal-area-add").click();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[3] 글 저장 실패 → 영역 추가 요청 안 보냄", !env.calls.some(function (c) { return c.method === "POST" && /\/areas$/.test(c.url); }),
|
||||
env.calls.map(function (c) { return c.method + " " + c.url; }));
|
||||
check("[3] 표를 다시 받지 않음", !st.gets);
|
||||
check("[3] 미저장 계획 그대로", env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]').value === "unsaved important plan");
|
||||
check("[3] 실패 안내", /저장/.test(env.toastText()), env.toastText());
|
||||
});
|
||||
await section(async function () { // 진행 중 저장 → 그 저장이 끝난 뒤에 영역 추가, 성공하면 표 교체(새 영역 보임, 저장된 글 유지)
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||
const gate = deferred();
|
||||
const st = goalsServer(env, { cellHook: async function () { await gate.promise; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
ta.focus(); type(env, ta, "plan v2"); ta.blur();
|
||||
await settle();
|
||||
env.d.getElementById("pj-goal-area-add").click();
|
||||
await settle();
|
||||
check("[3b] 진행 중 저장이 끝나기 전엔 영역 추가 안 보냄", !env.calls.some(function (c) { return c.method === "POST"; }));
|
||||
gate.resolve();
|
||||
await settle(); await wait(20); await settle();
|
||||
const order = env.calls.filter(function (c) { return c.method !== "GET" || /goals\/2026$/.test(c.url); }).map(function (c) { return c.method + " " + c.url.replace(/^https?:\/\/[^/]+/, ""); });
|
||||
check("[3b] 순서: 글 PUT → 영역 POST → 표 GET", order.join(" | ") === "PUT /project/api/goals/rows/10/cells/1 | POST /project/api/goals/2026/areas | GET /project/goals/2026", order);
|
||||
check("[3b] 새 영역이 그 자리에 보임(새로고침 없음)", !!env.d.querySelector('tbody.pj-goal-area[data-area-id="3"]') && env.navigations === 0);
|
||||
check("[3b] 저장된 글 유지", env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]').value === "plan v2");
|
||||
});
|
||||
await section(async function () { // 표를 받는 사이에 새로 입력 → 저장 후 다시 받아 교체(입력 유실 없음)
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||
const gate = deferred();
|
||||
let first = true;
|
||||
const st = goalsServer(env, { getHook: async function () { if (first) { first = false; await gate.promise; } } });
|
||||
await boot(env);
|
||||
env.d.getElementById("pj-goal-area-add").click();
|
||||
await settle();
|
||||
const ta = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="1"]');
|
||||
ta.focus(); type(env, ta, "typed during refresh");
|
||||
gate.resolve();
|
||||
await settle(); await wait(30); await settle();
|
||||
check("[3c] 받는 사이 입력한 글 저장됨", st.cells["11:1"] === "typed during refresh", st.cells);
|
||||
check("[3c] 교체된 표에도 그 글", env.d.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').value === "typed during refresh");
|
||||
check("[3c] 표를 다시 받음(2회)", st.gets === 2, st.gets);
|
||||
});
|
||||
await section(async function () { // 병합 — 저장 실패면 병합 요청 안 보냄
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const st = goalsServer(env, { cellHook: function () { return { status: 503, body: { detail: "x" } }; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
ta.focus(); type(env, ta, "draft before merge");
|
||||
const a = env.d.querySelector('td.pj-goal-texttd[data-month="1"]'), b = env.d.querySelector('tr[data-row-id="10"] td.pj-goal-texttd[data-month="2"]');
|
||||
a.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0 }));
|
||||
b.dispatchEvent(new env.w.MouseEvent("mouseover", { bubbles: true }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||
b.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||
const merge = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (x) { return /셀 병합/.test(itemLabel(x)); });
|
||||
check("[3d] 끌어 고른 뒤 우클릭 → 셀 병합 메뉴(기존 동작)", !!merge);
|
||||
if (merge) merge.click();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[3d] 저장 실패 → 병합 요청 안 보냄, 글 유지", !st.merged && ta.value === "draft before merge");
|
||||
});
|
||||
|
||||
// ════════════════════ [7] 정량 목표 저장 → 이번주 실적 % 즉시 갱신, 다시 그리기와 엇갈려도 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
const slot = function () { return env.d.querySelector('tr[data-item="1"] .pj-meet-week-slot').textContent.trim(); };
|
||||
check("[7] 처음 = 실적 100 · 목표 100 → 100%", /100%/.test(slot()), slot());
|
||||
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
|
||||
tin.focus(); tin.value = "200"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 200 저장 → 50%", /· 50%$/.test(slot()), slot());
|
||||
tin.focus(); tin.value = "0"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 0 → % 없음", slot() === "이번주 실적 100", slot());
|
||||
tin.focus(); tin.value = ""; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 삭제 → % 없음", slot() === "이번주 실적 100", slot());
|
||||
// 다시 그리기(옛 화면: 목표 100·100%)가 목표 저장 뒤에 도착해도 옛 비율이 들어오지 않는다
|
||||
const gate = deferred();
|
||||
st.getHook = async function () { await gate.promise; };
|
||||
const p = env.w.eval("null"); void p;
|
||||
tin.focus(); tin.value = "400"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 400 → 25%", /· 25%$/.test(slot()), slot());
|
||||
gate.resolve(); await settle(); await wait(10); await settle();
|
||||
check("[7] 늦게 온 옛 화면(100%)이 덮지 않음 — 지금 목표 기준 25%", /· 25%$/.test(slot()), slot());
|
||||
// 저장 실패 — 확정 목표(400)는 그대로라 25% 유지, 입력값은 남김
|
||||
st.itemHook = function () { return { status: 503, body: { detail: "x" } }; };
|
||||
tin.focus(); tin.value = "800"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 저장 실패 → 비율은 확정값(25%), 입력 800 유지", /· 25%$/.test(slot()) && tin.value === "800", [slot(), tin.value]);
|
||||
});
|
||||
await section(async function () { // 실적 조회 실패 화면 — 미확인(0원·0% 아님)
|
||||
const env = makeEnv(PAGE.meeting_err, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||
meetServer(env, { page: PAGE.meeting_err });
|
||||
await boot(env);
|
||||
const kpi = Array.from(env.d.querySelectorAll(".pj-meet-kpi")).map(function (k) { return k.textContent.replace(/\s+/g, " ").trim(); });
|
||||
const mtd = kpi.find(function (t) { return /월 누적 실적/.test(t); });
|
||||
check("[6] 월 누적 = 미확인(0원 아님)", /미확인/.test(mtd) && !/0원|0 원/.test(mtd), mtd);
|
||||
check("[6] 주당 필요 = 미확인(목표로 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /주당 필요/.test(t); })));
|
||||
check("[6] 전주 결과·금주 실적 = 미확인", /미확인/.test(kpi.find(function (t) { return /전주 결과/.test(t); })) && /미확인/.test(kpi.find(function (t) { return /금주 현재 실적/.test(t); })));
|
||||
const row = env.d.querySelector('tr[data-item="1"]');
|
||||
check("[6] 쇼핑몰 연결 줄 결과 = 미확인, 직접 입력 칸으로 바뀌지 않음", /미확인/.test(row.querySelector(".pj-meet-c-result").textContent) && !row.querySelector(".pj-meet-c-result input"));
|
||||
check("[6] 이번주 실적 미확인 · 달성률 비움", /미확인/.test(row.querySelector(".pj-meet-week-slot").textContent) && row.querySelector("[data-rate]").textContent.trim() === "");
|
||||
check("[6] 회의록 입력은 그대로 가능", !!row.querySelector("textarea.pj-meet-text") && !!env.d.getElementById("pj-meet-target"));
|
||||
check("[6] 조회 실패 안내 문구", /미확인/.test(env.d.querySelector(".pj-meet-perf-warn").textContent));
|
||||
});
|
||||
await section(async function () { // 지난주 리뷰 머리 = 지난주(9/21~) — 지난주 회의록에 없는 줄 안내
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||
meetServer(env);
|
||||
await boot(env);
|
||||
check("[5] 지난주 리뷰 머리 = 09/21 ~ 09/27", /09\/21 ~ 09\/27/.test(env.d.querySelector("th.is-prev").textContent));
|
||||
check("[5] 새 줄 = 지난주 회의록에 없는 줄", /지난주 회의록에 없는 줄/.test(env.d.querySelector('tr[data-item="3"]').textContent));
|
||||
});
|
||||
|
||||
// ════════════════════ [8] 구역·항목 메뉴 — ⋮ 버튼(키보드·터치) + 우클릭 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "줄 이름" });
|
||||
goalsServer(env);
|
||||
await boot(env);
|
||||
const btns = env.d.querySelectorAll(".pj-goal-menu-btn");
|
||||
check("[8] 관리자: 구역 2 + 항목 4 메뉴 버튼", btns.length === 6, btns.length);
|
||||
const areaBtn = env.d.querySelector('tbody[data-area-id="1"] .pj-goal-menu-btn[data-goal-menu="area"]');
|
||||
check("[8] 접근성 이름", areaBtn.getAttribute("aria-label") === "상품 구역 메뉴" && areaBtn.getAttribute("aria-haspopup") === "menu");
|
||||
check("[8] Tab 으로 갈 수 있는 버튼", areaBtn.tagName === "BUTTON" && areaBtn.tabIndex === 0);
|
||||
areaBtn.focus();
|
||||
areaBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 })); // Enter/Space → click(detail 0)
|
||||
let menu = env.d.querySelector(".pj-ctxmenu");
|
||||
check("[8] 키보드로 열기 → role=menu, 첫 항목 포커스", menu && menu.getAttribute("role") === "menu" && env.d.activeElement === menu.querySelector(".pj-ctxmenu-item"));
|
||||
check("[8] aria-expanded=true", areaBtn.getAttribute("aria-expanded") === "true");
|
||||
key(env, env.d.activeElement, "ArrowDown");
|
||||
check("[8] ↓ 로 다음 항목", env.d.activeElement === menu.querySelectorAll(".pj-ctxmenu-item")[1]);
|
||||
await settle();
|
||||
key(env, env.d.activeElement, "Escape");
|
||||
check("[8] Esc 닫기 → 버튼으로 포커스 복귀", !env.d.querySelector(".pj-ctxmenu") && env.d.activeElement === areaBtn && areaBtn.getAttribute("aria-expanded") === "false");
|
||||
// 키보드로 항목 실행 — "줄 추가(구역 맨 아래)"
|
||||
areaBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }));
|
||||
menu = env.d.querySelector(".pj-ctxmenu");
|
||||
const add = Array.from(menu.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /줄 추가/.test(itemLabel(b)); });
|
||||
add.focus(); add.click();
|
||||
await settle(); await wait(20); await settle();
|
||||
check("[8] 메뉴 항목 실행 → 줄 추가 API", env.calls.some(function (c) { return c.method === "POST" && /areas\/1\/rows$/.test(c.url); }));
|
||||
// 터치(탭) — 포인터 터치 뒤 click(detail 1)
|
||||
const rowBtn = env.d.querySelector('tr[data-row-id="20"] .pj-goal-menu-btn[data-goal-menu="row"]');
|
||||
rowBtn.dispatchEvent(new env.w.Event("pointerdown", { bubbles: true }));
|
||||
rowBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
|
||||
menu = env.d.querySelector(".pj-ctxmenu");
|
||||
const labels = menu ? Array.from(menu.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel) : [];
|
||||
check("[8] 탭(click) → 줄 메뉴(우클릭과 같은 항목)", labels.indexOf("위에 줄 추가") >= 0 && labels.indexOf("아래에 줄 추가") >= 0 && labels.indexOf("줄 삭제") >= 0, labels);
|
||||
check("[8] 터치로 연 메뉴도 ↑↓·Esc 가능(메뉴에 포커스)", env.d.activeElement === menu);
|
||||
// 다시 누르면 닫힘(토글) — 마우스는 mousedown 이 먼저 닫는다
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true }));
|
||||
rowBtn.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true }));
|
||||
await settle();
|
||||
rowBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
|
||||
check("[8] 열린 메뉴 버튼 다시 누름 = 닫힘", !env.d.querySelector(".pj-ctxmenu"));
|
||||
// 우클릭은 그대로
|
||||
env.d.querySelector('tbody[data-area-id="2"] th.pj-goal-area-name').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 3, clientY: 3 }));
|
||||
const ctx = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[8] 우클릭 메뉴 그대로(색·위로·줄 추가·삭제)", ctx.indexOf("색 바꾸기") >= 0 && ctx.indexOf("위로") >= 0 && ctx.indexOf("영역 삭제") >= 0, ctx);
|
||||
key(env, env.d.body, "Escape");
|
||||
// 이름 칸 — Tab 으로 와서 Enter = 이름 수정, 한글 조합 중 Enter 는 무시
|
||||
const name = env.d.querySelector('tr[data-row-id="10"] .pj-goal-row-text');
|
||||
check("[8] 이름 칸 Tab 접근(tabindex=0)", name.getAttribute("tabindex") === "0");
|
||||
name.focus();
|
||||
key(env, name, "Enter", { isComposing: true });
|
||||
check("[8] 한글 조합 중 Enter 는 편집 시작 안 함", name.isContentEditable !== true && name.contentEditable !== "true");
|
||||
key(env, name, "Enter");
|
||||
check("[8] Enter → 이름 수정", name.contentEditable === "true");
|
||||
key(env, name, "Escape");
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_ro, GOALS_URL);
|
||||
goalsServer(env);
|
||||
await boot(env);
|
||||
check("[8] 보기 전용: 메뉴 버튼·이름 편집 없음", !env.d.querySelector(".pj-goal-menu-btn") && !env.d.querySelector("[data-goal-edit]"));
|
||||
const th = env.d.querySelector("th.pj-goal-area-name");
|
||||
th.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
check("[8] 보기 전용: 우클릭은 너비 맞춤만 제공", Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel).join("|") === "현재 열 너비 자동 맞춤|전체 열 너비 자동 맞춤");
|
||||
// 분기 접기는 보기 전용도
|
||||
const qth = env.d.querySelector('th.pj-goal-fold-th[data-h="1"]');
|
||||
qth.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true }));
|
||||
check("[회귀] 분기 머리 클릭 → 접힘(보기 전용도)", qth.classList.contains("is-folded") && env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-shrunk"));
|
||||
check("[회귀] 접기 상태 기억", /"1":true/.test(env.w.localStorage.getItem("pj_goal_fold_q") || ""));
|
||||
});
|
||||
await section(async function () { // 회귀 — 열 너비 끌기·고정 열 변수·스크롤 위치 되살리기
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { session: { pj_goal_scroll: JSON.stringify(["/project/goals/2026", 120, 45]) } });
|
||||
goalsServer(env);
|
||||
await boot(env);
|
||||
const pane = env.d.getElementById("pj-goal-pane");
|
||||
check("[회귀] 스크롤 위치 되살림", pane.scrollLeft === 120 && pane.scrollTop === 45, [pane.scrollLeft, pane.scrollTop]);
|
||||
const h = env.d.querySelector('.pj-goal-colresize[data-col="c1"]');
|
||||
h.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 100 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 140 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||
const table = env.d.getElementById("pj-goal-table");
|
||||
check("[회귀] 1열 너비 끌기 → --goal-c1-w 112px·기억", table.style.getPropertyValue("--goal-c1-w") === "112px" && /"c1":112/.test(env.w.localStorage.getItem("pj_goal_col_w") || ""),
|
||||
table.style.getPropertyValue("--goal-c1-w"));
|
||||
check("[너비] 지표·업무 모든 행의 셀 경계에 손잡이", Array.from(table.querySelectorAll("tbody th, tbody td")).every(function (td) { return !!td.querySelector(".pj-goal-colresize"); }));
|
||||
const lower = env.d.querySelector('tbody.pj-goal-area .pj-goal-colresize[data-col="m1"]');
|
||||
lower.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 100 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 160 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||
check("[너비] 아래 행에서 월 너비 조절", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "145px");
|
||||
env.d.getElementById("pj-goal-area-add").click(); await settle(); await wait(20); await settle();
|
||||
const fresh = env.d.querySelector('tbody.pj-goal-area .pj-goal-colresize[data-col="m1"]');
|
||||
check("[너비] 표 새로 그린 뒤에도 손잡이", !!fresh && fresh !== lower);
|
||||
mockAutoFitLayout(env);
|
||||
fresh.dispatchEvent(new env.w.MouseEvent("dblclick", { bubbles: true }));
|
||||
check("[너비] 표를 다시 그린 뒤에도 더블클릭 내용 맞춤", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "95px");
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
goalsServer(env); await boot(env);
|
||||
const table = env.d.getElementById("pj-goal-table"), measured = mockAutoFitLayout(env);
|
||||
const first = table.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const second = table.querySelector('.pj-goal-text[data-row="11"][data-month="1"]');
|
||||
first.value = "짧은 문단\n다담: 100 백만(김지통)\n주부콩: 20백만(김지통)";
|
||||
second.value = "pj-rich:v1:" + JSON.stringify([{ text: "가장 긴 문단", size: 32, bold: true }, { text: " 끝" }]);
|
||||
const draft = second.value, calls = env.calls.length;
|
||||
function fit(key, body) {
|
||||
const handle = table.querySelector((body ? "tbody " : "thead ") + '.pj-goal-colresize[data-col="' + key + '"]');
|
||||
handle.dispatchEvent(new env.w.MouseEvent("dblclick", { bubbles: true, cancelable: true }));
|
||||
}
|
||||
function width(key) { return parseFloat(table.querySelector('thead th[data-col="' + key + '"]').style.getPropertyValue("--cw")); }
|
||||
fit("m1", true);
|
||||
const wanted = Math.ceil(7 * 32 * 1.2 + 2 * 10 + 13) + 2;
|
||||
check("[자동 너비] 모든 행 중 가장 긴 문단·큰 글씨·굵기 반영", width("m1") === wanted, [width("m1"), wanted]);
|
||||
check("[자동 너비] 원본 초안·부분 서식 보존·저장 요청 없음", second.value === draft && env.calls.length === calls);
|
||||
check("[자동 너비] 복사본만 줄바꿈 해제·메뉴/손잡이 제외·측정 뒤 제거", measured.every(function (cell) {
|
||||
const editor = cell.querySelector(".pj-goal-text");
|
||||
return !cell.querySelector(".pj-goal-colresize, .pj-goal-menu-btn") && (!editor || editor.style.whiteSpace === "pre");
|
||||
}) && !table.querySelector(".pj-goal-autofit-measure"));
|
||||
second.value = "짧음";
|
||||
fit("m1");
|
||||
const paragraphWidth = Math.max.apply(null, first.textContent.split("\n").map(function (line) { return line.length; })) * 10 + 15;
|
||||
check("[자동 너비] 명시적 줄바꿈 유지·문단 너비로 축소도 가능", width("m1") === paragraphWidth, [width("m1"), paragraphWidth]);
|
||||
env.d.documentElement.classList.add("pj-ui-scale"); fit("m1");
|
||||
check("[자동 너비] 75% 화면 배율에서도 같은 논리 너비", width("m1") === paragraphWidth);
|
||||
env.d.documentElement.classList.remove("pj-ui-scale");
|
||||
first.value = "긴".repeat(100); fit("m1");
|
||||
const saved = env.w.localStorage.getItem("pj_goal_col_w");
|
||||
check("[자동 너비] 600px를 넘는 문단도 잘리지 않고 기억", width("m1") === 1015 && JSON.parse(saved).m1 === 1015);
|
||||
const restored = makeEnv(PAGE.goals_ro, GOALS_URL, { storage: { pj_goal_col_w: saved } });
|
||||
goalsServer(restored); await boot(restored);
|
||||
check("[자동 너비] 다시 열면 큰 자동 너비도 복원", restored.d.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "1015px");
|
||||
const numeric = table.querySelector('input.pj-goal-num[data-month="2"]');
|
||||
numeric.value = "12345678901234567890"; fit("m2");
|
||||
check("[자동 너비] 숫자 입력칸의 현재 초안도 측정", width("m2") === 215);
|
||||
table.querySelector(".pj-goal-area-text").textContent = "아주 긴 영역 이름"; fit("c1", true);
|
||||
check("[자동 너비] rowspan 이름 열·메뉴 아이콘 제외", table.style.getPropertyValue("--goal-c1-w") === "115px");
|
||||
const row = first.closest("tr"), merged = first.closest("td");
|
||||
merged.colSpan = 2; merged.dataset.goalCols = "m1,m2";
|
||||
merged.querySelector(".pj-goal-colresize").dataset.col = "m2";
|
||||
row.querySelector('td[data-month="2"]').remove();
|
||||
first.value = "병합".repeat(80);
|
||||
const beforeM1 = width("m1"); fit("m2", true);
|
||||
check("[자동 너비] 병합 셀은 나머지 열 유지·오른쪽 끝 열만 맞춤", width("m1") === beforeM1 && width("m2") === 1615 - beforeM1, [width("m1"), width("m2")]);
|
||||
const qth = table.querySelector('thead th[data-col="q1"]'), folded = qth.classList.contains("is-folded");
|
||||
fit("q1");
|
||||
check("[자동 너비] 분기 열 더블클릭은 접기 상태를 바꾸지 않음", qth.classList.contains("is-folded") === folded);
|
||||
mockAutoFitLayout(restored);
|
||||
restored.d.querySelector('tbody .pj-goal-colresize[data-col="m1"]').dispatchEvent(new restored.w.MouseEvent("dblclick", { bubbles: true }));
|
||||
check("[자동 너비] 보기 전용도 내용 맞춤 가능·쓰기 요청 없음", restored.d.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "95px" && !restored.calls.some(function (c) { return c.method !== "GET"; }));
|
||||
});
|
||||
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL); goalsServer(env); await boot(env); mockAutoFitLayout(env);
|
||||
const table = env.d.getElementById("pj-goal-table"), editor = table.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
editor.value = "길게".repeat(25);
|
||||
function menu(cell) { cell.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true })); }
|
||||
function action(label) { return Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === label; }); }
|
||||
menu(editor);
|
||||
check("[너비 메뉴] 기존 내용 지우기·현재 열·전체 열 맞춤 함께 표시", !!action("내용 지우기 (Del)") && !!action("현재 열 너비 자동 맞춤") && !!action("전체 열 너비 자동 맞춤"));
|
||||
action("현재 열 너비 자동 맞춤").click();
|
||||
check("[너비 메뉴] 현재 열만 맞춤", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "515px" && table.querySelector('thead th[data-col="m2"]').style.getPropertyValue("--cw") === "85px");
|
||||
table.querySelector('thead th[data-col="q1"]').click();
|
||||
menu(table.querySelector('thead th[data-col="y"]')); action("전체 열 너비 자동 맞춤").click();
|
||||
check("[너비 메뉴] 머리에서도 전체 맞춤·접힌 열 포함·저장", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "515px" && table.querySelector('thead th[data-col="q1"]').classList.contains("is-folded") && JSON.parse(env.w.localStorage.getItem("pj_goal_col_w")).m1 === 515);
|
||||
menu(table.querySelector("th.pj-goal-area-name"));
|
||||
check("[너비 메뉴] 구역 이름 편집 메뉴에도 맞춤 제공", !!action("색 바꾸기") && !!action("현재 열 너비 자동 맞춤"));
|
||||
});
|
||||
await section(async function () {
|
||||
const gate = deferred(), env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const st = goalsServer(env, { moveHook: async function (body) { await gate.promise; return { body: { ok: true, body: body.body } }; } });
|
||||
await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
type(env, source, "pj-rich:v1:" + JSON.stringify([{ text: "이동할 글", color: "#ff0000", size: 24, bold: true, italic: true, underline: true }]));
|
||||
const original = source.value;
|
||||
const drop = beginGoalMove(env, source, target);
|
||||
check("[셀 이동] 대상 미리보기·일반 범위 선택과 분리", target.closest("td").classList.contains("is-goal-move-target") && env.d.documentElement.classList.contains("pj-goal-moving"));
|
||||
drop(); await settle();
|
||||
check("[셀 이동] 먼저 초안 저장·이동은 한 번·응답 전 원본 유지", st.moves === 1 && source.value === original && target.value === "" && source.getAttribute("contenteditable") === "false" && target.getAttribute("contenteditable") === "false");
|
||||
const moveIndex = env.calls.findIndex(function (c) { return /cells\/move$/.test(c.url); });
|
||||
check("[셀 이동] 글 PUT 뒤 원자적 이동 API", moveIndex > env.calls.findIndex(function (c) { return c.method === "PUT" && /rows\/10\/cells\/1$/.test(c.url); }));
|
||||
gate.resolve(); await settle();
|
||||
const run = JSON.parse(target.value.slice(11))[0];
|
||||
check("[셀 이동] 성공 뒤 원본 비우기·대상 글과 모든 서식 보존", source.value === "" && run.text === "이동할 글" && run.color === "#ff0000" && run.size === 24 && run.bold && run.italic && run.underline);
|
||||
const count = env.calls.length; fire(env, source, "blur"); fire(env, target, "blur"); await settle();
|
||||
check("[셀 이동] 저장 기준값·초안 정리·후속 blur 중복 저장 없음", env.calls.length === count && !env.w.localStorage.getItem("pj_draft:goal:10:1") && source.getAttribute("contenteditable") === "true" && target.closest("td").classList.contains("is-goal-active"));
|
||||
});
|
||||
for (const failure of ["network", "conflict", "save"]) await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const st = goalsServer(env, { moveHook: function () { return failure === "network" ? "NETWORK" : { status: 409, body: { detail: "다른 창에서 수정" } }; },
|
||||
cellHook: failure === "save" ? function () { return { status: 503, body: { detail: "저장 장애" } }; } : null });
|
||||
await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
if (failure === "save") type(env, source, "미저장 초안");
|
||||
const before = source.value; beginGoalMove(env, source, target)(); await settle();
|
||||
check("[셀 이동 " + failure + "] 실패해도 양쪽 내용·편집 가능 상태 유지", source.value === before && target.value === "" && source.getAttribute("contenteditable") === "true" && !env.d.documentElement.classList.contains("pj-goal-moving"));
|
||||
check("[셀 이동 " + failure + "] 저장 실패면 이동 API 생략", failure !== "save" || !st.moves);
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
target.value = "대상 기존 글"; let confirmations = 0;
|
||||
env.w.erpConfirm = function () { confirmations++; return Promise.resolve(false); };
|
||||
beginGoalMove(env, source, target)(); await settle();
|
||||
check("[셀 이동] 덮어쓰기 취소는 두 내용 유지·이동 없음", confirmations === 1 && !st.moves && source.value === "original" && target.value === "대상 기존 글");
|
||||
env.w.erpConfirm = function () { return Promise.resolve(true); };
|
||||
beginGoalMove(env, source, target)(); await settle();
|
||||
check("[셀 이동] 확인 뒤 덮어쓰기·원본 비우기", st.moves === 1 && source.value === "" && target.textContent === "original");
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
beginGoalMove(env, source, target); key(env, env.d, "Escape"); await settle();
|
||||
check("[셀 이동] Esc 취소는 원본 유지·이동 요청 없음", !st.moves && source.value === "original" && !env.d.documentElement.classList.contains("pj-goal-moving"));
|
||||
beginGoalMove(env, source, target); env.w.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
check("[셀 이동] 창 포커스 이탈도 이동 취소·드래그 정리", !st.moves && !env.d.querySelector(".is-goal-move-target"));
|
||||
beginGoalMove(env, source, source)(); await settle();
|
||||
check("[셀 이동] 자기 셀에 놓기 = 변경 없음", !st.moves && source.value === "original");
|
||||
const ro = makeEnv(PAGE.goals_ro, GOALS_URL); goalsServer(ro); await boot(ro);
|
||||
check("[셀 이동] 보기 전용에는 이동 테두리 없음", !ro.d.querySelector(".pj-goal-move-edge"));
|
||||
});
|
||||
|
||||
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
await wait(20); await settle();
|
||||
const box = env.d.getElementById("pj-meet-sync");
|
||||
check("[9] 정상 갱신 → 안내 숨김(조용)", st.syncCalls === 1 && box.hidden === true);
|
||||
check("[9] 갱신 뒤 숫자 칸 다시 그림(GET)", (st.gets || 0) >= 1);
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env, { syncHook: function (body) {
|
||||
return { body: { joined: false, job: { id: "j1", finished: true, from: body.from, to: body.to,
|
||||
shops: [{ name: "쿠팡", state: "done", active: true }, { name: "네이버", state: "error", label: "인증 오류", active: true }], overall: {} } } };
|
||||
} });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "editing while sync");
|
||||
await wait(20); await settle();
|
||||
const box = env.d.getElementById("pj-meet-sync"), btn = env.d.getElementById("pj-meet-sync-btn");
|
||||
check("[9] 일부 실패 → 안내 보임 + 실패 쇼핑몰 이름", !box.hidden && box.dataset.state === "partial" && /네이버\(인증 오류\)/.test(box.textContent), box.textContent);
|
||||
check("[9] 일부 실패를 전체 성공처럼 쓰지 않음 + 서버 기록 시각", !/갱신 성공 10\/01 14:20.*전체/.test(box.textContent) && /마지막 갱신 성공 10\/01 14:20/.test(box.textContent), box.textContent);
|
||||
check("[9] 재시도 버튼", !btn.hidden);
|
||||
check("[9] 갱신·다시 그리기 중에도 편집 글 유지", ta.value === "editing while sync");
|
||||
const rec = JSON.parse(env.w.sessionStorage.getItem("pj_meet_sync:2026-09-28"));
|
||||
check("[9] 기록 = partial(성공으로 기록하지 않음)", rec.state === "partial");
|
||||
btn.click(); await wait(20); await settle();
|
||||
check("[9] 재시도 → 다시 부름", st.syncCalls === 2);
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env, { syncHook: function () { return { status: 500, body: { detail: "서버 오류" } }; } });
|
||||
await boot(env);
|
||||
await wait(20); await settle();
|
||||
const box = env.d.getElementById("pj-meet-sync");
|
||||
check("[9] 실패 → 식별 가능한 안내 + 재시도", !box.hidden && box.dataset.state === "error" && /실패/.test(box.textContent) && !env.d.getElementById("pj-meet-sync-btn").hidden, box.textContent);
|
||||
st.syncHook = null;
|
||||
env.d.getElementById("pj-meet-sync-btn").click(); await wait(20); await settle();
|
||||
check("[9] 재시도 성공 → 안내 사라짐", box.hidden === true);
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env, { syncHook: function () { return { status: 403, body: { detail: "권한 없음" } }; } });
|
||||
await boot(env);
|
||||
await wait(20); await settle();
|
||||
const box = env.d.getElementById("pj-meet-sync");
|
||||
check("[9] 403 → 권한 없음 설명, 재시도 버튼 없음", box.dataset.state === "noperm" && env.d.getElementById("pj-meet-sync-btn").hidden);
|
||||
check("[9] 403 기억 → 같은 세션 자동 재호출 안 함", JSON.parse(env.w.sessionStorage.getItem("pj_meet_sync:2026-09-28")).state === "noperm");
|
||||
void st;
|
||||
});
|
||||
await section(async function () { // 권한 없음(서버가 can_sync=0) — API 를 아예 부르지 않는다
|
||||
const env = makeEnv(PAGE.meeting_ro, MEET_URL);
|
||||
const st = meetServer(env, { page: PAGE.meeting_ro });
|
||||
await boot(env);
|
||||
await wait(20); await settle();
|
||||
check("[9] 실적 권한 없음 → sync API 호출 0", !st.syncCalls && !env.calls.some(function (c) { return /performance/.test(c.url); }));
|
||||
check("[9] 권한 없음 설명(저장된 실적·마지막 갱신 시각)", /권한이 없어/.test(env.d.getElementById("pj-meet-sync").textContent) && /10\/01 14:20/.test(env.d.getElementById("pj-meet-sync").textContent));
|
||||
check("[9] 보기 전용: 입력칸 없음", !env.d.querySelector("textarea.pj-meet-text") && !env.d.getElementById("pj-meet-target"));
|
||||
});
|
||||
await section(async function () { // 10분 제한 — 최근 기록이 있으면 다시 부르지 않고 그 상태만(일부 실패면 안내 유지)
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "partial", bad: ["네이버"] }) } });
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
await wait(20); await settle();
|
||||
check("[9] 10분 안 = 다시 부르지 않음, 일부 실패 안내 유지", !st.syncCalls && env.d.getElementById("pj-meet-sync").dataset.state === "partial");
|
||||
});
|
||||
await section(async function () { // 다른 사람 업데이트에 합류했는데 기간이 이 주를 다 덮지 못하면 한 번 더
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
let n = 0;
|
||||
const st = meetServer(env, { syncHook: function (body) {
|
||||
n++;
|
||||
if (n === 1) return { body: { joined: true, job: { id: "other", finished: true, from: "2026-09-29", to: "2026-10-01", shops: [], overall: {} } } };
|
||||
return { body: { joined: false, job: { id: "mine", finished: true, from: body.from, to: body.to, shops: [], overall: {} } } };
|
||||
} });
|
||||
await boot(env);
|
||||
await wait(20); await settle();
|
||||
check("[9] 합류한 작업이 기간을 못 덮으면 이 주 기간으로 한 번 더", st.syncCalls === 2 && env.d.getElementById("pj-meet-sync").hidden);
|
||||
});
|
||||
await section(async function () { // 회귀 — 참석자 고르기(칩·저장)
|
||||
const html = PAGE.meeting_admin.replace("window.PJ_MEET_MEMBERS = []", 'window.PJ_MEET_MEMBERS = [{"email":"a@test.local","name":"에이","avatar":""}]');
|
||||
const env = makeEnv(html, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
env.d.getElementById("pj-meet-attend-add").click();
|
||||
const cb = env.d.querySelector('.pj-meet-pick input[type=checkbox][data-email="a@test.local"]');
|
||||
cb.checked = true; cb.dispatchEvent(new env.w.Event("change", { bubbles: true }));
|
||||
await settle();
|
||||
check("[회귀] 참석자 고르기 → 칩 + 저장", !!env.d.querySelector('.pj-meet-chip[data-key="a@test.local"]') && st.head.attendees === "a@test.local", st.head);
|
||||
});
|
||||
|
||||
await section(async function () { // 선택한 글자만 서식·서식 초기화·저장·다시 그리기
|
||||
const env = makeEnv(PAGE.goals_admin, "http://localhost/project/goals/2026"); const st = goalsServer(env); await boot(env);
|
||||
const d = env.d, w = env.w, editor = d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const toolbar = d.getElementById("pj-goal-format");
|
||||
check("[서식] 글자를 선택하기 전 도구 숨김", toolbar.hidden);
|
||||
const swatches = Array.from(d.querySelectorAll("[data-goal-color]"));
|
||||
check("[서식] 요청한 12색 견본만 표시", swatches.map(function (b) { return b.dataset.goalColor; }).join(",") === "#000000,#4B5563,#9CA3AF,#DC2626,#EA580C,#CA8A04,#16A34A,#0891B2,#2563EB,#7C3AED,#DB2777,#FFFFFF" && swatches.every(function (b) { return !b.textContent.trim(); }));
|
||||
type(env, editor, "앞 선택 뒤"); editor.focus();
|
||||
const range = d.createRange(); range.setStart(editor.firstChild, 2); range.setEnd(editor.firstChild, 4);
|
||||
w.getSelection().removeAllRanges(); w.getSelection().addRange(range); fire(env, editor, "mouseup");
|
||||
check("[서식] 글자 선택하면 body 팝업 표시", !toolbar.hidden && toolbar.parentElement === d.body);
|
||||
const format = function (name) { d.querySelector('[data-goal-format="' + name + '"]').click(); };
|
||||
format("bold"); format("italic"); format("underline");
|
||||
d.querySelector('[data-goal-format="color"]').click();
|
||||
check("[서식] 색상 버튼으로 견본 펼침", !d.getElementById("pj-goal-color-grid").hidden);
|
||||
d.querySelector('[data-goal-color="#DC2626"]').click(); format("size-up"); format("size-up"); format("size-up");
|
||||
let runs = w.PJGoalText.readRuns(editor);
|
||||
check("[서식] 선택한 두 글자에만 색·굵게·기울임·밑줄·크기", runs.length === 3 && runs[0].text === "앞 " && runs[1].text === "선택" && runs[1].bold === true && runs[1].italic === true && runs[1].underline === true && runs[1].color === "#dc2626" && runs[1].size === 20 && !runs[2].bold, runs);
|
||||
check("[서식] 토글 버튼은 적용 상태 표시", ["bold", "italic", "underline"].every(function (k) { return d.querySelector('[data-goal-format="' + k + '"]').getAttribute("aria-pressed") === "true"; }));
|
||||
format("size-down");
|
||||
check("[서식] 크기 줄이기는 2px", w.PJGoalText.readRuns(editor)[1].size === 18 && d.querySelector('[data-goal-format="size"]').textContent === "18px");
|
||||
format("size-up"); format("italic"); format("underline");
|
||||
check("[서식] 다시 누르면 기울임·밑줄 해제", w.PJGoalText.readRuns(editor)[1].italic === false && w.PJGoalText.readRuns(editor)[1].underline === false);
|
||||
format("italic"); format("underline");
|
||||
fire(env, editor, "blur"); await settle();
|
||||
check("[서식] 텍스트 조각을 기존 셀 API에 저장", st.cells["10:1"].startsWith("pj-rich:v1:") && JSON.parse(st.cells["10:1"].slice(11))[1].size === 20);
|
||||
const persisted = st.cells["10:1"];
|
||||
d.querySelector('[data-goal-format="reset"]').click(); fire(env, editor, "blur"); await settle();
|
||||
check("[서식] 선택 서식 초기화는 글을 유지하고 평문 저장", editor.textContent === "앞 선택 뒤" && st.cells["10:1"] === "앞 선택 뒤");
|
||||
editor.value = persisted; fire(env, editor, "input"); fire(env, editor, "blur"); await settle();
|
||||
d.getElementById("pj-goal-area-add").click(); await settle(); await wait(20); await settle();
|
||||
const fresh = d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
check("[서식] 표 다시 그리기에도 선택 서식 유지", fresh !== editor && w.PJGoalText.readRuns(fresh)[1].size === 20 && w.PJGoalText.readRuns(fresh)[1].italic === true && w.PJGoalText.readRuns(fresh)[1].underline === true);
|
||||
fresh.focus();
|
||||
const plainRange = d.createRange(); plainRange.setStart(fresh.firstChild, 0); plainRange.setEnd(fresh.firstChild, 1);
|
||||
w.getSelection().removeAllRanges(); w.getSelection().addRange(plainRange); fire(env, fresh, "mouseup");
|
||||
check("[서식] 새 평문 선택은 도구 값을 기본값으로 표시", d.querySelector('[data-goal-format="bold"]').getAttribute("aria-pressed") === "false" && d.querySelector('[data-goal-format="size"]').textContent === "14px");
|
||||
plainRange.collapse(true); w.getSelection().removeAllRanges(); w.getSelection().addRange(plainRange); fire(env, fresh, "keyup");
|
||||
check("[서식] 글자 선택을 해제하면 숨김·이전 선택 적용 차단", toolbar.hidden && d.querySelector('[data-goal-format="reset"]').disabled);
|
||||
});
|
||||
|
||||
await section(async function () { // 혼합 서식·각 조각 크기 변경·상한/하한
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL); goalsServer(env); await boot(env);
|
||||
const d = env.d, w = env.w, editor = d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
editor.value = 'pj-rich:v1:' + JSON.stringify([{text:"작은", size:10, bold:true, italic:true}, {text:"큰", size:30, underline:true}]);
|
||||
editor.focus(); const r = d.createRange(); r.selectNodeContents(editor);
|
||||
w.getSelection().removeAllRanges(); w.getSelection().addRange(r); fire(env, editor, "mouseup");
|
||||
const button = function (key) { return d.querySelector('[data-goal-format="' + key + '"]'); };
|
||||
check("[서식 혼합] 크기는 혼합·토글은 혼합 상태", button("size").textContent === "혼합" && button("bold").getAttribute("aria-pressed") === "mixed");
|
||||
button("size-up").click(); let runs = w.PJGoalText.readRuns(editor);
|
||||
check("[서식 혼합] 선택 조각마다 2px 증가", runs[0].size === 12 && runs[1].size === 32);
|
||||
button("size-up").click(); runs = w.PJGoalText.readRuns(editor);
|
||||
check("[서식 혼합] 32px 상한 보존", runs[0].size === 14 && runs[1].size === 32);
|
||||
button("bold").click(); runs = w.PJGoalText.readRuns(editor);
|
||||
check("[서식 혼합] 혼합에서 클릭하면 전체 굵게·다른 서식 유지", runs.every(function (run) { return run.bold === true; }) && runs[0].italic && runs[1].underline);
|
||||
button("bold").click();
|
||||
check("[서식 혼합] 다시 클릭하면 전체 굵게 해제", w.PJGoalText.readRuns(editor).every(function (run) { return run.bold === false; }));
|
||||
for (let i = 0; i < 12; i++) button("size-down").click();
|
||||
check("[서식 혼합] 10px 하한·감소 비활성", w.PJGoalText.readRuns(editor).every(function (run) { return run.size === 10; }) && button("size-down").disabled);
|
||||
for (let i = 0; i < 12; i++) button("size-up").click();
|
||||
check("[서식 혼합] 32px 상한·증가 비활성", w.PJGoalText.readRuns(editor).every(function (run) { return run.size === 32; }) && button("size-up").disabled);
|
||||
button("reset").click();
|
||||
check("[서식 혼합] 초기화는 모든 서식 제거·내용 보존", editor.value === "작은큰");
|
||||
});
|
||||
|
||||
clearTimeout(WATCHDOG);
|
||||
const realUnhandled = unhandled.filter(function (m) { return !/Not implemented/.test(m); });
|
||||
check("처리 안 된 Promise 거부 없음", realUnhandled.length === 0, realUnhandled);
|
||||
console.log(fails.length ? fails.length + " FAIL" : "ALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})().catch(function (e) { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,81 @@
|
||||
// 실제 Chromium + ERP 셸에서 검색·이동과 데스크톱/모바일 표시 검증(DB 미사용).
|
||||
// python tests/js/render_help.py
|
||||
// PJ_TEST_BROWSER=<설치된 Chrome 경로> node tests/js/help.browser.test.js (playwright 필요)
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../..");
|
||||
const STATIC = path.join(ROOT, "app/static");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const server = http.createServer(function (req, res) {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/project/help") {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(fs.readFileSync(path.join(OUT, "help_render.html"))); return;
|
||||
}
|
||||
const file = path.resolve(STATIC, "." + decodeURIComponent(url.pathname.slice(7)));
|
||||
if (!url.pathname.startsWith("/static/") || !file.startsWith(STATIC + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
||||
res.statusCode = 404; res.end(); return;
|
||||
}
|
||||
const types = { ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".woff": "font/woff", ".png": "image/png" };
|
||||
res.setHeader("Content-Type", types[path.extname(file)] || "application/octet-stream");
|
||||
fs.createReadStream(file).pipe(res);
|
||||
});
|
||||
|
||||
(async function () {
|
||||
let browser;
|
||||
try {
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined });
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
const errors = [], mutations = [];
|
||||
page.on("pageerror", e => errors.push(e.message));
|
||||
page.on("request", r => { if (r.method() !== "GET") mutations.push(r.url()); });
|
||||
await page.goto("http://127.0.0.1:" + server.address().port + "/project/help");
|
||||
await page.locator("#pjh-query").waitFor({ state: "visible" });
|
||||
await page.locator("#pjh-query").fill("셀 병합");
|
||||
const first = page.locator("#pjh-results a").first();
|
||||
assert.equal(await first.getAttribute("href"), "#goals-merge");
|
||||
await page.screenshot({ path: path.join(OUT, "help-desktop.png") });
|
||||
await first.click();
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "goals-merge");
|
||||
assert.ok(await page.locator("#goals-merge").isVisible());
|
||||
const rect = await page.locator("#goals-merge").boundingBox();
|
||||
assert.ok(rect.y >= 0 && rect.y < 300, "앵커 이동 후 소제목이 화면 위에 표시");
|
||||
await page.screenshot({ path: path.join(OUT, "help-goals.png") });
|
||||
await page.keyboard.press("/");
|
||||
await page.locator("#pjh-query").fill("쇼핑몰 연결");
|
||||
await page.locator("#pjh-query").press("Enter");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "meetings-markets");
|
||||
await page.reload();
|
||||
await page.locator("#pjh-query").waitFor({ state: "visible" });
|
||||
assert.equal(await page.locator("#pjh-query").inputValue(), "쇼핑몰 연결");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "meetings-markets");
|
||||
await page.goBack();
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "goals-merge");
|
||||
assert.equal(await page.locator("#pjh-query").inputValue(), new URL(page.url()).searchParams.get("q"), "뒤로 간 주소의 검색어 복원");
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.waitForFunction(() => document.querySelector(".erp-sidebar").getBoundingClientRect().right <= 1);
|
||||
await page.keyboard.press("/");
|
||||
await page.locator("#pjh-query").fill("회의록");
|
||||
await page.screenshot({ path: path.join(OUT, "help-mobile.png") });
|
||||
assert.ok(await page.locator("#pjh-query").isVisible(), "모바일에서 목차가 숨겨져도 검색 유지");
|
||||
const widths = await page.evaluate(() => {
|
||||
const nodes = [document.documentElement, document.querySelector(".erp-page"), document.querySelector(".pjh"), document.querySelector(".pjh-body")];
|
||||
return nodes.map(n => ({ name: n.className || n.tagName, scroll: n.scrollWidth, client: n.clientWidth }));
|
||||
});
|
||||
assert.ok(widths.every(n => n.scroll <= n.client + 1), "모바일에서 가로 넘침 없음: " + JSON.stringify(widths));
|
||||
await page.locator('#pjh-results a[href="#meetings-review"]').click();
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "meetings-review");
|
||||
await page.screenshot({ path: path.join(OUT, "help-meeting-mobile.png") });
|
||||
assert.deepEqual(errors, [], "브라우저 JS 오류 없음");
|
||||
assert.deepEqual(mutations, [], "도움말 검색은 데이터 쓰기 요청 없음");
|
||||
console.log("ALL PASS — Chromium 검색·Enter·새로고침·뒤로 가기·390px 모바일 레이아웃");
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
}
|
||||
})().catch(function (e) { console.error(e); process.exitCode = 1; });
|
||||
@@ -0,0 +1,100 @@
|
||||
// python tests/js/render_help.py && node tests/js/help_ui.test.js (jsdom 필요)
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const ROOT = path.resolve(__dirname, "../..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out/help_render.html"), "utf8");
|
||||
const js = fs.readFileSync(path.join(ROOT, "app/static/project-help.js"), "utf8");
|
||||
function boot(url) {
|
||||
const dom = new JSDOM(html, { url: url || "http://localhost/project/help", runScripts: "outside-only" });
|
||||
const w = dom.window;
|
||||
w.HTMLElement.prototype.scrollIntoView = function () { w.lastScroll = this.id; };
|
||||
w.eval(js);
|
||||
return dom;
|
||||
}
|
||||
const dom = boot(), w = dom.window, d = w.document;
|
||||
const input = d.getElementById("pjh-query");
|
||||
function search(query) { input.value = query; input.dispatchEvent(new w.Event("input", { bubbles: true })); }
|
||||
function links() { return Array.from(d.querySelectorAll("#pjh-results a")); }
|
||||
function reset() { d.getElementById("pjh-search-clear").click(); }
|
||||
|
||||
assert.equal(d.querySelectorAll(".pjh-sec").length, 22);
|
||||
assert.equal(d.querySelectorAll(".pjh-toc a").length, 22);
|
||||
assert.equal(d.getElementById("pjh-search").hidden, false);
|
||||
assert.equal(d.getElementById("pjh-results").hidden, true);
|
||||
const ids = Array.from(d.querySelectorAll("[id]")).map(n => n.id);
|
||||
assert.equal(new Set(ids).size, ids.length, "앵커 ID는 중복 없음");
|
||||
Array.from(d.querySelectorAll('.pjh a[href^="#"]')).forEach(function (link) {
|
||||
assert.ok(d.getElementById(link.getAttribute("href").slice(1)), "도움말 내부 링크 유효");
|
||||
});
|
||||
|
||||
search("셀 병합");
|
||||
assert.equal(links()[0].hash, "#goals-merge", "소제목 일치를 먼저 표시");
|
||||
assert.ok(links()[0].querySelector("mark"));
|
||||
assert.ok(d.querySelector("#goals mark"), "본문도 일치어 강조");
|
||||
links()[0].click();
|
||||
assert.equal(w.location.hash, "#goals-merge");
|
||||
assert.equal(d.activeElement.id, "goals-merge", "결과 클릭은 해당 소제목에 포커스");
|
||||
assert.equal(w.lastScroll, "goals-merge");
|
||||
assert.equal(d.querySelector('.pjh-toc [aria-current="location"]').hash, "#goals");
|
||||
assert.equal(new URL(w.location.href).searchParams.get("q"), "셀 병합");
|
||||
|
||||
search("7일 전");
|
||||
assert.ok(links().some(a => a.hash === "#meetings-review"), "제목에 없는 본문 단어도 검색");
|
||||
search("쇼핑몰 연결");
|
||||
assert.equal(links()[0].hash, "#meetings-markets");
|
||||
d.getElementById("pjh-search-form").dispatchEvent(new w.Event("submit", { bubbles: true, cancelable: true }));
|
||||
assert.equal(d.activeElement.id, "meetings-markets", "Enter/submit은 첫 결과 이동");
|
||||
|
||||
const original = d.getElementById("meetings").textContent;
|
||||
search("ROAS");
|
||||
assert.ok(links().some(a => a.hash === "#goals-metrics"), "영문 대소문자 구분 안 함");
|
||||
search("로아스");
|
||||
assert.ok(links().length > 0, "한글 검색");
|
||||
search("원");
|
||||
assert.ok(links().length > 0, "한 글자 검색");
|
||||
search(" 쇼핑몰 연결 ");
|
||||
assert.equal(links()[0].hash, "#meetings-markets", "연속 공백·여러 단어 검색");
|
||||
search("zz-no-help-match");
|
||||
assert.equal(links().length, 0);
|
||||
assert.match(d.getElementById("pjh-search-status").textContent, /결과가 없습니다/);
|
||||
search("<img src=x onerror=alert(1)>");
|
||||
assert.equal(links().length, 0, "HTML을 검색어 문자열로만 처리");
|
||||
assert.equal(d.querySelector('img[src="x"]'), null);
|
||||
search("[");
|
||||
assert.equal(links().length, 0, "정규식 특수문자에도 예외 없음");
|
||||
reset();
|
||||
assert.equal(input.value, "");
|
||||
assert.equal(d.getElementById("pjh-results").hidden, true);
|
||||
assert.equal(d.querySelectorAll("mark.pjh-match").length, 0);
|
||||
assert.equal(d.getElementById("meetings").textContent, original, "검색·초기화 뒤 원문 보존");
|
||||
assert.equal(new URL(w.location.href).searchParams.has("q"), false);
|
||||
assert.equal(d.activeElement, input);
|
||||
search("분기");
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
|
||||
assert.equal(input.value, "");
|
||||
d.body.dispatchEvent(new w.KeyboardEvent("keydown", { key: "/", bubbles: true, cancelable: true }));
|
||||
assert.equal(d.activeElement, input, "/ 단축키는 도움말 검색");
|
||||
|
||||
search("셀 병합");
|
||||
input.dispatchEvent(new w.CompositionEvent("compositionstart", { bubbles: true }));
|
||||
input.value = "회의록";
|
||||
input.dispatchEvent(new w.Event("input", { bubbles: true }));
|
||||
const before = w.location.hash;
|
||||
d.getElementById("pjh-search-form").dispatchEvent(new w.Event("submit", { cancelable: true }));
|
||||
assert.equal(w.location.hash, before, "한글 조합 중 submit은 이동 안 함");
|
||||
assert.equal(links()[0].hash, "#goals-merge", "조합 중 검색 안 함");
|
||||
input.dispatchEvent(new w.CompositionEvent("compositionend", { bubbles: true }));
|
||||
assert.ok(links().some(a => a.hash === "#meetings-intro"), "조합 확정 뒤 검색");
|
||||
|
||||
const restored = boot("http://localhost/project/help?q=" + encodeURIComponent("쇼핑몰 연결") + "#meetings-markets");
|
||||
assert.equal(restored.window.document.getElementById("pjh-query").value, "쇼핑몰 연결");
|
||||
assert.equal(restored.window.document.activeElement.id, "meetings-markets", "공유 링크·새로고침 복원");
|
||||
w.history.pushState(null, "", "/project/help?q=" + encodeURIComponent("셀 병합") + "#goals-merge");
|
||||
w.dispatchEvent(new w.PopStateEvent("popstate"));
|
||||
assert.equal(input.value, "셀 병합");
|
||||
assert.equal(d.activeElement.id, "goals-merge", "뒤로 가기 위치·검색 복원");
|
||||
restored.window.close();
|
||||
dom.window.close();
|
||||
console.log("ALL PASS — 도움말 검색·앵커·한글 조합·안전한 문자열·초기화·URL 복원");
|
||||
@@ -33,6 +33,9 @@ function makeEnv() {
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
|
||||
const w = dom.window, d = w.document;
|
||||
w.__PJ_TEST__ = true;
|
||||
w.HTMLDialogElement.prototype.showModal = function () { this.open = true; };
|
||||
w.HTMLDialogElement.prototype.close = function () { this.open = false; this.dispatchEvent(new w.Event("close")); };
|
||||
Object.defineProperty(d, "fonts", { configurable: true, value: { load: async function () { return [{}]; } } });
|
||||
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
|
||||
w.URL.createObjectURL = function () { return "blob:x"; };
|
||||
w.URL.revokeObjectURL = function () {};
|
||||
@@ -103,6 +106,7 @@ async function boot(env) {
|
||||
// 문제없음, 기존 코드 그대로). 테스트에서는 버튼 보강을 건너뛰고 원래 입력칸으로 시험한다.
|
||||
env.d.querySelectorAll("select").forEach(function (s) { s.dataset.pjEnhanced = "1"; });
|
||||
env.d.querySelectorAll("input[type=date]").forEach(function (i) { i.dataset.pjDate = "1"; });
|
||||
env.w.eval(fs.readFileSync(path.join(ROOT, "app", "static", "project-options.js"), "utf8"));
|
||||
env.w.eval(JS);
|
||||
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
@@ -419,6 +423,211 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
check("[01][02] 이 프로젝트 권한 회수 → 작업 비우고 안내", !!d.querySelector(".pj-access-lost") && P.state().tasks.length === 0);
|
||||
}
|
||||
|
||||
// 보드 빠른 추가 — 세 필드, 조합 입력·중복 저장·실패 복구·취소.
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); const P = await boot(env);
|
||||
const d = env.d, w = env.w, pending = deferred();
|
||||
const posts = function () { return env.calls.filter(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }); };
|
||||
env.route("POST", /projects\/1\/tasks$/, function () { return pending.promise; });
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-addtask').click(); await wait(10);
|
||||
let input = d.querySelector(".pj-tasknew-title");
|
||||
check("[board] 추가는 상세창 대신 이름·담당자·마감일 카드", input && d.getElementById("pj-modal-task").hidden && d.querySelectorAll(".pj-tasknew input").length === 1 && d.querySelectorAll(".pj-tasknew-meta button").length === 2);
|
||||
input.value = "간단한 새 작업"; input.dispatchEvent(new w.Event("input"));
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true })); await settle();
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", keyCode: 229, bubbles: true })); await settle();
|
||||
check("[board] 한글 조합 중 Enter는 저장하지 않음", posts().length === 0);
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
d.body.dispatchEvent(new w.Event("pointerdown", { bubbles: true })); await settle();
|
||||
check("[board] 반복 Enter·바깥 클릭에도 저장은 한 번", posts().length === 1 && input.disabled);
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-addtask').click(); await settle();
|
||||
input = d.querySelector(".pj-tasknew-title");
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Enter", bubbles: true })); await settle();
|
||||
check("[board] 보드 다시 그리는 중에도 저장 상태 유지", input.disabled && input.value === "간단한 새 작업" && posts().length === 1);
|
||||
check("[board] 생성 요청은 현재 섹션과 세 필드만", Object.keys(posts()[0].body).sort().join(",") === "assignee_email,assignee_name,due_date,stage_id,title" && posts()[0].body.stage_id === 11);
|
||||
pending.resolve({ body: { task: detail(801, "간단한 새 작업") } }); await settle(); await wait(10);
|
||||
check("[board] Enter 저장 후 새 카드와 다음 빈 입력 유지", !!d.querySelector('.pj-card[data-task-id="801"]') && d.querySelector(".pj-tasknew-title").value === "");
|
||||
input = d.querySelector(".pj-tasknew-title");
|
||||
input.dispatchEvent(new w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[board] Esc는 입력 카드만 취소", !d.querySelector(".pj-tasknew") && posts().length === 1);
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-addtask').click(); await settle();
|
||||
d.body.dispatchEvent(new w.Event("pointerdown", { bubbles: true })); await wait(10); await settle();
|
||||
check("[board] 빈 카드 바깥 클릭은 빈 작업 생성 없이 닫기", !d.querySelector(".pj-tasknew") && posts().length === 1);
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-add').click(); await wait(10);
|
||||
check("[board] 상단 +는 기존 오른쪽 상세창을 열기", !d.getElementById("pj-modal-task").hidden && !d.querySelector(".pj-tasknew"));
|
||||
await P.attemptClose(); await wait(400);
|
||||
d.querySelector('.pj-col[data-stage-id="11"] .pj-col-addtask').click(); await wait(10);
|
||||
input = d.querySelector(".pj-tasknew-title"); input.value = "실패해도 유지"; input.dispatchEvent(new w.Event("input"));
|
||||
env.route("POST", /projects\/1\/tasks$/, function () { return { status: 500, body: { detail: "잠시 오류" } }; });
|
||||
d.body.dispatchEvent(new w.Event("pointerdown", { bubbles: true })); await wait(10); await settle();
|
||||
input = d.querySelector(".pj-tasknew-title");
|
||||
check("[board] 저장 실패는 입력 복구 후 다시 입력 가능", input && input.value === "실패해도 유지" && !input.disabled);
|
||||
env.route("POST", /projects\/1\/tasks$/, function (u, b) { return { body: { task: detail(802, b.title) } }; });
|
||||
d.body.dispatchEvent(new w.Event("pointerdown", { bubbles: true })); await wait(10); await settle();
|
||||
check("[board] 바깥 클릭 재시도 성공은 입력 닫고 카드 표시", !d.querySelector(".pj-tasknew") && !!d.querySelector('.pj-card[data-task-id="802"]'));
|
||||
}
|
||||
// 보드 하위 작업 — 앞·뒤 삽입, 실패 복구, 제자리 무요청, 다른 부모 이동.
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w;
|
||||
const subs = [901, 902, 903].map(function (id) { return detail(id, "하위 " + id, { parent_task_id: 101 }); });
|
||||
env.route("GET", /tasks\/101$/, function () { return { body: { task: detail(101, "작업 A", { subtasks: subs }) } }; });
|
||||
env.route("PUT", /tasks\/101\/subtasks\/order$/, function () { return { body: { ok: true } }; });
|
||||
await boot(env);
|
||||
d.querySelector('.pj-card[data-task-id="101"] .pj-card-subtoggle').click(); await settle();
|
||||
const rows = function () { return Array.from(d.querySelectorAll('.pj-card[data-task-id="101"] .pj-card-sub')).map(function (r) { return Number(r.dataset.subId); }); };
|
||||
const calls = function () { return env.calls.filter(function (c) { return /subtasks\/order$/.test(c.url); }); };
|
||||
async function drag(fromId, toId, after) {
|
||||
const from = d.querySelector('[data-sub-id="' + fromId + '"]'), to = d.querySelector('[data-sub-id="' + toId + '"]');
|
||||
to.getBoundingClientRect = function () { return { top: 100, height: 34 }; };
|
||||
const data = {}; const transfer = { types: [], setData: function (k, v) { data[k] = v; this.types.push(k); }, getData: function (k) { return data[k]; } };
|
||||
function fire(el, kind) { const e = new w.MouseEvent(kind, { bubbles: true, cancelable: true, clientY: after ? 130 : 105 }); Object.defineProperty(e, "dataTransfer", { value: transfer }); el.dispatchEvent(e); }
|
||||
fire(from, "dragstart"); fire(to, "dragover");
|
||||
check("[board] 하위 작업 드래그는 카드 드래그와 분리", !transfer.types.includes("text/plain"));
|
||||
if (fromId !== toId) check("[board] 삽입 위치 표시", to.classList.contains(after ? "pj-sub-drop-after" : "pj-sub-drop-before"));
|
||||
fire(to, "drop"); fire(from, "dragend"); await settle();
|
||||
}
|
||||
await drag(903, 901, false);
|
||||
check("[board] 마지막 하위 작업을 맨 앞으로 저장", rows().join(",") === "903,901,902" && calls()[0].body.ordered_ids.join(",") === "903,901,902");
|
||||
await drag(903, 902, true);
|
||||
check("[board] 첫 하위 작업을 맨 뒤로 저장", rows().join(",") === "901,902,903");
|
||||
const before = calls().length; await drag(902, 902, false);
|
||||
check("[board] 자기 위치에 놓으면 저장하지 않음", calls().length === before);
|
||||
env.route("PUT", /tasks\/101\/subtasks\/order$/, function () { return { status: 500, body: { detail: "잠시 오류" } }; });
|
||||
await drag(903, 901, false);
|
||||
check("[board] 재정렬 실패는 기존 순서 유지·삽입 표시 정리", rows().join(",") === "901,902,903" && !d.querySelector(".pj-sub-drop-before, .pj-sub-drop-after"));
|
||||
env.route("POST", /tasks\/901\/move-parent$/, function () { return { body: { ok: true } }; });
|
||||
const from = d.querySelector('[data-sub-id="901"]'), target = d.querySelector('.pj-card[data-task-id="102"]');
|
||||
const data = {}; const transfer = { types: [], setData: function (k, v) { data[k] = v; this.types.push(k); }, getData: function (k) { return data[k]; } };
|
||||
["dragstart", "dragover", "drop", "dragend"].forEach(function (kind) { const e = new w.Event(kind, { bubbles: true, cancelable: true }); Object.defineProperty(e, "dataTransfer", { value: transfer }); (kind === "dragstart" || kind === "dragend" ? from : target).dispatchEvent(e); });
|
||||
await settle();
|
||||
check("[board] 기존 다른 부모 카드 이동 유지", env.calls.some(function (c) { return /tasks\/901\/move-parent$/.test(c.url) && c.body.parent_task_id === 102; }) && rows().join(",") === "902,903");
|
||||
}
|
||||
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); await boot(env); const d = env.d, w = env.w;
|
||||
const button = d.getElementById("pj-options-btn"), dialog = d.getElementById("pj-options-dialog"), select = d.getElementById("pj-options-font");
|
||||
button.click();
|
||||
check("[옵션] 도움말 옆 옵션은 기본 폰트로 대화창 열기", dialog.open && select.value === "system" && select.options.length === 5);
|
||||
select.value = "pretendard"; select.dispatchEvent(new w.Event("change")); d.getElementById("pj-options-cancel").click();
|
||||
check("[옵션] 취소는 선택한 폰트를 적용하지 않음", !dialog.open && !w.localStorage.getItem("pj_font"));
|
||||
button.click(); select.value = "nanum-square-neo"; d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션] 저장은 폰트 적용·기억 후 대화창 닫기", !dialog.open && w.localStorage.getItem("pj_font") === "nanum-square-neo" && d.documentElement.dataset.pjFont === "nanum-square-neo");
|
||||
button.click(); check("[옵션] 다시 열면 저장한 선택 유지", select.value === "nanum-square-neo");
|
||||
const loading = deferred(); d.fonts.load = function () { return loading.promise; };
|
||||
select.value = "pretendard"; d.getElementById("pj-options-save").click(); await settle();
|
||||
const cancel = new w.Event("cancel", { cancelable: true }); dialog.dispatchEvent(cancel);
|
||||
check("[옵션] 저장 중 취소·Esc로 지연 적용이 발생하지 않음", d.getElementById("pj-options-cancel").disabled && cancel.defaultPrevented && dialog.open);
|
||||
loading.resolve([{}]); await settle();
|
||||
check("[옵션] 폰트 로딩 후 저장 완료", !dialog.open && w.localStorage.getItem("pj_font") === "pretendard");
|
||||
button.click();
|
||||
d.fonts.load = async function () { throw new Error("font failed"); };
|
||||
select.value = "nanum-square-round"; d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션] 폰트 로딩 실패는 이전 설정 유지·재시도 가능", dialog.open && !d.getElementById("pj-options-error").hidden && !select.disabled && w.localStorage.getItem("pj_font") === "pretendard");
|
||||
}
|
||||
|
||||
// 카드 완료 체크 — 상세창과 분리, 중복 요청·실패 복구·읽기 전용.
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w;
|
||||
const seed = JSON.parse(d.getElementById("pj-data").textContent);
|
||||
seed.tasks.find(function (t) { return t.id === 301; }).stage_id = 11;
|
||||
d.getElementById("pj-data").textContent = JSON.stringify(seed);
|
||||
const P = await boot(env);
|
||||
const pending = deferred(); env.route("PUT", /tasks\/101$/, function () { return pending.promise; });
|
||||
const button = function () { return d.querySelector('.pj-card[data-task-id="101"] .pj-card-check'); };
|
||||
const puts = function () { return env.calls.filter(function (c) { return c.method === "PUT" && /tasks\/101$/.test(c.url); }); };
|
||||
check("[카드 완료] 미완료는 선택되지 않은 원형 체크", button().getAttribute("role") === "checkbox" && button().getAttribute("aria-checked") === "false");
|
||||
button().focus(); button().click(); button().dispatchEvent(new w.MouseEvent("click", { bubbles: true })); await settle();
|
||||
check("[카드 완료] 체크는 상세창 없이 완료 요청 한 번", puts().length === 1 && puts()[0].body.completed === true && d.getElementById("pj-modal-task").hidden && button().disabled);
|
||||
pending.resolve({ body: { task: detail(101, "작업 A", { completed_at: "2026-10-02" }) } }); await settle();
|
||||
check("[카드 완료] 서버 응답 뒤 완료 카드·체크·포커스 반영", !!taskOf(P, 101).completed_at && button().getAttribute("aria-checked") === "true" && !button().disabled && button().closest(".pj-card").classList.contains("is-done") && d.activeElement === button());
|
||||
env.route("PUT", /tasks\/101$/, function () { return { status: 500, body: { detail: "잠시 오류" } }; });
|
||||
button().click(); await settle();
|
||||
check("[카드 완료] 실패하면 완료 상태 유지·버튼 재시도 가능", button().getAttribute("aria-checked") === "true" && !button().disabled && puts()[1].body.completed === false);
|
||||
env.route("PUT", /tasks\/101$/, function () { return { body: { task: detail(101, "작업 A") } }; });
|
||||
button().click(); await settle();
|
||||
check("[카드 완료] 다시 누르면 완료 취소", !taskOf(P, 101).completed_at && button().getAttribute("aria-checked") === "false" && !button().closest(".pj-card").classList.contains("is-done"));
|
||||
const read = d.querySelector('.pj-card[data-task-id="301"] .pj-card-check'), before = env.calls.length;
|
||||
check("[카드 완료] 연결된 읽기 전용 작업은 비활성 체크", !!read && read.disabled);
|
||||
read.dispatchEvent(new w.MouseEvent("click", { bubbles: true })); await settle();
|
||||
check("[카드 완료] 읽기 전용 체크는 서버 요청을 보내지 않음", env.calls.length === before);
|
||||
}
|
||||
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.w.localStorage.setItem("pj_board_fold:1", '{"id:11":true}');
|
||||
env.w.localStorage.setItem("pj_side_w", "100");
|
||||
await boot(env);
|
||||
const d = env.d, w = env.w;
|
||||
const col = function () { return d.querySelector('.pj-col[data-stage-id="11"]'); };
|
||||
const btn = function () { return col().querySelector(".pj-col-collapse"); };
|
||||
check("[그룹 축소] 저장된 상태로 시작·확장 접근성 표시", col().classList.contains("is-collapsed") && btn().getAttribute("aria-expanded") === "false" && col().querySelector(".pj-col-body").inert);
|
||||
const before = env.calls.length;
|
||||
btn().click();
|
||||
check("[그룹 축소] 펼치기는 작업 변경 없이 상태만 저장", !col().classList.contains("is-collapsed") && btn().getAttribute("aria-expanded") === "true" && env.calls.length === before);
|
||||
btn().click();
|
||||
w.dispatchEvent(new w.Event("resize")); await settle();
|
||||
check("[그룹 축소] 보드 다시 그리기 뒤에도 축소 유지", col().classList.contains("is-collapsed") && /"id:11":true/.test(w.localStorage.getItem("pj_board_fold:1")));
|
||||
const layout = d.querySelector(".pj-layout"), handle = d.querySelector(".pj-side-resizer");
|
||||
check("[왼쪽 메뉴] 저장된 좁은 너비는 최소 170px", layout.style.getPropertyValue("--pj-side-w") === "170px");
|
||||
handle.dispatchEvent(new w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 200 }));
|
||||
d.dispatchEvent(new w.MouseEvent("mousemove", { bubbles: true, clientX: 100 }));
|
||||
d.dispatchEvent(new w.MouseEvent("mouseup", { bubbles: true }));
|
||||
check("[왼쪽 메뉴] 드래그 최소 너비·저장", layout.style.getPropertyValue("--pj-side-w") === "170px" && w.localStorage.getItem("pj_side_w") === "170");
|
||||
handle.dispatchEvent(new w.KeyboardEvent("keydown", { bubbles: true, key: "ArrowRight" }));
|
||||
check("[왼쪽 메뉴] 방향키 너비 조절", layout.style.getPropertyValue("--pj-side-w") === "180px");
|
||||
// 프레임을 직접 진행시켜 빠른 마우스 이동과 놓는 순간의 순서를 검증한다.
|
||||
const realRaf = w.requestAnimationFrame, realCancel = w.cancelAnimationFrame;
|
||||
let nextFrame = 0, resizeCount = 0;
|
||||
const frames = new Map();
|
||||
w.requestAnimationFrame = function (fn) { frames.set(++nextFrame, fn); return nextFrame; };
|
||||
w.cancelAnimationFrame = function (id) { frames.delete(id); };
|
||||
function paint() {
|
||||
const batch = Array.from(frames.values()); frames.clear(); batch.forEach(function (fn) { fn(); });
|
||||
}
|
||||
w.addEventListener("resize", function () { resizeCount++; });
|
||||
function down(x) { handle.dispatchEvent(new w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: x })); }
|
||||
function move(x) { d.dispatchEvent(new w.MouseEvent("mousemove", { bubbles: true, clientX: x })); }
|
||||
function up() { d.dispatchEvent(new w.MouseEvent("mouseup", { bubbles: true })); }
|
||||
down(200); move(220); move(240); move(260);
|
||||
check("[왼쪽 메뉴] 빠른 이동은 프레임 하나로 모으고 전체 재계산 없음", frames.size === 1 && resizeCount === 0 && handle.getAttribute("aria-valuenow") === "180");
|
||||
paint();
|
||||
check("[왼쪽 메뉴] 프레임에서 최신 위치만 즉시 표시", layout.style.getPropertyValue("--pj-side-w") === "240px" && resizeCount === 0);
|
||||
move(290); up();
|
||||
check("[왼쪽 메뉴] 놓는 순간 마지막 위치 반영·한 번 재계산·콜백 정리", layout.style.getPropertyValue("--pj-side-w") === "270px" && w.localStorage.getItem("pj_side_w") === "270" && resizeCount === 1 && frames.size === 0 && !d.documentElement.classList.contains("pj-side-resizing"));
|
||||
move(400); paint();
|
||||
check("[왼쪽 메뉴] 종료 뒤 이동은 너비를 바꾸지 않음", handle.getAttribute("aria-valuenow") === "270");
|
||||
d.documentElement.classList.add("pj-ui-scale");
|
||||
down(200); move(230); paint(); up();
|
||||
check("[왼쪽 메뉴] 75% 화면 배율에서도 이동 거리 보정", handle.getAttribute("aria-valuenow") === "310" && resizeCount === 2);
|
||||
d.documentElement.classList.remove("pj-ui-scale");
|
||||
down(200); move(1000); paint(); move(1100); paint(); up();
|
||||
check("[왼쪽 메뉴] 최대 500px·중복 프레임은 재계산 없음", handle.getAttribute("aria-valuenow") === "500" && resizeCount === 3);
|
||||
down(200); move(300); paint(); up();
|
||||
check("[왼쪽 메뉴] 한계에서 너비가 그대로면 재계산 생략", resizeCount === 3);
|
||||
down(200); move(150); w.dispatchEvent(new w.Event("blur"));
|
||||
check("[왼쪽 메뉴] 창 포커스를 잃어도 저장·드래그 정리", handle.getAttribute("aria-valuenow") === "450" && w.localStorage.getItem("pj_side_w") === "450" && resizeCount === 4 && frames.size === 0 && !handle.classList.contains("is-dragging"));
|
||||
handle.dispatchEvent(new w.KeyboardEvent("keydown", { bubbles: true, key: "Home" }));
|
||||
handle.dispatchEvent(new w.KeyboardEvent("keydown", { bubbles: true, key: "ArrowLeft" }));
|
||||
check("[왼쪽 메뉴] Home 최소값·한계 방향키 재계산 생략", handle.getAttribute("aria-valuenow") === "170" && resizeCount === 5);
|
||||
handle.dispatchEvent(new w.MouseEvent("dblclick", { bubbles: true }));
|
||||
check("[왼쪽 메뉴] 더블클릭 기본 너비·저장값 초기화", !layout.style.getPropertyValue("--pj-side-w") && handle.getAttribute("aria-valuenow") === "250" && w.localStorage.getItem("pj_side_w") === null && resizeCount === 6);
|
||||
// jsdom에는 레이아웃이 없으므로 좁은 창의 CSS 기본 너비(220px)를 직접 제공한다.
|
||||
d.querySelector(".pj-side").getBoundingClientRect = function () { return { width: 220 }; };
|
||||
handle.dispatchEvent(new w.KeyboardEvent("keydown", { bubbles: true, key: "ArrowRight" }));
|
||||
check("[왼쪽 메뉴] 기본값 복원 뒤 창 크기가 바뀌면 현재 너비에서 조절", handle.getAttribute("aria-valuenow") === "230" && resizeCount === 7);
|
||||
w.requestAnimationFrame = realRaf; w.cancelAnimationFrame = realCancel;
|
||||
const input = d.getElementById("pj-cm-input");
|
||||
Object.defineProperty(input, "scrollHeight", { value: 300 });
|
||||
input.value = "첫 줄\n둘째 줄\n셋째 줄"; input.dispatchEvent(new w.Event("input", { bubbles: true }));
|
||||
check("[댓글] 긴 글도 높이 70px·내부 스크롤", input.style.height === "70px" && input.style.overflowY === "auto");
|
||||
input.value = ""; input.dispatchEvent(new w.Event("input", { bubbles: true }));
|
||||
check("[댓글] 비운 뒤에도 높이 70px", input.style.height === "70px");
|
||||
}
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.w.localStorage.setItem("pj_side_w", "250"); await boot(env);
|
||||
check("[왼쪽 메뉴] 저장값이 기본 너비와 같아도 명시적으로 복원", env.d.querySelector(".pj-layout").style.getPropertyValue("--pj-side-w") === "250px");
|
||||
}
|
||||
clearTimeout(WATCHDOG);
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""연간 목표(goals.html)·주간 회의록(goal_meeting.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_goals.py # → tests/js/.out/goals_admin.html · goals_ro.html · meeting_admin.html · meeting_err.html · meeting_ro.html
|
||||
|
||||
칸 배치는 실제 라우터 도우미(_goal_area_layout·_goal_label_spans)로 만든다. DB·실적 모듈은 쓰지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
|
||||
import jinja2
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.project import store # noqa: E402
|
||||
from app.modules.project.router import _goal_area_layout, _goal_label_spans # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_after_logout %}{% endblock %}{% block topbar_actions %}{% endblock %}"
|
||||
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||
ME = "me@test.local"
|
||||
|
||||
|
||||
def board() -> dict:
|
||||
rows_a = [{"id": 10, "label": "신제품", "cells": {0: "연간 계획", 1: "original"}, "merges": {}},
|
||||
{"id": 11, "label": "리뉴얼", "cells": {}, "merges": {}}]
|
||||
rows_b = [{"id": 20, "label": "쿠팡", "cells": {2: "행사"}, "merges": {}},
|
||||
{"id": 21, "label": "", "cells": {}, "merges": {}}]
|
||||
areas = [{"id": 1, "name": "상품", "color": "#fde2e4", "rows": rows_a},
|
||||
{"id": 2, "name": "유통", "color": "", "rows": rows_b}]
|
||||
for a in areas:
|
||||
_goal_area_layout(a["rows"], 10)
|
||||
_goal_label_spans(a["rows"])
|
||||
return {
|
||||
"year": 2026, "sales_unit": "만원", "halves": True, "quarters": True,
|
||||
"metrics": {"sales": {"target_label": {1: "100", 2: "100"}, "actual_label": {1: "50"}},
|
||||
"roas": {"target_label": {}, "actual_label": {}}},
|
||||
"areas": areas,
|
||||
}
|
||||
|
||||
|
||||
def goals_ctx(admin: bool) -> dict:
|
||||
return {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
|
||||
"project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(),
|
||||
"months": list(range(1, 13)),
|
||||
"quarters": [(q, list(range(q * 3 - 2, q * 3 + 1)), store.GOAL_QUARTER_COL[q], f"{q}분기") for q in (1, 2, 3, 4)],
|
||||
"this_month": 10, "goal_area_colors": list(store.GOAL_AREA_COLORS),
|
||||
}
|
||||
|
||||
|
||||
def meeting_view(err: bool) -> dict:
|
||||
"""회의록 2026-09-28 주 — 유통 쿠팡(쇼핑몰 연결, 이번주 실적 100, 정량 목표 100), 상품1(직접 입력 결과)."""
|
||||
prev_cou = {"id": 901, "week_start": "2026-09-21", "content": "지난주 행사", "target_amount": 100, "result_amount": None,
|
||||
"status": "", "marketplace_code": "coupang", "period": "9/21~9/27", "not_started": False,
|
||||
"market_off": False, "auto_error": err, "auto_result": None if err else 80,
|
||||
"result": None if err else 80, "market_name": "쿠팡"}
|
||||
prev_p1 = {"id": 902, "week_start": "2026-09-21", "content": "샘플", "target_amount": 200, "result_amount": 100,
|
||||
"status": "partial", "marketplace_code": "", "period": "9/21~9/27", "not_started": False,
|
||||
"market_off": False, "auto_error": False, "auto_result": None, "result": 100, "market_name": ""}
|
||||
it_cou = {"id": 1, "section": "유통", "section_color": "", "label": "쿠팡", "content": "original",
|
||||
"target_amount": 100, "marketplace_code": "coupang", "market_name": "쿠팡", "market_off": False,
|
||||
"market_unknown": err, "week_auto": None if err else 100, "week_error": err,
|
||||
"prev": prev_cou, "rate": None if err else 80.0}
|
||||
it_p1 = {"id": 2, "section": "상품", "section_color": "#fde2e4", "label": "상품1", "content": "",
|
||||
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||
"market_unknown": False, "week_auto": None, "week_error": False, "prev": prev_p1, "rate": 50.0}
|
||||
it_new = {"id": 3, "section": "상품", "section_color": "#fde2e4", "label": "새 줄", "content": "",
|
||||
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||
"market_unknown": False, "week_auto": None, "week_error": False, "prev": None, "rate": None}
|
||||
meeting = {"week_start": "2026-09-28", "week_target": 1000, "attendees": "", "notes": "메모 원본",
|
||||
"items": [it_p1, it_new, it_cou],
|
||||
"sections": [{"name": "상품", "color": "#fde2e4", "rows": [it_p1, it_new]},
|
||||
{"name": "유통", "color": "", "rows": [it_cou]}]}
|
||||
head = {"sales_unit": "원", "sales_target": 10000.0, "roas_target": None, "month_target_won": 10000,
|
||||
"mtd": None if err else 0, "mtd_end": "2026-09-27", "weeks_left": 1,
|
||||
"need_per_week": None if err else 10000, "prev_target": 500, "prev_exists": True,
|
||||
"prev_result": None if err else 0, "week_result": None if err else 0,
|
||||
"perf": True, "perf_state": "error" if err else "ok",
|
||||
"unknown": ["mtd", "prev_result", "week_result"] if err else [],
|
||||
"fresh_oldest": "" if err else "10/01 14:20",
|
||||
"fresh_tip": "" if err else "매출 자료(실적 모듈) 쇼핑몰별 마지막 갱신 성공 — 쿠팡 10/01 14:20"}
|
||||
return {"meeting": meeting, "head": head, "markets": [] if err else [{"code": "coupang", "name": "쿠팡"}]}
|
||||
|
||||
|
||||
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
|
||||
view = meeting_view(err)
|
||||
return {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
|
||||
"project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True,
|
||||
"weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False,
|
||||
"days": []}],
|
||||
"cal_weeks": [], "week": "2026-09-28", "week_n": 4, "week_end": "2026-10-04",
|
||||
"prev_week": "2026-09-21", "prev_week_end": "2026-09-27", "sync_from": "2026-09-21", "sync_to": "2026-10-01",
|
||||
"can_sync": can_sync, "meeting_status": store.MEETING_STATUS, "meet_members": [], "month_plan": None,
|
||||
"attendee_list": [], **copy.deepcopy(view),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
]))
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
pages = {
|
||||
"goals_admin.html": ("project/goals.html", goals_ctx(True)),
|
||||
"goals_ro.html": ("project/goals.html", goals_ctx(False)),
|
||||
"meeting_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False)),
|
||||
"meeting_err.html": ("project/goal_meeting.html", meeting_ctx(True, True)),
|
||||
"meeting_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False)),
|
||||
}
|
||||
for name, (tpl, ctx) in pages.items():
|
||||
html = env.get_template(tpl).render(**ctx)
|
||||
path = os.path.join(OUT_DIR, name)
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""실제 ERP 기본 템플릿으로 도움말을 렌더한다. DB·운영 사용자 데이터 미사용.
|
||||
|
||||
python tests/js/render_help.py -> tests/js/.out/help_render.html
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import jinja2
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
env = jinja2.Environment(
|
||||
loader=jinja2.ChoiceLoader([
|
||||
jinja2.FileSystemLoader(ROOT / "app/modules/project/templates"),
|
||||
jinja2.FileSystemLoader(ROOT / "app/templates"),
|
||||
]),
|
||||
autoescape=jinja2.select_autoescape(["html"]),
|
||||
)
|
||||
html = env.get_template("project/help.html").render(
|
||||
user={"email": "reader@test.local", "name": "Reader", "is_super_admin": False},
|
||||
is_admin=False, nav_items=[], force_sidebar_collapsed=True,
|
||||
page_title="프로젝트 관리 도움말", page_subtitle="처음 쓰는 분을 위한 기능 안내",
|
||||
)
|
||||
out = ROOT / "tests/js/.out/help_render.html"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(html, encoding="utf-8")
|
||||
print("rendered:", out)
|
||||
@@ -13,7 +13,7 @@ import jinja2
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_actions %}{% endblock %}"
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_after_logout %}{% endblock %}{% block topbar_actions %}{% endblock %}"
|
||||
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||
|
||||
ME = "me@test.local"
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""쿠팡 밀크런 — 제품 포장무게(g) (마이그레이션 007).
|
||||
|
||||
DB 없이 돈다: 입력 읽기(parse_weight_g)와, 가짜 연결로 등록·수정 SQL 이 무게 칸 유무에 맞게
|
||||
만들어지는지(열·자리표시자·값 개수) 확인한다.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.cupang.db import CupangDBStore
|
||||
from app.modules.cupang.store import parse_weight_g
|
||||
|
||||
|
||||
def test_parse_weight_g():
|
||||
assert parse_weight_g("1,070") == 1070
|
||||
assert parse_weight_g(" 1,070 ") == 1070
|
||||
assert parse_weight_g("1070g") == 1070
|
||||
assert parse_weight_g("1070 G") == 1070
|
||||
assert parse_weight_g("1070.0") == 1070
|
||||
assert parse_weight_g(450) == 450
|
||||
assert parse_weight_g("0") == 0
|
||||
for empty in ("", " ", None):
|
||||
assert parse_weight_g(empty) is None
|
||||
for bad in ("abc", "-5", "0.5", "1,000,001", "nan"):
|
||||
with pytest.raises(ValueError):
|
||||
parse_weight_g(bad)
|
||||
|
||||
|
||||
class _Cur:
|
||||
def __init__(self, row):
|
||||
self._row = row
|
||||
self.rowcount = 1
|
||||
|
||||
def fetchone(self):
|
||||
return self._row
|
||||
|
||||
|
||||
class _Conn:
|
||||
def __init__(self, log, row):
|
||||
self.log, self.row = log, row
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
self.log.append((sql, params))
|
||||
if "information_schema" in sql:
|
||||
return _Cur(None)
|
||||
if sql.lstrip().startswith("SELECT 1 FROM cupang"):
|
||||
return _Cur(None) # 제품코드 중복·상자 규칙 없음
|
||||
return _Cur(dict(self.row))
|
||||
|
||||
def transaction(self):
|
||||
return self
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
class _Pool:
|
||||
def __init__(self, row):
|
||||
self.log: list[tuple[str, Any]] = []
|
||||
self.row = row
|
||||
|
||||
def connection(self):
|
||||
return _Conn(self.log, self.row)
|
||||
|
||||
|
||||
ROW = {"id": 7, "product_code": "MS-9809", "product_name": "미라클통", "coupang_item_code": "",
|
||||
"active": True, "sort_order": 0, "weight_g": 1070}
|
||||
|
||||
|
||||
def _store(weight: bool) -> tuple[CupangDBStore, _Pool]:
|
||||
st = CupangDBStore.__new__(CupangDBStore)
|
||||
pool = _Pool(ROW if weight else {k: v for k, v in ROW.items() if k != "weight_g"})
|
||||
st._pool = pool
|
||||
st._weight_col = weight or False
|
||||
return st, pool
|
||||
|
||||
|
||||
def _main_sql(pool: _Pool, verb: str) -> tuple[str, Any]:
|
||||
return next((q, p) for q, p in pool.log if q.lstrip().startswith(verb))
|
||||
|
||||
|
||||
def test_upsert_with_weight():
|
||||
st, pool = _store(True)
|
||||
out = st.upsert_product(product_code="MS-9809", product_name="미라클통", weight_g=1070)
|
||||
sql, params = _main_sql(pool, "INSERT")
|
||||
assert "weight_g)" in sql and "%(w)s)" in sql
|
||||
assert "weight_g = COALESCE(%(w)s, cupang_products.weight_g)" in sql # 비워 두면 기존 무게 유지
|
||||
assert params["w"] == 1070
|
||||
assert set(re.findall(r"%\((\w+)\)s", sql)) <= set(params)
|
||||
assert out["weight_g"] == 1070
|
||||
|
||||
|
||||
def test_upsert_without_column_ignores_weight():
|
||||
st, pool = _store(False)
|
||||
out = st.upsert_product(product_code="MS-9809", product_name="미라클통", weight_g=1070)
|
||||
sql, _ = _main_sql(pool, "INSERT")
|
||||
assert "weight_g" not in sql
|
||||
assert out["weight_g"] is None
|
||||
|
||||
|
||||
def test_update_weight_set_clear_keep():
|
||||
for weight_arg, expect_col, expect_val in ((950, True, 950), (None, True, None), (..., False, None)):
|
||||
st, pool = _store(True)
|
||||
st.update_product(product_id=7, product_name="미라클통", product_code="MS-9809",
|
||||
weight_g=weight_arg)
|
||||
sql, params = _main_sql(pool, "UPDATE cupang_products")
|
||||
assert ("weight_g = %s" in sql) is expect_col, weight_arg
|
||||
assert sql.count("%s") == len(params) # 자리표시자 = 값 개수
|
||||
if expect_col:
|
||||
assert params[-2] == expect_val and params[-1] == 7
|
||||
|
||||
|
||||
def test_update_without_column_ignores_weight():
|
||||
st, pool = _store(False)
|
||||
st.update_product(product_id=7, product_name="미라클통", product_code="MS-9809", weight_g=950)
|
||||
sql, params = _main_sql(pool, "UPDATE cupang_products")
|
||||
assert "weight_g" not in sql and sql.count("%s") == len(params) == 4
|
||||
|
||||
|
||||
# ── 상자 목록 무게 합계(상자별) ──────────────────────────────────────
|
||||
class _WStore:
|
||||
def __init__(self, enabled: bool, weights: dict[str, int | None]):
|
||||
self.enabled, self.weights = enabled, weights
|
||||
|
||||
def weight_enabled(self) -> bool:
|
||||
return self.enabled
|
||||
|
||||
def list_products(self, include_inactive: bool = False):
|
||||
return [{"product_code": c, "weight_g": w} for c, w in self.weights.items()]
|
||||
|
||||
|
||||
def _boxes():
|
||||
mt = {"product_name": "멀티 5,000ml x4", "product_code": "MT-5000_4", "quantity": 2}
|
||||
mix = [{"product_name": "미라클 통 점보 x2", "product_code": "MT-7000_2", "quantity": 6},
|
||||
{"product_name": "무게 없음", "product_code": "XX-0001", "quantity": 1}]
|
||||
return [{"no": 1, "kind": "product", "items": [mt]},
|
||||
{"no": 2, "kind": "mix", "items": mix},
|
||||
{"no": 3, "kind": "product", "items": [{"product_name": "없음", "product_code": "XX-0001", "quantity": 3}]}]
|
||||
|
||||
|
||||
def test_box_weights():
|
||||
from app.modules.cupang.router import _attach_box_weights
|
||||
boxes = _boxes()
|
||||
assert _attach_box_weights(_WStore(True, {"MT-5000_4": 1800, "MT-7000_2": 1060, "XX-0001": None}), boxes) is True
|
||||
assert boxes[0]["weight_g"] == 3600 and boxes[0]["weight_missing"] == [] # 2 × 1,800
|
||||
assert boxes[1]["weight_g"] == 6360 and boxes[1]["weight_missing"] == ["XX-0001"] # 6 × 1,060, 무게 없는 제품은 빼고
|
||||
assert boxes[2]["weight_g"] is None and boxes[2]["weight_missing"] == ["XX-0001"] # 하나도 모르면 None
|
||||
plain = _boxes()
|
||||
assert _attach_box_weights(_WStore(False, {}), plain) is False and "weight_g" not in plain[0]
|
||||
|
||||
|
||||
def test_box_list_workbook_weight_column():
|
||||
from app.modules.cupang.export import build_box_list_workbook
|
||||
from app.modules.cupang.router import _attach_box_weights
|
||||
boxes = _boxes()
|
||||
_attach_box_weights(_WStore(True, {"MT-5000_4": 1800, "MT-7000_2": 1060}), boxes)
|
||||
ws = build_box_list_workbook({"ship_date": "2026-10-02", "center_name_snapshot": "대구3"}, boxes, with_weight=True).active
|
||||
assert [ws.cell(row=2, column=c).value for c in range(1, 6)] == ["상자번호", "제품명", "제품코드", "수량", "무게(g)"]
|
||||
assert ws.cell(row=3, column=5).value == 3600 and ws.cell(row=4, column=5).value == 6360
|
||||
assert any(str(r) == "E4:E5" for r in ws.merged_cells.ranges) # 혼합 상자 무게 칸 세로 병합
|
||||
assert ws.cell(row=6, column=5).value is None
|
||||
ws2 = build_box_list_workbook({"ship_date": "2026-10-02"}, _boxes()).active # 예전처럼 4열
|
||||
assert ws2.cell(row=2, column=5).value is None and ws2.cell(row=2, column=4).value == "수량"
|
||||
@@ -0,0 +1,132 @@
|
||||
"""마이그레이션 018(주간 회의록 줄 연결키 line_key) 백필 검증 — 로컬 테스트용 PostgreSQL 에서만.
|
||||
|
||||
예전 코드가 만든 데이터 모양(carry_from 사슬·역순 생성·끊긴 연결·같은 이름 줄)을 임시 스키마에 만들고
|
||||
scripts/sql/project_db_018_meeting_line_keys.sql 을 두 번 돌려(멱등) 결과를 확인한다.
|
||||
전부 한 트랜잭션 안에서 하고 마지막에 ROLLBACK — 테스트 DB 에 아무것도 남기지 않는다(DROP 없음).
|
||||
|
||||
PROJECT_TEST_DB_URL=postgresql://postgres@127.0.0.1:55432/project_db \
|
||||
python tests/test_meeting_line_keys_migration.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import date, timedelta
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
|
||||
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
DDL = """
|
||||
CREATE TABLE goal_meetings (
|
||||
week_start DATE PRIMARY KEY CHECK (EXTRACT(ISODOW FROM week_start) = 1),
|
||||
week_target BIGINT NULL, 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 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, result_amount BIGINT NULL,
|
||||
status TEXT NOT NULL DEFAULT '', 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()
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def migration_sql() -> str:
|
||||
"""018 파일에서 psql 메타 명령(\\set·\\connect)과 BEGIN/COMMIT 을 뺀 본문 — 바깥 트랜잭션(ROLLBACK) 안에서 돌린다."""
|
||||
path = os.path.join(ROOT, "scripts", "sql", "project_db_018_meeting_line_keys.sql")
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
lines = [ln for ln in fh.read().splitlines()
|
||||
if not ln.startswith("\\") and ln.strip() not in ("BEGIN;", "COMMIT;")]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
return 0
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
schema = "mig018_" + uuid.uuid4().hex[:8]
|
||||
W = [date(2026, 9, 7) + timedelta(days=7 * i) for i in range(5)] # 9/7 9/14 9/21 9/28 10/5 (월요일)
|
||||
with psycopg.connect(DSN, row_factory=dict_row) as conn: # autocommit 아님 — 끝에 rollback
|
||||
conn.execute(f"CREATE SCHEMA {schema}")
|
||||
conn.execute(f"SET LOCAL search_path TO {schema}")
|
||||
conn.execute(DDL)
|
||||
for w in W:
|
||||
conn.execute("INSERT INTO goal_meetings (week_start) VALUES (%s)", (w,))
|
||||
|
||||
def add(week, section, label, carry=None, order=0):
|
||||
return conn.execute(
|
||||
"INSERT INTO goal_meeting_items (week_start, section, label, carry_from, sort_order) "
|
||||
"VALUES (%s,%s,%s,%s,%s) RETURNING id", (week, section, label, carry, order),
|
||||
).fetchone()["id"]
|
||||
|
||||
# 9/14 = 양식으로 처음(사슬 뿌리) — 같은 구역에 같은 이름 "기타" 두 줄
|
||||
a_cou = add(W[1], "유통", "쿠팡", order=0)
|
||||
a_et1 = add(W[1], "유통", "기타", order=1)
|
||||
a_et2 = add(W[1], "유통", "기타", order=2)
|
||||
a_meta = add(W[1], "마케팅", "메타", order=3)
|
||||
# 9/28 을 먼저 만듦(예전 코드: 앞선 가장 가까운 9/14 를 원본으로) → 9/21 을 나중에(역시 9/14 원본)
|
||||
b_cou = add(W[3], "유통", "쿠팡", a_cou, 0)
|
||||
b_et1 = add(W[3], "유통", "기타", a_et1, 1)
|
||||
b_et2 = add(W[3], "유통", "기타", a_et2, 2)
|
||||
b_meta = add(W[3], "마케팅", "메타 광고", a_meta, 3) # 이름 바꾼 줄
|
||||
b_new = add(W[3], "유통", "쿠팡", None, 4) # 9/28 에 새로 추가한 같은 이름 줄
|
||||
c_cou = add(W[2], "유통", "쿠팡", a_cou, 0)
|
||||
c_et1 = add(W[2], "유통", "기타", a_et1, 1)
|
||||
c_et2 = add(W[2], "유통", "기타", a_et2, 2)
|
||||
c_meta = add(W[2], "마케팅", "메타", a_meta, 3)
|
||||
# 10/5 = 9/28 원본 — 9/28 의 새 줄도 이어받음
|
||||
d_cou = add(W[4], "유통", "쿠팡", b_cou, 0)
|
||||
d_new = add(W[4], "유통", "쿠팡", b_new, 1)
|
||||
# 9/7 = 앞 주를 지웠다 다시 만든 흔적 — 연결 끊김(carry_from NULL), 같은 이름이지만 붙이면 안 됨
|
||||
e_cou = add(W[0], "유통", "쿠팡", None, 0)
|
||||
|
||||
sql = migration_sql()
|
||||
conn.execute(sql)
|
||||
key = lambda i: conn.execute("SELECT line_key FROM goal_meeting_items WHERE id = %s", (i,)).fetchone()["line_key"] # noqa: E731
|
||||
first = {i: key(i) for i in (a_cou, b_cou, c_cou, d_cou, a_et1, a_et2, b_et1, b_et2, c_et1, c_et2,
|
||||
a_meta, b_meta, c_meta, b_new, d_new, e_cou)}
|
||||
conn.execute(sql) # 두 번째 — 멱등(키가 바뀌지 않아야)
|
||||
second = {i: key(i) for i in first}
|
||||
|
||||
checks = [
|
||||
("모든 줄에 키", conn.execute("SELECT count(*) AS n FROM goal_meeting_items WHERE line_key IS NULL").fetchone()["n"] == 0),
|
||||
("역순 생성: 9/28 쿠팡 ↔ 9/21 쿠팡 같은 키", first[b_cou] == first[c_cou] == first[a_cou] == first[d_cou]),
|
||||
("같은 이름 '기타' 두 줄은 서로 다른 키", first[a_et1] != first[a_et2]),
|
||||
("'기타' 각 줄이 자기 사슬로만", first[b_et1] == first[c_et1] == first[a_et1] and first[b_et2] == first[c_et2] == first[a_et2]),
|
||||
("이름 바꾼 줄도 같은 키", first[b_meta] == first[c_meta] == first[a_meta]),
|
||||
("새로 추가한 같은 이름 줄은 다른 키", first[b_new] != first[b_cou] and first[d_new] == first[b_new]),
|
||||
("끊긴 연결(carry_from NULL)은 이름이 같아도 붙이지 않음", first[e_cou] != first[a_cou]),
|
||||
("두 번 돌려도 같은 키(멱등)", first == second),
|
||||
("NOT NULL 제약", conn.execute(
|
||||
"SELECT is_nullable FROM information_schema.columns WHERE table_schema = %s "
|
||||
"AND table_name = 'goal_meeting_items' AND column_name = 'line_key'", (schema,)).fetchone()["is_nullable"] == "NO"),
|
||||
]
|
||||
# UNIQUE(week_start, line_key) — 같은 주 같은 키는 막힌다
|
||||
try:
|
||||
with conn.transaction():
|
||||
conn.execute("UPDATE goal_meeting_items SET line_key = %s WHERE id = %s", (first[b_cou], b_new))
|
||||
checks.append(("한 주 안 같은 키 금지(UNIQUE)", False))
|
||||
except psycopg.errors.UniqueViolation:
|
||||
checks.append(("한 주 안 같은 키 금지(UNIQUE)", True))
|
||||
conn.rollback() # 아무것도 남기지 않는다
|
||||
|
||||
bad = [n for n, ok in checks if not ok]
|
||||
for n, ok in checks:
|
||||
print(("PASS " if ok else "FAIL ") + n)
|
||||
print("ALL PASS" if not bad else f"{len(bad)} FAIL")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,179 @@
|
||||
"""셀 이동의 실제 저장소/라우터 로직을 트랜잭션 대역으로 검증(실제 PostgreSQL 테스트는 test_project_module.py)."""
|
||||
import copy
|
||||
import importlib
|
||||
import json
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import store
|
||||
from app.modules.project.db import ProjectStore
|
||||
|
||||
api_module = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class Rows:
|
||||
def __init__(self, rows=()):
|
||||
self.rows = list(rows)
|
||||
|
||||
def fetchall(self):
|
||||
return self.rows
|
||||
|
||||
def fetchone(self):
|
||||
return self.rows[0] if self.rows else None
|
||||
|
||||
|
||||
class Connection:
|
||||
def __init__(self):
|
||||
self.rows = {10: {"id": 10, "area_id": 2, "year": 2026}, 20: {"id": 20, "area_id": 1, "year": 2026}}
|
||||
self.cells = {(10, 1): "original", (20, 2): "existing"}
|
||||
self.calls, self.commits, self.rollbacks = [], 0, 0
|
||||
self.fail_delete = False
|
||||
self.transaction_depth = 0
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
before = copy.deepcopy(self.cells)
|
||||
self.transaction_depth += 1
|
||||
try:
|
||||
yield self
|
||||
except Exception:
|
||||
self.cells = before
|
||||
self.rollbacks += 1
|
||||
raise
|
||||
else:
|
||||
self.commits += 1
|
||||
finally:
|
||||
self.transaction_depth -= 1
|
||||
|
||||
def execute(self, sql, params):
|
||||
self.calls.append((sql, params))
|
||||
if sql.startswith("SELECT r.id, r.area_id, a.year"):
|
||||
return Rows(self.rows[r] for r in set(params[0]) if r in self.rows)
|
||||
if sql.startswith("SELECT id FROM goal_areas"):
|
||||
return Rows({"id": a} for a in params[0])
|
||||
if sql.startswith("SELECT id, area_id FROM goal_rows"):
|
||||
return Rows(self.rows[r] for r in sorted(set(params[0])) if r in self.rows)
|
||||
if sql.startswith("SELECT row_id, month, body"):
|
||||
keys = [(params[0], params[1]), (params[2], params[3])]
|
||||
return Rows({"row_id": r, "month": m, "body": self.cells[r, m]} for r, m in keys if (r, m) in self.cells)
|
||||
if sql.startswith("INSERT INTO goal_cells"):
|
||||
assert self.transaction_depth > 0, "Cell writes must hold the area lock until commit"
|
||||
self.cells[params[0], params[1]] = params[2]
|
||||
return Rows()
|
||||
if sql.startswith("DELETE FROM goal_cells"):
|
||||
assert self.transaction_depth > 0, "Cell writes must hold the area lock until commit"
|
||||
if self.fail_delete:
|
||||
raise RuntimeError("simulated delete failure")
|
||||
self.cells.pop((params[0], params[1]), None)
|
||||
return Rows()
|
||||
if sql.startswith("SELECT a.id AS area_id"):
|
||||
assert self.transaction_depth > 0, "Autocommit releases the area lock before the write"
|
||||
row = self.rows.get(params[0])
|
||||
return Rows([{"area_id": row["area_id"]}] if row else [])
|
||||
raise AssertionError("Unexpected SQL: " + sql)
|
||||
|
||||
|
||||
class GoalMoveTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = Connection()
|
||||
@contextmanager
|
||||
def connection():
|
||||
yield self.conn
|
||||
self.st = ProjectStore.__new__(ProjectStore)
|
||||
self.st._pool = SimpleNamespace(connection=connection)
|
||||
self.st._table_exists = lambda conn, name: True
|
||||
self.st._goal_quarters = lambda conn: True
|
||||
self.merges = {}
|
||||
self.st._area_geometry = lambda conn, area: (
|
||||
[r for r in self.conn.rows if self.conn.rows[r]["area_id"] == area], self.merges.get(area, []), True)
|
||||
self.payload = dict(source_row=10, source_month=1, target_row=20, target_month=2,
|
||||
source_body="original", target_body="existing", body="original", updated_by="ADMIN@TEST.LOCAL")
|
||||
|
||||
def move(self, **changes):
|
||||
return self.st.move_goal_cell(**(self.payload | changes))
|
||||
|
||||
def test_move_preserves_all_explicit_formats_and_locks_in_order(self):
|
||||
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([
|
||||
{"text": "formatted", "bold": True, "italic": True, "underline": True, "size": 24, "color": "#ff0000"}]))
|
||||
self.conn.cells[10, 1] = rich
|
||||
self.assertEqual(self.move(source_body=rich, body=rich), rich)
|
||||
self.assertNotIn((10, 1), self.conn.cells)
|
||||
self.assertEqual(self.conn.cells[20, 2], rich)
|
||||
self.assertEqual(self.conn.commits, 1)
|
||||
self.assertTrue(any("goal_areas" in sql and "FOR UPDATE" in sql and p == ([1, 2],) for sql, p in self.conn.calls))
|
||||
|
||||
def test_failure_after_target_write_rolls_back_both_cells(self):
|
||||
before = dict(self.conn.cells)
|
||||
self.conn.fail_delete = True
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.move()
|
||||
self.assertEqual(self.conn.cells, before)
|
||||
self.assertEqual(self.conn.rollbacks, 1)
|
||||
|
||||
def test_concurrent_change_in_either_cell_aborts_without_writes(self):
|
||||
for key in ((10, 1), (20, 2)):
|
||||
with self.subTest(key=key):
|
||||
self.setUp()
|
||||
self.conn.cells[key] = "another user's edit"
|
||||
before = dict(self.conn.cells)
|
||||
with self.assertRaises(store.GoalCellConflict):
|
||||
self.move()
|
||||
self.assertEqual(self.conn.cells, before)
|
||||
|
||||
def test_lost_response_retry_succeeds_without_writing_again(self):
|
||||
self.move()
|
||||
count = len([sql for sql, _ in self.conn.calls if sql.startswith(("INSERT", "DELETE"))])
|
||||
self.assertEqual(self.move(), "original")
|
||||
self.assertEqual(len([sql for sql, _ in self.conn.calls if sql.startswith(("INSERT", "DELETE"))]), count)
|
||||
|
||||
def test_empty_target_and_defaults_become_explicit_styles(self):
|
||||
self.conn.cells.pop((20, 2))
|
||||
rich = store.GOAL_RICH_PREFIX + json.dumps([{"text": "original", "bold": False, "size": 14, "color": "#050505"}])
|
||||
result = self.move(target_body="", body=rich)
|
||||
self.assertEqual(store.goal_text_plain(result), "original")
|
||||
self.assertIn('"bold":false', result)
|
||||
|
||||
def test_bad_content_missing_rows_wrong_year_and_hidden_merge_cell(self):
|
||||
for changes, error in [({"body": "different"}, ValueError), ({"target_row": 999}, KeyError),
|
||||
({"target_month": 17}, ValueError), ({"target_row": 10, "target_month": 1}, ValueError)]:
|
||||
with self.subTest(changes=changes), self.assertRaises(error):
|
||||
self.move(**changes)
|
||||
self.conn.rows[20]["year"] = 2027
|
||||
with self.assertRaises(ValueError):
|
||||
self.move()
|
||||
self.conn.rows[20]["year"] = 2026
|
||||
self.merges[1] = [{"r0": 0, "r1": 0, "c0": 1, "c1": 2}]
|
||||
with self.assertRaises(store.GoalCellConflict):
|
||||
self.move()
|
||||
|
||||
def test_normal_save_uses_the_same_area_lock(self):
|
||||
self.st.set_goal_cell(row_id=10, month=1, body="new")
|
||||
self.assertIn("FOR UPDATE OF a", self.conn.calls[0][0])
|
||||
self.assertEqual(self.conn.cells[10, 1], "new")
|
||||
self.assertEqual(self.conn.commits, 1)
|
||||
|
||||
def test_http_admin_permissions_validation_and_conflict_status(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api_module.router)
|
||||
app.state.project_store = self.st
|
||||
client = TestClient(app)
|
||||
payload = {k: v for k, v in self.payload.items() if k != "updated_by"}
|
||||
with patch.object(api_module, "_require_user", return_value={"email": "a@test.local", "role": "user"}):
|
||||
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload).status_code, 403)
|
||||
with patch.object(api_module, "_require_user", return_value={"email": "a@test.local", "role": "admin"}):
|
||||
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload | {"source_body": None}).status_code, 400)
|
||||
self.conn.cells[20, 2] = "changed"
|
||||
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload).status_code, 409)
|
||||
self.conn.cells[20, 2] = "existing"
|
||||
result = client.post("/project/api/goals/cells/move", json=payload)
|
||||
self.assertEqual(result.status_code, 200)
|
||||
self.assertEqual(result.json(), {"ok": True, "body": "original"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,54 @@
|
||||
import json
|
||||
import unittest
|
||||
from app.modules.project import store
|
||||
|
||||
|
||||
def rich(runs):
|
||||
return store.GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False)
|
||||
|
||||
|
||||
class GoalRichTextTests(unittest.TestCase):
|
||||
def test_selected_styles_are_safe_and_legacy_text_stays_literal(self):
|
||||
body = rich([{"text": "<img src=x onerror=alert(1)>", "bold": True,
|
||||
"color": "#FF0000", "size": 20, "onclick": "alert(1)"},
|
||||
{"text": " untouched", "color": "url(javascript:x)", "size": 99}])
|
||||
stored = store.validate_goal_text(body)
|
||||
html = store.goal_text_html(stored)
|
||||
assert '<img' in html and '<img' not in html
|
||||
assert 'font-weight:700' in html and 'color:#ff0000' in html and 'font-size:20px' in html
|
||||
assert 'javascript' not in html and 'onclick' not in stored and '99px' not in html
|
||||
assert store.goal_text_html('<b>legacy</b>') == '<b>legacy</b>'
|
||||
|
||||
|
||||
def test_rich_merge_preserves_styles_and_plain_meeting_plan(self):
|
||||
value = store.merge_goal_texts(['first', rich([{"text": "second", "bold": True, "size": 18}])])
|
||||
assert store.goal_text_plain(value) == 'first\nsecond'
|
||||
assert 'font-size:18px' in store.goal_text_html(value)
|
||||
assert store.merge_goal_texts(['a', 'b']) == 'a\nb'
|
||||
assert store.validate_goal_text(rich([{"text": " "}])) == ''
|
||||
|
||||
def test_italic_and_underline_survive_save_render_and_merge(self):
|
||||
body = rich([{"text": "<선택>", "italic": True, "underline": True, "size": 16},
|
||||
{"text": "해제", "italic": False, "underline": False},
|
||||
{"text": "invalid", "italic": "url(javascript:x)", "underline": 1}])
|
||||
stored = store.validate_goal_text(body)
|
||||
runs = store.goal_text_runs(stored)
|
||||
assert runs[0]["italic"] is True and runs[0]["underline"] is True
|
||||
assert runs[1]["italic"] is False and runs[1]["underline"] is False
|
||||
assert runs[2] == {"text": "invalid"}
|
||||
html = store.goal_text_html(stored)
|
||||
assert '<선택>' in html and 'font-style:italic' in html and 'text-decoration:underline' in html
|
||||
assert 'font-style:normal' in html and 'text-decoration:none' in html
|
||||
assert 'javascript' not in stored
|
||||
merged = store.merge_goal_texts([stored, 'plain'])
|
||||
assert store.goal_text_runs(merged)[0]["underline"] is True
|
||||
assert store.goal_text_plain(merged) == '<선택>해제invalid\nplain'
|
||||
|
||||
|
||||
def test_rich_payload_limits_and_malformed_data(self):
|
||||
with self.assertRaises(ValueError):
|
||||
store.validate_goal_text(rich([{"text": "x" * (store.GOAL_TEXT_MAX + 1)}]))
|
||||
with self.assertRaises(ValueError):
|
||||
store.validate_goal_text(store.GOAL_RICH_PREFIX + '{"unexpected":1}')
|
||||
with self.assertRaises(ValueError):
|
||||
store.validate_goal_text(store.GOAL_RICH_PREFIX + '[broken')
|
||||
@@ -20,7 +20,7 @@ import tempfile
|
||||
import threading
|
||||
import types
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from datetime import date, timedelta
|
||||
from urllib.parse import urlparse
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
@@ -456,6 +456,553 @@ def test_store_date_range_unit():
|
||||
raise AssertionError(args)
|
||||
|
||||
|
||||
def test_store_goal_merge_unit():
|
||||
from app.modules.project import store
|
||||
assert store.validate_goal_merge(3, 1) == (1, 3)
|
||||
assert store.validate_goal_merge(10, 12) == (10, 12)
|
||||
assert store.validate_goal_month(13, allow_year=True) == 13
|
||||
assert store.validate_goal_month(16, allow_year=True) == 16
|
||||
for bad in (17, -1):
|
||||
try:
|
||||
store.validate_goal_month(bad, allow_year=True)
|
||||
except ValueError:
|
||||
continue
|
||||
raise AssertionError(bad)
|
||||
# 분기를 넘는 병합(3~4월, 6~7월, 7~12월)은 거절
|
||||
for args in ((3, 4), (6, 7), (7, 12), (3, 3), (0, 2), (11, 13)):
|
||||
try:
|
||||
store.validate_goal_merge(*args)
|
||||
except ValueError:
|
||||
continue
|
||||
raise AssertionError(args)
|
||||
|
||||
|
||||
def test_store_goal_quarters_unit():
|
||||
"""분기 칸(2026-10-01 상·하반기 → 1~4분기): 칸 순서·묶음·사각형 범위."""
|
||||
from app.modules.project import store
|
||||
assert store.GOAL_COL_ORDER == (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)
|
||||
assert [store.goal_quarter_of(m) for m in (1, 3, 4, 6, 7, 9, 10, 12)] == [1, 1, 2, 2, 3, 3, 4, 4]
|
||||
assert store.GOAL_QUARTER_COL == {1: 13, 2: 15, 3: 14, 4: 16}
|
||||
assert store.goal_col_group(13) == "q1" and store.goal_col_group(14) == "q3"
|
||||
assert store.goal_col_group(5) == store.goal_col_group(6) != store.goal_col_group(7)
|
||||
assert store.validate_goal_rect_cols(4, 6) == (4, 3)
|
||||
assert store.validate_goal_rect_cols(15, 15) == (15, 1)
|
||||
for a, b in ((3, 4), (3, 13), (6, 15), (0, 1)):
|
||||
try:
|
||||
store.validate_goal_rect_cols(a, b)
|
||||
except ValueError:
|
||||
continue
|
||||
raise AssertionError((a, b))
|
||||
assert store.MEETING_TEMPLATE["마케팅"][0] == "메타"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_goal_cell_content_move():
|
||||
"""실제 PostgreSQL: 서식 포함 이동·동시 이동 충돌·권한·병합 가림·응답 유실 재시도."""
|
||||
from app.modules.project import store
|
||||
year = 2060 + int(RUN, 16) % 40
|
||||
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
|
||||
try:
|
||||
board = ST.get_goal_board(year=year)
|
||||
rid = board["areas"][0]["rows"][0]["id"]
|
||||
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + '[{"text":"move","color":"#ff0000","size":24,"bold":true,"italic":true,"underline":true}]')
|
||||
ST.set_goal_cell(row_id=rid, month=1, body=rich)
|
||||
payload = {"source_row": rid, "source_month": 1, "target_row": rid, "target_month": 2,
|
||||
"source_body": rich, "target_body": "", "body": rich}
|
||||
endpoint = "/project/api/goals/cells/move"
|
||||
assert req("POST", endpoint, BOB, json=payload).status_code == 403
|
||||
assert req("POST", endpoint, ADMIN, json=payload | {"target_month": 17}).status_code == 400
|
||||
ST.set_goal_cell(row_id=rid, month=2, body="another edit")
|
||||
assert req("POST", endpoint, ADMIN, json=payload).status_code == 409
|
||||
ST.set_goal_cell(row_id=rid, month=2, body="")
|
||||
assert req("POST", endpoint, ADMIN, json=payload).json() == {"ok": True, "body": rich}
|
||||
assert req("POST", endpoint, ADMIN, json=payload).status_code == 200
|
||||
cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"]
|
||||
assert 1 not in cells and cells[2] == rich
|
||||
|
||||
# 같은 원본을 서로 다른 대상으로 동시에 이동하면 한 요청만 성공한다.
|
||||
ST.set_goal_cell(row_id=rid, month=1, body=rich)
|
||||
ST.set_goal_cell(row_id=rid, month=2, body="")
|
||||
barrier = threading.Barrier(2)
|
||||
results = []
|
||||
def move_to(month):
|
||||
barrier.wait()
|
||||
try:
|
||||
ST.move_goal_cell(source_row=rid, source_month=1, target_row=rid, target_month=month,
|
||||
source_body=rich, target_body="", body=rich, updated_by=ADMIN)
|
||||
results.append("ok")
|
||||
except store.GoalCellConflict:
|
||||
results.append("conflict")
|
||||
workers = [threading.Thread(target=move_to, args=(m,)) for m in (2, 3)]
|
||||
for t in workers: t.start()
|
||||
for t in workers: t.join(timeout=10)
|
||||
assert sorted(results) == ["conflict", "ok"], results
|
||||
aid = board["areas"][0]["id"]
|
||||
ST.merge_goal_rect(area_id=aid, row_from=rid, row_to=rid, col_from=4, col_to=5)
|
||||
hidden = payload | {"source_month": 2 if 2 in ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] else 3,
|
||||
"target_month": 5}
|
||||
assert req("POST", endpoint, ADMIN, json=hidden).status_code == 409
|
||||
finally:
|
||||
ST.delete_goal_year(year=year)
|
||||
|
||||
|
||||
def test_goal_halves_and_merges():
|
||||
year = 2060 + int(RUN, 16) % 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:
|
||||
board = ST.get_goal_board(year=year)
|
||||
assert board["halves"] is True, "마이그레이션 014 적용 필요"
|
||||
assert board["quarters"] is True, "마이그레이션 017 적용 필요"
|
||||
rid = board["areas"][0]["rows"][0]["id"]
|
||||
aid0 = board["areas"][0]["id"]
|
||||
cell = lambda m, body, who=ADMIN: req( # noqa: E731
|
||||
"PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body})
|
||||
# 분기 글 칸(13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기), 범위 밖(17)은 400, 비관리자는 403
|
||||
for m, body in ((13, "1분기 글"), (15, "2분기 글"), (14, "3분기 글"), (16, "4분기 글")):
|
||||
assert cell(m, body).status_code == 200, m
|
||||
assert cell(17, "x").status_code == 400
|
||||
assert cell(13, "y", BOB).status_code == 403
|
||||
for m, body in ((2, "이월"), (3, "삼월")):
|
||||
assert cell(m, body).status_code == 200
|
||||
merge = lambda s, e: req( # noqa: E731 — 엑셀식 병합 API(한 줄 가로)
|
||||
"POST", f"/project/api/goals/areas/{aid0}/merge", ADMIN,
|
||||
json={"row_from": rid, "row_to": rid, "col_from": s, "col_to": e})
|
||||
# 분기를 넘는 병합(3~4월, 사이에 1분기 칸)·한 칸 병합은 400
|
||||
assert merge(3, 4).status_code == 400 and merge(4, 4).status_code == 400
|
||||
r = merge(2, 3)
|
||||
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"]
|
||||
assert cells[2] == "이월\n삼월" and 3 not in cells
|
||||
# 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만)
|
||||
assert cell(3, "늦은 저장").status_code == 400
|
||||
# 걸친 병합은 흡수: 1~2 → 1~3, 글은 월 순서대로 이어진다
|
||||
r = merge(1, 2)
|
||||
assert r.json() == {"ok": True, "row_id": rid, "start": 1, "span": 3, "row_span": 1}, r.text
|
||||
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
|
||||
assert row["merges"] == {1: (3, 1)} and row["cells"][1] == "이월\n삼월" and 2 not in row["cells"]
|
||||
assert row["cells"][13] == "1분기 글" and row["cells"][15] == "2분기 글" and row["cells"][16] == "4분기 글"
|
||||
# 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404
|
||||
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 200
|
||||
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 404
|
||||
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
|
||||
assert row["merges"] == {} and row["cells"][1] == "이월\n삼월"
|
||||
# 로아스 % 표기(입력에 % 가 있어도 숫자로 저장)
|
||||
r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN,
|
||||
json={"metric": "roas", "kind": "target", "month": 1, "value": "499%"})
|
||||
assert r.status_code == 200 and r.json()["label"] == "499%" and r.json()["value"] == 499
|
||||
r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN,
|
||||
json={"metric": "sales", "kind": "target", "month": 1, "value": "1,200"})
|
||||
assert r.json()["label"] == "1,200"
|
||||
# 영역·줄 이름(그 자리 수정이 쓰는 API) — 영역 이름은 빈 값 400, 줄 이름은 빈 값 허용
|
||||
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
|
||||
assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": ""}).status_code == 400
|
||||
assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": "상품2"}).status_code == 200
|
||||
assert req("PUT", f"/project/api/goals/rows/{rid}", ADMIN, json={"label": ""}).status_code == 200
|
||||
# 줄 추가 — 기준 줄 위/아래(ref_row_id + place), 없으면 맨 끝. 다른 영역 줄 기준은 404, place 오류는 400
|
||||
add = lambda body, who=ADMIN: req( # noqa: E731
|
||||
"POST", f"/project/api/goals/areas/{aid}/rows", who, json=body)
|
||||
labels = lambda: [r["label"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
|
||||
before = labels()
|
||||
assert add({"label": "끝"}).status_code == 201
|
||||
assert add({"label": "아래", "ref_row_id": rid, "place": "below"}).status_code == 201
|
||||
assert add({"label": "위", "ref_row_id": rid, "place": "above"}).status_code == 201
|
||||
assert labels() == ["위", before[0], "아래"] + before[1:] + ["끝"], labels()
|
||||
areas = ST.get_goal_board(year=year)["areas"]
|
||||
if len(areas) > 1:
|
||||
assert add({"label": "x", "ref_row_id": areas[1]["rows"][0]["id"]}).status_code == 404
|
||||
assert add({"label": "x", "ref_row_id": rid, "place": "left"}).status_code == 400
|
||||
assert add({"label": "x", "ref_row_id": "abc"}).status_code == 400
|
||||
assert add({"label": "x"}, BOB).status_code == 403
|
||||
finally:
|
||||
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
|
||||
# 분기를 넘는 사각형(3~4월)은 400
|
||||
assert merge(r1, r2, 3, 4).status_code == 400
|
||||
# 사각형 2줄 × 2칸(4~5월) → 걸친 병합으로 넓히기: 5월 r2 ~ 6월 r3 → 4~6월 × r1~r3
|
||||
assert merge(r1, r2, 4, 5).json()["row_span"] == 2
|
||||
r = merge(r2, r3, 5, 6)
|
||||
assert r.json() == {"ok": True, "row_id": r1, "start": 4, "span": 3, "row_span": 3}, r.text
|
||||
assert rows()[0]["cells"].get(4) == "사월2"
|
||||
# 2분기 칸(15) 세로 병합(017)
|
||||
r = merge(r1, r2, 15, 15)
|
||||
assert r.status_code == 200 and r.json()["start"] == 15 and r.json()["row_span"] == 2, r.text
|
||||
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/15", ADMIN).status_code == 200
|
||||
# 세로 병합에 걸린 줄 이동 거절, 걸리지 않은 맨 아래 줄(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), 4: (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), 4: (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), 4: (3, 3)}
|
||||
# 해제 — 글은 왼쪽 위 칸에
|
||||
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/0", ADMIN).status_code == 200
|
||||
b = rows()
|
||||
assert b[0]["merges"] == {4: (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_label_groups():
|
||||
"""항목 칸(2열) 묶음(016): 3열 추가(same_label) 아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이 첫 줄(이름 넘겨받음),
|
||||
묶음 첫 줄 삭제 → 다음 줄이 첫 줄(이름 넘겨받음), 묶인 줄 이동 400, 항목 칸 나누기, 새 연도 복사에 묶음 유지."""
|
||||
year = 2060 + (int(RUN, 16) + 13) % 40
|
||||
for y in (year, year + 1):
|
||||
ST.delete_goal_year(year=y) if y 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)["groups"] is True, "마이그레이션 016 적용 필요"
|
||||
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
|
||||
rows = lambda: [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
|
||||
ids = lambda: [r["id"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
|
||||
first = ids()[0]
|
||||
assert req("PUT", f"/project/api/goals/rows/{first}", ADMIN, json={"label": "마케팅1"}).status_code == 200
|
||||
add = lambda body: req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json=body) # noqa: E731
|
||||
assert add({"ref_row_id": first, "place": "below", "same_label": True}).status_code == 201
|
||||
assert rows()[:2] == [("마케팅1", False), ("", True)]
|
||||
# 같은 항목 칸 위(첫 줄 위) — 새 줄이 첫 줄, 이름을 넘겨받고 예전 첫 줄은 이어 붙음
|
||||
r = add({"ref_row_id": first, "place": "above", "same_label": True})
|
||||
assert r.status_code == 201
|
||||
assert rows()[:3] == [("마케팅1", False), ("", True), ("", True)], rows()
|
||||
assert ids()[1] == first
|
||||
assert add({"same_label": True}).status_code == 400 # 기준 줄 없음
|
||||
# 묶인 줄 이동 거절
|
||||
assert req("POST", f"/project/api/goals/rows/{first}/move", ADMIN, json={"direction": 1}).status_code == 400
|
||||
# 묶음 첫 줄 삭제 → 다음 줄이 첫 줄 + 이름
|
||||
head = ids()[0]
|
||||
assert req("DELETE", f"/project/api/goals/rows/{head}", ADMIN).status_code == 200
|
||||
assert rows()[:2] == [("마케팅1", False), ("", True)], rows()
|
||||
# 새 연도 복사 — 묶음 유지
|
||||
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year + 1}).status_code == 201
|
||||
nxt = [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year + 1)["areas"][0]["rows"]]
|
||||
assert nxt[:2] == [("마케팅1", False), ("", True)], nxt
|
||||
# 항목 칸 나누기
|
||||
r = req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", ADMIN)
|
||||
assert r.status_code == 200 and r.json()["split"] == 1
|
||||
assert rows()[:2] == [("마케팅1", False), ("", False)]
|
||||
assert req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", BOB).status_code == 403
|
||||
finally:
|
||||
for y in (year, year + 1):
|
||||
ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _meet_weeks(seed: int, n: int) -> list[date]:
|
||||
"""지난 주들(실적 기간이 "진행 전"이 아니게) — test_goal_meetings(2001~2008)와 겹치지 않는 2010~2018 의 월요일 n 개."""
|
||||
base = date(2010, 1, 4) + timedelta(days=7 * ((int(RUN, 16) + seed * 60) % 400))
|
||||
assert base.weekday() == 0
|
||||
return [base + timedelta(days=7 * i) for i in range(n)]
|
||||
|
||||
|
||||
def _drop_meetings(weeks: list[date]) -> None:
|
||||
for w in weeks:
|
||||
try:
|
||||
ST.delete_meeting(week_start=w)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
def _create_meeting(w: date) -> None:
|
||||
r = req("POST", f"/project/api/goals/meetings/{w}", ADMIN, json={"year": w.year})
|
||||
assert r.status_code == 201, r.text
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [G4·G5] 회의록 "지난주" — 정확히 7일 전 주, 생성 순서·이름 변경·같은 이름·삭제/재생성과 무관(018 line_key)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_meeting_prev_week_links():
|
||||
"""지난주 = 정확히 7일 전 주 회의록의 같은 연결키 줄. 018 미적용이면 carry_from 이 7일 전 주일 때만."""
|
||||
w0, w1, w2, w3 = _meet_weeks(1, 4)
|
||||
_drop_meetings([w0, w1, w2, w3])
|
||||
with ST._pool.connection() as conn: # noqa: SLF001
|
||||
keyed = ST._meeting_keys(conn) # noqa: SLF001
|
||||
print(" meeting line_key(018):", "applied" if keyed else "not applied — carry_from fallback")
|
||||
try:
|
||||
# ① 역순 생성 — 다음 주(w3)를 먼저(양식), 앞 주(w2)를 나중에
|
||||
_create_meeting(w3)
|
||||
_create_meeting(w2)
|
||||
m3 = ST.get_meeting(week_start=w3)
|
||||
assert m3["prev_meeting"] is not None and m3["prev_meeting"]["week_start"] == w2.isoformat()
|
||||
if keyed:
|
||||
assert all(it["prev"] is not None for it in m3["items"]), "역순 생성인데 지난주 줄이 빠짐"
|
||||
for it in m3["items"]:
|
||||
assert it["prev"]["week_start"] == w2.isoformat()
|
||||
assert (it["prev"]["section"], it["prev"]["label"]) == (it["section"], it["label"])
|
||||
# 다른 구역의 같은 이름(마케팅 "네이버" ↔ 유통 "네이버")이 섞이지 않는다
|
||||
navers = [it for it in m3["items"] if it["label"] == "네이버"]
|
||||
assert len(navers) == 2 and len({it["prev"]["id"] for it in navers}) == 2
|
||||
assert all(it["prev"]["section"] == it["section"] for it in navers)
|
||||
else:
|
||||
assert all(it["prev"] is None for it in m3["items"]), "018 미적용 — 역순 생성 연결은 안 됨(문서화된 제한)"
|
||||
# ② 지난주(w2) 결과를 w2 줄에 저장 → w3 화면에서 보인다(그 주 데이터만)
|
||||
m2 = ST.get_meeting(week_start=w2)
|
||||
cou2 = next(it for it in m2["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||
assert req("PUT", f"/project/api/goals/meeting-items/{cou2['id']}", ADMIN,
|
||||
json={"content": "w2 쿠팡 행사", "target_amount": "100", "result_amount": "50"}).status_code == 200
|
||||
cou3 = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||
if keyed:
|
||||
assert cou3["prev"]["id"] == cou2["id"] and cou3["prev"]["content"] == "w2 쿠팡 행사"
|
||||
# ③ 이름 변경·순서 이동에도 연결 유지
|
||||
assert req("PUT", f"/project/api/goals/meeting-items/{cou3['id']}", ADMIN, json={"label": "쿠팡 로켓"}).status_code == 200
|
||||
assert req("POST", f"/project/api/goals/meeting-items/{cou3['id']}/move", ADMIN, json={"direction": -1}).status_code == 200
|
||||
again = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["id"] == cou3["id"])
|
||||
assert again["prev"]["id"] == cou2["id"]
|
||||
# ④ 같은 이름의 새 줄은 지난주와 연결되지 않고, 기존 줄 연결도 그대로
|
||||
r = req("POST", f"/project/api/goals/meetings/{w3}/items", ADMIN,
|
||||
json={"section": "유통", "label": "쿠팡", "ref_item_id": cou3["id"], "place": "below"})
|
||||
new_id = r.json()["id"]
|
||||
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
|
||||
assert items3[new_id]["prev"] is None and items3[cou3["id"]]["prev"]["id"] == cou2["id"]
|
||||
# ⑤ 앞 주 삭제 → 지난주 칸 빔, 다시 만들면(앞선 회의록 없음 → 다음 주 w3 양식·키) 다시 연결
|
||||
ST.delete_meeting(week_start=w2)
|
||||
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w3)["items"])
|
||||
_create_meeting(w2)
|
||||
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
|
||||
assert items3[cou3["id"]]["prev"] is not None and items3[cou3["id"]]["prev"]["week_start"] == w2.isoformat()
|
||||
assert items3[cou3["id"]]["prev"]["content"] == "" # 새 회의록 — 예전 글이 섞이지 않는다
|
||||
# ⑥ 한 주 건너뜀 — w0 를 만들고 w1 없이 w2 를 보면 지난주(w1) 자료 없음(w0 결과를 지난주로 보이지 않음)
|
||||
_drop_meetings([w2, w3])
|
||||
_create_meeting(w0)
|
||||
cou0 = next(it for it in ST.get_meeting(week_start=w0)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||
req("PUT", f"/project/api/goals/meeting-items/{cou0['id']}", ADMIN, json={"target_amount": "100", "result_amount": "50"})
|
||||
_create_meeting(w2)
|
||||
m2 = ST.get_meeting(week_start=w2)
|
||||
assert m2["prev_meeting"] is None and all(it["prev"] is None for it in m2["items"])
|
||||
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
|
||||
assert v["head"]["prev_exists"] is False and v["head"]["prev_target"] is None
|
||||
assert all(it["rate"] is None for it in v["meeting"]["items"])
|
||||
# w1 을 만들면 w2 의 지난주 = w1(그 주 줄, 비어 있음) — w0 의 50/100 이 아니다
|
||||
_create_meeting(w1)
|
||||
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
|
||||
assert v["head"]["prev_exists"] is True
|
||||
prevs = [it["prev"] for it in v["meeting"]["items"] if it["prev"]]
|
||||
if keyed:
|
||||
assert prevs and all(p["week_start"] == w1.isoformat() for p in prevs)
|
||||
assert all(p["week_start"] == w1.isoformat() for p in prevs)
|
||||
assert all(it["rate"] is None for it in v["meeting"]["items"])
|
||||
finally:
|
||||
_drop_meetings([w0, w1, w2, w3])
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [G6] 실적 조회 장애 ≠ 0원 — 목록 장애·매출 조회 장애·부분 실패·정상 0건·미연결·집계 쇼핑몰 없음
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _FakePerf:
|
||||
def __init__(self, *, list_error=False, sales_error=None, markets=None, amounts=None):
|
||||
self.list_error, self.sales_error = list_error, sales_error or (lambda a, b: False)
|
||||
self.markets = markets if markets is not None else [
|
||||
{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True}]
|
||||
self.amounts = amounts or {}
|
||||
self.calls = []
|
||||
|
||||
def list_marketplaces(self):
|
||||
if self.list_error:
|
||||
raise RuntimeError("perf db down")
|
||||
return self.markets
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
self.calls.append((start, end))
|
||||
if self.sales_error(start, end):
|
||||
raise RuntimeError("sales query failed")
|
||||
return {(d, c): v for (d, c), v in self.amounts.items() if start <= d <= end and c in codes}
|
||||
|
||||
def statuses(self):
|
||||
return {"coupang": {"last_success_sync_at": "2026-10-01T14:20:00+09:00"}}
|
||||
|
||||
|
||||
def test_meeting_perf_unknown_vs_zero():
|
||||
"""실적 모듈 장애는 미확인(None + head.unknown), 정상 무매출만 0. 의존하는 필요 매출·달성률도 미확인."""
|
||||
from app.modules.project import store
|
||||
|
||||
(w,) = _meet_weeks(2, 1)
|
||||
# 그 달 셋째 주 — 월 누적(1일~지난주 일요일)과 전주 결과(지난주 월~일) 조회 기간이 서로 다르게
|
||||
weeks = store.month_weeks(w.year, w.month)
|
||||
w = weeks[2][0]
|
||||
month_first = date(w.year, w.month, 1)
|
||||
_drop_meetings([w, w - timedelta(days=7)])
|
||||
orig_targets = ST.goal_month_targets
|
||||
ST.goal_month_targets = lambda **kw: {"sales_unit": "원", "sales_target": 1000.0, "sales_actual": None, "roas_target": None}
|
||||
try:
|
||||
_create_meeting(w - timedelta(days=7))
|
||||
_create_meeting(w)
|
||||
prev = ST.get_meeting(week_start=w - timedelta(days=7))
|
||||
cou_prev = next(it for it in prev["items"] if it["label"] == "쿠팡")
|
||||
req("PUT", f"/project/api/goals/meeting-items/{cou_prev['id']}", ADMIN, json={"target_amount": "100"})
|
||||
url = f"/project/api/goals/meetings/{w}?year={w.year}&month={w.month}"
|
||||
|
||||
def view(perf):
|
||||
APP.state.performance_store = perf
|
||||
try:
|
||||
r = req("GET", url, ADMIN)
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
finally:
|
||||
APP.state.performance_store = None
|
||||
|
||||
def coupang_row(v):
|
||||
return next(it for it in v["meeting"]["items"] if it["label"] == "쿠팡" and it["section"] == "유통")
|
||||
|
||||
# 실적 모듈 미연결 — perf False, 값 없음(미확인 아님)
|
||||
v = view(None)
|
||||
assert v["head"]["perf"] is False and v["head"]["perf_state"] == "off" and v["head"]["unknown"] == []
|
||||
# 쇼핑몰 목록 장애 — 0 이 아니라 미확인, 필요 매출도 계산하지 않음, 회의록은 열림
|
||||
v = view(_FakePerf(list_error=True))
|
||||
h = v["head"]
|
||||
assert h["perf"] is True and h["perf_state"] == "error"
|
||||
assert h["mtd"] is None and h["prev_result"] is None and h["need_per_week"] is None
|
||||
assert {"mtd", "prev_result"} <= set(h["unknown"]), h
|
||||
row = coupang_row(v)
|
||||
assert row["prev"]["auto_error"] is True and row["prev"]["result"] is None and row["rate"] is None
|
||||
assert row["market_unknown"] is True and row["market_off"] is False
|
||||
assert v["markets"] == []
|
||||
# 매출 조회 장애(목록은 정상) — 전부 미확인
|
||||
v = view(_FakePerf(sales_error=lambda a, b: True))
|
||||
h = v["head"]
|
||||
assert h["perf_state"] == "ok" and h["mtd"] is None and h["need_per_week"] is None
|
||||
assert {"mtd", "prev_result"} <= set(h["unknown"])
|
||||
assert coupang_row(v)["prev"]["auto_error"] is True and coupang_row(v)["rate"] is None
|
||||
# 정상 조회 0 건 — 진짜 0원(미확인 아님), 필요 매출 = 목표 ÷ 남은 주
|
||||
v = view(_FakePerf())
|
||||
h = v["head"]
|
||||
assert h["mtd"] == 0 and h["prev_result"] == 0 and h["unknown"] == [], h
|
||||
assert h["need_per_week"] == 1000 // h["weeks_left"]
|
||||
row = coupang_row(v)
|
||||
assert row["prev"]["auto_result"] == 0 and row["prev"]["auto_error"] is False and row["rate"] == 0.0
|
||||
assert h["fresh_oldest"] == "10/01 14:20" and "쿠팡 10/01 14:20" in h["fresh_tip"]
|
||||
# 부분 실패 — 월 누적(1일부터) 조회만 실패: 누적·필요 매출만 미확인, 전주 결과·줄 결과는 정상
|
||||
prev_start = w - timedelta(days=7)
|
||||
v = view(_FakePerf(sales_error=lambda a, b: a == month_first and a != prev_start,
|
||||
amounts={(prev_start, "coupang"): 70}))
|
||||
h = v["head"]
|
||||
assert "mtd" in h["unknown"] and "prev_result" not in h["unknown"], h
|
||||
assert h["mtd"] is None and h["need_per_week"] is None and h["prev_result"] == 70
|
||||
assert coupang_row(v)["prev"]["auto_result"] == 70 and coupang_row(v)["rate"] == 70.0
|
||||
# 매출 집계 쇼핑몰 없음 — 0 원으로 보이지 않게(empty, 미확인도 아님)
|
||||
v = view(_FakePerf(markets=[{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": False}]))
|
||||
assert v["head"]["perf_state"] == "empty" and v["head"]["mtd"] is None and v["head"]["unknown"] == []
|
||||
# 금주 목표 저장 응답 = 서버 확정값(원 정수)
|
||||
r = req("PUT", f"/project/api/goals/meetings/{w}", ADMIN, json={"week_target": "120만"})
|
||||
assert r.status_code == 200 and r.json()["week_target"] == 1_200_000
|
||||
finally:
|
||||
ST.goal_month_targets = orig_targets
|
||||
_drop_meetings([w, w - timedelta(days=7)])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
|
||||
Reference in New Issue
Block a user