Merge branch 'feat/project-creator-paste-inout-calendar-groups'
This commit is contained in:
@@ -60,6 +60,22 @@
|
||||
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
|
||||
- **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개).
|
||||
|
||||
## 상품 그룹·색상 (006, 2026-10-21)
|
||||
|
||||
- 옵션 → 상품 정보 위 **그룹** 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`).
|
||||
상품 줄 **그룹** 고르기 → 그 상품의 은 함유량·색상 = 그룹 값(자기 값 칸은 숨김·보존, 그룹 지우면 자기 값으로). 그룹 없는 상품은 상품마다.
|
||||
계산은 `db._PRODUCT_SELECT_006`(silver_pct·color = 그룹 적용 값, own_* = 자기 값) 한 곳 — 목록·발주서 제품 고르기·발주 품목 사본이 같은 값.
|
||||
- 색상 = 색없음·오렌지·파랑·회색·아이보리색(`store.COLORS` 키 none·orange·blue·gray·ivory → 이름·칸 색), 화면은 색 사각형 + 이름(`_macros.swatch`).
|
||||
- 발주 품목에 그때 색상 사본(`inout_order_lines.color`, 006 전 품목 NULL = 지금 상품 색상). **발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 그 색**(tr + 칸마다).
|
||||
- 006 확인(`groups_ready`)은 연결을 열기 **전에** — 미적용이면 1분 기억(발주 저장 트랜잭션 안에서 두 번째 연결을 잡아 동시 발주에서 풀이 바닥났었다).
|
||||
- 옵션 → 담당자 = 아이콘(구글 프로필 사진, 없으면 기본 아이콘) + 이름, 아래 이메일.
|
||||
|
||||
## 오른쪽 달력 (2026-10-21)
|
||||
|
||||
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html` 300px, 1100px 미만은 한 열). 달력 300×320, 스크롤해도 위에 붙음.
|
||||
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
|
||||
- 날짜 칸 = 발주(발주일, 파랑)·입고(입고일, 초록) 건수(취소된 발주 제외), 누르면 그날 목록 팝업 → 발주서. 달 이동은 새로고침 없이 `GET /inout/api/calendar?month=YYYY-MM`(`db.calendar`).
|
||||
|
||||
## 시각 / 날짜
|
||||
|
||||
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
|
||||
|
||||
+155
-10
@@ -8,10 +8,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from psycopg.errors import UndefinedColumn, UndefinedTable
|
||||
from psycopg.errors import UndefinedColumn, UndefinedTable, UniqueViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.datetime import TimestamptzLoader
|
||||
from psycopg_pool import ConnectionPool
|
||||
@@ -23,6 +24,15 @@ from . import store
|
||||
|
||||
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
|
||||
|
||||
# 상품 정보 + 그룹(006) — 그룹 상품은 그룹의 은 함유량·색상, 그룹 없는 상품은 자기 값(own_*).
|
||||
_PRODUCT_SELECT_006 = (
|
||||
"SELECT p.item_code, p.item_name, p.unit_price, p.weight_g, p.imported_at, p.updated_by, p.updated_at, "
|
||||
"p.group_id, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, "
|
||||
"CASE WHEN g.id IS NULL THEN p.silver_pct ELSE g.silver_pct END AS silver_pct, "
|
||||
"CASE WHEN g.id IS NULL THEN COALESCE(p.color, 'none') ELSE g.color END AS color "
|
||||
"FROM inout_products p LEFT JOIN inout_product_groups g ON g.id = p.group_id"
|
||||
)
|
||||
|
||||
|
||||
class OverReceipt(Exception):
|
||||
"""확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}]."""
|
||||
@@ -134,10 +144,21 @@ class InoutDBStore:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 발주서
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _ready_flags(self) -> tuple[bool, bool]:
|
||||
"""(004 상품 정보, 006 그룹·색상) — 발주 저장 트랜잭션을 열기 전에 확인해 _insert_line 에 넘긴다."""
|
||||
return self.products_ready(), self.groups_ready()
|
||||
|
||||
def _insert_line(self, conn: Any, order_id: int, line_no: int, ln: dict[str, Any], names: dict[str, str],
|
||||
specs: dict[str, dict[str, Any]]) -> None:
|
||||
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을 그때 값으로 함께 남긴다."""
|
||||
if self.products_ready():
|
||||
specs: dict[str, dict[str, Any]], ready: tuple[bool, bool]) -> None:
|
||||
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을(006 이면 색상도) 그때 값으로 함께 남긴다."""
|
||||
products_ok, groups_ok = ready
|
||||
if groups_ok: # 006 — 색상 사본도(그룹 상품은 그룹 색상)
|
||||
sp = specs.get(ln["item_code"]) or {}
|
||||
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct, color) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"],
|
||||
sp.get("unit_price"), sp.get("weight_g"), sp.get("silver_pct"), sp.get("color") or "none"))
|
||||
elif products_ok:
|
||||
sp = specs.get(ln["item_code"]) or {}
|
||||
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
@@ -150,6 +171,7 @@ class InoutDBStore:
|
||||
def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str,
|
||||
specs: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
"""data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {id, order_no}."""
|
||||
ready = self._ready_flags()
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
self._require_factory(conn, data["factory_id"])
|
||||
conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))")
|
||||
@@ -166,13 +188,14 @@ class InoutDBStore:
|
||||
(no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)),
|
||||
).fetchone()["id"]
|
||||
for i, ln in enumerate(data["lines"], start=1):
|
||||
self._insert_line(conn, oid, i, ln, names, specs or {})
|
||||
self._insert_line(conn, oid, i, ln, names, specs or {}, ready)
|
||||
return {"id": int(oid), "order_no": no}
|
||||
|
||||
def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str,
|
||||
specs: dict[str, dict[str, Any]] | None = None) -> None:
|
||||
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.
|
||||
이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004)."""
|
||||
ready = self._ready_flags()
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
head = self._lock_order(conn, order_id)
|
||||
if head["cancelled_at"]:
|
||||
@@ -194,7 +217,7 @@ class InoutDBStore:
|
||||
conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s",
|
||||
(i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"]))
|
||||
else:
|
||||
self._insert_line(conn, order_id, i, ln, names, specs or {})
|
||||
self._insert_line(conn, order_id, i, ln, names, specs or {}, ready)
|
||||
conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s",
|
||||
(data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id))
|
||||
|
||||
@@ -273,6 +296,11 @@ class InoutDBStore:
|
||||
by_receipt: dict[int, list[dict[str, Any]]] = {}
|
||||
for r in rlines:
|
||||
by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
|
||||
if any("color" in ln and ln["color"] is None for ln in lines): # 006 전 품목 = 지금 상품 색상
|
||||
cur = self.catalog_lookup([ln["item_code"] for ln in lines if ln["color"] is None])
|
||||
for ln in lines:
|
||||
if ln.get("color") is None and ln["item_code"] in cur:
|
||||
ln["color"] = cur[ln["item_code"]].get("color")
|
||||
lines = store.decorate_lines(lines)
|
||||
status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"]))
|
||||
return {**head, "lines": lines, "summary": store.summarize(lines), "status": status,
|
||||
@@ -531,9 +559,13 @@ class InoutDBStore:
|
||||
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
|
||||
|
||||
def list_products(self) -> list[dict[str, Any]]:
|
||||
"""상품 정보 — 006 이면 그룹 이름·그룹 적용 값(silver_pct·color)·상품 자기 값(own_*)까지."""
|
||||
if not self.products_ready():
|
||||
return []
|
||||
grouped = self.groups_ready()
|
||||
with self._pool.connection() as conn:
|
||||
if grouped:
|
||||
return conn.execute(_PRODUCT_SELECT_006 + " ORDER BY p.item_code").fetchall()
|
||||
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
|
||||
|
||||
def list_excluded(self) -> list[dict[str, Any]]:
|
||||
@@ -571,9 +603,25 @@ class InoutDBStore:
|
||||
return out
|
||||
|
||||
def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int:
|
||||
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션."""
|
||||
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션.
|
||||
006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다."""
|
||||
self._need_products()
|
||||
grouped = self.groups_ready() and any("group_id" in r for r in rows)
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
if grouped:
|
||||
known = {int(g["id"]) for g in conn.execute("SELECT id FROM inout_product_groups").fetchall()}
|
||||
for r in rows:
|
||||
gid = r.get("group_id")
|
||||
if gid is not None and int(gid) not in known:
|
||||
raise ValueError(f"{r['code']}: 없는 그룹입니다(다른 사람이 지웠을 수 있음 — 옵션을 다시 여세요).")
|
||||
hit = conn.execute(
|
||||
"UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, group_id=%s, color=%s, "
|
||||
"updated_by=%s, updated_at=now() WHERE item_code=%s RETURNING item_code",
|
||||
(r["unit_price"], r["weight_g"], r["silver_pct"], gid, r.get("color") or "none",
|
||||
_norm_email(by), r["code"])).fetchone()
|
||||
if not hit:
|
||||
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
|
||||
return len(rows)
|
||||
for r in rows:
|
||||
hit = conn.execute("UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, updated_by=%s, updated_at=now() "
|
||||
"WHERE item_code=%s RETURNING item_code",
|
||||
@@ -614,20 +662,117 @@ class InoutDBStore:
|
||||
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
if not esc:
|
||||
return []
|
||||
args = {"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}
|
||||
grouped = self.groups_ready()
|
||||
with self._pool.connection() as conn:
|
||||
if grouped: # 그룹 상품은 그룹의 은 함유량·색상
|
||||
return conn.execute(
|
||||
_PRODUCT_SELECT_006 + " WHERE p.item_code ILIKE %(q)s OR p.item_name ILIKE %(q)s "
|
||||
"ORDER BY (p.item_code ILIKE %(p)s) DESC, p.item_code LIMIT %(n)s", args).fetchall()
|
||||
return conn.execute(
|
||||
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products "
|
||||
"WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s "
|
||||
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s",
|
||||
{"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}).fetchall()
|
||||
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall()
|
||||
|
||||
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
|
||||
if not codes or not self.products_ready():
|
||||
return {}
|
||||
grouped = self.groups_ready()
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT * FROM inout_products WHERE item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
||||
if grouped: # 발주 품목 사본 = 그룹 적용 값
|
||||
rows = conn.execute(_PRODUCT_SELECT_006 + " WHERE p.item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
||||
else:
|
||||
rows = conn.execute("SELECT * FROM inout_products WHERE item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
||||
return {r["item_code"]: r for r in rows}
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상품 그룹(006) — 은 함유량·색상을 그룹에 한 번만. 그룹을 지우면 그 상품들은 그룹 없음(자기 값)으로.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def groups_ready(self) -> bool:
|
||||
"""006 이 적용됐나(그룹 표·상품 group_id·발주 품목 color). 적용됐으면 계속, 아직이면 1분 동안 기억한다 —
|
||||
부를 때마다 연결을 하나 더 잡지 않게(발주 저장 트랜잭션이 연결을 쥔 채 부르면 동시 발주에서 풀이 바닥난다).
|
||||
그래서 연결을 열기 전에 먼저 부른다."""
|
||||
if getattr(self, "_groups_ok", False):
|
||||
return True
|
||||
if time.monotonic() - getattr(self, "_groups_checked", -1e9) < 60:
|
||||
return False
|
||||
if not self.products_ready():
|
||||
return False
|
||||
with self._pool.connection() as conn:
|
||||
ok = bool(conn.execute(
|
||||
"SELECT to_regclass('public.inout_product_groups') IS NOT NULL "
|
||||
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' AND column_name = 'group_id') "
|
||||
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_order_lines' AND column_name = 'color') AS ok"
|
||||
).fetchone()["ok"])
|
||||
self._groups_ok = ok
|
||||
self._groups_checked = time.monotonic()
|
||||
return ok
|
||||
|
||||
def _need_groups(self) -> None:
|
||||
if not self.groups_ready():
|
||||
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
|
||||
|
||||
def list_groups(self) -> list[dict[str, Any]]:
|
||||
if not self.groups_ready():
|
||||
return []
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute(
|
||||
"SELECT g.*, (SELECT count(*) FROM inout_products p WHERE p.group_id = g.id)::int AS product_count "
|
||||
"FROM inout_product_groups g ORDER BY g.sort_order, g.name").fetchall()
|
||||
|
||||
def save_group(self, *, group_id: int | None, name: str, silver_pct: Any, color: str, sort_order: int, by: str) -> int:
|
||||
"""그룹 만들기·고치기(store.validate_group 를 거친 값). 같은 이름은 거절. 반환 = 그룹 id."""
|
||||
self._need_groups()
|
||||
try:
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
if group_id:
|
||||
row = conn.execute(
|
||||
"UPDATE inout_product_groups SET name=%s, silver_pct=%s, color=%s, sort_order=%s, updated_by=%s, "
|
||||
"updated_at=now() WHERE id=%s RETURNING id",
|
||||
(name, silver_pct, color, sort_order, _norm_email(by), group_id)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("그룹을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||
else:
|
||||
row = conn.execute(
|
||||
"INSERT INTO inout_product_groups (name, silver_pct, color, sort_order, updated_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
|
||||
(name, silver_pct, color, sort_order, _norm_email(by))).fetchone()
|
||||
except UniqueViolation:
|
||||
raise ValueError(f"같은 이름의 그룹이 있습니다: {name}") from None
|
||||
return int(row["id"])
|
||||
|
||||
def delete_group(self, group_id: int) -> str:
|
||||
"""그룹 지우기 — 그 그룹 상품은 그룹 없음(상품 자기 은 함유량·색상)으로. 지난 발주서는 그대로. 반환 = 이름."""
|
||||
self._need_groups()
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
row = conn.execute("DELETE FROM inout_product_groups WHERE id=%s RETURNING name", (group_id,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("그룹을 찾을 수 없습니다.")
|
||||
return str(row["name"])
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 달력(2026-10-21) — 화면 오른쪽 달력에 날짜별 발주(발주일)·입고(입고일). 취소된 발주는 뺀다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def calendar(self, start: date, end: date) -> dict[str, list[dict[str, Any]]]:
|
||||
with self._pool.connection() as conn:
|
||||
orders = conn.execute(
|
||||
"SELECT o.id, o.order_no, o.order_date, f.name AS factory_name, "
|
||||
"(SELECT COALESCE(sum(qty), 0) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS qty, "
|
||||
"(SELECT count(*) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS kinds, "
|
||||
"(SELECT l.item_name FROM inout_order_lines l WHERE l.order_id = o.id ORDER BY l.line_no LIMIT 1) AS first_item "
|
||||
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
|
||||
"WHERE o.cancelled_at IS NULL AND o.order_date BETWEEN %s AND %s ORDER BY o.order_date, o.id",
|
||||
(start, end)).fetchall()
|
||||
receipts = conn.execute(
|
||||
"SELECT r.id, r.order_id, r.receipt_date, o.order_no, f.name AS factory_name, "
|
||||
"COALESCE(sum(rl.qty), 0)::int AS qty "
|
||||
"FROM inout_receipts r JOIN inout_orders o ON o.id = r.order_id JOIN inout_factories f ON f.id = o.factory_id "
|
||||
"LEFT JOIN inout_receipt_lines rl ON rl.receipt_id = r.id "
|
||||
"WHERE o.cancelled_at IS NULL AND r.receipt_date BETWEEN %s AND %s "
|
||||
"GROUP BY r.id, o.order_no, f.name ORDER BY r.receipt_date, r.id",
|
||||
(start, end)).fetchall()
|
||||
return {"orders": orders, "receipts": receipts}
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -841,7 +841,8 @@ def _candidates() -> list[dict[str, str]]:
|
||||
out = []
|
||||
for u in user_store.list_all():
|
||||
if has_module(u, "inout"):
|
||||
out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or "")})
|
||||
out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or ""),
|
||||
"picture": str(u.get("picture") or "")}) # 옵션 → 담당자 = 아이콘 + 이름(2026-10-21)
|
||||
return sorted(out, key=lambda x: x["email"])
|
||||
|
||||
|
||||
@@ -852,13 +853,14 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
|
||||
for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다
|
||||
for e in emails:
|
||||
if e not in known:
|
||||
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"})
|
||||
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)", "picture": ""})
|
||||
known.add(e)
|
||||
reader = _items(request)
|
||||
products = st.list_products()
|
||||
for pr in products:
|
||||
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
|
||||
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
|
||||
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
|
||||
"fmt_num": store.fmt_num,
|
||||
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
|
||||
"settings": st.get_settings(), "settings_ready": st.settings_ready(),
|
||||
@@ -1013,7 +1015,14 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
|
||||
for r in (payload.get("rows") or [])[:5000]:
|
||||
code = str((r or {}).get("code") or "").strip().upper()
|
||||
try:
|
||||
rows.append({"code": code, **store.validate_product_values(r)})
|
||||
row = {"code": code, **store.validate_product_values(r)}
|
||||
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
|
||||
gid = str(r.get("group_id") or "").strip()
|
||||
if gid and not gid.isdigit():
|
||||
raise ValueError("그룹이 올바르지 않습니다.")
|
||||
row["group_id"] = int(gid) if gid else None
|
||||
row["color"] = store.norm_color(r.get("color"))
|
||||
rows.append(row)
|
||||
except ValueError as exc:
|
||||
errors.append(f"{code}: {exc}")
|
||||
if errors:
|
||||
@@ -1027,6 +1036,38 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
|
||||
return _options_done(request, f"상품 정보 {n}개를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/groups")
|
||||
async def settings_group_save(request: Request) -> Any:
|
||||
"""상품 그룹 만들기·고치기(006) — 이름·은 함유량·색상·순서. 그룹 상품 모두에 은 함유량·색상이 적용된다."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
form = await request.form()
|
||||
try:
|
||||
vals = store.validate_group(dict(form))
|
||||
gid = _opt_int(form.get("id"))
|
||||
st.save_group(group_id=gid, by=user.get("email", ""), **vals)
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"그룹 '{vals['name']}' 을(를) {'저장' if gid else '추가'}했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/groups/{group_id}/delete")
|
||||
def settings_group_delete(request: Request, group_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
try:
|
||||
name = st.delete_group(group_id)
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"그룹 '{name}' 을(를) 지웠습니다 — 그 상품들은 그룹 없음(상품마다 값)으로 바뀝니다.")
|
||||
|
||||
|
||||
@router.post("/settings/products/{code}/exclude")
|
||||
def settings_product_exclude(request: Request, code: str) -> Any:
|
||||
got = _ctx(request)
|
||||
@@ -1070,7 +1111,8 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
|
||||
"unit_price": store.fmt_num(r["unit_price"]) if r["unit_price"] is not None else "",
|
||||
"price": float(r["unit_price"]) if r["unit_price"] is not None else None,
|
||||
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
|
||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else ""} for r in rows]})
|
||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
|
||||
"color": r.get("color") or "none"} for r in rows]})
|
||||
reader = _items(request)
|
||||
if reader is None or not reader.enabled:
|
||||
return JSONResponse({"items": [], "enabled": False,
|
||||
@@ -1078,6 +1120,49 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
|
||||
return JSONResponse({"items": reader.search(q, limit=30), "enabled": True})
|
||||
|
||||
|
||||
@router.get("/api/calendar")
|
||||
def api_calendar(request: Request, month: str = "") -> JSONResponse:
|
||||
"""오른쪽 달력(2026-10-21) — month=YYYY-MM(없으면 이번 달) 앞뒤 주까지(6주 칸)의 날짜별 발주·입고.
|
||||
days = {"YYYY-MM-DD": {"orders": [...], "receipts": [...]}}, holidays = {"YYYY-MM-DD": 이름}."""
|
||||
from datetime import timedelta # noqa: WPS433
|
||||
|
||||
_user(request)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail="입출고 관리 DB 가 설정되지 않았습니다.")
|
||||
today = today_kst()
|
||||
try:
|
||||
y, m = (int(x) for x in month.split("-", 1)) if month else (today.year, today.month)
|
||||
first = date(y, m, 1)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="month 는 YYYY-MM 입니다.") from None
|
||||
start = first - timedelta(days=(first.weekday() + 1) % 7) # 일요일 시작
|
||||
end = start + timedelta(days=41)
|
||||
data = st.calendar(start, end)
|
||||
days: dict[str, dict[str, list[dict[str, Any]]]] = {}
|
||||
for o in data["orders"]:
|
||||
days.setdefault(o["order_date"].isoformat(), {"orders": [], "receipts": []})["orders"].append({
|
||||
"id": int(o["id"]), "order_no": o["order_no"], "factory": o["factory_name"], "qty": int(o["qty"]),
|
||||
"item": (o["first_item"] or "") + (f" 외 {int(o['kinds']) - 1}종" if int(o["kinds"]) > 1 else "")})
|
||||
for r in data["receipts"]:
|
||||
days.setdefault(r["receipt_date"].isoformat(), {"orders": [], "receipts": []})["receipts"].append({
|
||||
"id": int(r["id"]), "order_id": int(r["order_id"]), "order_no": r["order_no"], "factory": r["factory_name"],
|
||||
"qty": int(r["qty"])})
|
||||
holidays: dict[str, str] = {}
|
||||
try:
|
||||
from app.modules.project.store import holiday_name # noqa: WPS433 — 프로젝트 달력과 같은 공휴일 표
|
||||
d = start
|
||||
while d <= end:
|
||||
name = holiday_name(d.isoformat())
|
||||
if name:
|
||||
holidays[d.isoformat()] = name
|
||||
d += timedelta(days=1)
|
||||
except Exception: # noqa: BLE001 — 공휴일 표가 없어도 달력은 보인다
|
||||
holidays = {}
|
||||
return JSONResponse({"month": f"{first:%Y-%m}", "start": start.isoformat(), "end": end.isoformat(),
|
||||
"today": today.isoformat(), "days": days, "holidays": holidays})
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> dict[str, str]:
|
||||
return {"status": "ok" if _store(request) is not None else "not_configured"}
|
||||
|
||||
@@ -319,12 +319,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
rows = []
|
||||
for i, x in enumerate(lines, start=1):
|
||||
c = cells(x)
|
||||
# 색상 있는 품목(006) = 줄 전체 배경 그 색 — 메일 프로그램이 tr 배경을 무시하기도 해서 칸마다도 칠한다
|
||||
hexc = color_hex(x.get("color"))
|
||||
ctd = f"{td}background:{hexc};" if hexc else td
|
||||
tr_style = f' style="background:{hexc}"' if hexc else ""
|
||||
rows.append(
|
||||
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}{r}">{int(x["qty"]):,}</td>'
|
||||
f'<td style="{td}{r}">{e(c["price"])}</td><td style="{td}{r}">{e(c["amount"])}</td>'
|
||||
f'<td style="{td}{r}">{e(c["weight"])}</td><td style="{td}{r}">{e(c["pp_use"])}</td><td style="{td}{r}">{e(c["ag"])}</td>'
|
||||
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>')
|
||||
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
|
||||
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>'
|
||||
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
||||
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>'
|
||||
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
||||
foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else ""
|
||||
foot_pp = fmt_num(money["pp_kg"], 3) if money["pp_kg"] is not None else ""
|
||||
foot_use = fmt_num(money["pp_use_kg"], 3) if money["pp_use_kg"] is not None else ""
|
||||
@@ -437,8 +442,51 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
|
||||
|
||||
|
||||
def has_values(p: dict[str, Any]) -> bool:
|
||||
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||
return any(p.get(k) is not None for k in PRODUCT_LIMITS)
|
||||
"""단가·무게·은 함유량(·그룹·색상, 006) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
|
||||
or (p.get("color") or "none") != "none")
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
||||
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
||||
# 색상 = 키 → (이름, 칸 색). 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 칸 색(옅게 — 글자가 읽히게).
|
||||
# ════════════════════════════════════════════════════════════
|
||||
COLORS = {"none": ("색없음", ""), "orange": ("오렌지", "#FFD8B0"), "blue": ("파랑", "#CFE0FA"),
|
||||
"gray": ("회색", "#DDDFE3"), "ivory": ("아이보리색", "#FFF6D9")}
|
||||
MAX_GROUP_NAME = 100
|
||||
|
||||
|
||||
def norm_color(raw: Any) -> str:
|
||||
"""색상 키(none·orange·blue·gray·ivory). 빈칸 = none. 모르는 값은 ValueError."""
|
||||
key = str(raw if raw is not None else "").strip().lower() or "none"
|
||||
if key not in COLORS:
|
||||
raise ValueError("색상은 " + "·".join(v[0] for v in COLORS.values()) + " 중에서 고르세요.")
|
||||
return key
|
||||
|
||||
|
||||
def color_hex(key: Any) -> str:
|
||||
"""색상 키 → 칸 색(#RRGGBB). 색없음·모름 = ''."""
|
||||
return COLORS.get(str(key or "none"), ("", ""))[1]
|
||||
|
||||
|
||||
def color_name(key: Any) -> str:
|
||||
return COLORS.get(str(key or "none"), COLORS["none"])[0]
|
||||
|
||||
|
||||
def validate_group(values: dict[str, Any]) -> dict[str, Any]:
|
||||
"""그룹 저장 값 — 이름(필수, 100자)·은 함유량(빈칸 = 미입력)·색상·순서."""
|
||||
name = str(values.get("name") or "").strip()
|
||||
if not name:
|
||||
raise ValueError("그룹 이름을 넣으세요.")
|
||||
if len(name) > MAX_GROUP_NAME:
|
||||
raise ValueError(f"그룹 이름은 {MAX_GROUP_NAME}자까지입니다.")
|
||||
try:
|
||||
sort_order = int(str(values.get("sort_order") or "0").strip() or 0)
|
||||
except ValueError:
|
||||
raise ValueError("순서는 숫자로 넣으세요.") from None
|
||||
return {"name": name, "silver_pct": parse_decimal(values.get("silver_pct"), key="silver_pct"),
|
||||
"color": norm_color(values.get("color")), "sort_order": max(-9999, min(9999, sort_order))}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{# 오른쪽 달력(2026-10-21) — 입출고 모든 화면 오른쪽 위 300×320, 오른쪽 열 너비 = 달력 너비.
|
||||
프로젝트 달력과 같은 모양(일요일 시작 · 요일 줄 회색 · 오늘 검은 동그라미 · 토 파랑 · 일/공휴일 빨강 · 다른 달 흐리게).
|
||||
날짜 칸 = 발주(발주일, 파랑) · 입고(입고일, 초록) 건수, 누르면 그날 목록(발주서로 이동). 내용은 inout.js 가 GET /inout/api/calendar 로 그린다. #}
|
||||
<aside class="io-side" aria-label="발주·입고 달력">
|
||||
<div class="io-cal" id="io-cal" data-month="{{ today.strftime('%Y-%m') }}">
|
||||
<div class="io-cal-head">
|
||||
<button type="button" class="io-cal-nav" data-step="-1" aria-label="이전 달" title="이전 달">‹</button>
|
||||
<h3 class="io-cal-title" aria-live="polite">{{ today.year }}년 {{ today.month }}월</h3>
|
||||
<button type="button" class="io-cal-nav" data-step="1" aria-label="다음 달" title="다음 달">›</button>
|
||||
<button type="button" class="io-cal-today">오늘</button>
|
||||
</div>
|
||||
<div class="io-cal-box">
|
||||
<div class="io-cal-wd" aria-hidden="true">
|
||||
<span class="is-sun">일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span>
|
||||
</div>
|
||||
<div class="io-cal-days" role="grid"></div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="io-cal-legend"><i class="io-cal-m is-order">n</i>발주 <i class="io-cal-m is-receipt">n</i>입고 <span class="io-sub">· 날짜를 누르면 목록</span></p>
|
||||
</aside>
|
||||
@@ -26,3 +26,8 @@
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
|
||||
|
||||
{# 색상 사각형(006) — 색이 칠해진 네모. 색없음은 빗금 없는 흰 네모 + 테두리. colors = store.COLORS #}
|
||||
{% macro swatch(key, colors) -%}
|
||||
<i class="io-swatch{% if not colors.get(key or 'none', ('', ''))[1] %} is-none{% endif %}" style="background:{{ colors.get(key or 'none', ('', ''))[1] or '#fff' }}" aria-hidden="true"></i>
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{% from "inout/_macros.html" import ymd %}
|
||||
{% from "inout/_macros.html" import ymd, swatch %}
|
||||
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
|
||||
공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}
|
||||
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
|
||||
@@ -20,7 +20,11 @@
|
||||
<tbody>
|
||||
{% for c in candidates %}
|
||||
<tr>
|
||||
<td><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></td>
|
||||
<td><span class="io-person">
|
||||
{% if c.picture %}<img class="io-avatar" src="{{ c.picture }}" alt="" referrerpolicy="no-referrer" loading="lazy" />
|
||||
{% else %}<svg class="io-avatar io-avatar-empty" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="12" fill="#d5d9de"/><circle cx="12" cy="9.5" r="4" fill="#fff"/><path d="M4.6 19.6a8.6 8.6 0 0 1 14.8 0A11.9 11.9 0 0 1 12 24a11.9 11.9 0 0 1-7.4-4.4z" fill="#fff"/></svg>{% endif %}
|
||||
<span class="io-person-text"><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></span>
|
||||
</span></td>
|
||||
{% for role in role_labels %}
|
||||
<td class="io-c"><input type="checkbox" name="{{ role }}_email" value="{{ c.email }}" {% if c.email in roles[role] %}checked{% endif %}
|
||||
aria-label="{{ c.email }} {{ role_labels[role] }}" /></td>
|
||||
@@ -88,7 +92,50 @@
|
||||
<p class="io-help">
|
||||
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
|
||||
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
||||
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(그룹에서 한 번만 설정). 색상 있는 품목은 발주 메일 표에서 그 줄 배경이 그 색입니다.{% endif %}
|
||||
</p>
|
||||
{% if groups_ready %}
|
||||
{% for g in groups %}<form method="post" action="/inout/settings/groups" id="io-g{{ g.id }}" class="io-dlg-form io-group-form"><input type="hidden" name="id" value="{{ g.id }}" /></form>{% endfor %}
|
||||
<form method="post" action="/inout/settings/groups" id="io-gnew" class="io-dlg-form io-group-form"></form>
|
||||
<details class="io-groups" open>
|
||||
<summary>그룹 {{ groups|length }}개 — 은 함유량·색상을 그룹마다 한 번만</summary>
|
||||
<table class="io-dlg-table io-group-table">
|
||||
<colgroup><col class="w-gname" /><col class="w-num" /><col class="w-color" /><col class="w-sort" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
|
||||
<thead><tr><th>그룹 이름</th><th class="io-r">은 함유량(%)</th><th>색상</th><th class="io-c">순서</th><th class="io-c">상품</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for g in groups %}
|
||||
{% set gf = 'io-g' ~ g.id %}
|
||||
<tr>
|
||||
<td><input class="io-in" form="{{ gf }}" type="text" name="name" value="{{ g.name }}" maxlength="100" required aria-label="그룹 이름" /></td>
|
||||
<td><input class="io-in io-in-num" form="{{ gf }}" type="text" name="silver_pct" value="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ g.name }} 은 함유량" /></td>
|
||||
<td><span class="io-color">{{ swatch(g.color, colors) }}<select class="io-in io-color-select" form="{{ gf }}" name="color" aria-label="{{ g.name }} 색상">
|
||||
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if g.color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
|
||||
</select></span></td>
|
||||
<td class="io-c"><input class="io-in io-in-num" form="{{ gf }}" type="number" name="sort_order" value="{{ g.sort_order }}" aria-label="순서" /></td>
|
||||
<td class="io-c io-sub">{{ g.product_count }}개</td>
|
||||
<td class="io-btns">
|
||||
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
|
||||
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/groups/{{ g.id }}/delete"
|
||||
formnovalidate data-confirm="그룹 '{{ g.name }}' 을(를) 지울까요? 그룹 상품 {{ g.product_count }}개는 그룹 없음(상품마다 값)으로 바뀝니다.">지우기</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
<tr class="io-new-row">
|
||||
<td><input class="io-in" form="io-gnew" type="text" name="name" maxlength="100" required placeholder="새 그룹 이름" aria-label="새 그룹 이름" /></td>
|
||||
<td><input class="io-in io-in-num" form="io-gnew" type="text" name="silver_pct" inputmode="decimal" placeholder="%" aria-label="새 그룹 은 함유량" /></td>
|
||||
<td><span class="io-color">{{ swatch('none', colors) }}<select class="io-in io-color-select" form="io-gnew" name="color" aria-label="새 그룹 색상">
|
||||
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}">{{ c[0] }}</option>{% endfor %}
|
||||
</select></span></td>
|
||||
<td class="io-c"><input class="io-in io-in-num" form="io-gnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
|
||||
<td></td>
|
||||
<td class="io-btns"><button form="io-gnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
{% else %}
|
||||
<p class="io-error">상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.</p>
|
||||
{% endif %}
|
||||
<div class="io-prod-bar">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||
<input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
|
||||
@@ -98,18 +145,32 @@
|
||||
</div>
|
||||
{% if products %}
|
||||
<div class="io-prod-scroll">
|
||||
<table class="io-dlg-table io-prod-table">
|
||||
<colgroup><col class="w-code" /><col /><col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" /><col class="w-del" /></colgroup>
|
||||
<thead><tr><th>코드</th><th>제품명</th><th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th><th></th></tr></thead>
|
||||
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
|
||||
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
|
||||
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for p in products %}
|
||||
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name)|lower }}">
|
||||
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
|
||||
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
|
||||
<td class="io-code">{{ p.item_code }}</td>
|
||||
<td class="io-prod-name">{{ p.item_name }}</td>
|
||||
{% if groups_ready %}
|
||||
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
|
||||
<option value="" data-silver="" data-color="">그룹 없음</option>
|
||||
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
|
||||
</select></td>
|
||||
{% endif %}
|
||||
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="silver_pct" value="{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" /></td>
|
||||
<td><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
|
||||
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
|
||||
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
||||
{% if groups_ready %}
|
||||
<td><span class="io-color io-own">{{ swatch(p.own_color, colors) }}<select class="io-in io-color-select" data-key="color" aria-label="{{ p.item_code }} 색상">
|
||||
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if p.own_color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
|
||||
</select></span>
|
||||
<span class="io-color io-group-val" title="그룹 값 — 그룹에서 바꿉니다">{{ swatch(p.color, colors) }}<span class="io-color-name">{{ colors[p.color][0] if p.color in colors else '' }}</span></span></td>
|
||||
{% endif %}
|
||||
<td class="io-r"><button type="button" class="io-icon-btn" data-exclude="{{ p.item_code }}" title="지우기 — 다음 불러오기에서도 뺌" aria-label="{{ p.item_code }} 지우기">✕</button></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
<section class="io">
|
||||
{% include "inout/_nav.html" %}
|
||||
|
||||
@@ -67,5 +68,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</footer>
|
||||
</dialog>
|
||||
{%- endmacro -%}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% set active = order.status in ('open', 'partial') %}
|
||||
@@ -29,6 +29,7 @@
|
||||
{% set recv_done = order.status in ('done', 'over') %}
|
||||
{% set dis = ' disabled' if recv_done else '' %}
|
||||
{% set photo_admin = perms.can_receive and not order.cancelled_at %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
<section class="io">
|
||||
{% include "inout/_nav.html" %}
|
||||
|
||||
@@ -252,5 +253,7 @@
|
||||
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
|
||||
{% endif %}
|
||||
</section>
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
<section class="io">
|
||||
{% include "inout/_nav.html" %}
|
||||
|
||||
@@ -79,5 +80,7 @@
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
<section class="io">
|
||||
{% include "inout/_nav.html" %}
|
||||
|
||||
@@ -87,5 +88,7 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
|
||||
|
||||
@@ -58,6 +58,9 @@
|
||||
## 업무 창 / 댓글 / 협업자
|
||||
|
||||
- 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성).
|
||||
- 업무 창 맨 위 **삭제 오른쪽 = 작성자**(2026-10-21, `showTaskCreator` — `created_by` 아이콘 + 이름(yyyy.mm.dd(요일) hh:mm:ss), `created_at` KST ISO 글자를 그대로 잘라 씀, 세부 업무도).
|
||||
- 업무 창 댓글 칸 **Ctrl+V 이미지 붙여넣기**(2026-10-21) — 칸 위 썸네일(×로 빼기) → [등록] = `POST …/comments/files` 한 요청(댓글 대화창과 같은 API, 글 없이 이미지만도), 업무를 바꾸면 비움.
|
||||
복사한 내용에 글자가 있으면 글자 붙여넣기가 먼저(대화창과 같음). 브라우저 테스트 `tests/js/task_creator_paste.browser.test.js`.
|
||||
- **파일 끌어 놓기**(2026-10-19): 종류 "Files" 로 카드·세부 업무 끌기와 구분, 받는 곳 밖에 놓친 파일은 document 가 막아 화면이 파일로 넘어가지 않음.
|
||||
- **설명란·세부 업무 목록·보드 카드(펼친 세부 업무 줄) → 구글 드라이브**: `POST /project/api/tasks/{id}/drive-files`(`app/integrations/google_drive.py`, 최상위 `PROJECT_DRIVE_FOLDER_ID` 기본 `1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG` 아래 `프로젝트/섹션/업무/세부 업무` 폴더 자동, 세부 업무 섹션 = 맨 위 업무 섹션). 링크 제목 = 파일 이름.확장자(새 탭). 설명란 = 놓은 자리(`descEditor.insertDriveFiles`, 올리는 중 표시·저장 미룸), 세부 업무 줄·카드 = `append=true` 로 서버가 설명 끝에 붙임 — 단 지금 업무 창에 열린 업무면 편집기 끝에(옛 설명 저장이 링크를 덮지 않게, `dropDriveFilesOnTask`).
|
||||
- **링크를 지우면 드라이브 휴지통**: `api_update_task` 가 설명 저장 전후 드라이브 링크 id 를 비교 → 백그라운드 `_sync_drive_links` — 우리가 올린 파일(appProperties `dbxTaskId`)만, 다른 업무 설명에 같은 링크가 있으면 그대로(`db.description_mentions`), 링크가 다시 생기면 휴지통에서 꺼냄. DB 변경 없음.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -289,5 +289,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project.js?v=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -326,6 +326,7 @@
|
||||
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 업무의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 업무를 엽니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>업무를 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
||||
<tr><td><span class="pjh-ui">삭제</span></td><td>업무를 지웁니다(만든 사람만). 세부 업무가 있으면 함께 지울지 한 번 더 묻습니다. 지운 업무는 휴지통에 3개월 보관됩니다.</td></tr>
|
||||
<tr><td>작성자</td><td><span class="pjh-ui">삭제</span> 오른쪽에 업무를 만든 사람(아이콘 + 이름)과 만든 시각 <b>yyyy.mm.dd(요일) hh:mm:ss</b>가 보입니다. 세부 업무도 같습니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 업무를 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
||||
</table>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
@@ -373,6 +374,7 @@
|
||||
<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>캡처한 이미지를 댓글 칸에 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여넣으면 칸 위에 작은 미리보기로 담기고(<span class="pjh-ui">×</span>로 빼기), <span class="pjh-ui">등록</span>하면 글과 함께 댓글 첨부로 올라갑니다. 글 없이 이미지만 보내도 됩니다. 복사한 내용에 글자가 함께 있으면 글자가 붙습니다.</p>
|
||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 업무를 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -106,5 +106,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -244,6 +244,8 @@
|
||||
</button>
|
||||
<button type="button" class="pj-btn pj-btn-complete" id="pj-toggle-complete" hidden>✓ 완료로 표시</button>
|
||||
<button type="button" class="pj-btn pj-btn-danger" id="pj-delete-task" hidden>삭제</button>
|
||||
<!-- 작성자 — 아이콘 + 이름(yyyy.mm.dd(요일) hh:mm:ss), 만든 사람(created_by)이 있는 업무만(2026-10-21). -->
|
||||
<span class="pj-task-creator" id="pj-task-creator" hidden></span>
|
||||
<!-- 수신함 오른쪽 패널(?embed=1)에서만 보인다 — 이 작업이 있는 프로젝트 화면으로 이동. -->
|
||||
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 업무가 있는 프로젝트 화면으로 이동">
|
||||
<span class="material-symbols-outlined">open_in_new</span> 프로젝트로 이동
|
||||
@@ -400,6 +402,8 @@
|
||||
<!-- 댓글 입력칸 — 아사나처럼 작업 창 맨 아래에 항상 고정. 스크롤 영역(.pj-modal-body)
|
||||
바깥이라 끝까지 내려도 마지막 내용은 이 칸 바로 위에서 멈추고 가리지 않는다. -->
|
||||
<div class="pj-comment-dock" id="pj-comment-dock" hidden>
|
||||
<!-- Ctrl+V 로 붙여넣은 이미지(보내기 전) — 썸네일 + ×, 등록하면 댓글 첨부로 같이 간다(2026-10-21). -->
|
||||
<div class="pj-comment-pending" id="pj-comment-pending" hidden></div>
|
||||
<div class="pj-comment-form">
|
||||
<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>
|
||||
@@ -472,5 +476,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261021a" />
|
||||
<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=20261019g" defer></script>
|
||||
<script src="/static/project.js?v=20261021a" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
+96
-1
@@ -1,6 +1,6 @@
|
||||
/* 입출고 관리(inout) — ERP 공용(erp.css·erp-shell.css) 위에 이 화면만의 것 */
|
||||
/* 공용 .erp-page 는 width:100% + 안쪽 여백(content-box)이라 표가 넓으면 48px 넘친다 — 이 화면에서만 테두리 기준으로 */
|
||||
.erp-page:has(> .io) { box-sizing: border-box; }
|
||||
.erp-page:has(> .io), .erp-page:has(> .io-split) { box-sizing: border-box; }
|
||||
.io { display: flex; flex-direction: column; gap: 14px; min-width: 0; } /* 넓은 표는 안에서 가로 스크롤(페이지가 화면보다 넓어지지 않게) */
|
||||
.io-nav { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.io-nav-gap { flex: 1 1 auto; }
|
||||
@@ -321,3 +321,98 @@
|
||||
.io-receipt-bar #io-fill-remaining.is-filled { border-color: #1e7a34; color: #1e7a34; background: #f3fbf5; }
|
||||
/* 발주 메일 창 — 입고 담당 발주 알림 자동 발송 안내 */
|
||||
.io-mail-notice { margin: -4px 0 12px; padding: 8px 12px; border-radius: 8px; background: #f0f6ff; border: 1px solid #cfe0fb; color: #1d4f91; font-size: 12.5px; }
|
||||
|
||||
/* ── 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21). 오른쪽 열 너비 = 달력 너비(300px), 스크롤해도 위에 붙어 있음.
|
||||
좁은 화면(1100px 미만)은 한 열 — 달력은 아래로. ── */
|
||||
.io-split { display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 20px; align-items: start; }
|
||||
.io-split > .io { min-width: 0; }
|
||||
.io-side { width: 300px; position: sticky; top: 12px; display: flex; flex-direction: column; gap: 6px; }
|
||||
@media (max-width: 1100px) {
|
||||
.io-split { grid-template-columns: minmax(0, 1fr); }
|
||||
.io-side { position: static; }
|
||||
}
|
||||
/* 달력 300×320 — 프로젝트 달력 모양(.pj-cal)을 작게: 머리(제목 ‹ › 오늘) + 둥근 테두리 안 요일 줄(회색) + 6주 */
|
||||
.io-cal { width: 300px; height: 320px; box-sizing: border-box; display: flex; flex-direction: column; }
|
||||
.io-cal.is-loading .io-cal-days { opacity: .55; }
|
||||
.io-cal-head { flex: none; height: 36px; display: flex; align-items: center; gap: 4px; }
|
||||
.io-cal-title { margin: 0 2px; font-size: 16px; font-weight: 600; letter-spacing: -0.3px; white-space: nowrap; color: #0a0a0a; }
|
||||
.io-cal-nav, .io-cal-today {
|
||||
border: 1px solid var(--color-subtle-ash, #e5e5e5); background: #fff; border-radius: 8px; cursor: pointer; color: #0a0a0a;
|
||||
height: 28px; line-height: 1; padding: 0 9px; font-size: 13px;
|
||||
}
|
||||
.io-cal-nav { font-size: 18px; padding: 0 8px; }
|
||||
.io-cal-nav:hover, .io-cal-today:hover { background: #f5f5f5; }
|
||||
.io-cal-today { margin-left: auto; }
|
||||
.io-cal-box { flex: 1 1 auto; min-height: 0; border: 1px solid #e5e5e5; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; background: #fff; }
|
||||
.io-cal-wd { flex: none; display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); background: #f2f2f2; border-bottom: 1px solid #e5e5e5; }
|
||||
.io-cal-wd span { text-align: center; padding: 4px 0; font-size: 12px; font-weight: 600; color: #0a0a0a; }
|
||||
.io-cal-wd .is-sun { color: #c22b10; }
|
||||
.io-cal-wd .is-sat { color: #1d4ed8; }
|
||||
.io-cal-days { flex: 1 1 auto; min-height: 0; display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); grid-template-rows: repeat(6, minmax(0, 1fr)); }
|
||||
.io-cal-day {
|
||||
all: unset; box-sizing: border-box; min-width: 0; min-height: 0; padding: 3px 3px 2px; cursor: default;
|
||||
display: flex; flex-direction: column; align-items: center; gap: 1px;
|
||||
border-right: 1px solid #efefef; border-bottom: 1px solid #efefef;
|
||||
}
|
||||
.io-cal-day:nth-child(7n) { border-right: 0; }
|
||||
.io-cal-day:nth-last-child(-n+7) { border-bottom: 0; }
|
||||
.io-cal-day.has-ev { cursor: pointer; }
|
||||
.io-cal-day.has-ev:hover { background: #f2f6ff; }
|
||||
.io-cal-day:focus-visible { outline: 2px solid #1d4ed8; outline-offset: -2px; }
|
||||
.io-cal-num { font-size: 12px; font-weight: 600; color: #0a0a0a; line-height: 18px; min-width: 18px; text-align: center; border-radius: 9999px; }
|
||||
.io-cal-day.is-sun .io-cal-num { color: #c22b10; }
|
||||
.io-cal-day.is-sat .io-cal-num { color: #1d4ed8; }
|
||||
.io-cal-day.is-out { background: #fafafa; }
|
||||
.io-cal-day.is-out .io-cal-num { color: #bbb; }
|
||||
.io-cal-day.is-today { background: #f5f5f5; }
|
||||
.io-cal-day.is-today .io-cal-num { background: #0a0a0a; color: #fff; padding: 0 5px; }
|
||||
.io-cal-day.is-today.is-sun .io-cal-num { background: #c22b10; color: #fff; }
|
||||
.io-cal-day.is-today.is-sat .io-cal-num { background: #1d4ed8; color: #fff; }
|
||||
.io-cal-marks { display: flex; gap: 2px; flex-wrap: wrap; justify-content: center; }
|
||||
.io-cal-m { font-style: normal; display: inline-block; min-width: 14px; height: 14px; line-height: 14px; padding: 0 3px; box-sizing: border-box;
|
||||
border-radius: 7px; font-size: 10px; font-weight: 700; color: #fff; text-align: center; }
|
||||
.io-cal-m.is-order { background: #2f6fde; }
|
||||
.io-cal-m.is-receipt { background: #1e8e5a; }
|
||||
.io-cal-err { grid-column: 1 / -1; margin: auto; font-size: 12px; color: #a1261b; }
|
||||
.io-cal-legend { margin: 0; font-size: 11.5px; color: var(--color-midtone-gray, #666); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
|
||||
.io-cal-legend .io-cal-m { margin-left: 4px; }
|
||||
.io-cal-legend .io-cal-m:first-child { margin-left: 0; }
|
||||
/* 그날 목록 팝업 — 프로젝트 달력 .pj-daypop 모양 */
|
||||
.io-calpop { position: absolute; z-index: 2100; width: 280px; max-height: 320px; overflow: auto; background: #fff; border: 1px solid #e2e5e9;
|
||||
border-radius: 12px; box-shadow: 0 8px 28px rgba(0,0,0,.16); padding: 8px; box-sizing: border-box; }
|
||||
.io-calpop-head { font-size: 12px; font-weight: 700; color: #525860; padding: 4px 6px 8px; }
|
||||
.io-calpop-head .is-hol { color: #c22b10; }
|
||||
.io-calpop-item { display: grid; grid-template-columns: auto minmax(0, 1fr); column-gap: 8px; align-items: center; padding: 6px; border-radius: 8px;
|
||||
text-decoration: none; color: #1e1f21; font-size: 12.5px; }
|
||||
.io-calpop-item:hover { background: #f2f4f6; }
|
||||
.io-calpop-item .io-cal-m { grid-row: span 2; height: 18px; line-height: 18px; border-radius: 9px; padding: 0 6px; font-size: 11px; }
|
||||
.io-calpop-main { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.io-calpop-sub { color: #6b6f76; font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* ── 옵션 → 담당자: 아이콘 + 이름, 아래 이메일(2026-10-21) ── */
|
||||
.io-person { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.io-avatar { flex: none; width: 28px; height: 28px; border-radius: 50%; object-fit: cover; }
|
||||
.io-person-text { display: flex; flex-direction: column; line-height: 1.3; }
|
||||
.io-person-text .io-sub { display: block; }
|
||||
|
||||
/* ── 옵션 → 상품 정보: 그룹·색상(2026-10-21, 006) ── */
|
||||
.io-swatch { display: inline-block; flex: none; width: 14px; height: 14px; border-radius: 3px; border: 1px solid rgba(0,0,0,.18); vertical-align: middle; box-sizing: border-box; }
|
||||
.io-swatch.is-none { background: #fff !important; border-style: dashed; border-color: #b9bdc3; }
|
||||
.io-color { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.io-color .io-color-select { width: auto; min-width: 96px; }
|
||||
.io-groups { margin: 12px 20px 0; border: 1px solid #e6e8eb; border-radius: 10px; padding: 8px 10px; background: #fbfbfc; }
|
||||
.io-groups > summary { cursor: pointer; font-weight: 600; font-size: 13px; padding: 2px 0 6px; }
|
||||
.io-group-table col.w-gname { width: auto; }
|
||||
.io-group-table col.w-num { width: 120px; }
|
||||
.io-group-table col.w-color { width: 170px; }
|
||||
.io-group-table col.w-sort { width: 72px; }
|
||||
.io-group-table col.w-cnt { width: 60px; }
|
||||
.io-group-table col.w-btn { width: 128px; }
|
||||
.io-prod-table col.w-group { width: 130px; }
|
||||
.io-prod-table col.w-color { width: 150px; }
|
||||
.io-prod-table .io-group-select { width: 100%; }
|
||||
.io-prod-table .io-group-val { display: none; color: #4b5563; }
|
||||
.io-prod-table tr.is-grouped .io-own { display: none; }
|
||||
.io-prod-table tr.is-grouped .io-group-val { display: inline-flex; }
|
||||
.io-prod-table tr.is-grouped .io-group-val.io-r { display: block; padding-right: 9px; font-variant-numeric: tabular-nums; }
|
||||
.io-prod-table tr.is-grouped td:has(> .io-group-val) { background: #f6f8fb; }
|
||||
|
||||
+161
-6
@@ -332,6 +332,9 @@
|
||||
e.preventDefault();
|
||||
const sub = e.submitter;
|
||||
if (sub && sub.dataset.confirm && !(await confirmMsg(sub.dataset.confirm))) return;
|
||||
// 그룹 저장은 옵션을 다시 그린다 — 저장 안 한 상품 정보 변경이 사라지기 전에 묻는다
|
||||
if (form.classList.contains("io-group-form") && dirtyRows().length &&
|
||||
!(await confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 버리고 그룹을 저장할까요?"))) return;
|
||||
const action = sub && sub.getAttribute("formaction") ? sub.getAttribute("formaction") : form.getAttribute("action");
|
||||
const buttons = Array.from(dlg.querySelectorAll("button[type=submit]"));
|
||||
buttons.forEach(function (b) { b.disabled = true; });
|
||||
@@ -351,10 +354,43 @@
|
||||
}
|
||||
});
|
||||
// ── 상품 정보 탭(004) — 단가·무게·은 함유량, 바뀐 줄만 [변경 저장], 불러오기·지우기·되살리기 ──
|
||||
// 006: 그룹(select)·색상(select) — 그룹 상품은 은 함유량·색상을 그룹 값으로 보여 준다(자기 값 칸은 숨김, 저장은 그대로).
|
||||
function isChanged(el) {
|
||||
if (el.tagName === "SELECT") {
|
||||
const d = Array.from(el.options).find(function (o) { return o.defaultSelected; }) || el.options[0];
|
||||
return el.value !== (d ? d.value : "");
|
||||
}
|
||||
return el.value.trim() !== el.defaultValue.trim();
|
||||
}
|
||||
function rowChanged(tr) { return Array.from(tr.querySelectorAll("[data-key]")).some(isChanged); }
|
||||
function dirtyRows() {
|
||||
return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(function (tr) {
|
||||
return Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); });
|
||||
});
|
||||
return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(rowChanged);
|
||||
}
|
||||
function paintSwatch(sel) {
|
||||
const sw = sel.parentNode && sel.parentNode.querySelector(".io-swatch");
|
||||
const opt = sel.options[sel.selectedIndex];
|
||||
const hex = opt ? opt.dataset.hex : "";
|
||||
if (!sw) return;
|
||||
sw.style.background = hex || "#fff";
|
||||
sw.classList.toggle("is-none", !hex);
|
||||
}
|
||||
// 그룹을 바꾸면 그 줄의 그룹 값(은 함유량·색상)을 고른 그룹 것으로 다시 보여 준다
|
||||
function paintGroup(tr) {
|
||||
const sel = tr.querySelector(".io-group-select");
|
||||
if (!sel) return;
|
||||
const opt = sel.options[sel.selectedIndex];
|
||||
const grouped = !!sel.value;
|
||||
tr.classList.toggle("is-grouped", grouped);
|
||||
const vals = tr.querySelectorAll(".io-group-val");
|
||||
if (vals[0]) vals[0].textContent = (opt && opt.dataset.silver) || "-";
|
||||
if (vals[1]) {
|
||||
const key = (opt && opt.dataset.color) || "none";
|
||||
const csel = tr.querySelector(".io-color-select");
|
||||
const copt = csel && Array.from(csel.options).find(function (o) { return o.value === key; });
|
||||
const sw = vals[1].querySelector(".io-swatch"), nm = vals[1].querySelector(".io-color-name");
|
||||
if (sw) { sw.style.background = (copt && copt.dataset.hex) || "#fff"; sw.classList.toggle("is-none", !(copt && copt.dataset.hex)); }
|
||||
if (nm) nm.textContent = copt ? copt.textContent : "";
|
||||
}
|
||||
}
|
||||
function paintDirty() {
|
||||
const n = dirtyRows().length;
|
||||
@@ -391,12 +427,17 @@
|
||||
if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base;
|
||||
return;
|
||||
}
|
||||
if (inp.classList && inp.classList.contains("io-color-select")) paintSwatch(inp); // 그룹 표·상품 표 공통
|
||||
if (!inp.dataset || !inp.dataset.key) return;
|
||||
const tr = inp.closest("tr");
|
||||
const w = dec(tr.querySelector('[data-key="weight_g"]').value), pct = dec(tr.querySelector('[data-key="silver_pct"]').value);
|
||||
if (inp.dataset.key === "group_id") paintGroup(tr);
|
||||
const gsel = tr.querySelector(".io-group-select");
|
||||
const gopt = gsel && gsel.value ? gsel.options[gsel.selectedIndex] : null;
|
||||
const w = dec(tr.querySelector('[data-key="weight_g"]').value);
|
||||
const pct = gopt ? dec(gopt.dataset.silver) : dec(tr.querySelector('[data-key="silver_pct"]').value);
|
||||
const ag = tr.querySelector(".io-ag");
|
||||
if (ag) ag.textContent = w !== null && pct !== null ? (Math.round(w * pct / 100 * 10000) / 10000).toLocaleString("ko-KR", { maximumFractionDigits: 4 }) : "-";
|
||||
tr.classList.toggle("is-dirty", Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); }));
|
||||
tr.classList.toggle("is-dirty", rowChanged(tr));
|
||||
paintDirty();
|
||||
});
|
||||
body.addEventListener("click", async function (e) {
|
||||
@@ -409,7 +450,9 @@
|
||||
} else if (t.closest("#io-prod-save")) {
|
||||
const rows = dirtyRows().map(function (tr) {
|
||||
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); };
|
||||
return { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
|
||||
const row = { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
|
||||
if (tr.querySelector('[data-key="group_id"]')) { row.group_id = v("group_id"); row.color = v("color"); } // 006
|
||||
return row;
|
||||
});
|
||||
if (rows.length) await act("/inout/settings/products/save", { rows: rows });
|
||||
} else if (t.dataset && t.dataset.exclude) {
|
||||
@@ -696,4 +739,116 @@
|
||||
});
|
||||
return { open: open };
|
||||
}
|
||||
|
||||
// ── 오른쪽 달력(2026-10-21) — 입출고 모든 화면. 프로젝트 달력과 같은 모양(일요일 시작·오늘 검은 동그라미·토 파랑·일/공휴일 빨강),
|
||||
// 날짜 칸 = 발주(파랑)·입고(초록) 건수, 누르면 그날 목록 팝업(발주서로 이동). 달 이동은 새로고침 없이 GET /inout/api/calendar.
|
||||
const calEl = document.getElementById("io-cal");
|
||||
if (calEl) initCalendar(calEl);
|
||||
|
||||
function initCalendar(cal) {
|
||||
const daysEl = cal.querySelector(".io-cal-days"), titleEl = cal.querySelector(".io-cal-title");
|
||||
let month = cal.dataset.month, data = null, pop = null, seq = 0;
|
||||
const pad = function (n) { return String(n).padStart(2, "0"); };
|
||||
const isoOf = function (d) { return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); };
|
||||
const escH = function (v) { const d = document.createElement("div"); d.textContent = v == null ? "" : String(v); return d.innerHTML; };
|
||||
const WD = "일월화수목금토";
|
||||
function shift(ym, step) {
|
||||
const p = ym.split("-").map(Number);
|
||||
const d = new Date(p[0], p[1] - 1 + step, 1);
|
||||
return d.getFullYear() + "-" + pad(d.getMonth() + 1);
|
||||
}
|
||||
function closePop() { if (pop) { pop.remove(); pop = null; } }
|
||||
async function load() {
|
||||
closePop();
|
||||
const p = month.split("-").map(Number);
|
||||
titleEl.textContent = p[0] + "년 " + p[1] + "월";
|
||||
const mine = ++seq; // 빠르게 넘기면 늦게 온 앞 달 응답이 덮지 않게
|
||||
cal.classList.add("is-loading");
|
||||
try {
|
||||
const res = await fetch("/inout/api/calendar?month=" + encodeURIComponent(month));
|
||||
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||
const got = await res.json();
|
||||
if (mine !== seq) return;
|
||||
data = got;
|
||||
render();
|
||||
} catch (_) {
|
||||
if (mine !== seq) return;
|
||||
data = null;
|
||||
daysEl.innerHTML = '<p class="io-cal-err">달력을 불러오지 못했습니다.</p>';
|
||||
} finally {
|
||||
if (mine === seq) cal.classList.remove("is-loading");
|
||||
}
|
||||
}
|
||||
function render() {
|
||||
const start = new Date(data.start + "T00:00:00");
|
||||
let html = "";
|
||||
for (let i = 0; i < 42; i++) {
|
||||
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
|
||||
const iso = isoOf(d), wd = d.getDay();
|
||||
const ev = data.days[iso] || { orders: [], receipts: [] };
|
||||
const hol = data.holidays[iso] || "";
|
||||
const cls = ["io-cal-day"];
|
||||
if (iso.slice(0, 7) !== data.month) cls.push("is-out");
|
||||
if (iso === data.today) cls.push("is-today");
|
||||
if (wd === 0 || hol) cls.push("is-sun"); else if (wd === 6) cls.push("is-sat");
|
||||
if (ev.orders.length || ev.receipts.length) cls.push("has-ev");
|
||||
const tip = [iso.replace(/-/g, ".") + "(" + WD[wd] + ")" + (hol ? " " + hol : "")];
|
||||
if (ev.orders.length) tip.push("발주 " + ev.orders.length + "건");
|
||||
if (ev.receipts.length) tip.push("입고 " + ev.receipts.length + "건");
|
||||
html += '<button type="button" class="' + cls.join(" ") + '" data-date="' + iso + '" title="' + escH(tip.join(" · ")) + '">' +
|
||||
'<span class="io-cal-num">' + d.getDate() + "</span>" +
|
||||
'<span class="io-cal-marks">' +
|
||||
(ev.orders.length ? '<i class="io-cal-m is-order">' + ev.orders.length + "</i>" : "") +
|
||||
(ev.receipts.length ? '<i class="io-cal-m is-receipt">' + ev.receipts.length + "</i>" : "") +
|
||||
"</span></button>";
|
||||
}
|
||||
daysEl.innerHTML = html;
|
||||
}
|
||||
// 그날 목록 — body 에 붙이는 작은 팝업(달력 칸 아래, 화면 밖이면 위로)
|
||||
function openDay(btn) {
|
||||
closePop();
|
||||
const iso = btn.dataset.date;
|
||||
const ev = (data && data.days[iso]) || { orders: [], receipts: [] };
|
||||
if (!ev.orders.length && !ev.receipts.length) return;
|
||||
const d = new Date(iso + "T00:00:00"), hol = (data.holidays || {})[iso];
|
||||
const item = function (href, kind, label, main, sub) {
|
||||
return '<a class="io-calpop-item" href="' + href + '"><i class="io-cal-m ' + kind + '">' + label + "</i>" +
|
||||
'<span class="io-calpop-main">' + main + '</span><span class="io-calpop-sub">' + sub + "</span></a>";
|
||||
};
|
||||
let html = '<div class="io-calpop-head">' + iso.replace(/-/g, ".") + "(" + WD[d.getDay()] + ")" + (hol ? ' <span class="is-hol">' + escH(hol) + "</span>" : "") + "</div>";
|
||||
ev.orders.forEach(function (o) {
|
||||
html += item("/inout/orders/" + o.id, "is-order", "발주", escH(o.order_no) + " · " + escH(o.factory),
|
||||
escH(o.item) + " · " + Number(o.qty).toLocaleString("ko-KR") + "개");
|
||||
});
|
||||
ev.receipts.forEach(function (r) {
|
||||
html += item("/inout/orders/" + r.order_id, "is-receipt", "입고", escH(r.order_no) + " · " + escH(r.factory),
|
||||
Number(r.qty).toLocaleString("ko-KR") + "개 입고");
|
||||
});
|
||||
pop = document.createElement("div");
|
||||
pop.className = "io-calpop";
|
||||
pop.setAttribute("role", "dialog");
|
||||
pop.setAttribute("aria-label", iso + " 발주·입고");
|
||||
pop.innerHTML = html;
|
||||
document.body.appendChild(pop);
|
||||
const r = btn.getBoundingClientRect(), w = pop.offsetWidth, h = pop.offsetHeight;
|
||||
let left = Math.min(Math.max(8, r.left + r.width / 2 - w / 2), window.innerWidth - w - 8);
|
||||
let top = r.bottom + 6;
|
||||
if (top + h > window.innerHeight - 8) top = Math.max(8, r.top - h - 6);
|
||||
pop.style.left = left + window.scrollX + "px";
|
||||
pop.style.top = top + window.scrollY + "px";
|
||||
}
|
||||
cal.addEventListener("click", function (e) {
|
||||
const nav = e.target.closest(".io-cal-nav");
|
||||
if (nav) { month = shift(month, Number(nav.dataset.step)); load(); return; }
|
||||
if (e.target.closest(".io-cal-today")) { month = (data && data.today ? data.today : cal.dataset.month).slice(0, 7); load(); return; }
|
||||
const day = e.target.closest(".io-cal-day");
|
||||
if (day) { if (pop && pop.dataset.date === day.dataset.date) closePop(); else { openDay(day); if (pop) pop.dataset.date = day.dataset.date; } }
|
||||
});
|
||||
document.addEventListener("mousedown", function (e) {
|
||||
if (pop && !pop.contains(e.target) && !e.target.closest(".io-cal-day")) closePop();
|
||||
});
|
||||
document.addEventListener("keydown", function (e) { if (e.key === "Escape") closePop(); });
|
||||
window.addEventListener("resize", closePop);
|
||||
load();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -825,6 +825,15 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
position: relative; z-index: 2;
|
||||
}
|
||||
.pj-comment-dock[hidden] { display: none; }
|
||||
/* Ctrl+V 로 붙여넣은 이미지(보내기 전) — 입력칸 위 썸네일 줄, × 로 빼기(2026-10-21) */
|
||||
.pj-comment-pending { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 2px 8px; }
|
||||
.pj-comment-pending[hidden] { display: none; }
|
||||
.pj-comment-pending-img { position: relative; width: 64px; height: 64px; border: 1px solid #d8dce2; border-radius: 8px; overflow: hidden; background: #f6f7f9; }
|
||||
.pj-comment-pending-img img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.pj-comment-pending-img.is-failed { border-color: #e5484d; box-shadow: 0 0 0 1px #e5484d; }
|
||||
.pj-comment-pending-img button { position: absolute; top: 2px; right: 2px; width: 18px; height: 18px; border: none; border-radius: 50%;
|
||||
background: rgba(0,0,0,.55); color: #fff; font-size: 13px; line-height: 18px; padding: 0; cursor: pointer; }
|
||||
.pj-comment-pending-img button:hover { background: #c22b10; }
|
||||
.pj-comment-dock .pj-comment-form {
|
||||
border: 1px solid #d8dce2; border-radius: 12px; padding: 6px 6px 6px 4px; background: #fff;
|
||||
transition: border-color .12s, box-shadow .12s;
|
||||
@@ -970,6 +979,12 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
.pj-btn-complete { background: #e9f7ef; color: #1e8e5a; border: 1px solid #bfe8d2; font-weight: 500; }
|
||||
.pj-btn-complete:hover { background: #d9f2e4; }
|
||||
.pj-btn-complete.is-done { background: #f2f2f4; color: #6b6f76; border-color: var(--pj-border); }
|
||||
/* 업무 창 맨 위 작성자 — 삭제 버튼 오른쪽, 아이콘 + 이름(작성 시각) 한 줄(2026-10-21) */
|
||||
.pj-task-creator { flex: none; display: inline-flex; align-items: center; gap: 5px; margin-left: 4px;
|
||||
font-size: var(--pj-small-size); color: #6b6f76; white-space: nowrap; }
|
||||
.pj-task-creator[hidden] { display: none; }
|
||||
.pj-task-creator .pj-person-ic { width: 20px; height: 20px; font-size: 20px; border-radius: 50%; flex: none; }
|
||||
.pj-task-creator-name { color: #1e1f21; font-weight: 500; }
|
||||
|
||||
/* 색상표(아사나) — 8칸씩 둥근 네모, 고른 색엔 체크 */
|
||||
/* 12칸씩(2026-10-08) — 32색이 3줄 */
|
||||
|
||||
+94
-3
@@ -7639,6 +7639,7 @@
|
||||
syncDueBtn(); // 완료 여부(지남 표시)를 보려면 currentTaskData 다음에
|
||||
el("pj-delete-task").hidden = !task;
|
||||
el("pj-toggle-complete").hidden = !task;
|
||||
showTaskCreator(task);
|
||||
// 공유 링크는 저장된 업무에만 있다(새 업무는 아직 id 가 없다).
|
||||
const shareBtn = el("pj-share-task");
|
||||
if (shareBtn) shareBtn.hidden = !task;
|
||||
@@ -7649,6 +7650,7 @@
|
||||
el("pj-attach-block").hidden = !task;
|
||||
el("pj-comment-block").hidden = !task;
|
||||
el("pj-comment-dock").hidden = !task;
|
||||
clearCommentImages();
|
||||
// 세부 업무도 업무와 같은 팝업·같은 편집(아사나식). 다른 점은 세 가지 —
|
||||
// 제목 위에 상위 업무 경로, 세션 칸 없음(세부 업무는 세션이 없다),
|
||||
// 다른 프로젝트 연결(멀티호밍) 없음.
|
||||
@@ -7675,6 +7677,25 @@
|
||||
if (!task) setTimeout(function () { el("pj-t-title").focus(); }, 0);
|
||||
}
|
||||
|
||||
// 업무 창 맨 위 삭제 버튼 오른쪽 — 작성자 아이콘 + 이름(yyyy.mm.dd(요일) hh:mm:ss).
|
||||
// created_at 은 서버가 KST ISO(2026-10-21T13:05:12+09:00)로 주므로 글자를 그대로 잘라 쓴다(브라우저 시간대 무관).
|
||||
function showTaskCreator(task) {
|
||||
const box = el("pj-task-creator");
|
||||
if (!box) return;
|
||||
const who = task && task.created_by;
|
||||
box.hidden = !who;
|
||||
if (!who) { box.innerHTML = ""; return; }
|
||||
const at = String(task.created_at || "");
|
||||
let when = "";
|
||||
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(at)) {
|
||||
const wd = ["일", "월", "화", "수", "목", "금", "토"][new Date(at.slice(0, 10) + "T00:00:00").getDay()];
|
||||
when = at.slice(0, 4) + "." + at.slice(5, 7) + "." + at.slice(8, 10) + "(" + wd + ") " + at.slice(11, 19);
|
||||
}
|
||||
box.innerHTML = personIconHtml(who) + '<span class="pj-task-creator-name">' + escapeHtml(idOf(who)) + "</span>" +
|
||||
(when ? '<span class="pj-task-creator-at">(' + escapeHtml(when) + ")</span>" : "");
|
||||
box.title = "작성자 " + who + (when ? " · " + when : "");
|
||||
}
|
||||
|
||||
// 작업 제목 — 한 줄 input 대신 textarea 라 창보다 길면 다음 줄로 넘어간다.
|
||||
// 제목은 한 줄 값이므로 Enter·붙여넣은 줄바꿈은 막고 공백으로 바꾼다.
|
||||
function fitTitleHeight() {
|
||||
@@ -8189,20 +8210,90 @@
|
||||
// 응답을 못 받고 다시 보내도 서버가 한 번만 만든다. 실패하면 입력은 그대로 남아 다시 보낼 수 있다.
|
||||
let commentSending = false;
|
||||
let commentToken = null;
|
||||
// Ctrl+V 로 붙여넣은 이미지 — 등록 때 본문과 한 요청(/comments/files, 댓글 대화창과 같은 API)으로 보낸다.
|
||||
// 업무를 바꾸면 비운다(다른 업무 댓글에 딸려 가지 않게). var — 페이지를 열자마자 업무 창이 열려
|
||||
// (?task=) 이 줄보다 먼저 clearCommentImages 가 불려도 TDZ 오류가 나지 않게.
|
||||
var commentImages = [];
|
||||
function renderCommentImages() {
|
||||
const box = el("pj-comment-pending");
|
||||
if (!box) return;
|
||||
box.querySelectorAll("img[data-url]").forEach(function (img) { URL.revokeObjectURL(img.dataset.url); });
|
||||
box.hidden = !commentImages.length;
|
||||
box.innerHTML = commentImages.map(function (it, i) {
|
||||
return '<span class="pj-comment-pending-img' + (it.err ? " is-failed" : "") + '" title="' +
|
||||
escapeHtml(it.err ? "보낼 수 없음: " + it.err : it.file.name) + '">' +
|
||||
'<img src="' + it.url + '" data-url="' + it.url + '" alt="' + escapeHtml(it.file.name) + '">' +
|
||||
'<button type="button" data-idx="' + i + '" title="빼기">×</button></span>';
|
||||
}).join("");
|
||||
box.querySelectorAll("button[data-idx]").forEach(function (btn) {
|
||||
btn.addEventListener("click", function () {
|
||||
commentImages.splice(parseInt(btn.dataset.idx, 10), 1);
|
||||
commentToken = null;
|
||||
renderCommentImages();
|
||||
});
|
||||
});
|
||||
}
|
||||
function clearCommentImages() {
|
||||
commentImages = [];
|
||||
renderCommentImages();
|
||||
}
|
||||
el("pj-comment-input").addEventListener("paste", function (e) {
|
||||
if (taskReadOnly) return;
|
||||
const cd = e.clipboardData || {};
|
||||
if (cd.getData && cd.getData("text/plain")) return; // 글자(주소 등)가 있으면 글자 붙여넣기가 먼저(대화창과 같음)
|
||||
const items = cd.items || [];
|
||||
let added = false;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
if (!items[i].type || items[i].type.indexOf("image/") !== 0) continue;
|
||||
const f = items[i].getAsFile();
|
||||
if (!f) continue;
|
||||
const ext = (f.type.split("/")[1] || "png").replace("jpeg", "jpg");
|
||||
const file = new File([f], "붙여넣은 이미지 " + (commentImages.length + 1) + "." + ext, { type: f.type });
|
||||
commentImages.push({ file: file, url: URL.createObjectURL(file), err: "" });
|
||||
added = true;
|
||||
}
|
||||
if (added) { e.preventDefault(); commentToken = null; renderCommentImages(); }
|
||||
});
|
||||
async function sendComment() {
|
||||
const inp = el("pj-comment-input");
|
||||
const body = inp.value.trim();
|
||||
const taskId = currentTaskId;
|
||||
if (!taskId || !body || commentSending || taskReadOnly) return;
|
||||
const imgs = commentImages.slice();
|
||||
if (!taskId || (!body && !imgs.length) || commentSending || taskReadOnly) return;
|
||||
const gen = taskGen;
|
||||
commentSending = true;
|
||||
commentToken = commentToken || newClientToken();
|
||||
el("pj-comment-send").disabled = true;
|
||||
try {
|
||||
const res = await api("POST", "/project/api/tasks/" + taskId + "/comments",
|
||||
{ body: body, mentions: takeMentions(inp), client_token: commentToken });
|
||||
let res;
|
||||
if (imgs.length) {
|
||||
const fd = new FormData();
|
||||
fd.append("body", body);
|
||||
fd.append("mentions", JSON.stringify(takeMentions(inp)));
|
||||
fd.append("client_token", commentToken);
|
||||
imgs.forEach(function (it) { fd.append("files", it.file, it.file.name); });
|
||||
const r = await fetch("/project/api/tasks/" + taskId + "/comments/files", { method: "POST", body: fd });
|
||||
let data = null;
|
||||
try { data = await r.json(); } catch (_) {}
|
||||
if (!r.ok) {
|
||||
const d = data && data.detail;
|
||||
const err = new Error(typeof d === "string" ? d : (d && d.message) || ("요청 실패 (" + r.status + ")"));
|
||||
err.status = r.status;
|
||||
(d && d.failed || []).forEach(function (f) {
|
||||
const it = imgs[parseInt(f.index, 10)];
|
||||
if (it) it.err = f.reason || "실패";
|
||||
});
|
||||
if (d && d.failed) renderCommentImages();
|
||||
throw err;
|
||||
}
|
||||
res = data;
|
||||
} else {
|
||||
res = await api("POST", "/project/api/tasks/" + taskId + "/comments",
|
||||
{ body: body, mentions: takeMentions(inp), client_token: commentToken });
|
||||
}
|
||||
commentToken = null;
|
||||
if (gen !== taskGen) return; // 그 사이 다른 작업 창 — 그 창의 입력칸을 비우지 않는다
|
||||
clearCommentImages();
|
||||
inp.value = "";
|
||||
fitComposer(inp);
|
||||
clearMentions(inp);
|
||||
|
||||
@@ -333,6 +333,19 @@ cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres proj
|
||||
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_031_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_031_owner_as_member.sql && docker compose build web && docker compose up -d web
|
||||
```
|
||||
|
||||
## 입출고 관리 상품 그룹·색상 마이그레이션 (inout_db 006)
|
||||
|
||||
006은 표 1개·열 3개만 추가한다 — `inout_product_groups`(그룹 이름·은 함유량·색상·순서)·`inout_products.group_id`·`inout_products.color`·
|
||||
`inout_order_lines.color`(발주 당시 색상 사본). 다시 실행 가능, 기존 데이터 변경 없음, 새 환경변수 없음. 004 다음에 적용한다.
|
||||
미적용이어도 발주·입고·메일은 그대로 — 옵션 → 상품 정보에 "006 필요" 안내만 나오고 그룹·색상 칸이 없다.
|
||||
적용 뒤 옵션(톱니) → **상품 정보** → 그룹을 만들고(은 함유량·색상) 상품마다 그룹을 고른 뒤 [변경 저장].
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_006_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_006_product_groups.sql && docker compose up --build -d --no-deps web
|
||||
```
|
||||
|
||||
되돌리기(그룹·색상만 사라짐): 백업에서 복원.
|
||||
|
||||
## 입출고 관리 물류센터 이메일·입고 요청 메일 마이그레이션 (inout_db 005)
|
||||
|
||||
005는 표 2개만 추가한다 — `inout_settings`(모듈 설정: 물류센터 담당자 이메일·입고 요청 메일 참조, 참조 기본값 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 한 줄 넣음)·
|
||||
|
||||
@@ -73,6 +73,10 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
|
||||
| `/inout/orders/{id}` | 발주서 — 품목별 발주·(발주 담당) **단가·금액·PP(g/개)·은(Ag)** ·입고·미입고·상태 + 합계 줄(금액·PP kg·은 g), **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소. 입고 담당만이면 이름·발주 수량만 |
|
||||
| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3) · **물류센터**(6-4). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) |
|
||||
|
||||
**2열 + 오른쪽 달력(2026-10-21)** — 모든 화면이 왼쪽 화면 | 오른쪽 300px(달력 300×320, 프로젝트 달력 모양). 날짜별 발주(발주일)·입고(입고일) 건수,
|
||||
누르면 그날 목록 팝업, 달 이동은 `GET /inout/api/calendar?month=YYYY-MM`(6주 칸 = 일요일 시작 42일, 취소된 발주 제외, 공휴일 이름 포함).
|
||||
옵션 → 담당자 표 = 아이콘(구글 프로필 사진) + 이름, 아래 이메일.
|
||||
|
||||
화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여
|
||||
표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`).
|
||||
공용 스타일과 겹치는 것 — 이 모듈 안에서만 바로잡는다(공용 파일은 그대로):
|
||||
@@ -173,6 +177,19 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
|
||||
두 표 사이는 표 margin 대신 높이 18px 빈 줄(`<div style="height:18px;line-height:18px;font-size:1px">`) — 메일 프로그램이 표 margin 을 무시하기도 해서. 글 본문(HTML 못 보는 메일 프로그램용)도 같은 값. 발주서 화면 표는 그대로.
|
||||
- 004 미적용이면 탭에 "마이그레이션 004 필요" 안내, 발주서는 예전처럼 코드표에서(`products_ready`).
|
||||
|
||||
## 6-3-1. 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
||||
|
||||
- 사용자 요청: 은 함유량이 그룹마다 다르다 → 그룹별로 한 번만 설정. 아이템별 색상도 같은 방식(그룹에 한 번). 그룹 기준은 사용자 선택 = **옵션에서 직접 그룹을 만들고 상품마다 고름**
|
||||
(코드 앞부분·이름 자동 묶음은 쓰지 않음).
|
||||
- 표 `inout_product_groups`(id·name UNIQUE·silver_pct·color·sort_order), `inout_products.group_id`(FK, 그룹 지우면 NULL)·`color`, `inout_order_lines.color`.
|
||||
- 적용 값: 그룹 상품 = 그룹의 은 함유량·색상, 그룹 없는 상품 = 상품 자기 값. 상품 자기 값은 그룹에 넣어도 지우지 않는다(그룹에서 빼면 다시 보임).
|
||||
다시 불러오기에서 그룹·색상만 넣은 상품도 "값 있는 상품"(`store.has_values`)이라 그대로.
|
||||
- 색상: 색없음(none)·오렌지(orange `#FFD8B0`)·파랑(blue `#CFE0FA`)·회색(gray `#DDDFE3`)·아이보리색(ivory `#FFF6D9`) — 메일 글자가 읽히게 옅은 색.
|
||||
- 발주 메일(6-1) 품목 표: 색상 있는 품목은 줄 전체 배경을 그 색으로(`<tr style="background:…">` + 칸마다 — 메일 프로그램이 tr 배경을 무시하기도 함).
|
||||
색상 = 발주 품목 사본(발주 당시), 006 전 품목은 지금 상품 색상.
|
||||
- 옵션 화면: 그룹 표(이름·은 함유량·색상[사각형 + 고르기]·순서·상품 수·저장/지우기·추가), 상품 표에 그룹·색상 열. 그룹 상품은 은 함유량·색상 칸 대신 그룹 값(회색 칸),
|
||||
그룹을 바꾸면 그 자리에서 그룹 값·은 g 다시 계산. 저장 안 한 상품 변경이 있으면 그룹 저장 전에 묻는다.
|
||||
|
||||
## 6-4. 입고 요청 메일 — 물류센터 전산 등록 부탁(2026-10-19, 마이그레이션 005)
|
||||
|
||||
- **왜**(사용자 요청): 물류에 들어온 입고를 물류센터 입고 담당자가 전산에 등록하도록, 입고 담당이 입고를 저장하면 메일로 알린다.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
-- =====================================================================
|
||||
-- inout_db 마이그레이션 006 — 상품 그룹(은 함유량·색상 한 번에) · 상품 색상 · 발주 품목 색상 사본(2026-10-21)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 표·열 추가만, 기존 값 변경·삭제 없음. 004 다음에 적용. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_006_product_groups.sql
|
||||
--
|
||||
-- 왜(사용자 요청):
|
||||
-- 은 함유량이 그룹마다 다르다 → 옵션 → 상품 정보에서 그룹을 직접 만들고 상품마다 그룹을 고른다. 그룹의 은 함유량·색상을
|
||||
-- 한 번만 넣으면 그 그룹 상품 모두에 적용(그룹 없는 상품은 예전처럼 상품마다 입력).
|
||||
-- 색상 = 색없음·오렌지·파랑·회색·아이보리색. 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경을 그 색으로.
|
||||
-- 발주 품목에는 그때 색상 사본(color) — 단가 등과 같은 방식(나중에 바꿔도 지난 발주는 그대로, 006 전 품목은 지금 색상).
|
||||
-- 되돌리기: 백업에서 복원(새 표·열만 생기므로 남아 있어도 이전 앱은 동작).
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_product_groups (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE CHECK (char_length(name) BETWEEN 1 AND 100),
|
||||
silver_pct NUMERIC(9,4) NULL CHECK (silver_pct IS NULL OR (silver_pct >= 0 AND silver_pct <= 100)), -- 은(Ag) 함유량 %
|
||||
color TEXT NOT NULL DEFAULT 'none' CHECK (color IN ('none', 'orange', 'blue', 'gray', 'ivory')),
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_product_groups IS '입출고 — 상품 그룹(은 함유량·색상을 그룹에 한 번만)';
|
||||
|
||||
-- 상품 — 그룹(지우면 그룹 없음으로) · 그룹 없을 때 쓰는 상품 자신의 색상
|
||||
ALTER TABLE inout_products ADD COLUMN IF NOT EXISTS group_id INT NULL REFERENCES inout_product_groups(id) ON DELETE SET NULL;
|
||||
ALTER TABLE inout_products ADD COLUMN IF NOT EXISTS color TEXT NULL;
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE inout_products ADD CONSTRAINT inout_products_color_chk
|
||||
CHECK (color IS NULL OR color IN ('none', 'orange', 'blue', 'gray', 'ivory'));
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_products_group ON inout_products (group_id);
|
||||
|
||||
-- 발주 품목 — 발주 당시 색상 사본(NULL = 006 전 품목 → 지금 상품 색상으로 보여 줌)
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS color TEXT NULL;
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON inout_product_groups TO inout_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'inout_db 006 product groups ready' AS status;
|
||||
@@ -32,7 +32,7 @@ def task(tid: int, title: str, pid: int, stage: int, *, ctx: int | None = None,
|
||||
"stage_id": stage, "home_stage_id": stage, "stage_name": "할 일", "is_done_stage": False,
|
||||
"description": "", "assignee_email": "", "assignee_name": "", "priority": "normal",
|
||||
"start_date": None, "due_date": None, "completed_at": None, "created_by": ME,
|
||||
"parent_task_id": None, "comment_count": 0, "subtask_count": 0, "subtask_done": 0,
|
||||
"created_at": "2026-10-21T13:05:09+09:00", "parent_task_id": None, "comment_count": 0, "subtask_count": 0, "subtask_done": 0,
|
||||
"project_name": {1: "P1", 2: "P2", 3: "비밀"}[pid], "project_color": "#4573d2", "sort_order": tid}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// 실제 브라우저 — 업무 창 맨 위 작성자(아이콘 + 이름(yyyy.mm.dd(요일) hh:mm:ss), 삭제 버튼 오른쪽)와
|
||||
// 댓글 칸 Ctrl+V 이미지 붙여넣기(썸네일 → 등록 = /comments/files 한 요청, 업무를 바꾸면 비움)를 확인한다(2026-10-21).
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/task_creator_paste.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
|
||||
const detail = (id) => ({ id, title: "작업 " + id, project_id: 1, stage_id: 11, description: "", priority: "normal",
|
||||
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null,
|
||||
created_by: "me@test.local", created_at: "2026-10-21T13:05:09+09:00" });
|
||||
const posts = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "project_render.html"))); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
const raw = Buffer.concat(chunks);
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") return json(200, { task: detail(+task[1]) });
|
||||
if (/\/comments(\/files)?$/.test(url.pathname) && req.method === "POST") {
|
||||
posts.push({ path: url.pathname, type: req.headers["content-type"] || "", body: raw.toString("utf8") });
|
||||
return json(201, { comment: { id: 1 }, attachments: [], mention_skipped: [] });
|
||||
}
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
// 붙여넣기 — 이미지만 든 클립보드(캡처 도구)를 흉내 낸다. 반환 = 기본 동작(글자 붙여넣기)을 막았는지.
|
||||
const pasteImage = (page) => page.evaluate(async () => {
|
||||
const c = document.createElement("canvas"); c.width = 8; c.height = 8;
|
||||
c.getContext("2d").fillRect(0, 0, 8, 8);
|
||||
const blob = await new Promise(r => c.toBlob(r, "image/png"));
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(new File([blob], "image.png", { type: "image/png" }));
|
||||
const ev = new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true });
|
||||
document.getElementById("pj-comment-input").dispatchEvent(ev);
|
||||
return ev.defaultPrevented;
|
||||
});
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", e => errors.push(e.message));
|
||||
const pass = [];
|
||||
const ok = (name, cond, extra) => { assert.ok(cond, name + (extra === undefined ? "" : " → " + JSON.stringify(extra))); pass.push(name); console.log("PASS " + name); };
|
||||
try {
|
||||
await page.goto(base + "/project/p/1?task=101");
|
||||
await page.waitForFunction(() => { const m = document.getElementById("pj-modal-task"); return m && !m.hidden && document.getElementById("pj-t-id").value; });
|
||||
const creator = await page.evaluate(() => {
|
||||
const b = document.getElementById("pj-task-creator"), del = document.getElementById("pj-delete-task");
|
||||
const br = b.getBoundingClientRect(), dr = del.getBoundingClientRect();
|
||||
const text = b.querySelector(".pj-task-creator-name").textContent + b.querySelector(".pj-task-creator-at").textContent;
|
||||
return { hidden: b.hidden, text: text, icon: !!b.querySelector(".pj-person-ic"),
|
||||
rightOfDelete: br.left >= dr.right, sameRow: Math.abs((br.top + br.bottom) / 2 - (dr.top + dr.bottom) / 2) < 4 };
|
||||
});
|
||||
ok("작성자 = 아이콘 + 이름(yyyy.mm.dd(요일) hh:mm:ss)", !creator.hidden && creator.icon && creator.text === "Me(2026.10.21(수) 13:05:09)", creator);
|
||||
ok("작성자는 삭제 버튼 오른쪽 같은 줄", creator.rightOfDelete && creator.sameRow, creator);
|
||||
await page.locator("#pj-modal-task .pj-modal-actions-top").screenshot({ path: path.join(OUT, "task_creator.png") });
|
||||
|
||||
ok("이미지 붙여넣기는 기본 붙여넣기를 막고 담는다", await pasteImage(page));
|
||||
await pasteImage(page);
|
||||
ok("입력칸 위 썸네일 두 개", await page.evaluate(() => {
|
||||
const box = document.getElementById("pj-comment-pending");
|
||||
return !box.hidden && box.querySelectorAll(".pj-comment-pending-img img").length === 2; }));
|
||||
await page.click("#pj-comment-pending button[data-idx='1']");
|
||||
ok("× 로 하나 빼기", await page.evaluate(() => document.querySelectorAll("#pj-comment-pending img").length === 1));
|
||||
await page.click("#pj-comment-send"); // 글 없이 이미지만
|
||||
await page.waitForFunction(() => document.getElementById("pj-comment-pending").hidden);
|
||||
const p = posts[posts.length - 1];
|
||||
ok("등록 = /comments/files 한 요청(파일 1개, '붙여넣은 이미지 1.png')", p && p.path === "/project/api/tasks/101/comments/files" &&
|
||||
/multipart\/form-data/.test(p.type) && (p.body.match(/name="files"/g) || []).length === 1 &&
|
||||
p.body.includes("붙여넣은 이미지 1.png"), p && { path: p.path, type: p.type });
|
||||
|
||||
await page.fill("#pj-comment-input", "글만");
|
||||
await page.click("#pj-comment-send");
|
||||
await page.waitForFunction(() => document.getElementById("pj-comment-input").value === "");
|
||||
ok("이미지 없으면 예전처럼 JSON 댓글", posts[posts.length - 1].path === "/project/api/tasks/101/comments");
|
||||
|
||||
await pasteImage(page);
|
||||
await page.goto(base + "/project/p/1?task=102");
|
||||
await page.waitForFunction(() => document.getElementById("pj-t-id").value === "102");
|
||||
ok("새로 연 업무 창엔 붙여넣은 이미지 없음", await page.evaluate(() => document.getElementById("pj-comment-pending").hidden));
|
||||
ok("페이지 오류 없음", errors.length === 0, errors);
|
||||
console.log("\nALL PASS (" + pass.length + ")");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -335,6 +335,85 @@ class InoutDbTests(unittest.TestCase):
|
||||
pass
|
||||
self.assertEqual(self.st.catalog_count(), before)
|
||||
|
||||
def test_product_groups_colors_and_calendar(self):
|
||||
"""006 — 그룹의 은 함유량·색상이 그룹 상품에 적용(그룹 없는 상품은 자기 값), 같은 이름 거절, 발주 품목 색상 사본,
|
||||
메일 품목 줄 배경, 그룹 지우면 자기 값으로, 다시 불러와도 그룹·색상만 넣은 상품은 그대로. 달력 = 발주일·입고일(취소 제외)."""
|
||||
from decimal import Decimal as D
|
||||
|
||||
from app.modules.inout import store
|
||||
|
||||
if not self.st.groups_ready():
|
||||
self.skipTest("inout_db 006 미적용")
|
||||
T = self.tag.upper()
|
||||
A, B, C = f"ZG-{T}-A", f"ZG-{T}-B", f"ZG-{T}-C"
|
||||
before = self.st.catalog_count()
|
||||
gid = None
|
||||
try:
|
||||
self.st.import_products([{"code": A, "name": "가"}, {"code": B, "name": "나"}, {"code": C, "name": "다"}], by="b@x")
|
||||
gid = self.st.save_group(group_id=None, by="b@x", **store.validate_group(
|
||||
{"name": f"은30-{T}", "silver_pct": "30", "color": "orange", "sort_order": "1"}))
|
||||
with self.assertRaisesRegex(ValueError, "같은 이름"):
|
||||
self.st.save_group(group_id=None, by="b@x", **store.validate_group({"name": f"은30-{T}", "color": "blue"}))
|
||||
with self.assertRaisesRegex(ValueError, "색상은"):
|
||||
store.validate_group({"name": "x", "color": "pink"})
|
||||
vals = store.validate_product_values({"weight_g": "50", "silver_pct": "5"})
|
||||
self.st.save_products([{"code": A, **vals, "group_id": gid, "color": "blue"}, # 그룹 → 그룹 값(30%·오렌지)
|
||||
{"code": B, **vals, "group_id": None, "color": "ivory"}], by="b@x") # 자기 값(5%·아이보리)
|
||||
with self.assertRaisesRegex(ValueError, "없는 그룹"):
|
||||
self.st.save_products([{"code": C, **vals, "group_id": 999999999, "color": "none"}], by="b@x")
|
||||
got = self.st.catalog_lookup([A, B, C])
|
||||
self.assertEqual((got[A]["silver_pct"], got[A]["color"], got[A]["own_silver_pct"], got[A]["own_color"], got[A]["group_name"]),
|
||||
(D("30.0000"), "orange", D("5.0000"), "blue", f"은30-{T}"))
|
||||
self.assertEqual((got[B]["silver_pct"], got[B]["color"], got[B]["group_id"]), (D("5.0000"), "ivory", None))
|
||||
self.assertEqual(got[C]["color"], "none")
|
||||
self.assertEqual([x["color"] for x in self.st.catalog_search(f"ZG-{T}")], ["orange", "ivory", "none"])
|
||||
g = next(x for x in self.st.list_groups() if x["id"] == gid)
|
||||
self.assertEqual((g["product_count"], g["color"]), (1, "orange"))
|
||||
# 발주 = 그룹 적용 값·색상 사본, 메일 품목 줄 배경
|
||||
data = store.validate_order(factory_id=self.fid, order_date="2026-10-21", due_date="", memo="",
|
||||
codes=[A, B, C], quantities=["10", "10", "10"])
|
||||
o = self.st.create_order(data, {A: "가", B: "나", C: "다"}, by="b@x", specs=self.st.catalog_lookup([A, B, C]))
|
||||
order = self.st.get_order(o["id"])
|
||||
lines = {x["item_code"]: x for x in order["lines"]}
|
||||
self.assertEqual((lines[A]["silver_pct"], lines[A]["color"], lines[B]["color"], lines[C]["color"]),
|
||||
(D("30.0000"), "orange", "ivory", "none"))
|
||||
html = store.order_mail(order, sender_name="", sender_email="b@x")["html"]
|
||||
self.assertEqual(html.count('<tr style="background:' + store.color_hex("orange") + '">'), 1)
|
||||
self.assertEqual(html.count('<tr style="background:' + store.color_hex("ivory") + '">'), 1)
|
||||
self.assertEqual(html.count("<tr><td"), 1) # 색없음 줄은 배경 없음
|
||||
# 그룹을 바꿔도 지난 발주서는 사본 그대로 / 그룹 지우면 상품은 자기 값으로
|
||||
self.st.save_group(group_id=gid, by="b@x", **store.validate_group({"name": f"은30-{T}", "silver_pct": "31", "color": "gray"}))
|
||||
self.assertEqual(self.st.get_order(o["id"])["lines"][0]["color"], "orange")
|
||||
self.assertEqual(self.st.catalog_lookup([A])[A]["color"], "gray")
|
||||
self.assertEqual(self.st.delete_group(gid), f"은30-{T}")
|
||||
gid = None
|
||||
got = self.st.catalog_lookup([A])[A]
|
||||
self.assertEqual((got["group_id"], got["silver_pct"], got["color"]), (None, D("5.0000"), "blue"))
|
||||
# 다시 불러와도 그룹·색상만 넣은 상품은 그대로(값 있는 상품)
|
||||
self.st.save_products([{"code": C, "unit_price": None, "weight_g": None, "silver_pct": None, "group_id": None,
|
||||
"color": "gray"}], by="b@x")
|
||||
self.assertEqual(self.st.import_products([{"code": C, "name": "다2"}], by="b@x")["kept"], 1)
|
||||
# 달력 — 발주일·입고일, 취소된 발주는 빠짐
|
||||
ids = self.line_ids(o["id"])
|
||||
self.st.add_receipt(o["id"], {ids[A]: "4"}, receipt_date="2026-10-23", memo="", confirm_over=False, by="w@x")
|
||||
cal = self.st.calendar(date(2026, 10, 1), date(2026, 10, 31))
|
||||
mine = [x for x in cal["orders"] if x["id"] == o["id"]]
|
||||
self.assertEqual((len(mine), mine[0]["qty"], mine[0]["kinds"], mine[0]["first_item"]), (1, 30, 3, "가"))
|
||||
rec = [x for x in cal["receipts"] if x["order_id"] == o["id"]]
|
||||
self.assertEqual((len(rec), rec[0]["qty"], rec[0]["receipt_date"]), (1, 4, date(2026, 10, 23)))
|
||||
o2 = self.order([("MT-X", 1)], order_date="2026-10-22")
|
||||
self.st.cancel_order(o2["id"], by="b@x")
|
||||
self.assertFalse([x for x in self.st.calendar(date(2026, 10, 22), date(2026, 10, 22))["orders"] if x["id"] == o2["id"]])
|
||||
finally:
|
||||
if gid:
|
||||
self.st.delete_group(gid)
|
||||
for code in (A, B, C):
|
||||
try:
|
||||
self.st.exclude_product(code, by="cleanup@x")
|
||||
except ValueError:
|
||||
pass
|
||||
self.assertEqual(self.st.catalog_count(), before)
|
||||
|
||||
|
||||
def test_delete_order_cascades(self):
|
||||
"""수퍼관리자 발주 삭제 — 품목·입고 기록·입고증 사진·메일 기록까지 함께 지워진다."""
|
||||
|
||||
Reference in New Issue
Block a user