e9be17faab
Registration was blocked whenever same-model candidates existed, so a second monitor of the same model (e.g. dual monitors) could not be added. Now only an existing asset with the same serial blocks a new one; the UI tells serial and model candidates apart and hides 'register' only for serial matches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1296 lines
53 KiB
JavaScript
1296 lines
53 KiB
JavaScript
/* 회사 자산대장: 변경 요청에는 세션 확인 토큰과 자산의 수정 버전을 함께 보냅니다. */
|
||
(() => {
|
||
"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 canDelete = app.dataset.canDelete === "true";
|
||
const names = {
|
||
create: "자산 등록",
|
||
update: "정보 수정",
|
||
checkout: "사용자 배정",
|
||
checkin: "자산 반납",
|
||
maintenance: "수리 시작",
|
||
available: "사용 가능으로 복구",
|
||
lost: "분실 처리",
|
||
retired: "폐기 처리",
|
||
report: "사양 보고서 등록",
|
||
photo: "사진 등록",
|
||
monitor: "모니터 자산 연결",
|
||
delete: "자산 삭제",
|
||
};
|
||
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();
|
||
}
|
||
let drawerAnimation = null;
|
||
let drawerMotionId = 0;
|
||
function moveDrawer(opening) {
|
||
const drawer = $("am-detail"),
|
||
motionId = ++drawerMotionId;
|
||
// 진행 중인 위치에서 방향을 바꾸므로 빠른 열기·닫기에도 패널이 튀지 않습니다.
|
||
const from =
|
||
drawerAnimation || !opening
|
||
? getComputedStyle(drawer).transform
|
||
: "translateX(100%)";
|
||
drawerAnimation?.cancel();
|
||
drawerAnimation = null;
|
||
drawer.classList.toggle("am-closing", !opening);
|
||
const finish = () => {
|
||
if (motionId !== drawerMotionId) return;
|
||
if (!opening) drawer.close();
|
||
drawer.classList.remove("am-closing");
|
||
drawerAnimation?.cancel();
|
||
drawerAnimation = null;
|
||
};
|
||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
|
||
finish();
|
||
return;
|
||
}
|
||
const animation = drawer.animate(
|
||
[
|
||
{ transform: from },
|
||
{ transform: opening ? "translateX(0)" : "translateX(100%)" },
|
||
],
|
||
{
|
||
duration: opening ? 280 : 220,
|
||
easing: opening
|
||
? "cubic-bezier(.22,1,.36,1)"
|
||
: "cubic-bezier(.4,0,1,1)",
|
||
fill: "both",
|
||
},
|
||
);
|
||
animation.id = "asset-drawer";
|
||
drawerAnimation = animation;
|
||
animation.finished.then(finish, () => {});
|
||
}
|
||
function show(id) {
|
||
const dialog = $(id);
|
||
if (id === "am-detail") {
|
||
if (!dialog.open) {
|
||
dialog.showModal();
|
||
moveDrawer(true);
|
||
} else if (dialog.classList.contains("am-closing")) moveDrawer(true);
|
||
return;
|
||
}
|
||
if (!dialog.open) dialog.showModal();
|
||
}
|
||
function close(id) {
|
||
// 저장 중에는 창을 닫거나 다시 제출해서 요청을 겹치지 않게 합니다.
|
||
if ($(id).querySelector('form[data-busy="true"]')) return;
|
||
if (id === "am-detail") {
|
||
if (!$(id).open || $(id).classList.contains("am-closing")) return;
|
||
++state.detailSeq;
|
||
state.detail = null;
|
||
syncURL();
|
||
moveDrawer(false);
|
||
return;
|
||
}
|
||
if (id === "am-upload") ++state.previewSeq;
|
||
$(id).close();
|
||
}
|
||
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 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.candidate_by === "serial" ? "같은 시리얼의 모니터 자산이 이미 있습니다. 같은 장비이므로 아래 자산에 연결하세요." : 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("") + (m.candidate_by === "serial" ? "" : `<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 = {
|
||
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;
|
||
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 === "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">',
|
||
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">${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(
|
||
([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;
|
||
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)
|
||
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.monitorRegistration) body.category = "monitor";
|
||
if (state.editing) body.version = state.editing.version;
|
||
const result = await api(
|
||
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(
|
||
state.monitorRegistration?.computer.id || id,
|
||
state.monitorRegistration ? "specs" : "overview",
|
||
);
|
||
} 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, 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 = "";
|
||
state.warranty = false;
|
||
state.page = 1;
|
||
}
|
||
document.addEventListener("click", (event) => {
|
||
const button = event.target.closest("button,a");
|
||
if (!button) return;
|
||
// 닫히는 동안 키보드로 이전 패널의 처리 버튼을 실행하지 않게 합니다.
|
||
if (button.closest("#am-detail.am-closing")) return;
|
||
if (button.dataset.close) {
|
||
close(button.dataset.close);
|
||
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;
|
||
}
|
||
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",
|
||
"am-photo",
|
||
"am-delete",
|
||
])
|
||
$(id).addEventListener("cancel", (event) => {
|
||
event.preventDefault();
|
||
close(id);
|
||
});
|
||
// 바깥에서 누르고 놓은 경우만 닫습니다. 패널 안에서 바깥으로 드래그하면 유지합니다.
|
||
let drawerBackdropPressed = false;
|
||
const outsideDrawer = (event) => {
|
||
const drawer = $("am-detail"),
|
||
rect = drawer.getBoundingClientRect();
|
||
return (
|
||
event.target === drawer &&
|
||
(event.clientX < rect.left ||
|
||
event.clientX >= rect.right ||
|
||
event.clientY < rect.top ||
|
||
event.clientY >= rect.bottom)
|
||
);
|
||
};
|
||
$("am-detail").addEventListener("pointerdown", (event) => {
|
||
drawerBackdropPressed = event.button === 0 && outsideDrawer(event);
|
||
});
|
||
$("am-detail").addEventListener("pointerup", (event) => {
|
||
const dismiss = drawerBackdropPressed && outsideDrawer(event);
|
||
drawerBackdropPressed = false;
|
||
if (dismiss) close("am-detail");
|
||
});
|
||
$("am-detail").addEventListener("pointercancel", () => {
|
||
drawerBackdropPressed = false;
|
||
});
|
||
$("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();
|
||
})();
|