bd0c47e6fc
Requires asset_db initialized with scripts/sql/asset_db_init.sql and ASSET_DB_URL configured before enabling storage.
184 lines
11 KiB
Python
184 lines
11 KiB
Python
"""자산·보고서·이력을 함께 저장합니다. 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)
|