feat(asset): add photos, monitor links and deletion
Apply asset_db_002_photos_monitors.sql before rebuilding web. Restrict soft deletion to the super admin; retain reports and audit.
This commit is contained in:
+114
-22
@@ -10,6 +10,8 @@ from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .store import AssetConflict, transition
|
||||
from .media import MAX_PHOTOS
|
||||
from .monitors import compatible_monitor, monitor_devices
|
||||
|
||||
FIELDS = ("tag", "name", "category", "manufacturer", "model", "serial", "location", "department",
|
||||
"purchased_on", "purchase_cost", "vendor", "warranty_until", "notes")
|
||||
@@ -25,7 +27,7 @@ def serialize(row):
|
||||
|
||||
|
||||
def filters(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||
conditions, params = ["TRUE"], []
|
||||
conditions, params = ["a.deleted_at IS NULL"], []
|
||||
if q:
|
||||
# %와 _도 입력한 글자 그대로 검색합니다. 검색어는 SQL과 분리해서 전달합니다.
|
||||
value = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
@@ -55,7 +57,9 @@ class AssetStore:
|
||||
|
||||
def health(self):
|
||||
with self._pool.connection(timeout=5) as conn:
|
||||
conn.execute("SELECT id FROM assets LIMIT 1")
|
||||
conn.execute("SELECT id,deleted_at FROM assets LIMIT 1")
|
||||
conn.execute("SELECT id FROM asset_photos LIMIT 0")
|
||||
conn.execute("SELECT monitor_key FROM asset_monitor_links LIMIT 0")
|
||||
|
||||
def list_assets(self, *, page=1, page_size=25, sort="updated", **kwargs):
|
||||
# 전체 개수와 목록을 같은 시점의 데이터로 읽어 페이지 숫자가 어긋나지 않게 합니다.
|
||||
@@ -82,29 +86,32 @@ class AssetStore:
|
||||
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()
|
||||
FROM assets WHERE deleted_at IS NULL""").fetchone()
|
||||
categories = conn.execute("SELECT category,count(*) AS count FROM assets WHERE deleted_at IS NULL GROUP BY category ORDER BY count(*) DESC,category").fetchall()
|
||||
locations = conn.execute("SELECT DISTINCT location FROM assets WHERE location<>'' AND deleted_at IS NULL 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 WHERE a.deleted_at IS NULL 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()
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL", (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]}
|
||||
photos = conn.execute("SELECT id,filename,width,height,uploaded_at,actor FROM asset_photos WHERE asset_id=%s ORDER BY uploaded_at DESC,id", (asset_id,)).fetchall()
|
||||
monitors = self._monitor_matches(conn, asset_id, report["parsed"]) if report else []
|
||||
return {"asset": serialize(asset), "report": serialize(report), "reports": [serialize(r) for r in reports],
|
||||
"events": [serialize(r) for r in events], "photos": [serialize(r) for r in photos], "monitors": monitors}
|
||||
|
||||
@staticmethod
|
||||
def _lock(conn, asset_id, version):
|
||||
# 같은 자산을 동시에 변경할 때 먼저 저장한 사용자의 값을 보호합니다.
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s FOR UPDATE", (asset_id,)).fetchone()
|
||||
if not asset:
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (asset_id,)).fetchone()
|
||||
if not asset or asset.get("deleted_at"):
|
||||
raise KeyError(asset_id)
|
||||
if asset["version"] != version:
|
||||
raise AssetConflict("다른 사용자가 수정했습니다. 상세 화면을 새로 열고 다시 시도하세요.")
|
||||
@@ -116,18 +123,22 @@ class AssetStore:
|
||||
(asset_id, actor, kind, note, Jsonb(changes)))
|
||||
|
||||
def create(self, payload, actor, report=None):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
return self._create(conn, payload, actor, report)
|
||||
|
||||
def _create(self, conn, 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)
|
||||
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):
|
||||
@@ -175,9 +186,90 @@ class AssetStore:
|
||||
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"
|
||||
columns = "r.filename,r.raw_xml" if raw else "r.id,r.filename,r.parsed,r.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()
|
||||
row = conn.execute(f"SELECT {columns} FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(report_id)
|
||||
return serialize(row)
|
||||
|
||||
def delete(self, asset_id, version, actor, note):
|
||||
# 수퍼 관리자 삭제도 이력과 원본은 보존하고 대장·다운로드에서 제외합니다.
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
self._lock(conn, asset_id, version)
|
||||
self._event(conn, asset_id, actor, "delete", note, {})
|
||||
conn.execute("UPDATE assets SET deleted_at=now(),deleted_by=%s,version=version+1,updated_at=now() WHERE id=%s", (actor, asset_id))
|
||||
|
||||
def add_photo(self, asset_id, version, actor, filename, image, mime, width, height):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
self._lock(conn, asset_id, version)
|
||||
count = conn.execute("SELECT count(*) AS n FROM asset_photos WHERE asset_id=%s", (asset_id,)).fetchone()["n"]
|
||||
if count >= MAX_PHOTOS:
|
||||
raise ValueError(f"사진은 자산당 {MAX_PHOTOS}개까지 등록할 수 있습니다.")
|
||||
photo_id = uuid.uuid4().hex
|
||||
conn.execute("INSERT INTO asset_photos(id,asset_id,filename,image,mime,width,height,actor) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(photo_id, asset_id, filename, image, mime, width, height, actor))
|
||||
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (asset_id,))
|
||||
self._event(conn, asset_id, actor, "photo", filename, {"photo_id": photo_id})
|
||||
return photo_id
|
||||
|
||||
def photo(self, asset_id, photo_id):
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT p.image,p.mime FROM asset_photos p JOIN assets a ON a.id=p.asset_id WHERE p.asset_id=%s AND p.id=%s AND a.deleted_at IS NULL", (asset_id, photo_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(photo_id)
|
||||
return row
|
||||
|
||||
@staticmethod
|
||||
def _monitor_matches(conn, computer_id, parsed):
|
||||
result = []
|
||||
for device in monitor_devices(parsed):
|
||||
linked = conn.execute("SELECT a.* FROM asset_monitor_links l JOIN assets a ON a.id=l.monitor_asset_id WHERE l.computer_id=%s AND l.monitor_key=%s AND a.category='monitor' AND a.deleted_at IS NULL", (computer_id, device["key"])).fetchone()
|
||||
matches = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND lower(btrim(serial))=%s ORDER BY id LIMIT 21", (device["serial"].casefold(),)).fetchall() if device["serial"] else []
|
||||
compatible = [a for a in matches if compatible_monitor(a, device)]
|
||||
asset = linked or (compatible[0] if len(compatible) == 1 else None)
|
||||
candidates = matches if not asset else []
|
||||
if not asset and not candidates:
|
||||
candidates = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND (lower(btrim(model))=%s OR lower(btrim(name))=%s) ORDER BY id LIMIT 20", (device["model"].casefold(), device["name"].casefold())).fetchall()
|
||||
result.append({**device, "asset": serialize(asset), "candidates": [serialize(r) for r in candidates],
|
||||
"match": "linked" if linked else "serial" if asset else "unconfirmed"})
|
||||
return result
|
||||
|
||||
def report_monitors(self, asset_id, report_id):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
row = conn.execute("SELECT r.parsed FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(report_id)
|
||||
return self._monitor_matches(conn, asset_id, row["parsed"])
|
||||
|
||||
def register_monitor(self, computer_id, index, payload, actor):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
computer = self._lock(conn, computer_id, payload.version)
|
||||
if computer["category"] != "computer" or computer["latest_report_id"] != payload.report_id:
|
||||
raise AssetConflict("최신 컴퓨터 보고서를 다시 열고 모니터를 등록하세요.")
|
||||
row = conn.execute("SELECT parsed FROM asset_reports WHERE asset_id=%s AND id=%s", (computer_id, payload.report_id)).fetchone()
|
||||
devices = monitor_devices(row["parsed"]) if row else []
|
||||
if index < 0 or index >= len(devices):
|
||||
raise KeyError(index)
|
||||
device = devices[index]
|
||||
# 서로 다른 컴퓨터에서 동일 시리얼을 동시에 등록하는 경우도 중복을 막습니다.
|
||||
if device["serial"]:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s,0))", ("asset-monitor:" + device["serial"].casefold(),))
|
||||
if payload.asset_id:
|
||||
target = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (payload.asset_id,)).fetchone()
|
||||
if not target or target["category"] != "monitor":
|
||||
raise ValueError("등록된 모니터 자산을 선택하세요.")
|
||||
monitor_id = target["id"]
|
||||
else:
|
||||
match = self._monitor_matches(conn, computer_id, row["parsed"])[index]
|
||||
if match["asset"] or (device["serial"] and match["candidates"]):
|
||||
raise AssetConflict("이미 등록된 모니터가 있습니다. 기존 자산을 확인하고 연결하세요.")
|
||||
# 보고서의 실제 시리얼을 유지해야 이후 보고서에서도 같은 장비를 찾습니다.
|
||||
data = payload.asset.model_copy(update={"serial": device["serial"] or payload.asset.serial})
|
||||
monitor_id = self._create(conn, data, actor)
|
||||
conn.execute("INSERT INTO asset_monitor_links(computer_id,monitor_key,monitor_asset_id,actor) VALUES(%s,%s,%s,%s) ON CONFLICT(computer_id,monitor_key) DO UPDATE SET monitor_asset_id=EXCLUDED.monitor_asset_id,actor=EXCLUDED.actor,linked_at=now()",
|
||||
(computer_id, device["key"], monitor_id, actor))
|
||||
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (computer_id,))
|
||||
self._event(conn, computer_id, actor, "monitor", "모니터 자산 연결", {"monitor_asset_id": monitor_id, "model": device["model"]})
|
||||
return monitor_id
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""사진을 실제 이미지로 확인하고 위치 정보 등 메타데이터를 제거합니다."""
|
||||
import io
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
||||
MAX_STORED_BYTES = 5 * 1024 * 1024
|
||||
MAX_PHOTOS = 10
|
||||
|
||||
|
||||
def prepare_photo(raw):
|
||||
if not raw or len(raw) > MAX_PHOTO_BYTES:
|
||||
raise ValueError("사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.")
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(raw)) as source:
|
||||
if source.format not in {"JPEG", "PNG", "WEBP"}:
|
||||
raise ValueError("JPG, PNG, WebP 사진만 등록할 수 있습니다.")
|
||||
if source.width * source.height > 20_000_000:
|
||||
raise ValueError("사진은 2천만 화소 이하로 등록하세요.")
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source)
|
||||
image.thumbnail((2400, 2400))
|
||||
transparent = "A" in image.getbands() or "transparency" in image.info
|
||||
mode = "RGBA" if transparent else "RGB"
|
||||
# 새 캔버스에 복사해 EXIF, GPS, 촬영기기 정보를 저장하지 않습니다.
|
||||
clean = Image.new(mode, image.size)
|
||||
clean.paste(image.convert(mode))
|
||||
output = io.BytesIO()
|
||||
clean.save(output, format="PNG" if transparent else "JPEG", **({} if transparent else {"quality": 88}))
|
||||
data = output.getvalue()
|
||||
if len(data) > MAX_STORED_BYTES:
|
||||
raise ValueError("사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.")
|
||||
return data, "image/png" if transparent else "image/jpeg", clean.width, clean.height
|
||||
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||
raise ValueError("사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.") from exc
|
||||
@@ -0,0 +1,47 @@
|
||||
"""이전 보고서에도 적용할 수 있도록 저장된 모니터 항목에서 식별 정보를 읽습니다."""
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
|
||||
def usable_serial(value):
|
||||
value = value.strip()
|
||||
if value.casefold() in {"", "unknown", "n/a", "none", "not specified", "serial number", "알 수 없음"}:
|
||||
return ""
|
||||
if re.fullmatch(r"[0\s-]+", value):
|
||||
return ""
|
||||
return value
|
||||
|
||||
|
||||
def compatible_monitor(asset, device):
|
||||
"""다른 제조사나 다른 모델이 같은 시리얼을 쓰면 자동 연결하지 않습니다."""
|
||||
def normalized(value):
|
||||
return "".join(c for c in value.casefold() if c.isalnum())
|
||||
brand = normalized(asset.get("manufacturer", ""))
|
||||
reported_brand = normalized(device["manufacturer"])
|
||||
if brand and reported_brand and brand != reported_brand:
|
||||
return False
|
||||
model = normalized(asset.get("model", ""))
|
||||
if not model:
|
||||
return True
|
||||
return any(model == value or len(model) >= 4 and model in value
|
||||
for value in (normalized(device["model"]), normalized(device["name"])))
|
||||
|
||||
|
||||
def monitor_devices(parsed):
|
||||
devices = []
|
||||
for index, item in enumerate(parsed.get("devices", {}).get("MONITOR", [])):
|
||||
props = item.get("properties", [])
|
||||
def pick(*labels, kind=""):
|
||||
return next((p["value"].strip() for p in props if p.get("label", "").casefold() in
|
||||
{label.casefold() for label in labels} or kind and p.get("type") == kind), "")
|
||||
name = item.get("name", "모니터")
|
||||
model = pick("모니터 이름(제조업체)", "Monitor Name (Manuf)", "Monitor Name (Manufacturer)") or name
|
||||
serial = usable_serial(pick("일련 번호", "Serial Number", "Monitor Serial Number"))
|
||||
instance = pick("디바이스 인스턴스 ID", "Device Instance ID", kind="DeviceInstanceId")
|
||||
# 시리얼이 없는 장치는 모델명만으로 동일 자산이라고 판단하지 않습니다.
|
||||
identity = ("serial:" + serial.casefold() + ":" + model.casefold()) if serial else (
|
||||
"instance:" + instance.casefold() if instance else f"report:{parsed.get('sha256', '')}:{index}")
|
||||
devices.append({"index": index, "key": hashlib.sha256(identity.encode()).hexdigest(),
|
||||
"name": name, "model": model[:200], "serial": serial[:200],
|
||||
"manufacturer": name.split(" ", 1)[0][:150], "properties": props})
|
||||
return devices
|
||||
@@ -19,6 +19,8 @@ from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .hwinfo import MAX_REPORT_BYTES, parse_hwinfo
|
||||
from .store import ActionInput, AssetConflict, AssetInput, AssetUpdate, CATEGORIES, STATUSES
|
||||
from .store import DeleteInput, MonitorInput
|
||||
from .media import MAX_PHOTO_BYTES, prepare_photo
|
||||
|
||||
router = APIRouter(prefix="/asset", tags=["asset"])
|
||||
|
||||
@@ -42,6 +44,17 @@ def _write(request: Request, user=Depends(_user)):
|
||||
return user
|
||||
|
||||
|
||||
def _super(user):
|
||||
from app.store import SUPER_ADMIN_EMAIL
|
||||
return user.get("email", "").lower() == SUPER_ADMIN_EMAIL
|
||||
|
||||
|
||||
def _super_write(user=Depends(_write)):
|
||||
if not _super(user):
|
||||
raise HTTPException(403, "수퍼 관리자만 자산을 삭제할 수 있습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _store(request):
|
||||
store = getattr(request.app.state, "asset_store", None)
|
||||
if store is None:
|
||||
@@ -82,6 +95,7 @@ def index(request: Request):
|
||||
"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,
|
||||
"can_delete": _super(user),
|
||||
})
|
||||
|
||||
|
||||
@@ -179,6 +193,50 @@ def update(request: Request, asset_id: str, payload: AssetUpdate, user=Depends(_
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/api/assets/{asset_id}")
|
||||
def delete(request: Request, asset_id: str, payload: DeleteInput, user=Depends(_super_write)):
|
||||
with _errors():
|
||||
_store(request).delete(asset_id, payload.version, user["email"], payload.note)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/photos")
|
||||
async def add_photo(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||
filename = (file.filename or "photo.jpg").replace("\\", "/").rsplit("/", 1)[-1]
|
||||
try:
|
||||
if len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||
raise HTTPException(422, "사진 파일 이름을 확인하세요.")
|
||||
raw = await file.read(MAX_PHOTO_BYTES + 1)
|
||||
finally:
|
||||
await file.close()
|
||||
with _errors():
|
||||
image, mime, width, height = await run_in_threadpool(prepare_photo, raw)
|
||||
photo_id = await run_in_threadpool(_store(request).add_photo, asset_id, version, user["email"], filename, image, mime, width, height)
|
||||
return {"id": photo_id}
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/photos/{photo_id}")
|
||||
def photo(request: Request, asset_id: str, photo_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
row = _store(request).photo(asset_id, photo_id)
|
||||
return Response(bytes(row["image"]), media_type=row["mime"],
|
||||
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/reports/{report_id}/monitors")
|
||||
def report_monitors(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
return {"items": _store(request).report_monitors(asset_id, report_id)}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/monitors/{index}")
|
||||
def register_monitor(request: Request, asset_id: str, index: int, payload: MonitorInput, user=Depends(_write)):
|
||||
with _errors():
|
||||
monitor_id = _store(request).register_monitor(asset_id, index, payload, user["email"])
|
||||
return {"id": monitor_id}
|
||||
|
||||
|
||||
@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
|
||||
|
||||
@@ -44,6 +44,28 @@ class AssetUpdate(AssetInput):
|
||||
version: int = Field(ge=1)
|
||||
|
||||
|
||||
class DeleteInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
note: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
class MonitorInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
report_id: str = Field(min_length=1, max_length=64)
|
||||
asset: AssetInput | None = None
|
||||
asset_id: str = Field(default="", max_length=64)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_target(self):
|
||||
if bool(self.asset) == bool(self.asset_id):
|
||||
raise ValueError("등록할 정보 또는 연결할 모니터 자산 중 하나를 지정하세요.")
|
||||
if self.asset and self.asset.category != "monitor":
|
||||
raise ValueError("모니터 분류로 등록하세요.")
|
||||
return self
|
||||
|
||||
|
||||
class ActionInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% set force_sidebar_collapsed = true %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006a">{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006b">{% endblock %}
|
||||
{% block content %}
|
||||
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}">
|
||||
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}" data-can-delete="{{ 'true' if can_delete 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>
|
||||
@@ -64,5 +64,7 @@
|
||||
<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>
|
||||
<dialog id="am-photo" class="am-dialog" aria-labelledby="am-photo-title"><div class="am-dialog-head"><h2 id="am-photo-title">자산 사진 등록</h2><button type="button" class="am-close" data-close="am-photo" aria-label="사진 등록 닫기">×</button></div><form id="am-photo-form" class="am-form"><p class="am-form-hint">JPG · PNG · WebP, 파일당 8 MB 이하 · 자산당 최대 10장. 촬영 위치 정보는 제거해 보관합니다.</p><label>사진 선택<input id="am-photo-file" type="file" accept="image/jpeg,image/png,image/webp" required></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-photo">취소</button><button type="submit" class="erp-btn erp-btn-primary">사진 저장</button></div></form></dialog>
|
||||
<dialog id="am-delete" class="am-dialog" aria-labelledby="am-delete-title"><div class="am-dialog-head"><h2 id="am-delete-title">자산 삭제</h2><button type="button" class="am-close" data-close="am-delete" aria-label="삭제 창 닫기">×</button></div><form id="am-delete-form" class="am-form"><p class="am-warning" id="am-delete-hint"></p><p class="am-form-hint">자산대장과 현황에서 제외됩니다. 사진·보고서·처리 이력은 보존됩니다.</p><label>삭제할 자산번호 확인<input id="am-delete-confirm" required autocomplete="off"></label><label>삭제 사유<textarea id="am-delete-note" required maxlength="2000" rows="3"></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-delete">취소</button><button type="submit" class="erp-btn am-danger">자산 삭제</button></div></form></dialog>
|
||||
{% 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 %}
|
||||
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261006b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,3 +1,86 @@
|
||||
.am-monitor-summary {
|
||||
margin: 18px 0;
|
||||
padding: 20px;
|
||||
border: 1px solid #e7e7e7;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.am-monitor-summary h3 {
|
||||
margin: 0 0 14px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #737373;
|
||||
}
|
||||
.am-monitor-grid,
|
||||
.am-photo-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
.am-monitor-card {
|
||||
min-width: 0;
|
||||
padding: 16px;
|
||||
background: #fafafa;
|
||||
border-radius: 10px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.am-monitor-card > strong,
|
||||
.am-monitor-card > small {
|
||||
display: block;
|
||||
}
|
||||
.am-monitor-card > small {
|
||||
color: #737373;
|
||||
margin: 8px 0 14px;
|
||||
}
|
||||
.am-linked-overview {
|
||||
border-top: 1px solid #e7e7e7;
|
||||
padding-top: 12px;
|
||||
}
|
||||
.am-linked-overview h4 {
|
||||
margin: 12px 0 8px;
|
||||
}
|
||||
.am-linked-overview p {
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.am-monitor-candidate {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.am-monitor-candidate small {
|
||||
display: block;
|
||||
color: #737373;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.am-photo-grid a {
|
||||
display: block;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
min-width: 0;
|
||||
}
|
||||
.am-photo-grid img {
|
||||
width: 100%;
|
||||
height: 180px;
|
||||
object-fit: contain;
|
||||
border: 1px solid #e7e7e7;
|
||||
border-radius: 10px;
|
||||
background: #fafafa;
|
||||
}
|
||||
.am-photo-grid small {
|
||||
display: block;
|
||||
margin-top: 7px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.am-danger {
|
||||
color: white;
|
||||
background: #b42318;
|
||||
border-color: #b42318;
|
||||
}
|
||||
.am-danger-outline {
|
||||
color: #b42318;
|
||||
}
|
||||
.erp-page:has(.am-workspace) {
|
||||
padding: 0;
|
||||
max-width: none;
|
||||
|
||||
+232
-5
@@ -6,6 +6,7 @@
|
||||
if (!app) return;
|
||||
const { categories, statuses } = JSON.parse($("am-config").textContent);
|
||||
const configured = app.dataset.configured === "true";
|
||||
const canDelete = app.dataset.canDelete === "true";
|
||||
const names = {
|
||||
create: "자산 등록",
|
||||
update: "정보 수정",
|
||||
@@ -16,6 +17,9 @@
|
||||
lost: "분실 처리",
|
||||
retired: "폐기 처리",
|
||||
report: "사양 보고서 등록",
|
||||
photo: "사진 등록",
|
||||
monitor: "모니터 자산 연결",
|
||||
delete: "자산 삭제",
|
||||
};
|
||||
const fieldNames = {
|
||||
tag: "자산번호",
|
||||
@@ -320,6 +324,25 @@
|
||||
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 monitorCards(report) {
|
||||
const monitors = state.reportView
|
||||
? state.reportView.monitors || []
|
||||
: state.detail.monitors || [];
|
||||
if (!monitors.length)
|
||||
return '<section class="am-monitor-summary"><h3>모니터 / MONITOR</h3><p class="am-muted">보고서에 모니터 정보가 없습니다.</p></section>';
|
||||
const current = report.id === state.detail.asset.latest_report_id;
|
||||
return `<section class="am-monitor-summary"><h3>모니터 / MONITOR <span class="am-badge">${monitors.length}개</span></h3><div class="am-monitor-grid">${monitors
|
||||
.map((m) => {
|
||||
const a = m.asset;
|
||||
return `<article class="am-monitor-card"><strong>${esc(m.name)}</strong><small>${esc(m.model)}${m.serial ? " · 시리얼 " + esc(m.serial) : " · 시리얼 미기록"}</small>${a ? `<div class="am-linked-overview"><span class="am-badge">등록된 자산</span><h4>${esc(a.name)}</h4><p>${esc(a.tag)} · ${esc(a.location || "위치 미지정")}<br>${esc(userName(a.assignee_email))} · ${esc(statuses[a.status])}<br>구매 ${money(a.purchase_cost)} · 보증 ${esc(a.warranty_until || "미입력")}</p><button class="am-text-btn" data-monitor-open="${esc(a.id)}">자산 개요 보기 ↗</button></div>` : `<p class="am-muted">${m.candidates?.length ? "같은 시리얼 또는 모델의 자산이 있습니다. 실제 장비를 확인하세요." : "연결된 자산이 없습니다."}</p>${current ? (m.candidates || []).map((c) => `<div class="am-monitor-candidate"><span>${esc(c.tag)} · ${esc(c.name)}<small>${esc(c.serial || "시리얼 미기록")} · ${esc(c.location || "위치 미지정")}</small></span><button class="am-text-btn" data-monitor-link="${m.index}" data-target="${esc(c.id)}">이 자산 연결</button></div>`).join("") + `<button class="erp-btn erp-btn-outline" data-monitor-create="${m.index}">+ 모니터 자산으로 등록</button>` : '<p class="am-muted">모니터 등록·연결은 최신 보고서에서 진행하세요.</p>'}`}</article>`;
|
||||
})
|
||||
.join("")}</div></section>`;
|
||||
}
|
||||
function photoGallery(a) {
|
||||
const photos = state.detail.photos || [];
|
||||
return `<section class="am-detail-section"><div class="am-panel-head"><h3 class="am-section-title">자산 사진 <span class="am-badge">${photos.length}/10</span></h3><button class="erp-btn erp-btn-outline" data-photo ${photos.length >= 10 ? "disabled" : ""}>+ 사진 등록</button></div>${photos.length ? `<div class="am-photo-grid">${photos.map((p) => `<a href="/asset/api/assets/${encodeURIComponent(a.id)}/photos/${encodeURIComponent(p.id)}" target="_blank" rel="noopener"><img src="/asset/api/assets/${encodeURIComponent(a.id)}/photos/${encodeURIComponent(p.id)}" alt="${esc(p.filename)}" loading="lazy"><small>${esc(p.filename)}</small></a>`).join("")}</div>` : '<p class="am-muted">자산의 외관이나 시리얼 라벨 사진을 등록하세요.</p>'}</section>`;
|
||||
}
|
||||
// 많은 기술 항목 중 용량·속도·시리얼을 먼저 보여주고, 전체 보고서는 아래에 보존합니다.
|
||||
function componentCards(parsed) {
|
||||
const groups = {
|
||||
@@ -477,6 +500,14 @@
|
||||
.join("") +
|
||||
'<p class="am-form-hint">최근 200개 이력을 표시합니다. 전체 이력은 저장소에 보존됩니다.</p>';
|
||||
}
|
||||
if (state.tab === "overview") body = photoGallery(a) + body;
|
||||
if (report && ["overview", "specs"].includes(state.tab)) {
|
||||
// 모니터도 CPU/RAM/GPU/저장장치 바로 다음에 핵심 사양으로 표시합니다.
|
||||
body = body.replace(
|
||||
summaryCards(report.parsed.summary),
|
||||
summaryCards(report.parsed.summary) + monitorCards(report),
|
||||
);
|
||||
}
|
||||
if (state.tab === "specs" && report)
|
||||
body = body.replace(
|
||||
'<div class="am-spec-tools">',
|
||||
@@ -488,7 +519,7 @@
|
||||
'<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(
|
||||
`<div class="am-detail-body"><div class="am-detail-actions">${state.returnComputer && a.category === "monitor" ? `<button class="am-text-btn" data-return-computer="${esc(state.returnComputer)}">← 컴퓨터 사양으로</button>` : ""}${badge(a.status)}${actionButtons(a)}<button class="erp-btn erp-btn-outline" data-edit>정보 수정</button>${canDelete ? '<button class="erp-btn erp-btn-outline am-danger-outline" data-delete>자산 삭제</button>' : ""}</div></div><nav class="am-tabs" aria-label="자산 상세 보기">${Object.entries(
|
||||
tabs,
|
||||
)
|
||||
.filter(
|
||||
@@ -540,6 +571,9 @@
|
||||
form.reset();
|
||||
clearError(form);
|
||||
state.editing = edit ? structuredClone(state.detail.asset) : null;
|
||||
state.monitorRegistration = null;
|
||||
form.elements.category.disabled = false;
|
||||
form.elements.serial.readOnly = false;
|
||||
$("am-editor-title").textContent = edit ? "자산 정보 수정" : "자산 등록";
|
||||
if (edit)
|
||||
for (const input of form.elements)
|
||||
@@ -576,16 +610,33 @@
|
||||
clearError(form);
|
||||
try {
|
||||
const body = assetPayload(form);
|
||||
if (state.monitorRegistration) body.category = "monitor";
|
||||
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 },
|
||||
state.monitorRegistration
|
||||
? `assets/${state.monitorRegistration.computer.id}/monitors/${state.monitorRegistration.index}`
|
||||
: state.editing
|
||||
? "assets/" + state.editing.id
|
||||
: "assets",
|
||||
{
|
||||
method: state.editing ? "PUT" : "POST",
|
||||
body: state.monitorRegistration
|
||||
? {
|
||||
asset: body,
|
||||
version: state.monitorRegistration.computer.version,
|
||||
report_id: state.monitorRegistration.reportId,
|
||||
}
|
||||
: body,
|
||||
},
|
||||
);
|
||||
const id = state.editing?.id || result.id;
|
||||
form.dataset.busy = "false";
|
||||
close("am-editor");
|
||||
message("자산 정보를 저장했습니다.");
|
||||
await afterSave(id);
|
||||
await afterSave(
|
||||
state.monitorRegistration?.computer.id || id,
|
||||
state.monitorRegistration ? "specs" : "overview",
|
||||
);
|
||||
} catch (error) {
|
||||
formError(form, error);
|
||||
} finally {
|
||||
@@ -764,15 +815,161 @@
|
||||
const assetId = state.detail.asset.id,
|
||||
seq = ++state.detailSeq;
|
||||
try {
|
||||
const report = await api(`assets/${assetId}/reports/${id}`);
|
||||
const [report, monitors] = await Promise.all([
|
||||
api(`assets/${assetId}/reports/${id}`),
|
||||
api(`assets/${assetId}/reports/${id}/monitors`),
|
||||
]);
|
||||
if (seq !== state.detailSeq || !$("am-detail").open) return;
|
||||
state.reportView = report;
|
||||
state.reportView.monitors = monitors.items;
|
||||
state.tab = "specs";
|
||||
renderDetail();
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
}
|
||||
}
|
||||
function openMonitorEditor(index) {
|
||||
const monitor = (state.detail.monitors || []).find(
|
||||
(m) => m.index === index,
|
||||
);
|
||||
if (!monitor) return;
|
||||
openEditor();
|
||||
const form = $("am-editor-form"),
|
||||
computer = structuredClone(state.detail.asset);
|
||||
state.monitorRegistration = {
|
||||
index,
|
||||
computer,
|
||||
reportId: computer.latest_report_id,
|
||||
};
|
||||
$("am-editor-title").textContent = "모니터 자산 등록";
|
||||
for (const [key, value] of Object.entries({
|
||||
name: monitor.name,
|
||||
category: "monitor",
|
||||
model: monitor.model,
|
||||
manufacturer: monitor.manufacturer,
|
||||
serial: monitor.serial,
|
||||
location: computer.location,
|
||||
department: computer.department,
|
||||
}))
|
||||
form.elements[key].value = value || "";
|
||||
form.elements.category.disabled = true;
|
||||
form.elements.serial.readOnly = Boolean(monitor.serial);
|
||||
}
|
||||
async function linkMonitor(button) {
|
||||
const computer = structuredClone(state.detail.asset);
|
||||
button.disabled = true;
|
||||
try {
|
||||
await api(
|
||||
`assets/${computer.id}/monitors/${button.dataset.monitorLink}`,
|
||||
{
|
||||
method: "POST",
|
||||
body: {
|
||||
version: computer.version,
|
||||
report_id: computer.latest_report_id,
|
||||
asset_id: button.dataset.target,
|
||||
},
|
||||
},
|
||||
);
|
||||
await afterSave(computer.id, "specs");
|
||||
message("모니터 자산을 연결했습니다.");
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
function openPhoto() {
|
||||
state.photoAsset = structuredClone(state.detail.asset);
|
||||
const form = $("am-photo-form");
|
||||
form.reset();
|
||||
clearError(form);
|
||||
show("am-photo");
|
||||
}
|
||||
async function savePhoto(event) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget,
|
||||
button = form.querySelector('[type="submit"]');
|
||||
if (form.dataset.busy === "true" || !form.reportValidity()) return;
|
||||
const file = $("am-photo-file").files[0];
|
||||
if (file.size > 8 * 1024 * 1024) {
|
||||
formError(form, new Error("사진은 8 MB 이하로 선택하세요."));
|
||||
return;
|
||||
}
|
||||
form.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
clearError(form);
|
||||
try {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
body.append("version", state.photoAsset.version);
|
||||
await api(`assets/${state.photoAsset.id}/photos`, {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
form.dataset.busy = "false";
|
||||
close("am-photo");
|
||||
await afterSave(state.photoAsset.id);
|
||||
message("사진을 등록했습니다.");
|
||||
} catch (error) {
|
||||
formError(form, error);
|
||||
} finally {
|
||||
form.dataset.busy = "false";
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
function openDelete() {
|
||||
if (!canDelete) return;
|
||||
state.deleteAsset = structuredClone(state.detail.asset);
|
||||
const form = $("am-delete-form");
|
||||
form.reset();
|
||||
clearError(form);
|
||||
$("am-delete-hint").textContent =
|
||||
`${state.deleteAsset.tag} · ${state.deleteAsset.name}을(를) 삭제합니다.`;
|
||||
$("am-delete-confirm").placeholder = state.deleteAsset.tag;
|
||||
show("am-delete");
|
||||
}
|
||||
async function saveDelete(event) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget,
|
||||
button = form.querySelector('[type="submit"]');
|
||||
if (form.dataset.busy === "true" || !form.reportValidity()) return;
|
||||
if ($("am-delete-confirm").value.trim() !== state.deleteAsset.tag) {
|
||||
formError(form, new Error("자산번호를 정확하게 입력하세요."));
|
||||
return;
|
||||
}
|
||||
form.dataset.busy = "true";
|
||||
button.disabled = true;
|
||||
clearError(form);
|
||||
try {
|
||||
await api(`assets/${state.deleteAsset.id}`, {
|
||||
method: "DELETE",
|
||||
body: {
|
||||
version: state.deleteAsset.version,
|
||||
note: $("am-delete-note").value.trim(),
|
||||
},
|
||||
});
|
||||
form.dataset.busy = "false";
|
||||
close("am-delete");
|
||||
close("am-detail");
|
||||
state.page = 1;
|
||||
message("자산을 삭제했습니다.");
|
||||
try {
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
message(
|
||||
"삭제는 완료됐지만 목록을 갱신하지 못했습니다. " + error.message,
|
||||
true,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
formError(form, error);
|
||||
} finally {
|
||||
form.dataset.busy = "false";
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
$("am-photo-form").addEventListener("submit", savePhoto);
|
||||
$("am-delete-form").addEventListener("submit", saveDelete);
|
||||
function resetFilters() {
|
||||
$("am-filters").reset();
|
||||
state.group = "";
|
||||
@@ -787,9 +984,37 @@
|
||||
return;
|
||||
}
|
||||
if (button.dataset.open) {
|
||||
state.returnComputer = null;
|
||||
openDetail(button.dataset.open, button.dataset.tab || "overview");
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-photo")) {
|
||||
openPhoto();
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-delete")) {
|
||||
openDelete();
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-monitor-create")) {
|
||||
openMonitorEditor(Number(button.dataset.monitorCreate));
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-monitor-link")) {
|
||||
linkMonitor(button);
|
||||
return;
|
||||
}
|
||||
if (button.dataset.monitorOpen) {
|
||||
state.returnComputer = state.detail.asset.id;
|
||||
openDetail(button.dataset.monitorOpen);
|
||||
return;
|
||||
}
|
||||
if (button.dataset.returnComputer) {
|
||||
const id = button.dataset.returnComputer;
|
||||
state.returnComputer = null;
|
||||
openDetail(id, "specs");
|
||||
return;
|
||||
}
|
||||
if (button.hasAttribute("data-create")) {
|
||||
openEditor();
|
||||
return;
|
||||
@@ -870,6 +1095,8 @@
|
||||
"am-action",
|
||||
"am-upload",
|
||||
"am-help",
|
||||
"am-photo",
|
||||
"am-delete",
|
||||
])
|
||||
$(id).addEventListener("cancel", (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
Reference in New Issue
Block a user