feat(asset): add inventory and HWiNFO reports
Requires asset_db initialized with scripts/sql/asset_db_init.sql and ASSET_DB_URL configured before enabling storage.
This commit is contained in:
+12
@@ -15,6 +15,8 @@ from pydantic import BaseModel
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from .modules.cafe24 import build_cafe24_store
|
||||
from .modules.asset import build_asset_store
|
||||
from .modules.asset import router as asset_router
|
||||
from .modules.cafe24 import router as cafe24_router
|
||||
from .modules.cupang import build_cupang_store, build_itemcode_reader
|
||||
from .modules.cupang import router as cupang_router
|
||||
@@ -52,6 +54,7 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"project": "프로젝트 관리",
|
||||
"cafe24": "카페24 상품관리",
|
||||
"performance": "실적",
|
||||
"asset": "자산관리",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -140,6 +143,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "project" / "templates",
|
||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||
BASE_DIR / "modules" / "performance" / "templates",
|
||||
BASE_DIR / "modules" / "asset" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -202,6 +206,7 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
||||
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
|
||||
|
||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||
app.include_router(expense_router)
|
||||
@@ -212,6 +217,7 @@ app.include_router(dispatch_router)
|
||||
app.include_router(project_router)
|
||||
app.include_router(cafe24_router)
|
||||
app.include_router(performance_router)
|
||||
app.include_router(asset_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
@@ -405,6 +411,11 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"category": "관리",
|
||||
},
|
||||
]
|
||||
items.append({
|
||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||
"description": "사무집기·전산장비의 배정·반납·구매 이력과 HWiNFO 컴퓨터 사양을 관리합니다.",
|
||||
"url": "/asset/", "health_url": "/asset/health", "status": "ready", "category": "관리",
|
||||
})
|
||||
allowed = allowed_modules(user_rec)
|
||||
for item in items:
|
||||
item["allowed"] = item["key"] in allowed
|
||||
@@ -414,6 +425,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
def _icon_svg(name: str) -> str:
|
||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||
paths = {
|
||||
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Company asset management; PostgreSQL only, never creates databases at startup."""
|
||||
from .router import router
|
||||
|
||||
|
||||
def build_asset_store(*, dsn: str | None):
|
||||
if not dsn:
|
||||
return None
|
||||
from .db import AssetStore
|
||||
return AssetStore(dsn)
|
||||
@@ -0,0 +1,183 @@
|
||||
"""자산·보고서·이력을 함께 저장합니다. DB 생성은 사용자가 서버에서 SQL로 진행합니다."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .store import AssetConflict, transition
|
||||
|
||||
FIELDS = ("tag", "name", "category", "manufacturer", "model", "serial", "location", "department",
|
||||
"purchased_on", "purchase_cost", "vendor", "warranty_until", "notes")
|
||||
SORTS = {"updated": "a.updated_at DESC", "name": "a.name ASC", "tag": "a.tag ASC",
|
||||
"cost": "a.purchase_cost DESC NULLS LAST", "warranty": "a.warranty_until ASC NULLS LAST"}
|
||||
|
||||
|
||||
def serialize(row):
|
||||
if row is None:
|
||||
return None
|
||||
return {k: (v.isoformat() if isinstance(v, (date, datetime)) else str(v) if isinstance(v, Decimal) else v)
|
||||
for k, v in row.items()}
|
||||
|
||||
|
||||
def filters(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||
conditions, params = ["TRUE"], []
|
||||
if q:
|
||||
# %와 _도 입력한 글자 그대로 검색합니다. 검색어는 SQL과 분리해서 전달합니다.
|
||||
value = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
conditions.append("(concat_ws(' ',a.tag,a.name,a.model,a.serial,a.manufacturer,a.location,a.department,a.assignee_email) ILIKE %s)")
|
||||
params.append(value)
|
||||
for col, value in (("category", category), ("status", status), ("location", location), ("assignee_email", assignee)):
|
||||
if value:
|
||||
conditions.append(f"a.{col} = %s")
|
||||
params.append(value)
|
||||
if warranty:
|
||||
conditions.append("a.warranty_until BETWEEN (now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date + 30 AND a.status <> 'retired'")
|
||||
if group == "furniture":
|
||||
conditions.append("a.category IN ('desk','chair','furniture')")
|
||||
elif group == "computer":
|
||||
conditions.append("a.category NOT IN ('desk','chair','furniture')")
|
||||
return " AND ".join(conditions), params
|
||||
|
||||
|
||||
class AssetStore:
|
||||
def __init__(self, dsn):
|
||||
self._pool = ConnectionPool(dsn, min_size=0, max_size=5, timeout=5, open=False,
|
||||
kwargs={"row_factory": dict_row, "autocommit": True})
|
||||
self._pool.open(wait=False)
|
||||
|
||||
def close(self):
|
||||
self._pool.close()
|
||||
|
||||
def health(self):
|
||||
with self._pool.connection(timeout=5) as conn:
|
||||
conn.execute("SELECT id FROM assets LIMIT 1")
|
||||
|
||||
def list_assets(self, *, page=1, page_size=25, sort="updated", **kwargs):
|
||||
# 전체 개수와 목록을 같은 시점의 데이터로 읽어 페이지 숫자가 어긋나지 않게 합니다.
|
||||
where, params = filters(**kwargs)
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
total = conn.execute(f"SELECT count(*) AS n FROM assets a WHERE {where}", params).fetchone()["n"]
|
||||
rows = conn.execute(
|
||||
f"SELECT a.*,r.parsed->'summary' AS specs,r.uploaded_at AS report_at FROM assets a "
|
||||
"LEFT JOIN asset_reports r ON r.id=a.latest_report_id "
|
||||
f"WHERE {where} ORDER BY {SORTS.get(sort, SORTS['updated'])},a.id LIMIT %s OFFSET %s",
|
||||
[*params, page_size, (page - 1) * page_size]).fetchall()
|
||||
return {"items": [serialize(r) for r in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
def dashboard(self):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
totals = conn.execute("""SELECT count(*) AS total,
|
||||
count(*) FILTER(WHERE status='available') AS available,
|
||||
count(*) FILTER(WHERE status='in_use') AS in_use,
|
||||
count(*) FILTER(WHERE status='maintenance') AS maintenance,
|
||||
count(*) FILTER(WHERE status='lost') AS lost,
|
||||
count(*) FILTER(WHERE status='retired') AS retired,
|
||||
coalesce(sum(purchase_cost) FILTER(WHERE status<>'retired'),0) AS purchase_total,
|
||||
count(*) FILTER(WHERE status<>'retired' AND warranty_until BETWEEN
|
||||
(now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date+30) AS warranty_soon
|
||||
FROM assets""").fetchone()
|
||||
categories = conn.execute("SELECT category,count(*) AS count FROM assets GROUP BY category ORDER BY count(*) DESC,category").fetchall()
|
||||
locations = conn.execute("SELECT DISTINCT location FROM assets WHERE location<>'' ORDER BY location").fetchall()
|
||||
activity = conn.execute("SELECT e.*,a.tag,a.name FROM asset_events e JOIN assets a ON a.id=e.asset_id ORDER BY e.id DESC LIMIT 12").fetchall()
|
||||
return {"totals": serialize(totals), "categories": categories, "locations": [r["location"] for r in locations],
|
||||
"activity": [serialize(r) for r in activity]}
|
||||
|
||||
def detail(self, asset_id):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s", (asset_id,)).fetchone()
|
||||
if not asset:
|
||||
raise KeyError(asset_id)
|
||||
reports = conn.execute("SELECT id,filename,sha256,uploaded_at,actor,parsed->'summary' AS summary,parsed->>'scan_time' AS scan_time FROM asset_reports WHERE asset_id=%s ORDER BY uploaded_at DESC,id DESC", (asset_id,)).fetchall()
|
||||
report = conn.execute("SELECT id,filename,uploaded_at,parsed FROM asset_reports WHERE id=%s AND asset_id=%s", (asset["latest_report_id"], asset_id)).fetchone() if asset["latest_report_id"] else None
|
||||
events = conn.execute("SELECT * FROM asset_events WHERE asset_id=%s ORDER BY id DESC LIMIT 200", (asset_id,)).fetchall()
|
||||
return {"asset": serialize(asset), "report": serialize(report), "reports": [serialize(r) for r in reports], "events": [serialize(r) for r in events]}
|
||||
|
||||
@staticmethod
|
||||
def _lock(conn, asset_id, version):
|
||||
# 같은 자산을 동시에 변경할 때 먼저 저장한 사용자의 값을 보호합니다.
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s FOR UPDATE", (asset_id,)).fetchone()
|
||||
if not asset:
|
||||
raise KeyError(asset_id)
|
||||
if asset["version"] != version:
|
||||
raise AssetConflict("다른 사용자가 수정했습니다. 상세 화면을 새로 열고 다시 시도하세요.")
|
||||
return asset
|
||||
|
||||
@staticmethod
|
||||
def _event(conn, asset_id, actor, kind, note, changes):
|
||||
conn.execute("INSERT INTO asset_events(asset_id,actor,kind,note,changes) VALUES(%s,%s,%s,%s,%s)",
|
||||
(asset_id, actor, kind, note, Jsonb(changes)))
|
||||
|
||||
def create(self, payload, actor, report=None):
|
||||
data = payload.model_dump()
|
||||
asset_id = uuid.uuid4().hex
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
if not data["tag"]:
|
||||
data["tag"] = "AST-" + str(conn.execute("SELECT nextval('asset_tag_seq') AS n").fetchone()["n"]).zfill(6)
|
||||
conn.execute(f"INSERT INTO assets(id,{','.join(FIELDS)}) VALUES({','.join(['%s'] * (len(FIELDS) + 1))})",
|
||||
[asset_id, *[data[k] for k in FIELDS]])
|
||||
self._event(conn, asset_id, actor, "create", "자산 등록", {"after": serialize(data)})
|
||||
if report:
|
||||
if data["category"] != "computer":
|
||||
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||
self._save_report(conn, asset_id, actor, *report)
|
||||
return asset_id
|
||||
|
||||
def update(self, asset_id, payload, actor):
|
||||
data = payload.model_dump(exclude={"version"})
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
old = self._lock(conn, asset_id, payload.version)
|
||||
if old["latest_report_id"] and data["category"] != "computer":
|
||||
raise ValueError("사양 보고서가 연결된 자산은 컴퓨터 분류를 유지해야 합니다.")
|
||||
if not data["tag"]:
|
||||
data["tag"] = old["tag"]
|
||||
changes = {k: {"before": serialize(old)[k], "after": serialize(data)[k]} for k in FIELDS if old[k] != data[k]}
|
||||
if changes:
|
||||
conn.execute(f"UPDATE assets SET {','.join(k+'=%s' for k in FIELDS)},version=version+1,updated_at=now() WHERE id=%s",
|
||||
[*[data[k] for k in FIELDS], asset_id])
|
||||
self._event(conn, asset_id, actor, "update", "자산 정보 수정", changes)
|
||||
|
||||
def action(self, asset_id, payload, actor):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
old = self._lock(conn, asset_id, payload.version)
|
||||
status, assignee = transition(old, payload)
|
||||
location = payload.location or old["location"]
|
||||
conn.execute("UPDATE assets SET status=%s,assignee_email=%s,location=%s,version=version+1,updated_at=now() WHERE id=%s",
|
||||
(status, assignee, location, asset_id))
|
||||
changes = {k: {"before": old[k], "after": value} for k, value in
|
||||
(("status", status), ("assignee_email", assignee), ("location", location)) if old[k] != value}
|
||||
self._event(conn, asset_id, actor, payload.action, payload.note, changes)
|
||||
|
||||
def _save_report(self, conn, asset_id, actor, filename, raw, parsed):
|
||||
# 원본과 분석 결과를 함께 저장하고 최신 보고서만 교체합니다. 이전 보고서는 남습니다.
|
||||
existing = conn.execute("SELECT id FROM asset_reports WHERE asset_id=%s AND sha256=%s", (asset_id, parsed["sha256"])).fetchone()
|
||||
if existing:
|
||||
raise AssetConflict("이 자산에 동일한 보고서가 이미 등록되어 있습니다.")
|
||||
report_id = uuid.uuid4().hex
|
||||
conn.execute("INSERT INTO asset_reports(id,asset_id,filename,sha256,raw_xml,parsed,actor) VALUES(%s,%s,%s,%s,%s,%s,%s)",
|
||||
(report_id, asset_id, filename, parsed["sha256"], raw, Jsonb(parsed), actor))
|
||||
conn.execute("UPDATE assets SET latest_report_id=%s,version=version+1,updated_at=now() WHERE id=%s", (report_id, asset_id))
|
||||
self._event(conn, asset_id, actor, "report", filename, {"report_id": report_id, "summary": parsed["summary"]})
|
||||
return report_id
|
||||
|
||||
def attach_report(self, asset_id, version, actor, filename, raw, parsed):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
asset = self._lock(conn, asset_id, version)
|
||||
if asset["category"] != "computer":
|
||||
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||
return self._save_report(conn, asset_id, actor, filename, raw, parsed)
|
||||
|
||||
def report(self, asset_id, report_id, *, raw=False):
|
||||
columns = "filename,raw_xml" if raw else "id,filename,parsed,uploaded_at"
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(f"SELECT {columns} FROM asset_reports WHERE asset_id=%s AND id=%s", (asset_id, report_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(report_id)
|
||||
return serialize(row)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""HWiNFO XML을 부품별로 읽습니다. 외부 파일이나 엔티티는 열지 않습니다."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime
|
||||
from xml.etree.ElementTree import ParseError
|
||||
|
||||
from defusedxml.ElementTree import fromstring
|
||||
from defusedxml.common import DefusedXmlException
|
||||
|
||||
MAX_REPORT_BYTES = 10 * 1024 * 1024
|
||||
SECTION_LABELS = {
|
||||
"SYSTEM": "시스템", "CPU": "프로세서", "MOBO": "메인보드 · BIOS",
|
||||
"MEMORY": "메모리", "VIDEO": "그래픽", "MONITOR": "모니터",
|
||||
"DRIVES": "저장장치", "NETWORK": "네트워크", "SOUND": "오디오",
|
||||
"PORTS": "포트 · USB", "BUS": "버스 · 컨트롤러",
|
||||
}
|
||||
|
||||
|
||||
def _text(node, tag):
|
||||
return (node.findtext(tag) or "").strip()
|
||||
|
||||
|
||||
def _props(node):
|
||||
return [{"label": _text(p, "Entry"), "value": _text(p, "Description"),
|
||||
"type": _text(p, "PropertyType")} for p in node.findall("Property")]
|
||||
|
||||
|
||||
def _pick(nodes, *, types=(), labels=()):
|
||||
# 언어와 무관한 PropertyType을 먼저 사용하고, 없을 때 한글/영문 항목명을 찾습니다.
|
||||
properties = [p for n in nodes for p in n["properties"]]
|
||||
for kind in types:
|
||||
for p in properties:
|
||||
if p["type"] == kind and p["value"]:
|
||||
return p["value"]
|
||||
for label in labels:
|
||||
for p in properties:
|
||||
if p["label"].casefold() == label.casefold() and p["value"]:
|
||||
return p["value"]
|
||||
return ""
|
||||
|
||||
|
||||
def parse_hwinfo(raw: bytes) -> dict:
|
||||
if not raw or len(raw) > MAX_REPORT_BYTES:
|
||||
raise ValueError("XML 보고서는 비어 있지 않은 10 MB 이하 파일이어야 합니다.")
|
||||
try:
|
||||
# HWiNFO의 DTD 선언은 허용하되 파일을 읽지 않습니다. 엔티티는 모두 차단합니다.
|
||||
root = fromstring(raw, forbid_dtd=False, forbid_entities=True, forbid_external=True)
|
||||
except (ParseError, DefusedXmlException, ValueError, LookupError) as exc:
|
||||
raise ValueError("XML을 읽을 수 없습니다. HWiNFO XML 보고서인지 확인하세요.") from exc
|
||||
if root.tag != "HWINFO" or len(root.findall("COMPUTER")) != 1:
|
||||
raise ValueError("컴퓨터 한 대의 HWiNFO XML 보고서만 업로드할 수 있습니다.")
|
||||
computer = root.find("COMPUTER")
|
||||
sections = [{"key": "SYSTEM", "label": "시스템", "nodes": []}]
|
||||
count = 0
|
||||
|
||||
def walk(node, path, result, depth=0):
|
||||
nonlocal count
|
||||
count += 1
|
||||
if count > 30000 or depth > 64:
|
||||
raise ValueError("보고서 구조가 너무 크거나 깊습니다.")
|
||||
name = _text(node, "NodeName")
|
||||
trail = path + ([name] if name else [])
|
||||
props = _props(node)
|
||||
if props:
|
||||
result.append({"name": name or node.tag, "path": " › ".join(trail), "properties": props})
|
||||
for child in node:
|
||||
if child.tag in {"SubNodes", "SubNode"}:
|
||||
walk(child, trail, result, depth + 1)
|
||||
elif child.find("NodeName") is not None:
|
||||
walk(child, trail, result, depth + 1)
|
||||
|
||||
sections[0]["nodes"] = [{"name": _text(computer, "NodeName") or "컴퓨터",
|
||||
"path": "시스템", "properties": _props(computer)}]
|
||||
subnodes = computer.find("SubNodes")
|
||||
if subnodes is not None:
|
||||
for node in subnodes:
|
||||
group = {"key": node.tag, "label": SECTION_LABELS.get(node.tag, _text(node, "NodeName") or node.tag), "nodes": []}
|
||||
walk(node, [], group["nodes"])
|
||||
sections.append(group)
|
||||
by_key = {s["key"]: s["nodes"] for s in sections}
|
||||
get = lambda key, **kw: _pick(by_key.get(key, []), **kw)
|
||||
summary = {
|
||||
"computer_name": _text(computer, "NodeName") or get("SYSTEM", labels=("컴퓨터 이름", "Computer Name")),
|
||||
"os": get("SYSTEM", labels=("운영 체제", "Operating System")),
|
||||
"manufacturer": get("SYSTEM", labels=("컴퓨터 브랜드", "Computer Brand Name")),
|
||||
"cpu": get("CPU", types=("CPU_NAME",), labels=("프로세서 이름", "Processor Name")),
|
||||
"cores": get("CPU", labels=("프로세서 코어 수", "CPU 코어 수", "Number of CPU Cores", "Number of Processor Cores")),
|
||||
"threads": get("CPU", labels=("논리 프로세서 수", "논리 CPU 수", "Number of Logical CPUs", "Number of Logical Processors")),
|
||||
"motherboard": get("MOBO", types=("SYSTEM_MAINBOARD",)),
|
||||
"bios": get("MOBO", labels=("BIOS 버전", "BIOS Version")),
|
||||
"memory": get("MEMORY", labels=("총 메모리 크기", "Total Memory Size")),
|
||||
"gpu": get("VIDEO", types=("GFXCARD_CHIPSET", "GFXCARD")),
|
||||
"gpu_memory": get("VIDEO", labels=("그래픽 메모리", "Video Memory", "Video Memory Size")),
|
||||
"serial": get("MOBO", labels=("제품 일련 번호", "Product Serial Number", "System Serial Number")),
|
||||
}
|
||||
if summary["serial"].casefold() in {"system serial number", "to be filled by o.e.m.", "default string", "none", "n/a"}:
|
||||
summary["serial"] = ""
|
||||
if not summary["memory"]:
|
||||
mb = get("MEMORY", types=("SYSTEM_MEMORY",))
|
||||
if re.fullmatch(r"\d+(\.\d+)?", mb):
|
||||
summary["memory"] = f"{float(mb) / 1024:g} GiB"
|
||||
devices = {}
|
||||
for key, types, labels in [
|
||||
("DRIVES", ("HDD",), ("드라이브 모델", "Drive Model")),
|
||||
("MEMORY", (), ("모듈 부품 번호", "Module Part Number")),
|
||||
("MONITOR", ("MONITOR",), ("모니터 이름", "Monitor Name")),
|
||||
("NETWORK", ("NETCARD",), ("네트워크 카드", "Network Card")),
|
||||
("VIDEO", ("GFXCARD_CHIPSET", "GFXCARD"), ("그래픽 프로세서", "Video Chipset")),
|
||||
]:
|
||||
devices[key] = []
|
||||
for node in by_key.get(key, []):
|
||||
model = _pick([node], types=types, labels=labels)
|
||||
if model:
|
||||
devices[key].append({"name": model, "node": node["name"], "properties": node["properties"]})
|
||||
summary["drive_count"] = len(devices["DRIVES"])
|
||||
summary["monitor_count"] = len(devices["MONITOR"])
|
||||
if not summary["computer_name"] or not any(summary[k] for k in ("cpu", "motherboard", "memory", "gpu")):
|
||||
raise ValueError("컴퓨터 이름과 하드웨어 사양이 포함된 HWiNFO 보고서가 필요합니다.")
|
||||
scan_time = _text(computer, "ScanTime")
|
||||
try:
|
||||
scan_time = datetime.strptime(scan_time, "%d.%m.%Y %H:%M").isoformat(timespec="minutes")
|
||||
except ValueError:
|
||||
pass # 날짜 형식이 다르면 원래 보고서에 적힌 시각을 그대로 보존합니다.
|
||||
warnings = [p["value"] for p in _props(computer) if p["label"] in ("가상 머신 경고", "Virtual Machine Warning") and p["value"]]
|
||||
return {"summary": summary, "sections": sections, "devices": devices, "scan_time": scan_time,
|
||||
"warnings": warnings, "sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"property_count": sum(len(n["properties"]) for s in sections for n in s["nodes"])}
|
||||
@@ -0,0 +1,246 @@
|
||||
from __future__ import annotations
|
||||
|
||||
# 화면, 권한 검사, 파일 업로드를 담당합니다. 실제 저장은 db.py에서 처리합니다.
|
||||
|
||||
import io
|
||||
import secrets
|
||||
from contextlib import contextmanager
|
||||
from typing import Annotated
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from openpyxl import Workbook
|
||||
from pydantic import ValidationError
|
||||
from psycopg import Error as DBError
|
||||
from psycopg.errors import UniqueViolation
|
||||
from psycopg_pool import PoolTimeout
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .hwinfo import MAX_REPORT_BYTES, parse_hwinfo
|
||||
from .store import ActionInput, AssetConflict, AssetInput, AssetUpdate, CATEGORIES, STATUSES
|
||||
|
||||
router = APIRouter(prefix="/asset", tags=["asset"])
|
||||
|
||||
|
||||
def _user(request: Request):
|
||||
from app.main import get_current_user_record
|
||||
from app.store import has_module
|
||||
user = get_current_user_record(request)
|
||||
if not user:
|
||||
raise HTTPException(401, "로그인이 필요합니다.")
|
||||
if not has_module(user, "asset"):
|
||||
raise HTTPException(403, "자산관리 권한이 없습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _write(request: Request, user=Depends(_user)):
|
||||
expected = request.session.get("asset_csrf", "")
|
||||
token = request.headers.get("x-asset-csrf", "")
|
||||
if not expected or not secrets.compare_digest(expected, token):
|
||||
raise HTTPException(403, "화면을 새로 열고 다시 시도하세요.")
|
||||
return user
|
||||
|
||||
|
||||
def _store(request):
|
||||
store = getattr(request.app.state, "asset_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(503, "자산관리 DB 설정이 필요합니다. 관리자에게 문의하세요.")
|
||||
return store
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _errors():
|
||||
try:
|
||||
yield
|
||||
except AssetConflict as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
except KeyError as exc:
|
||||
raise HTTPException(404, "자산 또는 보고서를 찾을 수 없습니다.") from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
except UniqueViolation as exc:
|
||||
raise HTTPException(409, "이미 등록된 자산번호입니다. 다른 번호를 사용하세요.") from exc
|
||||
except (DBError, PoolTimeout) as exc:
|
||||
# DB 오류에 접속 비밀번호가 섞일 수 있어 원문 대신 일반 안내만 보여줍니다.
|
||||
raise HTTPException(503, "자산관리 DB에 연결할 수 없습니다. 설정과 초기화를 확인하세요.") from exc
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def index(request: Request):
|
||||
from app.main import build_erp_nav, get_current_user_record, render_template
|
||||
from app.store import has_module, is_admin
|
||||
user = get_current_user_record(request)
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
if not has_module(user, "asset"):
|
||||
return render_template(request, "denied.html", {"reason": "자산관리 권한이 없습니다.", "user": user,
|
||||
"is_admin": is_admin(user)}, status_code=403)
|
||||
request.session.setdefault("asset_csrf", secrets.token_urlsafe(32))
|
||||
return render_template(request, "asset/index.html", {
|
||||
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="asset"),
|
||||
"page_title": "자산관리", "page_subtitle": "사무집기부터 컴퓨터 사양까지, 회사 자산을 한곳에서",
|
||||
"categories": CATEGORIES, "statuses": STATUSES, "csrf_token": request.session["asset_csrf"],
|
||||
"configured": getattr(request.app.state, "asset_store", None) is not None,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request, user=Depends(_user)):
|
||||
with _errors():
|
||||
_store(request).health()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/api/bootstrap")
|
||||
def bootstrap(request: Request, user=Depends(_user)):
|
||||
from app.main import user_store
|
||||
with _errors():
|
||||
data = _store(request).dashboard()
|
||||
data["users"] = [{"email": u["email"], "name": u.get("name") or u["email"]} for u in user_store.list_all()]
|
||||
return data
|
||||
|
||||
|
||||
def _query(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||
if category and category not in CATEGORIES or status and status not in STATUSES:
|
||||
raise HTTPException(422, "분류 또는 상태 필터가 올바르지 않습니다.")
|
||||
if group not in {"", "computer", "furniture"}:
|
||||
raise HTTPException(422, "자산 구분 필터가 올바르지 않습니다.")
|
||||
return dict(q=q, category=category, status=status, location=location, assignee=assignee, warranty=warranty, group=group)
|
||||
|
||||
|
||||
@router.get("/api/assets")
|
||||
def assets(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||
page: int = Query(1, ge=1, le=100000), page_size: int = Query(25, ge=1, le=100),
|
||||
sort: str = "updated", group: str = "", user=Depends(_user)):
|
||||
with _errors():
|
||||
return _store(request).list_assets(page=page, page_size=page_size, sort=sort,
|
||||
**_query(q, category, status, location, assignee, warranty, group))
|
||||
|
||||
|
||||
@router.get("/api/export")
|
||||
def export(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||
group: str = "", user=Depends(_user)):
|
||||
from app.timezone import today_kst
|
||||
with _errors():
|
||||
data = _store(request).list_assets(page=1, page_size=10001, **_query(q, category, status, location, assignee, warranty, group))
|
||||
if data["total"] > 10000:
|
||||
raise HTTPException(422, "한 번에 10,000개까지 내보낼 수 있습니다. 필터를 좁혀주세요.")
|
||||
book = Workbook()
|
||||
sheet = book.active
|
||||
sheet.title = "자산대장"
|
||||
headers = ["자산번호", "자산명", "분류", "상태", "제조사", "모델", "시리얼", "위치", "부서", "사용자", "구매일", "구매금액(원)", "구매처", "보증종료", "메모", "CPU", "메모리", "GPU", "운영체제"]
|
||||
sheet.append(headers)
|
||||
for row in data["items"]:
|
||||
specs = row.get("specs") or {}
|
||||
values = [row["tag"], row["name"], CATEGORIES[row["category"]], STATUSES[row["status"]],
|
||||
*[row[k] for k in ("manufacturer", "model", "serial", "location", "department", "assignee_email", "purchased_on")],
|
||||
float(row["purchase_cost"]) if row["purchase_cost"] is not None else None,
|
||||
row["vendor"], row["warranty_until"], row["notes"], *[specs.get(k, "") for k in ("cpu", "memory", "gpu", "os")]]
|
||||
sheet.append(values)
|
||||
# =로 시작하는 자산명도 엑셀 수식 대신 일반 글자로 저장합니다.
|
||||
for cell in sheet[sheet.max_row]:
|
||||
if isinstance(cell.value, str):
|
||||
cell.data_type = "s"
|
||||
sheet.freeze_panes = "C2"
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True, color="FFFFFF")
|
||||
cell.fill = PatternFill("solid", fgColor="171717")
|
||||
for i in range(1, len(headers) + 1):
|
||||
sheet.column_dimensions[get_column_letter(i)].width = 22 if i > 2 else 28
|
||||
buffer = io.BytesIO()
|
||||
book.save(buffer)
|
||||
return Response(buffer.getvalue(), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f'attachment; filename="assets-{today_kst().isoformat()}.xlsx"'})
|
||||
|
||||
|
||||
@router.post("/api/assets")
|
||||
def create(request: Request, payload: AssetInput, user=Depends(_write)):
|
||||
with _errors():
|
||||
asset_id = _store(request).create(payload, user["email"])
|
||||
return {"id": asset_id}
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}")
|
||||
def detail(request: Request, asset_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
return _store(request).detail(asset_id)
|
||||
|
||||
|
||||
@router.put("/api/assets/{asset_id}")
|
||||
def update(request: Request, asset_id: str, payload: AssetUpdate, user=Depends(_write)):
|
||||
with _errors():
|
||||
_store(request).update(asset_id, payload, user["email"])
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/actions")
|
||||
def action(request: Request, asset_id: str, payload: ActionInput, user=Depends(_write)):
|
||||
from app.main import user_store
|
||||
if payload.action == "checkout" and not user_store.get(payload.assignee_email.lower()):
|
||||
raise HTTPException(422, "등록된 회사 사용자를 선택하세요.")
|
||||
with _errors():
|
||||
_store(request).action(asset_id, payload, user["email"])
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
async def _report_file(file):
|
||||
filename = (file.filename or "report.xml").replace("\\", "/").rsplit("/", 1)[-1]
|
||||
if not filename.lower().endswith(".xml") or len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||
raise HTTPException(422, "이름이 200자 이하인 XML 보고서를 선택하세요.")
|
||||
try:
|
||||
raw = await file.read(MAX_REPORT_BYTES + 1)
|
||||
finally:
|
||||
await file.close()
|
||||
with _errors():
|
||||
parsed = await run_in_threadpool(parse_hwinfo, raw)
|
||||
return filename, raw, parsed
|
||||
|
||||
|
||||
@router.post("/api/reports/preview")
|
||||
async def preview(file: Annotated[UploadFile, File()], user=Depends(_write)):
|
||||
filename, raw, parsed = await _report_file(file)
|
||||
return {"filename": filename, "summary": parsed["summary"], "scan_time": parsed["scan_time"],
|
||||
"property_count": parsed["property_count"], "warnings": parsed["warnings"]}
|
||||
|
||||
|
||||
@router.post("/api/reports/import")
|
||||
async def import_report(request: Request, file: Annotated[UploadFile, File()], payload: Annotated[str, Form(max_length=20000)], user=Depends(_write)):
|
||||
with _errors():
|
||||
try:
|
||||
data = AssetInput.model_validate_json(payload)
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(422, "자산명·분류·구매일·금액을 확인하세요.") from exc
|
||||
report = await _report_file(file)
|
||||
with _errors():
|
||||
asset_id = await run_in_threadpool(_store(request).create, data, user["email"], report)
|
||||
return {"id": asset_id}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/reports")
|
||||
async def attach(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||
filename, raw, parsed = await _report_file(file)
|
||||
with _errors():
|
||||
report_id = await run_in_threadpool(_store(request).attach_report, asset_id, version, user["email"], filename, raw, parsed)
|
||||
return {"id": report_id}
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/reports/{report_id}")
|
||||
def report_detail(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
return _store(request).report(asset_id, report_id)
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/reports/{report_id}/download")
|
||||
def download(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
row = _store(request).report(asset_id, report_id, raw=True)
|
||||
return Response(bytes(row["raw_xml"]), media_type="application/octet-stream",
|
||||
headers={"Content-Disposition": f"attachment; filename=hwinfo.xml; filename*=UTF-8''{quote(row['filename'], safe='')}",
|
||||
"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Asset validation and lifecycle rules, shared by API and storage."""
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
CATEGORIES = {"computer": "컴퓨터", "monitor": "모니터", "mouse": "마우스", "keyboard": "키보드",
|
||||
"camera": "카메라", "hub": "허브 · 네트워크", "lighting": "조명", "desk": "책상",
|
||||
"chair": "의자", "furniture": "기타 사무집기", "equipment": "기타 전산장비"}
|
||||
STATUSES = {"available": "사용 가능", "in_use": "사용 중", "maintenance": "수리 중", "lost": "분실", "retired": "폐기"}
|
||||
|
||||
|
||||
class AssetInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
tag: str = Field(default="", max_length=64)
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
category: str
|
||||
manufacturer: str = Field(default="", max_length=150)
|
||||
model: str = Field(default="", max_length=200)
|
||||
serial: str = Field(default="", max_length=200)
|
||||
location: str = Field(default="", max_length=150)
|
||||
department: str = Field(default="", max_length=100)
|
||||
purchased_on: date | None = None
|
||||
purchase_cost: Decimal | None = Field(default=None, ge=0, le=10**12, decimal_places=2)
|
||||
vendor: str = Field(default="", max_length=200)
|
||||
warranty_until: date | None = None
|
||||
notes: str = Field(default="", max_length=10000)
|
||||
|
||||
@field_validator("category")
|
||||
@classmethod
|
||||
def valid_category(cls, value):
|
||||
if value not in CATEGORIES:
|
||||
raise ValueError("자산 분류가 올바르지 않습니다.")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_dates(self):
|
||||
if self.purchased_on and self.warranty_until and self.warranty_until < self.purchased_on:
|
||||
raise ValueError("보증 종료일은 구매일 이후여야 합니다.")
|
||||
return self
|
||||
|
||||
|
||||
class AssetUpdate(AssetInput):
|
||||
version: int = Field(ge=1)
|
||||
|
||||
|
||||
class ActionInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
action: str
|
||||
assignee_email: str = Field(default="", max_length=254)
|
||||
location: str = Field(default="", max_length=150)
|
||||
note: str = Field(default="", max_length=2000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_reason(self):
|
||||
if self.action in {"lost", "retired"} and not self.note:
|
||||
raise ValueError("분실·폐기 사유를 입력하세요.")
|
||||
return self
|
||||
|
||||
|
||||
class AssetConflict(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def transition(asset, payload: ActionInput):
|
||||
state = asset["status"]
|
||||
if payload.action == "checkout":
|
||||
if state != "available" or not payload.assignee_email:
|
||||
raise ValueError("사용 가능한 자산을 선택하고 배정할 사용자를 지정하세요.")
|
||||
return "in_use", payload.assignee_email.lower()
|
||||
if payload.action == "checkin":
|
||||
if state != "in_use":
|
||||
raise ValueError("사용 중인 자산만 반납할 수 있습니다.")
|
||||
return "available", ""
|
||||
if payload.action == "maintenance" and state == "available":
|
||||
return "maintenance", ""
|
||||
if payload.action == "available" and state in {"maintenance", "lost", "retired"}:
|
||||
return "available", ""
|
||||
if payload.action == "lost" and state in {"available", "in_use", "maintenance"}:
|
||||
return "lost", asset.get("assignee_email", "")
|
||||
if payload.action == "retired" and state in {"available", "maintenance", "lost"}:
|
||||
return "retired", ""
|
||||
raise ValueError("현재 상태에서 처리할 수 없습니다. 배정된 자산은 먼저 반납하세요.")
|
||||
@@ -0,0 +1,68 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% set force_sidebar_collapsed = true %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006a">{% endblock %}
|
||||
{% block content %}
|
||||
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}">
|
||||
<aside class="am-nav" aria-label="자산관리 탐색">
|
||||
<div class="am-nav-brand"><span class="am-mark">A</span><div><strong>회사 자산</strong><small>ASSET MANAGEMENT</small></div></div>
|
||||
<button class="am-nav-link is-active" data-view="all"><span>전체 자산</span><span id="am-nav-total" class="am-count">—</span></button>
|
||||
<button class="am-nav-link" data-view="computer"><span>컴퓨터 · 전산장비</span></button>
|
||||
<button class="am-nav-link" data-view="furniture"><span>사무실 · 집기</span></button>
|
||||
<p class="am-nav-label">자산 상태</p>
|
||||
{% for key,label in statuses.items() %}<button class="am-nav-link" data-state="{{ key }}"><span><i class="am-dot am-dot-{{ key }}"></i>{{ label }}</span><span class="am-count" id="am-count-{{ key }}">—</span></button>{% endfor %}
|
||||
<p class="am-nav-label">확인할 항목</p>
|
||||
<button class="am-nav-link" data-view="warranty"><span>보증 만료 예정</span><span class="am-count" id="am-count-warranty">—</span></button>
|
||||
<div class="am-nav-foot"><strong>자산 한 개, 기록 하나</strong><p>개별 자산번호로 등록하고<br>배정부터 폐기까지 추적하세요.</p><button class="am-text-btn" id="am-help-open">사용 안내 ↗</button></div>
|
||||
</aside>
|
||||
<section class="am-main" aria-label="자산대장">
|
||||
<div class="am-heading"><div><p class="am-eyebrow">COMPANY INVENTORY</p><h2>회사 자산 대장</h2><p>어떤 자산이, 어디에, 누구에게 있는지 확인하세요.</p></div><div class="am-heading-actions"><button class="erp-btn erp-btn-outline" id="am-import">↑ HWiNFO 보고서</button><button class="erp-btn erp-btn-primary" id="am-create" {% if not configured %}disabled{% endif %}>+ 자산 등록</button></div></div>
|
||||
{% if not configured %}<div class="am-notice" role="status"><strong>자산관리 저장소 설정이 필요합니다.</strong><p>관리자가 자산관리 DB를 연결하면 등록·배정·반납을 사용할 수 있습니다. HWiNFO 보고서는 지금도 분석 결과를 미리 볼 수 있습니다.</p></div>{% endif %}
|
||||
<div id="am-message" class="am-message" role="status" aria-live="polite" hidden></div>
|
||||
<div class="am-kpis" aria-label="자산 현황">
|
||||
<button data-kpi="all" class="am-kpi"><span>전체 자산</span><strong id="am-total">—</strong><small>회사에 등록된 자산</small></button>
|
||||
<button data-kpi="in_use" class="am-kpi"><span><i class="am-dot am-dot-in_use"></i>사용 중</span><strong id="am-in_use">—</strong><small>직원에게 배정된 자산</small></button>
|
||||
<button data-kpi="available" class="am-kpi"><span><i class="am-dot am-dot-available"></i>사용 가능</span><strong id="am-available">—</strong><small>새로 배정할 수 있는 자산</small></button>
|
||||
<button data-kpi="maintenance" class="am-kpi"><span><i class="am-dot am-dot-maintenance"></i>수리 중</span><strong id="am-maintenance">—</strong><small>점검 · 수리 중인 자산</small></button>
|
||||
<button data-kpi="warranty" class="am-kpi"><span>보증 만료 예정</span><strong id="am-warranty_soon">—</strong><small>오늘부터 30일 이내</small></button>
|
||||
</div>
|
||||
<div class="am-register">
|
||||
<div class="am-register-head"><div><h3 id="am-list-title">전체 자산</h3><span id="am-result-count">자산을 불러오는 중</span></div><div><button class="am-text-btn" id="am-refresh" aria-label="자산 새로고침">↻ 새로고침</button><button class="erp-btn erp-btn-outline" id="am-export" {% if not configured %}disabled{% endif %}>엑셀 내보내기 ↓</button></div></div>
|
||||
<form class="am-filters" id="am-filters" role="search">
|
||||
<label class="am-search"><span aria-hidden="true">⌕</span><input id="am-query" type="search" maxlength="200" placeholder="자산명, 번호, 모델, 시리얼 검색" aria-label="자산 검색"></label>
|
||||
<select id="am-category" aria-label="분류"><option value="">모든 분류</option>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||
<select id="am-status" aria-label="상태"><option value="">모든 상태</option>{% for key,label in statuses.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||
<select id="am-location" aria-label="위치"><option value="">모든 위치</option></select>
|
||||
<select id="am-assignee" aria-label="배정 사용자"><option value="">모든 사용자</option></select>
|
||||
<select id="am-sort" aria-label="정렬"><option value="updated">최근 변경순</option><option value="name">자산명순</option><option value="tag">자산번호순</option><option value="cost">구매금액순</option><option value="warranty">보증종료순</option></select>
|
||||
<button type="button" class="am-text-btn" id="am-reset">초기화</button>
|
||||
</form>
|
||||
<div class="am-table-scroll"><table class="am-table"><thead><tr><th>자산</th><th>분류</th><th>상태</th><th>사용자 / 위치</th><th>구매금액</th><th>보증 종료</th><th>사양</th></tr></thead><tbody id="am-rows"><tr><td colspan="7" class="am-empty">{% if configured %}자산을 불러오는 중입니다.{% else %}등록된 자산이 여기에 표시됩니다.{% endif %}</td></tr></tbody></table></div>
|
||||
<div class="am-pagination"><span id="am-page-info">—</span><div><button class="erp-btn erp-btn-outline" id="am-prev" disabled>← 이전</button><span id="am-page-number">1</span><button class="erp-btn erp-btn-outline" id="am-next" disabled>다음 →</button></div></div>
|
||||
</div>
|
||||
<div class="am-bottom"><section class="am-panel"><div class="am-panel-head"><h3>자산 구성</h3><span>분류별 등록 수</span></div><div id="am-breakdown" class="am-breakdown"><p class="am-muted">등록된 자산이 없습니다.</p></div><div class="am-value"><span>보유 자산 구매금액 <small>폐기 제외 · 입력된 금액 기준</small></span><strong id="am-value">—</strong></div></section><section class="am-panel"><div class="am-panel-head"><h3>최근 활동</h3><span>등록 · 배정 · 반납 · 변경</span></div><div id="am-activity" class="am-activity"><p class="am-muted">활동 이력이 여기에 표시됩니다.</p></div></section></div>
|
||||
</section>
|
||||
</div>
|
||||
<dialog id="am-detail" class="am-drawer" aria-labelledby="am-detail-title"><div class="am-dialog-head"><div><small id="am-detail-tag">자산 상세</small><h2 id="am-detail-title">자산 정보</h2></div><button type="button" class="am-close" data-close="am-detail" aria-label="자산 상세 닫기">×</button></div><div id="am-detail-content"></div></dialog>
|
||||
<dialog id="am-editor" class="am-dialog" aria-labelledby="am-editor-title"><div class="am-dialog-head"><div><small>ASSET REGISTER</small><h2 id="am-editor-title">자산 등록</h2></div><button type="button" class="am-close" data-close="am-editor" aria-label="등록 창 닫기">×</button></div><form id="am-editor-form" class="am-form"><div class="am-form-grid">
|
||||
<label>자산명 <span>*</span><input name="name" maxlength="200" required placeholder="예: 디자인팀 데스크톱"></label>
|
||||
<label>자산번호<input name="tag" maxlength="64" placeholder="비워두면 자동 발급 (AST-000001)"></label>
|
||||
<label>분류 <span>*</span><select name="category" required>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label>
|
||||
<label>제조사<input name="manufacturer" maxlength="150" placeholder="예: Dell, 시디즈"></label>
|
||||
<label>모델<input name="model" maxlength="200"></label><label>시리얼 번호<input name="serial" maxlength="200"></label>
|
||||
<label>위치<input name="location" maxlength="150" list="am-locations" placeholder="예: 본사 3층 디자인팀"></label><label>부서<input name="department" maxlength="100"></label>
|
||||
<label>구매일<input type="date" name="purchased_on"></label><label>구매금액 (원)<input type="number" name="purchase_cost" min="0" max="1000000000000" step="0.01" placeholder="미입력 가능"></label>
|
||||
<label>구매처<input name="vendor" maxlength="200"></label><label>보증 종료일<input type="date" name="warranty_until"></label>
|
||||
<label class="am-wide">메모<textarea name="notes" maxlength="10000" rows="3" placeholder="관리에 필요한 추가 정보를 입력하세요."></textarea></label>
|
||||
</div><p class="am-form-hint">같은 모델도 자산번호를 각각 발급합니다. 사용자 배정은 등록 후 상세 화면에서 진행합니다.</p><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-editor">취소</button><button type="submit" class="erp-btn erp-btn-primary">자산 저장</button></div></form></dialog>
|
||||
<dialog id="am-upload" class="am-dialog am-upload-dialog" aria-labelledby="am-upload-title"><div class="am-dialog-head"><div><small>HWiNFO XML IMPORT</small><h2 id="am-upload-title">컴퓨터 보고서 가져오기</h2></div><button type="button" class="am-close" data-close="am-upload" aria-label="업로드 창 닫기">×</button></div><form id="am-upload-form" class="am-form">
|
||||
<p class="am-form-hint" id="am-upload-hint">HWiNFO에서 저장한 XML 보고서를 선택하세요. 사양을 분석한 뒤 자산으로 등록합니다.</p>
|
||||
<label class="am-drop" id="am-drop"><span class="am-upload-icon">↑</span><strong>XML 보고서 선택</strong><span>파일을 여기에 놓거나 클릭하세요 · 최대 10 MB</span><input type="file" id="am-report-file" accept=".xml" aria-label="HWiNFO XML 보고서 선택" required></label>
|
||||
<div id="am-report-preview" hidden></div>
|
||||
<div id="am-import-fields" class="am-form-grid" hidden><label>자산명 <span>*</span><input id="am-import-name" maxlength="200" required></label><label>위치<input id="am-import-location" maxlength="150" list="am-locations" placeholder="예: 본사 3층"></label></div>
|
||||
<div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><span id="am-upload-status" class="am-muted"></span><button type="button" class="erp-btn erp-btn-outline" data-close="am-upload">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-import-save" disabled>자산으로 등록</button></div>
|
||||
</form></dialog>
|
||||
<dialog id="am-action" class="am-dialog am-action-dialog" aria-labelledby="am-action-title"><div class="am-dialog-head"><div><small id="am-action-tag"></small><h2 id="am-action-title">자산 배정</h2></div><button type="button" class="am-close" data-close="am-action" aria-label="처리 창 닫기">×</button></div><form id="am-action-form" class="am-form"><p id="am-action-hint" class="am-form-hint"></p><label id="am-action-user-label">배정할 사용자 <span>*</span><select id="am-action-user"><option value="">사용자 선택</option></select></label><label>자산 위치<input id="am-action-location" list="am-locations" maxlength="150"></label><label>처리 메모<textarea id="am-action-note" maxlength="2000" rows="3" placeholder="배정 사유, 반납 상태, 수리 내용 등을 기록하세요."></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-action">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-action-save">처리하기</button></div></form></dialog>
|
||||
<dialog id="am-help" class="am-dialog" aria-labelledby="am-help-title"><div class="am-dialog-head"><h2 id="am-help-title">자산관리 사용 안내</h2><button class="am-close" data-close="am-help" aria-label="사용 안내 닫기">×</button></div><div class="am-form am-help"><h3>01. 자산 등록</h3><p>책상·의자·마우스 등은 개별 자산으로 등록합니다. 자산번호를 비워두면 자동 발급합니다. 컴퓨터는 HWiNFO 보고서를 가져오면 이름과 주요 사양을 확인하고 등록할 수 있습니다.</p><h3>02. 배정과 반납</h3><p>사용 가능한 자산을 등록된 회사 사용자에게 배정합니다. 사용 중인 자산은 반납 후 수리·폐기할 수 있습니다. 위치·사유와 처리자가 이력에 남습니다. 분실 처리 시 기존 배정 사용자도 기록됩니다.</p><h3>03. 컴퓨터 사양</h3><p>HWiNFO → 보고서 저장 → XML 형식을 선택합니다. 핵심 사양, 부품별 상세와 보고서 전체 항목을 볼 수 있습니다. 재업로드할 때 컴퓨터 이름을 확인하세요. 이전 보고서와 원본 XML은 보존됩니다.</p><h3>04. 찾기와 내보내기</h3><p>검색·분류·상태·위치·사용자 필터를 조합합니다. 엑셀 내보내기는 현재 필터에 해당하는 자산 전체를 포함하며 최대 10,000개입니다. 보증 만료 예정은 오늘부터 30일 이내입니다.</p><p class="am-form-hint">보고서에는 시리얼·MAC 주소 등 회사 장비 정보가 포함될 수 있습니다. 자산관리 권한을 가진 사용자만 조회할 수 있습니다.</p></div></dialog>
|
||||
<datalist id="am-locations"></datalist>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261006a" defer></script>{% endblock %}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,990 @@
|
||||
/* 회사 자산대장: 변경 요청에는 세션 확인 토큰과 자산의 수정 버전을 함께 보냅니다. */
|
||||
(() => {
|
||||
"use strict";
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const app = $("asset-app");
|
||||
if (!app) return;
|
||||
const { categories, statuses } = JSON.parse($("am-config").textContent);
|
||||
const configured = app.dataset.configured === "true";
|
||||
const names = {
|
||||
create: "자산 등록",
|
||||
update: "정보 수정",
|
||||
checkout: "사용자 배정",
|
||||
checkin: "자산 반납",
|
||||
maintenance: "수리 시작",
|
||||
available: "사용 가능으로 복구",
|
||||
lost: "분실 처리",
|
||||
retired: "폐기 처리",
|
||||
report: "사양 보고서 등록",
|
||||
};
|
||||
const fieldNames = {
|
||||
tag: "자산번호",
|
||||
name: "자산명",
|
||||
category: "분류",
|
||||
status: "상태",
|
||||
manufacturer: "제조사",
|
||||
model: "모델",
|
||||
serial: "시리얼",
|
||||
location: "위치",
|
||||
department: "부서",
|
||||
assignee_email: "사용자",
|
||||
purchased_on: "구매일",
|
||||
purchase_cost: "구매금액",
|
||||
vendor: "구매처",
|
||||
warranty_until: "보증 종료",
|
||||
notes: "메모",
|
||||
};
|
||||
const state = {
|
||||
users: [],
|
||||
detail: null,
|
||||
page: 1,
|
||||
group: "",
|
||||
warranty: false,
|
||||
tab: "overview",
|
||||
editing: null,
|
||||
uploadTarget: null,
|
||||
preview: null,
|
||||
file: null,
|
||||
action: "",
|
||||
listSeq: 0,
|
||||
detailSeq: 0,
|
||||
previewSeq: 0,
|
||||
};
|
||||
const esc = (value) =>
|
||||
String(value ?? "").replace(
|
||||
/[&<>"']/g,
|
||||
(c) =>
|
||||
({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[c],
|
||||
);
|
||||
const money = (value) =>
|
||||
value === null || value === undefined
|
||||
? "미입력"
|
||||
: Number(value).toLocaleString("ko-KR", { maximumFractionDigits: 2 }) +
|
||||
"원";
|
||||
const date = (value) =>
|
||||
value
|
||||
? new Date(value).toLocaleString("ko-KR", {
|
||||
timeZone: "Asia/Seoul",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
})
|
||||
: "—";
|
||||
const userName = (email) =>
|
||||
state.users.find((u) => u.email === email)?.name || email || "미배정";
|
||||
const badge = (status) =>
|
||||
`<span class="am-badge am-badge-${esc(status)}"><i class="am-dot am-dot-${esc(status)}"></i>${esc(statuses[status] || status)}</span>`;
|
||||
const icon = (cat) =>
|
||||
`<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${["desk", "chair", "furniture"].includes(cat) ? '<path d="M4 11h16M6 11v9M18 11v9M6 11V4h12v7M4 16h16"/>' : cat === "camera" ? '<rect x="3" y="6" width="18" height="14" rx="2"/><circle cx="12" cy="13" r="4"/><path d="M8 6l1-3h6l1 3"/>' : '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/>'}</svg>`;
|
||||
let messageTimer;
|
||||
function message(text, error = false) {
|
||||
const box = $("am-message");
|
||||
box.textContent = text;
|
||||
box.hidden = false;
|
||||
box.classList.toggle("is-error", error);
|
||||
clearTimeout(messageTimer);
|
||||
if (!error)
|
||||
messageTimer = setTimeout(() => {
|
||||
box.hidden = true;
|
||||
}, 6000);
|
||||
}
|
||||
function formError(form, error) {
|
||||
const box = form.querySelector(".am-form-error");
|
||||
box.textContent = error?.message || String(error);
|
||||
box.hidden = false;
|
||||
}
|
||||
function clearError(form) {
|
||||
form.querySelector(".am-form-error").hidden = true;
|
||||
}
|
||||
// JSON과 파일 업로드를 같은 방식으로 처리하고 서버의 오류를 화면에 전달합니다.
|
||||
async function api(path, { method = "GET", body, signal } = {}) {
|
||||
const headers = { "X-Asset-CSRF": app.dataset.csrf };
|
||||
if (body && !(body instanceof FormData)) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
body = JSON.stringify(body);
|
||||
}
|
||||
const response = await fetch("/asset/api/" + path, {
|
||||
method,
|
||||
body,
|
||||
headers,
|
||||
signal,
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) {
|
||||
let detail;
|
||||
try {
|
||||
detail = (await response.json()).detail;
|
||||
} catch (_) {}
|
||||
const text = Array.isArray(detail)
|
||||
? detail
|
||||
.map(
|
||||
(e) =>
|
||||
`${fieldNames[e.loc?.at(-1)] || e.loc?.at(-1) || "입력"}: ${e.msg}`,
|
||||
)
|
||||
.join(" / ")
|
||||
: detail;
|
||||
const error = new Error(
|
||||
text || `요청을 처리할 수 없습니다 (${response.status}).`,
|
||||
);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
function query() {
|
||||
const p = new URLSearchParams();
|
||||
for (const [key, id] of [
|
||||
["q", "am-query"],
|
||||
["category", "am-category"],
|
||||
["status", "am-status"],
|
||||
["location", "am-location"],
|
||||
["assignee", "am-assignee"],
|
||||
["sort", "am-sort"],
|
||||
]) {
|
||||
const v = $(id).value;
|
||||
if (v) p.set(key, v);
|
||||
}
|
||||
if (state.group) p.set("group", state.group);
|
||||
if (state.warranty) p.set("warranty", "true");
|
||||
p.set("page", state.page);
|
||||
return p;
|
||||
}
|
||||
function syncURL() {
|
||||
const p = query();
|
||||
if (state.detail && $("am-detail").open) {
|
||||
p.set("asset", state.detail.asset.id);
|
||||
p.set("tab", state.tab);
|
||||
}
|
||||
history.replaceState(null, "", "/asset/?" + p);
|
||||
}
|
||||
function syncNavigation() {
|
||||
const category = $("am-category").value,
|
||||
status = $("am-status").value;
|
||||
document.querySelectorAll(".am-nav-link").forEach((b) => {
|
||||
const active = b.dataset.state
|
||||
? status === b.dataset.state
|
||||
: b.dataset.view === "warranty"
|
||||
? state.warranty
|
||||
: b.dataset.view === "all"
|
||||
? !state.group && !category && !status && !state.warranty
|
||||
: state.group === b.dataset.view;
|
||||
b.classList.toggle("is-active", active);
|
||||
b.setAttribute("aria-current", active ? "page" : "false");
|
||||
});
|
||||
$("am-list-title").textContent = state.warranty
|
||||
? "보증 만료 예정"
|
||||
: status
|
||||
? statuses[status] + " 자산"
|
||||
: category
|
||||
? categories[category]
|
||||
: state.group === "computer"
|
||||
? "컴퓨터 · 전산장비"
|
||||
: state.group === "furniture"
|
||||
? "사무실 · 집기"
|
||||
: "전체 자산";
|
||||
}
|
||||
let listController;
|
||||
// 빠르게 검색할 때 늦게 도착한 이전 응답이 최신 검색 결과를 덮어쓰지 않게 합니다.
|
||||
async function loadList() {
|
||||
syncNavigation();
|
||||
syncURL();
|
||||
if (!configured) {
|
||||
$("am-result-count").textContent = "저장소 설정 대기";
|
||||
return;
|
||||
}
|
||||
const seq = ++state.listSeq;
|
||||
listController?.abort();
|
||||
listController = new AbortController();
|
||||
$("am-rows").setAttribute("aria-busy", "true");
|
||||
try {
|
||||
const result = await api("assets?" + query(), {
|
||||
signal: listController.signal,
|
||||
});
|
||||
if (seq !== state.listSeq) return;
|
||||
if (!result.items.length && state.page > 1 && result.total) {
|
||||
state.page = Math.ceil(result.total / result.page_size);
|
||||
return loadList();
|
||||
}
|
||||
$("am-result-count").textContent =
|
||||
`${result.total.toLocaleString("ko-KR")}개 자산`;
|
||||
$("am-rows").innerHTML =
|
||||
result.items
|
||||
.map(
|
||||
(a) =>
|
||||
`<tr><td><div class="am-asset-cell"><span class="am-asset-icon">${icon(a.category)}</span><div><button class="am-asset-name" data-open="${esc(a.id)}">${esc(a.name)}</button><span class="am-asset-meta">${esc(a.tag)}${a.model ? " · " + esc(a.model) : ""}</span></div></div></td><td>${esc(categories[a.category])}</td><td>${badge(a.status)}</td><td>${esc(userName(a.assignee_email))}<span class="am-sub">${esc(a.location || "위치 미지정")}</span></td><td>${money(a.purchase_cost)}</td><td>${esc(a.warranty_until || "—")}</td><td>${a.specs ? `<button class="am-spec-link" data-open="${esc(a.id)}" data-tab="specs">사양 보기 ↗</button>` : '<span class="am-muted">—</span>'}</td></tr>`,
|
||||
)
|
||||
.join("") ||
|
||||
`<tr><td colspan="7" class="am-empty"><strong>${result.total ? "이 페이지에 자산이 없습니다." : "조건에 맞는 자산이 없습니다."}</strong>새 자산을 등록하거나 검색 조건을 변경하세요.<br><button class="erp-btn erp-btn-outline" data-create>+ 자산 등록</button></td></tr>`;
|
||||
const pages = Math.max(1, Math.ceil(result.total / result.page_size));
|
||||
$("am-page-info").textContent = result.total
|
||||
? `${(state.page - 1) * result.page_size + 1}–${Math.min(state.page * result.page_size, result.total)} / ${result.total}개`
|
||||
: "0개";
|
||||
$("am-page-number").textContent = `${state.page} / ${pages}`;
|
||||
$("am-prev").disabled = state.page <= 1;
|
||||
$("am-next").disabled = state.page >= pages;
|
||||
} catch (error) {
|
||||
if (error.name !== "AbortError" && seq === state.listSeq) {
|
||||
message(error.message, true);
|
||||
$("am-rows").innerHTML =
|
||||
'<tr><td colspan="7" class="am-empty"><strong>자산을 불러오지 못했습니다.</strong>새로고침하여 다시 시도하세요.</td></tr>';
|
||||
}
|
||||
} finally {
|
||||
if (seq === state.listSeq) $("am-rows").removeAttribute("aria-busy");
|
||||
}
|
||||
}
|
||||
async function loadDashboard() {
|
||||
if (!configured) return;
|
||||
const data = await api("bootstrap");
|
||||
state.users = data.users;
|
||||
for (const key of [
|
||||
"total",
|
||||
"in_use",
|
||||
"available",
|
||||
"maintenance",
|
||||
"warranty_soon",
|
||||
])
|
||||
$("am-" + key).textContent = data.totals[key].toLocaleString("ko-KR");
|
||||
$("am-nav-total").textContent = data.totals.total;
|
||||
for (const key of Object.keys(statuses))
|
||||
$("am-count-" + key).textContent = data.totals[key];
|
||||
$("am-count-warranty").textContent = data.totals.warranty_soon;
|
||||
$("am-value").textContent = money(data.totals.purchase_total);
|
||||
const currentLocation = $("am-location").value,
|
||||
currentAssignee = $("am-assignee").value;
|
||||
$("am-location").innerHTML =
|
||||
'<option value="">모든 위치</option>' +
|
||||
data.locations
|
||||
.map((l) => `<option value="${esc(l)}">${esc(l)}</option>`)
|
||||
.join("");
|
||||
$("am-location").value = currentLocation;
|
||||
$("am-locations").innerHTML = data.locations
|
||||
.map((l) => `<option value="${esc(l)}"></option>`)
|
||||
.join("");
|
||||
const users = state.users
|
||||
.map(
|
||||
(u) =>
|
||||
`<option value="${esc(u.email)}">${esc(u.name)} · ${esc(u.email)}</option>`,
|
||||
)
|
||||
.join("");
|
||||
$("am-assignee").innerHTML =
|
||||
'<option value="">모든 사용자</option>' + users;
|
||||
$("am-assignee").value = currentAssignee;
|
||||
$("am-action-user").innerHTML =
|
||||
'<option value="">사용자 선택</option>' + users;
|
||||
$("am-breakdown").innerHTML =
|
||||
data.categories
|
||||
.map(
|
||||
(c) =>
|
||||
`<button class="am-category-bar" data-category="${esc(c.category)}"><div><span>${esc(categories[c.category])}</span><span>${c.count}</span></div><span class="am-bar"><i style="width:${Math.round((c.count / Math.max(1, data.totals.total)) * 100)}%"></i></span></button>`,
|
||||
)
|
||||
.join("") || '<p class="am-muted">등록된 자산이 없습니다.</p>';
|
||||
$("am-activity").innerHTML =
|
||||
data.activity
|
||||
.map(
|
||||
(e) =>
|
||||
`<div class="am-event"><i class="am-event-dot"></i><div><p><button class="am-text-btn" data-open="${esc(e.asset_id)}">${esc(e.name)}</button> · ${esc(names[e.kind] || e.kind)}</p><small>${esc(userName(e.actor))}</small></div><time>${esc(date(e.created_at))}</time></div>`,
|
||||
)
|
||||
.join("") || '<p class="am-muted">활동 이력이 없습니다.</p>';
|
||||
}
|
||||
async function refresh() {
|
||||
await loadDashboard();
|
||||
await loadList();
|
||||
}
|
||||
function show(id) {
|
||||
$(id).showModal();
|
||||
}
|
||||
function close(id) {
|
||||
// 저장 중에는 창을 닫거나 다시 제출해서 요청을 겹치지 않게 합니다.
|
||||
if ($(id).querySelector('form[data-busy="true"]')) return;
|
||||
if (id === "am-detail") {
|
||||
++state.detailSeq;
|
||||
state.detail = null;
|
||||
}
|
||||
if (id === "am-upload") ++state.previewSeq;
|
||||
$(id).close();
|
||||
if (id === "am-detail") syncURL();
|
||||
}
|
||||
function info(label, value, wide = false) {
|
||||
return `<div class="am-info-field${wide ? " am-wide" : ""}"><span>${esc(label)}</span><strong>${esc(value || "—")}</strong></div>`;
|
||||
}
|
||||
function summaryCards(s) {
|
||||
return `<div class="am-spec-cards"><div class="am-spec-card"><span>프로세서 / CPU</span><strong>${esc(s.cpu || "정보 없음")}</strong><small>${esc(s.cores || "—")} 코어 · ${esc(s.threads || "—")} 스레드</small></div><div class="am-spec-card"><span>메모리 / RAM</span><strong>${esc(s.memory || "정보 없음")}</strong><small>설치된 전체 메모리</small></div><div class="am-spec-card"><span>그래픽 / GPU</span><strong>${esc(s.gpu || "정보 없음")}</strong><small>${esc(s.gpu_memory)}</small></div><div class="am-spec-card"><span>저장장치 / STORAGE</span><strong>${s.drive_count ?? 0}개 드라이브</strong><small>내장 · 외장 드라이브 포함</small></div></div>`;
|
||||
}
|
||||
// 많은 기술 항목 중 용량·속도·시리얼을 먼저 보여주고, 전체 보고서는 아래에 보존합니다.
|
||||
function componentCards(parsed) {
|
||||
const groups = {
|
||||
MEMORY: "메모리 모듈",
|
||||
DRIVES: "저장장치",
|
||||
MONITOR: "모니터",
|
||||
NETWORK: "네트워크",
|
||||
};
|
||||
const labels = {
|
||||
MEMORY: [
|
||||
"모듈 용량",
|
||||
"Module Size",
|
||||
"메모리 유형",
|
||||
"Memory Type",
|
||||
"메모리 속도",
|
||||
"Memory Speed",
|
||||
"모듈 제조업체",
|
||||
"Module Manufacturer",
|
||||
],
|
||||
DRIVES: [
|
||||
"드라이브 용량",
|
||||
"Drive Capacity",
|
||||
"디스크 컨트롤러",
|
||||
"Drive Controller",
|
||||
"드라이브 일련 번호",
|
||||
"Drive Serial Number",
|
||||
],
|
||||
MONITOR: [
|
||||
"모니터 이름(제조업체)",
|
||||
"Monitor Name (Manuf)",
|
||||
"일련 번호",
|
||||
"Serial Number",
|
||||
"최대 수평 크기",
|
||||
"Maximum Horizontal Size",
|
||||
"최대 수직 크기",
|
||||
"Maximum Vertical Size",
|
||||
],
|
||||
NETWORK: [
|
||||
"MAC 주소",
|
||||
"MAC Address",
|
||||
"최대 링크 속도",
|
||||
"Maximum Link Speed",
|
||||
"현재 링크 속도",
|
||||
"Current Link Speed",
|
||||
],
|
||||
};
|
||||
const parts = Object.entries(groups)
|
||||
.map(([key, label]) => {
|
||||
const devices = parsed.devices[key] || [];
|
||||
if (!devices.length) return "";
|
||||
return `<details class="am-components" open><summary>${label} <span class="am-badge">${devices.length}개</span></summary><div class="am-component-grid">${devices
|
||||
.map((d) => {
|
||||
const props = d.properties.filter((p) =>
|
||||
labels[key].includes(p.label),
|
||||
);
|
||||
return `<div class="am-component-card"><strong>${esc(d.name)}</strong><small>${esc(d.node)}</small><dl>${props.map((p) => `<dt>${esc(p.label)}</dt><dd>${esc(p.value)}</dd>`).join("")}</dl></div>`;
|
||||
})
|
||||
.join("")}</div></details>`;
|
||||
})
|
||||
.join("");
|
||||
const s = parsed.summary;
|
||||
return `<div class="am-system-strip">${info("운영체제", s.os)}${info("메인보드 / BIOS", [s.motherboard, s.bios].filter(Boolean).join(" · "))}</div>${parts}`;
|
||||
}
|
||||
async function openDetail(id, tab = "overview") {
|
||||
const seq = ++state.detailSeq;
|
||||
state.tab = tab;
|
||||
state.reportView = null;
|
||||
if (!$("am-detail").open) show("am-detail");
|
||||
$("am-detail-title").textContent = "자산 정보";
|
||||
$("am-detail-tag").textContent = "불러오는 중";
|
||||
$("am-detail-content").innerHTML =
|
||||
'<p class="am-detail-body am-muted">자산 정보를 불러오는 중입니다.</p>';
|
||||
try {
|
||||
const data = await api("assets/" + encodeURIComponent(id));
|
||||
if (seq !== state.detailSeq || !$("am-detail").open) return;
|
||||
state.detail = data;
|
||||
renderDetail();
|
||||
syncURL();
|
||||
} catch (error) {
|
||||
if (seq === state.detailSeq)
|
||||
$("am-detail-content").innerHTML =
|
||||
`<div class="am-detail-body"><p class="am-warning">${esc(error.message)}</p><button class="erp-btn erp-btn-outline" data-open="${esc(id)}">다시 시도</button></div>`;
|
||||
}
|
||||
}
|
||||
function actionButtons(a) {
|
||||
let buttons = [];
|
||||
if (a.status === "available")
|
||||
buttons = ["checkout", "maintenance", "lost", "retired"];
|
||||
if (a.status === "in_use") buttons = ["checkin", "lost"];
|
||||
if (a.status === "maintenance") buttons = ["available", "lost", "retired"];
|
||||
if (a.status === "lost") buttons = ["available", "retired"];
|
||||
if (a.status === "retired") buttons = ["available"];
|
||||
return buttons
|
||||
.map(
|
||||
(action, i) =>
|
||||
`<button class="erp-btn ${i === 0 ? "erp-btn-primary" : "erp-btn-outline"}" data-action="${action}">${esc(names[action])}</button>`,
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
function renderDetail() {
|
||||
const { asset: a, reports, events } = state.detail;
|
||||
const report =
|
||||
state.tab === "specs" && state.reportView
|
||||
? state.reportView
|
||||
: state.detail.report;
|
||||
$("am-detail-title").textContent = a.name;
|
||||
$("am-detail-tag").textContent = a.tag + " · " + categories[a.category];
|
||||
const tabs = {
|
||||
overview: "기본 정보",
|
||||
specs: "컴퓨터 사양",
|
||||
reports: `보고서 ${reports.length}`,
|
||||
history: "활동 이력",
|
||||
};
|
||||
let body = "";
|
||||
if (state.tab === "overview") {
|
||||
body = `<section class="am-detail-section"><h3 class="am-section-title">자산 정보</h3><div class="am-info-grid">${info("분류", categories[a.category])}${info("제조사", a.manufacturer)}${info("모델", a.model)}${info("시리얼 번호", a.serial)}${info("배정 사용자", userName(a.assignee_email))}${info("위치", a.location)}${info("부서", a.department)}${info("최근 변경", date(a.updated_at))}</div></section><section class="am-detail-section"><h3 class="am-section-title">구매 · 보증</h3><div class="am-info-grid">${info("구매일", a.purchased_on)}${info("구매금액", money(a.purchase_cost))}${info("구매처", a.vendor)}${info("보증 종료일", a.warranty_until)}${info("메모", a.notes, true)}</div></section>`;
|
||||
if (report)
|
||||
body += `<section class="am-detail-section"><h3 class="am-section-title">컴퓨터 주요 사양</h3>${summaryCards(report.parsed.summary)}<button class="am-text-btn" data-detail-tab="specs">부품별 상세 사양 보기 →</button></section>`;
|
||||
else if (a.category === "computer")
|
||||
body +=
|
||||
'<section class="am-detail-section"><h3 class="am-section-title">컴퓨터 사양 연결</h3><p class="am-muted">HWiNFO XML 보고서를 올리면 주요 사양과 부품별 상세 정보를 볼 수 있습니다.</p><button class="erp-btn erp-btn-outline" data-attach>↑ 보고서 업로드</button></section>';
|
||||
} else if (state.tab === "specs") {
|
||||
if (!report)
|
||||
body = '<p class="am-empty">연결된 컴퓨터 보고서가 없습니다.</p>';
|
||||
else
|
||||
body = `<div class="am-panel-head"><h3 class="am-section-title">${esc(report.parsed.summary.computer_name)}</h3><button class="erp-btn erp-btn-outline" data-attach>↑ 보고서 갱신</button></div>${summaryCards(report.parsed.summary)}<p class="am-form-hint">${esc(report.filename)} · 수집 시각 ${esc(report.parsed.scan_time || "미기록")} · ${report.parsed.property_count.toLocaleString()}개 항목</p>${report.parsed.warnings.map((w) => `<p class="am-warning">${esc(w)}</p>`).join("")}<div class="am-spec-tools"><label class="am-search"><span aria-hidden="true">⌕</span><input type="search" id="am-spec-query" placeholder="부품명, 사양 항목, 값 검색" aria-label="사양 검색"></label><select id="am-spec-section" aria-label="부품 구분"><option value="">모든 부품</option>${report.parsed.sections.map((s) => `<option value="${esc(s.key)}">${esc(s.label)}</option>`).join("")}</select></div><div id="am-spec-nodes"></div>`;
|
||||
} else if (state.tab === "reports") {
|
||||
body =
|
||||
a.category === "computer"
|
||||
? '<div class="am-panel-head"><span class="am-muted">이전 보고서와 원본 XML이 보존됩니다.</span><button class="erp-btn erp-btn-outline" data-attach>↑ 보고서 업로드</button></div>'
|
||||
: "";
|
||||
body +=
|
||||
reports
|
||||
.map(
|
||||
(r) =>
|
||||
`<div class="am-report-row"><div><strong>${esc(r.filename)}${r.id === a.latest_report_id ? ' <span class="am-badge">최신</span>' : ""}</strong><p>${esc(r.summary.computer_name)} · ${esc(r.summary.cpu)} · ${esc(r.summary.memory)}<br>업로드 ${esc(date(r.uploaded_at))} · ${esc(userName(r.actor))}<br>수집 ${esc(r.scan_time || "미기록")}</p></div><div><button class="erp-btn erp-btn-outline" data-report="${esc(r.id)}">사양 보기</button><a class="erp-btn erp-btn-outline" href="/asset/api/assets/${encodeURIComponent(a.id)}/reports/${encodeURIComponent(r.id)}/download">원본 ↓</a></div></div>`,
|
||||
)
|
||||
.join("") || '<p class="am-muted">업로드된 보고서가 없습니다.</p>';
|
||||
} else {
|
||||
body =
|
||||
events
|
||||
.map((e) => {
|
||||
const changes = Object.entries(e.changes)
|
||||
.filter(
|
||||
([k, v]) =>
|
||||
fieldNames[k] && v && typeof v === "object" && "before" in v,
|
||||
)
|
||||
.map(
|
||||
([k, v]) =>
|
||||
`${fieldNames[k]}: ${k === "status" ? statuses[v.before] : k === "category" ? categories[v.before] : v.before || "—"} → ${k === "status" ? statuses[v.after] : k === "category" ? categories[v.after] : v.after || "—"}`,
|
||||
)
|
||||
.join("\n");
|
||||
return `<div class="am-history-row"><h4>${esc(names[e.kind] || e.kind)}</h4>${e.note ? `<p>${esc(e.note)}</p>` : ""}${changes ? `<p>${esc(changes)}</p>` : ""}<small>${esc(date(e.created_at))} · ${esc(userName(e.actor))}</small></div>`;
|
||||
})
|
||||
.join("") +
|
||||
'<p class="am-form-hint">최근 200개 이력을 표시합니다. 전체 이력은 저장소에 보존됩니다.</p>';
|
||||
}
|
||||
if (state.tab === "specs" && report)
|
||||
body = body.replace(
|
||||
'<div class="am-spec-tools">',
|
||||
componentCards(report.parsed) +
|
||||
'<h3 class="am-section-title am-full-report-title">보고서 전체 항목</h3><div class="am-spec-tools">',
|
||||
);
|
||||
if (state.tab === "specs" && state.reportView)
|
||||
body =
|
||||
'<p class="am-warning">선택한 보고서의 사양입니다. 현재 자산의 최신 보고서는 변경되지 않습니다.</p>' +
|
||||
body;
|
||||
$("am-detail-content").innerHTML =
|
||||
`<div class="am-detail-body"><div class="am-detail-actions">${badge(a.status)}${actionButtons(a)}<button class="erp-btn erp-btn-outline" data-edit>정보 수정</button></div></div><nav class="am-tabs" aria-label="자산 상세 보기">${Object.entries(
|
||||
tabs,
|
||||
)
|
||||
.filter(
|
||||
([k]) =>
|
||||
a.category === "computer" || !["specs", "reports"].includes(k),
|
||||
)
|
||||
.map(
|
||||
([k, name]) =>
|
||||
`<button class="${state.tab === k ? "is-active" : ""}" data-detail-tab="${k}" aria-current="${state.tab === k ? "page" : "false"}">${esc(name)}</button>`,
|
||||
)
|
||||
.join("")}</nav><div class="am-detail-body">${body}</div>`;
|
||||
if (state.tab === "specs" && report) {
|
||||
renderSpecs();
|
||||
$("am-spec-query").addEventListener("input", renderSpecs);
|
||||
$("am-spec-section").addEventListener("change", renderSpecs);
|
||||
}
|
||||
}
|
||||
function renderSpecs() {
|
||||
const query = $("am-spec-query").value.trim().toLocaleLowerCase(),
|
||||
section = $("am-spec-section").value;
|
||||
const sections = (
|
||||
state.reportView || state.detail.report
|
||||
).parsed.sections.filter((s) => !section || section === s.key);
|
||||
let count = 0;
|
||||
$("am-spec-nodes").innerHTML =
|
||||
sections
|
||||
.map((s) =>
|
||||
s.nodes
|
||||
.map((n) => {
|
||||
const nameMatches = (n.name + " " + n.path)
|
||||
.toLocaleLowerCase()
|
||||
.includes(query);
|
||||
const props = n.properties.filter(
|
||||
(p) =>
|
||||
!query ||
|
||||
nameMatches ||
|
||||
(p.label + " " + p.value).toLocaleLowerCase().includes(query),
|
||||
);
|
||||
if (!props.length) return "";
|
||||
count++;
|
||||
return `<details class="am-node"${query || section ? " open" : ""}><summary>${esc(n.name)} <span class="am-badge">${props.length}</span><span class="am-node-path">${esc(s.label)} · ${esc(n.path)}</span></summary><dl class="am-properties">${props.map((p) => `<dt>${esc(p.label || p.type || "항목")}</dt><dd>${esc(p.value || "—")}</dd>`).join("")}</dl></details>`;
|
||||
})
|
||||
.join(""),
|
||||
)
|
||||
.join("") || '<p class="am-empty">검색 결과가 없습니다.</p>';
|
||||
}
|
||||
function openEditor(edit = false) {
|
||||
const form = $("am-editor-form");
|
||||
form.reset();
|
||||
clearError(form);
|
||||
state.editing = edit ? structuredClone(state.detail.asset) : null;
|
||||
$("am-editor-title").textContent = edit ? "자산 정보 수정" : "자산 등록";
|
||||
if (edit)
|
||||
for (const input of form.elements)
|
||||
if (input.name && input.name in state.editing)
|
||||
input.value = state.editing[input.name] ?? "";
|
||||
show("am-editor");
|
||||
form.elements.name.focus();
|
||||
}
|
||||
function assetPayload(form) {
|
||||
const data = Object.fromEntries(new FormData(form));
|
||||
for (const key of ["purchased_on", "warranty_until", "purchase_cost"])
|
||||
if (!data[key]) data[key] = null;
|
||||
return data;
|
||||
}
|
||||
// 저장에 실패하면 입력을 유지합니다. 저장 이후 조회 실패는 별도의 안내로 표시합니다.
|
||||
async function afterSave(id, tab = "overview") {
|
||||
try {
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
message(
|
||||
"저장은 완료됐지만 목록을 갱신하지 못했습니다. " + error.message,
|
||||
true,
|
||||
);
|
||||
}
|
||||
await openDetail(id, tab);
|
||||
}
|
||||
async function saveEditor(event) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget,
|
||||
button = form.querySelector('[type="submit"]');
|
||||
if (form.dataset.busy === "true" || !form.reportValidity()) return;
|
||||
form.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
clearError(form);
|
||||
try {
|
||||
const body = assetPayload(form);
|
||||
if (state.editing) body.version = state.editing.version;
|
||||
const result = await api(
|
||||
state.editing ? "assets/" + state.editing.id : "assets",
|
||||
{ method: state.editing ? "PUT" : "POST", body },
|
||||
);
|
||||
const id = state.editing?.id || result.id;
|
||||
form.dataset.busy = "false";
|
||||
close("am-editor");
|
||||
message("자산 정보를 저장했습니다.");
|
||||
await afterSave(id);
|
||||
} catch (error) {
|
||||
formError(form, error);
|
||||
} finally {
|
||||
form.dataset.busy = "false";
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
function openUpload(target = null) {
|
||||
state.uploadTarget = target ? structuredClone(target) : null;
|
||||
state.preview = null;
|
||||
state.file = null;
|
||||
++state.previewSeq;
|
||||
$("am-upload-form").reset();
|
||||
clearError($("am-upload-form"));
|
||||
$("am-report-preview").hidden = true;
|
||||
$("am-import-fields").hidden = true;
|
||||
$("am-import-name").required = !target;
|
||||
$("am-import-save").disabled = true;
|
||||
$("am-upload-title").textContent = target
|
||||
? "컴퓨터 사양 보고서 갱신"
|
||||
: "컴퓨터 보고서 가져오기";
|
||||
$("am-upload-hint").textContent = target
|
||||
? `${target.tag} · ${target.name}에 보고서를 연결합니다. 기존 보고서와 자산 정보는 보존됩니다.`
|
||||
: "HWiNFO에서 저장한 XML 보고서를 선택하세요. 사양을 분석한 뒤 자산으로 등록합니다.";
|
||||
$("am-import-save").textContent = target ? "보고서 저장" : "자산으로 등록";
|
||||
$("am-upload-status").textContent = "";
|
||||
show("am-upload");
|
||||
}
|
||||
async function previewFile(file) {
|
||||
if ($("am-upload-form").dataset.busy === "true") return;
|
||||
state.file = file;
|
||||
state.preview = null;
|
||||
const seq = ++state.previewSeq;
|
||||
clearError($("am-upload-form"));
|
||||
$("am-report-preview").hidden = true;
|
||||
$("am-import-fields").hidden = true;
|
||||
$("am-import-save").disabled = true;
|
||||
if (!file) return;
|
||||
if (!/\.xml$/i.test(file.name) || file.size > 10 * 1024 * 1024) {
|
||||
formError(
|
||||
$("am-upload-form"),
|
||||
new Error("10 MB 이하의 XML 보고서를 선택하세요."),
|
||||
);
|
||||
return;
|
||||
}
|
||||
$("am-upload-status").textContent = "보고서 분석 중…";
|
||||
try {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
const result = await api("reports/preview", { method: "POST", body });
|
||||
if (seq !== state.previewSeq || !$("am-upload").open) return;
|
||||
state.preview = result;
|
||||
const s = result.summary;
|
||||
let warning = "";
|
||||
if (
|
||||
state.uploadTarget &&
|
||||
state.detail?.report &&
|
||||
state.detail.report.parsed.summary.computer_name !== s.computer_name
|
||||
)
|
||||
warning = `<p class="am-warning">기존 보고서와 컴퓨터 이름이 다릅니다. ${esc(s.computer_name)}의 보고서를 ${esc(state.uploadTarget.name)}에 연결하는 것이 맞는지 확인하세요.</p>`;
|
||||
$("am-report-preview").innerHTML =
|
||||
`<div class="am-preview"><h3>${esc(s.computer_name)}</h3><dl><dt>CPU</dt><dd>${esc(s.cpu)} · ${esc(s.cores || "—")}코어 / ${esc(s.threads || "—")}스레드</dd><dt>메모리</dt><dd>${esc(s.memory)}</dd><dt>그래픽</dt><dd>${esc(s.gpu)}</dd><dt>메인보드</dt><dd>${esc(s.motherboard)}</dd><dt>저장장치</dt><dd>${s.drive_count}개</dd><dt>운영체제</dt><dd>${esc(s.os)}</dd></dl></div>${warning}`;
|
||||
$("am-report-preview").hidden = false;
|
||||
$("am-import-fields").hidden = !!state.uploadTarget;
|
||||
if (!state.uploadTarget) $("am-import-name").value = s.computer_name;
|
||||
$("am-import-save").disabled = !configured;
|
||||
$("am-upload-status").textContent = configured
|
||||
? `${file.name} · ${result.property_count.toLocaleString()}개 사양 항목`
|
||||
: "분석 완료 · DB 연결 후 저장할 수 있습니다.";
|
||||
} catch (error) {
|
||||
if (seq === state.previewSeq) {
|
||||
formError($("am-upload-form"), error);
|
||||
$("am-upload-status").textContent = "분석 실패";
|
||||
}
|
||||
}
|
||||
}
|
||||
async function saveUpload(event) {
|
||||
event.preventDefault();
|
||||
if ($("am-upload-form").dataset.busy === "true") return;
|
||||
if (!state.preview || !configured || !state.file) return;
|
||||
$("am-upload-form").dataset.busy = "true";
|
||||
const button = $("am-import-save"),
|
||||
fileInput = $("am-report-file");
|
||||
button.disabled = true;
|
||||
fileInput.disabled = true;
|
||||
const target = state.uploadTarget;
|
||||
clearError($("am-upload-form"));
|
||||
try {
|
||||
const body = new FormData();
|
||||
body.append("file", state.file);
|
||||
if (target) body.append("version", target.version);
|
||||
else
|
||||
body.append(
|
||||
"payload",
|
||||
JSON.stringify({
|
||||
name: $("am-import-name").value.trim(),
|
||||
category: "computer",
|
||||
location: $("am-import-location").value.trim(),
|
||||
manufacturer: state.preview.summary.manufacturer || "",
|
||||
serial: state.preview.summary.serial || "",
|
||||
}),
|
||||
);
|
||||
const result = await api(
|
||||
target ? `assets/${target.id}/reports` : "reports/import",
|
||||
{ method: "POST", body },
|
||||
);
|
||||
$("am-upload-form").dataset.busy = "false";
|
||||
close("am-upload");
|
||||
message("컴퓨터 보고서를 저장했습니다.");
|
||||
await afterSave(target?.id || result.id, "specs");
|
||||
} catch (error) {
|
||||
formError($("am-upload-form"), error);
|
||||
} finally {
|
||||
$("am-upload-form").dataset.busy = "false";
|
||||
button.disabled = false;
|
||||
fileInput.disabled = false;
|
||||
}
|
||||
}
|
||||
function openAction(action) {
|
||||
state.action = action;
|
||||
state.actionAsset = structuredClone(state.detail.asset);
|
||||
const form = $("am-action-form");
|
||||
form.reset();
|
||||
clearError(form);
|
||||
$("am-action-title").textContent = names[action];
|
||||
$("am-action-tag").textContent =
|
||||
state.actionAsset.tag + " · " + state.actionAsset.name;
|
||||
$("am-action-user-label").hidden = action !== "checkout";
|
||||
$("am-action-user").required = action === "checkout";
|
||||
$("am-action-location").value = state.actionAsset.location;
|
||||
$("am-action-note").required = ["lost", "retired"].includes(action);
|
||||
$("am-action-hint").textContent = {
|
||||
checkout:
|
||||
"등록된 회사 사용자를 선택하세요. 배정 후 사용 중 상태가 됩니다.",
|
||||
checkin: `현재 사용자: ${userName(state.actionAsset.assignee_email)}. 반납 후 사용 가능한 상태가 됩니다.`,
|
||||
maintenance: "수리 사유와 자산 위치를 기록하세요.",
|
||||
available: "배정 정보를 해제하고 사용 가능한 상태로 복구합니다.",
|
||||
lost: "분실 경위를 메모에 입력하세요. 기존 사용자는 기록에 유지됩니다.",
|
||||
retired:
|
||||
"폐기 사유를 메모에 입력하세요. 자산 기록과 보고서는 보존됩니다.",
|
||||
}[action];
|
||||
show("am-action");
|
||||
}
|
||||
async function saveAction(event) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget,
|
||||
button = $("am-action-save");
|
||||
if (form.dataset.busy === "true") return;
|
||||
form.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
clearError(form);
|
||||
try {
|
||||
const asset = state.actionAsset;
|
||||
await api(`assets/${asset.id}/actions`, {
|
||||
method: "POST",
|
||||
body: {
|
||||
version: asset.version,
|
||||
action: state.action,
|
||||
assignee_email: $("am-action-user").value,
|
||||
location: $("am-action-location").value.trim(),
|
||||
note: $("am-action-note").value.trim(),
|
||||
},
|
||||
});
|
||||
form.dataset.busy = "false";
|
||||
close("am-action");
|
||||
message(names[state.action] + "를 완료했습니다.");
|
||||
await afterSave(asset.id, state.tab);
|
||||
} catch (error) {
|
||||
formError(form, error);
|
||||
} finally {
|
||||
form.dataset.busy = "false";
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
async function historicalReport(id) {
|
||||
const assetId = state.detail.asset.id,
|
||||
seq = ++state.detailSeq;
|
||||
try {
|
||||
const report = await api(`assets/${assetId}/reports/${id}`);
|
||||
if (seq !== state.detailSeq || !$("am-detail").open) return;
|
||||
state.reportView = report;
|
||||
state.tab = "specs";
|
||||
renderDetail();
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
}
|
||||
}
|
||||
function resetFilters() {
|
||||
$("am-filters").reset();
|
||||
state.group = "";
|
||||
state.warranty = false;
|
||||
state.page = 1;
|
||||
}
|
||||
document.addEventListener("click", (event) => {
|
||||
const button = event.target.closest("button,a");
|
||||
if (!button) return;
|
||||
if (button.dataset.close) {
|
||||
close(button.dataset.close);
|
||||
return;
|
||||
}
|
||||
if (button.dataset.open) {
|
||||
openDetail(button.dataset.open, button.dataset.tab || "overview");
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-create")) {
|
||||
openEditor();
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-edit") && state.detail) {
|
||||
openEditor(true);
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-attach") && state.detail) {
|
||||
openUpload(state.detail.asset);
|
||||
return;
|
||||
}
|
||||
if (button.dataset.detailTab && state.detail) {
|
||||
state.tab = button.dataset.detailTab;
|
||||
renderDetail();
|
||||
syncURL();
|
||||
return;
|
||||
}
|
||||
if (button.dataset.action && state.detail) {
|
||||
openAction(button.dataset.action);
|
||||
return;
|
||||
}
|
||||
if (button.dataset.report) {
|
||||
historicalReport(button.dataset.report);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
button.dataset.view ||
|
||||
button.dataset.state ||
|
||||
button.dataset.kpi ||
|
||||
button.dataset.category
|
||||
) {
|
||||
const key = button.dataset.kpi;
|
||||
resetFilters();
|
||||
if (
|
||||
button.dataset.view === "computer" ||
|
||||
button.dataset.view === "furniture"
|
||||
)
|
||||
state.group = button.dataset.view;
|
||||
if (button.dataset.view === "warranty" || key === "warranty")
|
||||
state.warranty = true;
|
||||
if (button.dataset.state || (key && statuses[key]))
|
||||
$("am-status").value = button.dataset.state || key;
|
||||
if (button.dataset.category)
|
||||
$("am-category").value = button.dataset.category;
|
||||
loadList();
|
||||
}
|
||||
});
|
||||
$("am-create").addEventListener("click", () => openEditor());
|
||||
$("am-import").addEventListener("click", () => openUpload());
|
||||
$("am-help-open").addEventListener("click", () => show("am-help"));
|
||||
$("am-editor-form").addEventListener("submit", saveEditor);
|
||||
$("am-action-form").addEventListener("submit", saveAction);
|
||||
$("am-upload-form").addEventListener("submit", saveUpload);
|
||||
$("am-report-file").addEventListener("change", (event) =>
|
||||
previewFile(event.target.files[0]),
|
||||
);
|
||||
$("am-drop").addEventListener("dragover", (event) => {
|
||||
event.preventDefault();
|
||||
$("am-drop").classList.add("is-over");
|
||||
});
|
||||
$("am-drop").addEventListener("dragleave", () =>
|
||||
$("am-drop").classList.remove("is-over"),
|
||||
);
|
||||
$("am-drop").addEventListener("drop", (event) => {
|
||||
event.preventDefault();
|
||||
$("am-drop").classList.remove("is-over");
|
||||
if (event.dataTransfer.files.length !== 1) {
|
||||
formError($("am-upload-form"), new Error("보고서를 한 개씩 선택하세요."));
|
||||
return;
|
||||
}
|
||||
$("am-report-file").files = event.dataTransfer.files;
|
||||
previewFile(event.dataTransfer.files[0]);
|
||||
});
|
||||
for (const id of [
|
||||
"am-detail",
|
||||
"am-editor",
|
||||
"am-action",
|
||||
"am-upload",
|
||||
"am-help",
|
||||
])
|
||||
$(id).addEventListener("cancel", (event) => {
|
||||
event.preventDefault();
|
||||
close(id);
|
||||
});
|
||||
$("am-filters").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
state.page = 1;
|
||||
loadList();
|
||||
});
|
||||
let searchTimer;
|
||||
$("am-query").addEventListener("input", (event) => {
|
||||
if (event.isComposing) return;
|
||||
clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(() => {
|
||||
state.page = 1;
|
||||
loadList();
|
||||
}, 250);
|
||||
});
|
||||
$("am-query").addEventListener("compositionend", () => {
|
||||
clearTimeout(searchTimer);
|
||||
state.page = 1;
|
||||
loadList();
|
||||
});
|
||||
for (const id of [
|
||||
"am-category",
|
||||
"am-status",
|
||||
"am-location",
|
||||
"am-assignee",
|
||||
"am-sort",
|
||||
])
|
||||
$(id).addEventListener("change", () => {
|
||||
state.page = 1;
|
||||
if (id === "am-category") state.group = "";
|
||||
loadList();
|
||||
});
|
||||
$("am-reset").addEventListener("click", () => {
|
||||
resetFilters();
|
||||
loadList();
|
||||
});
|
||||
$("am-prev").addEventListener("click", () => {
|
||||
state.page--;
|
||||
loadList();
|
||||
});
|
||||
$("am-next").addEventListener("click", () => {
|
||||
state.page++;
|
||||
loadList();
|
||||
});
|
||||
$("am-refresh").addEventListener("click", () =>
|
||||
refresh().catch((e) => message(e.message, true)),
|
||||
);
|
||||
$("am-export").addEventListener("click", async () => {
|
||||
const button = $("am-export");
|
||||
button.disabled = true;
|
||||
try {
|
||||
const params = query();
|
||||
params.delete("page");
|
||||
params.delete("sort");
|
||||
const response = await fetch("/asset/api/export?" + params, {
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(
|
||||
typeof data.detail === "string"
|
||||
? data.detail
|
||||
: "내보내기에 실패했습니다.",
|
||||
);
|
||||
}
|
||||
const link = document.createElement("a"),
|
||||
url = URL.createObjectURL(await response.blob());
|
||||
link.href = url;
|
||||
link.download = "자산대장.xlsx";
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
async function init() {
|
||||
const p = new URLSearchParams(location.search),
|
||||
selectedId = p.get("asset"),
|
||||
selectedTab = p.get("tab");
|
||||
for (const [key, id] of [
|
||||
["q", "am-query"],
|
||||
["category", "am-category"],
|
||||
["status", "am-status"],
|
||||
["sort", "am-sort"],
|
||||
])
|
||||
if (p.has(key)) $(id).value = p.get(key);
|
||||
state.page = Math.max(
|
||||
1,
|
||||
Math.min(100000, Math.trunc(Number(p.get("page"))) || 1),
|
||||
);
|
||||
state.group = ["computer", "furniture"].includes(p.get("group"))
|
||||
? p.get("group")
|
||||
: "";
|
||||
state.warranty = p.get("warranty") === "true";
|
||||
try {
|
||||
await loadDashboard();
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
}
|
||||
if (p.get("location")) $("am-location").value = p.get("location");
|
||||
if (p.get("assignee")) $("am-assignee").value = p.get("assignee");
|
||||
await loadList();
|
||||
if (selectedId && configured)
|
||||
await openDetail(
|
||||
selectedId,
|
||||
["overview", "specs", "reports", "history"].includes(selectedTab)
|
||||
? selectedTab
|
||||
: "overview",
|
||||
);
|
||||
}
|
||||
init();
|
||||
})();
|
||||
@@ -33,6 +33,7 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"project",
|
||||
"cafe24",
|
||||
"performance",
|
||||
"asset",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user