文件
hyb-oa/client/src/pages/AssetRegistryPage.tsx
T

1500 行
70 KiB
TypeScript
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { mapApiErrorMessage } from "../api/errorMessages";
import {
assignAsset,
createAsset,
createAssetCategory,
fetchAssetAssignees,
fetchAssetCategories,
fetchAssetDetail,
fetchAssets,
patchAsset,
patchAssetCategory,
returnAsset,
transferAsset,
type AssetCategoryItem,
type AssetItem,
type AssetSensitivityLevel,
type AssetStatus,
type AssetType,
} from "../api/assets";
import { fetchPurchaseRequests } from "../api/purchaseRequests";
import { fetchCostCenters, fetchDocumentCategories, fetchLegalEntities } from "../api/masterData";
import { isApiError } from "../api/types";
import { useAuth } from "../auth/AuthContext";
import { hasAnyPermission, hasPermission } from "../auth/permissions";
import { DateTextInput } from "../components/common/DateTextInput";
import { useUnsavedChangesGuard } from "../components/common/UnsavedChangesGuard";
import { StatusBadge } from "../components/common/StatusBadge";
import { TableSkeleton } from "../components/common/TableSkeleton";
import {
BusinessDetailActionPanel,
BusinessDetailAside,
BusinessDetailFact,
BusinessDetailFactGrid,
BusinessDetailMain,
BusinessDetailWorkspace,
} from "../components/patterns/BusinessDetailTemplate";
import { HeaderActionGroup, ListWorkspace, PrimaryTable, WorkspaceHeader } from "../components/patterns/ListWorkspace";
import {
BusinessListToolbar,
BusinessMobileList,
BusinessTable,
} from "../components/patterns/BusinessListTemplate";
import { Button } from "../components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "../components/ui/dropdown-menu";
import { Input } from "../components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
import { formatCompactIdentifier, formatDisplayDateTime, formatTextWithCompactLongNumbers, isCompactedIdentifier } from "../lib/displayFormat";
function resolveError(error: unknown) {
if (isApiError(error)) {
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
}
if (error instanceof Error) {
return error.message;
}
return "请求失败,请稍后重试。";
}
function initialCategoryForm() {
return {
code: "",
name: "",
documentCategoryId: "",
enabled: true,
};
}
function initialAssetForm() {
return {
name: "",
assetType: "fixed_asset" as AssetType,
sensitivityLevel: "internal" as AssetSensitivityLevel,
categoryId: "",
legalEntityId: "",
costCenterId: "",
purchaseRequestId: "",
serialNo: "",
location: "",
status: "in_stock" as AssetStatus,
assigneeEmployeeId: "",
ownerEmployeeId: "",
keeperEmployeeId: "",
archiveLocation: "",
externalRef: "",
sourceHash: "",
verificationNo: "",
confidentialityNote: "",
metadataText: "",
lastVerifiedAt: "",
expiresAt: "",
activatedAt: "",
retiredAt: "",
};
}
function assetStatusOptions(): Array<{ value: AssetStatus | ""; label: string }> {
return [
{ value: "", label: "全部状态" },
{ value: "in_stock", label: "库存中" },
{ value: "in_use", label: "使用中" },
{ value: "under_repair", label: "维修中" },
{ value: "retired", label: "已退役" },
{ value: "archived", label: "已归档" },
];
}
function assetTypeOptions(): Array<{ value: AssetType | ""; label: string }> {
return [
{ value: "", label: "全部资产类型" },
{ value: "fixed_asset", label: "固定资产 FA" },
{ value: "electronic_document", label: "电子资料 EA-DOC" },
{ value: "electronic_system", label: "电子系统 EA-SYS" },
{ value: "code_repository", label: "代码仓库 EA-REPO" },
{ value: "backup_media", label: "备份介质 EA-BKP" },
];
}
function assetTypeLabel(value: AssetType | string | null | undefined) {
return assetTypeOptions().find((item) => item.value === value)?.label ?? "未知类型";
}
function assetStatusLabel(value: AssetStatus | string | null | undefined) {
return assetStatusOptions().find((item) => item.value === value)?.label ?? "未知状态";
}
function sensitivityOptions(): Array<{ value: AssetSensitivityLevel | ""; label: string }> {
return [
{ value: "", label: "全部敏感级别" },
{ value: "public_candidate", label: "可公开候选" },
{ value: "internal", label: "内部资料" },
{ value: "confidential", label: "商业秘密/机密" },
{ value: "strictly_confidential", label: "严格保密" },
];
}
function isElectronicAssetType(assetType: AssetType) {
return assetType !== "fixed_asset";
}
function formatEmployeeSummary(employee: { name: string; employeeNo: string } | null | undefined) {
return employee ? `${employee.name} · ${employee.employeeNo}` : "-";
}
function CompactAssetNo({ value, copyable = true }: { value: string; copyable?: boolean }) {
const displayValue = formatCompactIdentifier(value, { head: 14, tail: 6, minLength: 24 });
const compacted = isCompactedIdentifier(value, displayValue);
async function copyAssetNo() {
if (!compacted) return;
try {
await navigator.clipboard.writeText(value);
toast.success("已复制完整资产编号");
} catch {
toast.error("复制失败,可在资产详情中查看完整编号");
}
}
return (
<span className="inline-flex min-w-0 max-w-full items-center gap-1.5">
<span className="truncate" title={compacted ? value : undefined}>
{displayValue}
</span>
{compacted && copyable ? (
<button
className="shrink-0 rounded border border-zinc-200 px-1.5 py-0.5 text-[11px] font-medium text-zinc-500 hover:border-zinc-300 hover:text-zinc-700"
onClick={(event) => {
event.stopPropagation();
void copyAssetNo();
}}
type="button"
>
复制
</button>
) : null}
</span>
);
}
function unsafeAssetTextReason(value: string) {
if (!value.trim()) {
return "";
}
if (/(?:token|secret|password|passwd|pwd|api[_-]?key|access[_-]?key|private[_-]?key|encodingaeskey)\s*[:=]/i.test(value)) {
return "不要填写 token、Secret、密码或密钥";
}
if (/\b[A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ENCODINGAESKEY)[A-Z0-9_]*\b/.test(value)) {
return "不要填写密钥类环境变量名或配置片段";
}
if (/(?:密码|密钥|私钥|令牌)\s*[::=]/.test(value) || /\bBearer\s+[A-Za-z0-9._-]{10,}/i.test(value)) {
return "不要填写密码、密钥、令牌或授权头";
}
if (/-----BEGIN [A-Z ]*PRIVATE KEY-----/i.test(value)) {
return "不要填写证书私钥或密钥正文";
}
if (/(^|[\s"'((,,;;])(?:\/(?:home|root|Users|var|etc|mnt|Volumes|app)\/|[A-Za-z]:[\\/]|\\\\)/i.test(value)) {
return "不要填写本机或服务器完整路径";
}
if (/(原始\s*(?:payload|xml|报文|正文|表单)|raw\s*(?:payload|xml|body|form))/i.test(value)) {
return "不要填写原始 payload、XML、表单或正文";
}
return "";
}
export function AssetRegistryPage() {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const queryClient = useQueryClient();
const { permissions } = useAuth();
const canManage = hasPermission(permissions, "asset.manage");
const canTransfer = hasPermission(permissions, "asset.transfer");
const canViewAll = hasAnyPermission(permissions, ["asset.view_all", "asset.manage", "asset.transfer", "asset.inventory"]);
const canReadProcurementSources = canManage && hasAnyPermission(permissions, ["procurement.view_all", "procurement.manage"]);
const [categoryForm, setCategoryForm] = useState(initialCategoryForm);
const [editingCategoryId, setEditingCategoryId] = useState("");
const [statusFilter, setStatusFilter] = useState<AssetStatus | "">("");
const [assetTypeFilter, setAssetTypeFilter] = useState<AssetType | "">("");
const [sensitivityFilter, setSensitivityFilter] = useState<AssetSensitivityLevel | "">("");
const [categoryFilter, setCategoryFilter] = useState("");
const [legalEntityFilter, setLegalEntityFilter] = useState("");
const [costCenterFilter, setCostCenterFilter] = useState("");
const [assigneeFilter, setAssigneeFilter] = useState("");
const [assetSearch, setAssetSearch] = useState("");
const [mine, setMine] = useState(!canViewAll);
const [showCategoryManager, setShowCategoryManager] = useState(false);
const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
const [selectedAssetId, setSelectedAssetId] = useState(searchParams.get("id") ?? "");
const [isCreatingAsset, setIsCreatingAsset] = useState(false);
const [assetForm, setAssetForm] = useState(initialAssetForm);
const [savedAssetFormSignature, setSavedAssetFormSignature] = useState(() => JSON.stringify(initialAssetForm()));
const [assetFormError, setAssetFormError] = useState("");
const [movementEmployeeId, setMovementEmployeeId] = useState("");
const [movementLocation, setMovementLocation] = useState("");
const [movementNote, setMovementNote] = useState("");
const [movementError, setMovementError] = useState("");
const categoriesQuery = useQuery({
queryKey: ["assets", "categories", canManage],
queryFn: () => fetchAssetCategories({ includeArchived: canManage, enabled: canManage ? undefined : true }),
});
const assetsQuery = useQuery({
queryKey: ["assets", "list", statusFilter, assetTypeFilter, sensitivityFilter, categoryFilter, legalEntityFilter, costCenterFilter, assigneeFilter, assetSearch, mine, canViewAll],
queryFn: () =>
fetchAssets({
status: statusFilter || undefined,
assetType: assetTypeFilter || undefined,
sensitivityLevel: sensitivityFilter || undefined,
categoryId: categoryFilter || undefined,
legalEntityId: legalEntityFilter || undefined,
costCenterId: costCenterFilter || undefined,
assigneeId: assigneeFilter || undefined,
q: assetSearch.trim() || undefined,
mine: canViewAll ? mine : true,
}),
});
const assetDetailQuery = useQuery({
enabled: Boolean(selectedAssetId) && !isCreatingAsset,
queryKey: ["assets", "detail", selectedAssetId],
queryFn: () => fetchAssetDetail(selectedAssetId),
});
const legalEntitiesQuery = useQuery({
queryKey: ["assets", "legal-entities"],
queryFn: () => fetchLegalEntities({ enabled: true }),
});
const costCentersQuery = useQuery({
queryKey: ["assets", "cost-centers"],
queryFn: () => fetchCostCenters({ enabled: true }),
});
const documentCategoriesQuery = useQuery({
queryKey: ["assets", "document-categories"],
queryFn: () => fetchDocumentCategories({ entityType: "asset_card", enabled: true }),
});
const assigneesQuery = useQuery({
enabled: canManage,
queryKey: ["assets", "assignees"],
queryFn: () => fetchAssetAssignees(),
});
const approvedPurchasesQuery = useQuery({
enabled: canReadProcurementSources,
queryKey: ["assets", "approved-purchases"],
queryFn: () => fetchPurchaseRequests({ status: "approved", mine: false, page: 1, pageSize: 100 }),
});
useEffect(() => {
const searchSelectedId = searchParams.get("id") ?? "";
if (searchSelectedId && searchSelectedId !== selectedAssetId) {
setSelectedAssetId(searchSelectedId);
}
}, [searchParams, selectedAssetId]);
useEffect(() => {
const currentId = searchParams.get("id") ?? "";
if (isCreatingAsset) {
if (!currentId) {
return;
}
const next = new URLSearchParams(searchParams);
next.delete("id");
setSearchParams(next, { replace: true });
return;
}
if (!selectedAssetId && !currentId) {
return;
}
if (selectedAssetId === currentId) {
return;
}
const next = new URLSearchParams(searchParams);
if (selectedAssetId) {
next.set("id", selectedAssetId);
} else {
next.delete("id");
}
setSearchParams(next, { replace: true });
}, [isCreatingAsset, searchParams, selectedAssetId, setSearchParams]);
useEffect(() => {
if (isCreatingAsset || !assetDetailQuery.data?.asset) {
return;
}
const asset = assetDetailQuery.data.asset;
const nextAssetForm = {
name: asset.name,
assetType: asset.assetType,
sensitivityLevel: asset.sensitivityLevel,
categoryId: asset.categoryId,
legalEntityId: asset.legalEntityId,
costCenterId: asset.costCenterId,
purchaseRequestId: asset.purchaseRequestId ?? "",
serialNo: asset.serialNo ?? "",
location: asset.location ?? "",
status: asset.status,
assigneeEmployeeId: asset.assigneeEmployeeId ?? "",
ownerEmployeeId: asset.ownerEmployeeId ?? "",
keeperEmployeeId: asset.keeperEmployeeId ?? "",
archiveLocation: asset.archiveLocation ?? "",
externalRef: asset.externalRef ?? "",
sourceHash: asset.sourceHash ?? "",
verificationNo: asset.verificationNo ?? "",
confidentialityNote: asset.confidentialityNote ?? "",
metadataText: asset.metadata ? JSON.stringify(asset.metadata, null, 2) : "",
lastVerifiedAt: asset.lastVerifiedAt ?? "",
expiresAt: asset.expiresAt ?? "",
activatedAt: asset.activatedAt ?? "",
retiredAt: asset.retiredAt ?? "",
};
setAssetForm(nextAssetForm);
setSavedAssetFormSignature(JSON.stringify(nextAssetForm));
setMovementEmployeeId("");
setMovementLocation(asset.location ?? "");
setMovementNote("");
setMovementError("");
setAssetFormError("");
}, [assetDetailQuery.data, isCreatingAsset]);
const filteredAssetCostCenters = useMemo(() => {
if (!assetForm.legalEntityId) {
return [];
}
return (costCentersQuery.data?.items ?? []).filter((item) => item.legalEntityId === assetForm.legalEntityId);
}, [assetForm.legalEntityId, costCentersQuery.data?.items]);
const filteredFilterCostCenters = useMemo(() => {
if (!legalEntityFilter) {
return costCentersQuery.data?.items ?? [];
}
return (costCentersQuery.data?.items ?? []).filter((item) => item.legalEntityId === legalEntityFilter);
}, [costCentersQuery.data?.items, legalEntityFilter]);
const currentAsset = assetDetailQuery.data?.asset ?? null;
const canEditCurrent = canManage && (isCreatingAsset || currentAsset?.permissions.canEdit);
const runGuarded = useUnsavedChangesGuard(
Boolean(isCreatingAsset || selectedAssetId) && Boolean(canEditCurrent) && JSON.stringify(assetForm) !== savedAssetFormSignature,
"资产表单",
);
const hasAdvancedAssetFilters = Boolean(
sensitivityFilter ||
categoryFilter ||
legalEntityFilter ||
costCenterFilter ||
assigneeFilter,
);
const showAssetAdvancedFilters = showAdvancedFilters || hasAdvancedAssetFilters;
function resetCategoryEditor(category?: AssetCategoryItem) {
if (!category) {
setEditingCategoryId("");
setCategoryForm(initialCategoryForm());
return;
}
setEditingCategoryId(category.id);
setCategoryForm({
code: category.code,
name: category.name,
documentCategoryId: category.documentCategoryId ?? "",
enabled: category.enabled,
});
}
function resetAssetEditor() {
runGuarded(() => {
const nextAssetForm = initialAssetForm();
setIsCreatingAsset(true);
setSelectedAssetId("");
setAssetForm(nextAssetForm);
setSavedAssetFormSignature(JSON.stringify(nextAssetForm));
setAssetFormError("");
});
}
function parseAssetMetadata() {
const text = assetForm.metadataText.trim();
if (!text) {
return null;
}
const parsed = JSON.parse(text) as unknown;
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new Error("扩展元数据必须是 JSON 对象");
}
return parsed as Record<string, unknown>;
}
function buildCreateAssetPayload() {
return {
name: assetForm.name.trim(),
assetType: assetForm.assetType,
sensitivityLevel: assetForm.sensitivityLevel,
categoryId: assetForm.categoryId,
legalEntityId: assetForm.legalEntityId,
costCenterId: assetForm.costCenterId,
purchaseRequestId: assetForm.purchaseRequestId || null,
serialNo: assetForm.serialNo.trim() || null,
location: assetForm.location.trim() || null,
status: assetForm.status,
assigneeEmployeeId: assetForm.assigneeEmployeeId || null,
ownerEmployeeId: assetForm.ownerEmployeeId || null,
keeperEmployeeId: assetForm.keeperEmployeeId || null,
archiveLocation: assetForm.archiveLocation.trim() || null,
externalRef: assetForm.externalRef.trim() || null,
sourceHash: assetForm.sourceHash.trim() || null,
verificationNo: assetForm.verificationNo.trim() || null,
confidentialityNote: assetForm.confidentialityNote.trim() || null,
metadata: parseAssetMetadata(),
lastVerifiedAt: assetForm.lastVerifiedAt || null,
expiresAt: assetForm.expiresAt || null,
activatedAt: assetForm.activatedAt || null,
retiredAt: assetForm.retiredAt || null,
};
}
function buildPatchAssetPayload() {
return {
name: assetForm.name.trim(),
sensitivityLevel: assetForm.sensitivityLevel,
categoryId: assetForm.categoryId,
legalEntityId: assetForm.legalEntityId,
costCenterId: assetForm.costCenterId,
serialNo: assetForm.serialNo.trim() || null,
location: assetForm.location.trim() || null,
status: assetForm.status,
ownerEmployeeId: assetForm.ownerEmployeeId || null,
keeperEmployeeId: assetForm.keeperEmployeeId || null,
archiveLocation: assetForm.archiveLocation.trim() || null,
externalRef: assetForm.externalRef.trim() || null,
sourceHash: assetForm.sourceHash.trim() || null,
verificationNo: assetForm.verificationNo.trim() || null,
confidentialityNote: assetForm.confidentialityNote.trim() || null,
metadata: parseAssetMetadata(),
lastVerifiedAt: assetForm.lastVerifiedAt || null,
expiresAt: assetForm.expiresAt || null,
activatedAt: assetForm.activatedAt || null,
retiredAt: assetForm.retiredAt || null,
};
}
function validateAssetForm() {
if (!assetForm.name.trim()) {
throw new Error("请填写资产名称");
}
if (!assetForm.categoryId) {
throw new Error("请选择资产分类");
}
if (!assetForm.legalEntityId) {
throw new Error("请选择法体");
}
if (!assetForm.costCenterId) {
throw new Error("请选择成本中心");
}
if (assetForm.verificationNo.trim() && !/^VER-\d{5,}$/.test(assetForm.verificationNo.trim())) {
throw new Error("历史验证编号格式应为 VER-NNNNN");
}
if (assetForm.sourceHash.trim() && !/^[A-Za-z0-9:_-]+$/.test(assetForm.sourceHash.trim())) {
throw new Error("文件 hash / 校验摘要只能包含字母、数字、冒号、下划线和短横线");
}
if (["electronic_document", "electronic_system", "code_repository", "backup_media"].includes(assetForm.assetType) && !assetForm.ownerEmployeeId) {
throw new Error("电子资产请指定负责人");
}
const textFields = [
["资产名称", assetForm.name],
["归档位置/备份位置", assetForm.archiveLocation],
["外部引用/仓库地址", assetForm.externalRef],
["保密/回收要求", assetForm.confidentialityNote],
["扩展元数据 JSON", assetForm.metadataText],
] as const;
for (const [label, value] of textFields) {
const reason = unsafeAssetTextReason(value);
if (reason) {
throw new Error(`${label}:${reason}`);
}
}
}
const saveCategoryMutation = useMutation({
mutationFn: async () => {
if (!categoryForm.code.trim()) {
throw new Error("请填写分类编码");
}
if (!categoryForm.name.trim()) {
throw new Error("请填写分类名称");
}
const payload = {
code: categoryForm.code.trim(),
name: categoryForm.name.trim(),
documentCategoryId: categoryForm.documentCategoryId || null,
enabled: categoryForm.enabled,
};
return editingCategoryId ? patchAssetCategory(editingCategoryId, payload) : createAssetCategory(payload);
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["assets", "categories"] });
toast.success(editingCategoryId ? "资产分类已更新" : "资产分类已创建");
resetCategoryEditor();
},
onError: (error) => {
toast.error(resolveError(error));
},
});
const saveAssetMutation = useMutation({
mutationFn: async () => {
validateAssetForm();
if (isCreatingAsset) {
return createAsset(buildCreateAssetPayload());
}
if (!selectedAssetId) {
throw new Error("请先选择资产卡片");
}
return patchAsset(selectedAssetId, buildPatchAssetPayload());
},
onSuccess: async (data) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["assets", "list"] }),
queryClient.invalidateQueries({ queryKey: ["assets", "detail"] }),
]);
setAssetFormError("");
setSavedAssetFormSignature(JSON.stringify(assetForm));
setSelectedAssetId(data.asset.id);
setIsCreatingAsset(false);
toast.success(isCreatingAsset ? "资产卡片已创建" : "资产卡片已更新");
},
onError: (error) => {
const message = resolveError(error);
setAssetFormError(message);
toast.error(message);
},
});
const assignAssetMutation = useMutation({
mutationFn: async () => {
if (!currentAsset) {
throw new Error("请先选择资产卡片");
}
if (!movementEmployeeId) {
throw new Error("请选择领用人");
}
return assignAsset(currentAsset.id, {
employeeId: movementEmployeeId,
note: movementNote.trim() || null,
});
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["assets", "list"] }),
queryClient.invalidateQueries({ queryKey: ["assets", "detail"] }),
]);
setMovementEmployeeId("");
setMovementNote("");
setMovementError("");
toast.success("资产已领用");
},
onError: (error) => {
const message = resolveError(error);
setMovementError(message);
toast.error(message);
},
});
const returnAssetMutation = useMutation({
mutationFn: async () => {
if (!currentAsset) {
throw new Error("请先选择资产卡片");
}
return returnAsset(currentAsset.id, { note: movementNote.trim() || null });
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["assets", "list"] }),
queryClient.invalidateQueries({ queryKey: ["assets", "detail"] }),
]);
setMovementEmployeeId("");
setMovementNote("");
setMovementError("");
toast.success("资产已归还");
},
onError: (error) => {
const message = resolveError(error);
setMovementError(message);
toast.error(message);
},
});
const transferAssetMutation = useMutation({
mutationFn: async () => {
if (!currentAsset) {
throw new Error("请先选择资产卡片");
}
const nextLocation = movementLocation.trim() || null;
const nextEmployeeId = movementEmployeeId || undefined;
if (!nextEmployeeId && nextLocation === (currentAsset.location ?? null)) {
throw new Error("请至少调整归属人或位置");
}
return transferAsset(currentAsset.id, {
toEmployeeId: nextEmployeeId,
toLocation: nextLocation,
note: movementNote.trim() || null,
});
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["assets", "list"] }),
queryClient.invalidateQueries({ queryKey: ["assets", "detail"] }),
]);
setMovementEmployeeId("");
setMovementNote("");
setMovementError("");
toast.success("资产调拨已完成");
},
onError: (error) => {
const message = resolveError(error);
setMovementError(message);
toast.error(message);
},
});
const purchaseOptions = useMemo(() => {
const items = approvedPurchasesQuery.data?.items ?? [];
const currentPurchase = currentAsset?.purchaseRequest;
if (currentPurchase && !items.some((item) => item.id === currentPurchase.id)) {
return [
...items,
{
id: currentPurchase.id,
requestNo: currentPurchase.requestNo,
title: currentPurchase.title,
status: currentPurchase.status,
applicantId: "",
submitterId: null,
departmentId: "",
legalEntityId: null,
costCenterId: null,
supplierId: null,
documentCategoryId: null,
budgetPoolId: null,
reason: null,
currencyCode: "CNY",
totalAmount: "0.00",
expectedDeliveryDate: null,
createdAt: null,
updatedAt: null,
applicant: null,
submitter: null,
department: null,
legalEntity: null,
costCenter: null,
supplier: null,
documentCategory: null,
budgetPool: null,
},
];
}
return items;
}, [approvedPurchasesQuery.data?.items, currentAsset?.purchaseRequest]);
const categoryItems = categoriesQuery.data?.items ?? [];
const assetItems = assetsQuery.data?.items ?? [];
const orderedAssetItems = useMemo(() => {
return [...assetItems].sort((a, b) => {
const score = (item: AssetItem) => {
let value = 0;
if (item.status === "under_repair") value += 50;
if (item.assetType === "fixed_asset" && !item.assignee) value += 35;
if (!item.lastVerifiedAt) value += 25;
if (item.status === "in_use") value += 10;
return value;
};
const scoreDelta = score(b) - score(a);
if (scoreDelta !== 0) return scoreDelta;
return (b.updatedAt ?? "").localeCompare(a.updatedAt ?? "");
});
}, [assetItems]);
const selectAsset = (assetId: string) => {
runGuarded(() => {
setIsCreatingAsset(false);
setSelectedAssetId(assetId);
});
};
const returnToAssetList = () => {
runGuarded(() => {
setIsCreatingAsset(false);
setSelectedAssetId("");
const next = new URLSearchParams(searchParams);
next.delete("id");
setSearchParams(next, { replace: true });
});
};
const isAssetDetailMode = isCreatingAsset || Boolean(selectedAssetId);
return (
<ListWorkspace>
<WorkspaceHeader
title="资产"
actions={
<HeaderActionGroup>
{isAssetDetailMode ? (
<Button type="button" variant="secondary" onClick={returnToAssetList}>
返回列表
</Button>
) : (
<>
{canManage ? (
<Button type="button" data-testid="asset-create" onClick={resetAssetEditor}>
新增资产
</Button>
) : null}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant={showCategoryManager ? "default" : "secondary"}>
更多
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => navigate("/mobile/assets/scan")}>
移动扫码查找
</DropdownMenuItem>
{canManage ? (
<DropdownMenuItem onSelect={() => setShowCategoryManager((value) => !value)}>
{showCategoryManager ? "收起资产分类" : "资产分类"}
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
</>
)}
</HeaderActionGroup>
}
/>
{!isAssetDetailMode ? (
<div className="grid gap-6">
{showCategoryManager && canManage ? (
<div className="card-std space-y-4 p-4 md:p-5" data-testid="asset-category-manager">
<div className="flex items-center justify-between">
<h3 className="text-base font-semibold text-zinc-900">资产分类</h3>
{canManage ? (
<Button type="button" data-testid="asset-category-reset" variant="secondary" onClick={() => resetCategoryEditor()}>
新建分类
</Button>
) : null}
</div>
<div className="grid gap-3">
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">分类编码</label>
<Input data-testid="asset-category-code" value={categoryForm.code} disabled={!canManage} onChange={(event) => setCategoryForm((current) => ({ ...current, code: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">分类名称</label>
<Input data-testid="asset-category-name" value={categoryForm.name} disabled={!canManage} onChange={(event) => setCategoryForm((current) => ({ ...current, name: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">单据分类</label>
<select className="select-std" disabled={!canManage} value={categoryForm.documentCategoryId} onChange={(event) => setCategoryForm((current) => ({ ...current, documentCategoryId: event.target.value }))}>
<option value="">使用系统默认</option>
{(documentCategoriesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{formatTextWithCompactLongNumbers(item.name)} ({formatTextWithCompactLongNumbers(item.code)})
</option>
))}
</select>
</div>
<label className="flex items-center gap-2 text-sm text-zinc-700">
<input type="checkbox" className="h-4 w-4 rounded border-zinc-300" checked={categoryForm.enabled} disabled={!canManage} onChange={(event) => setCategoryForm((current) => ({ ...current, enabled: event.target.checked }))} />
启用分类
</label>
{canManage ? (
<Button data-testid="asset-category-save" type="button" onClick={() => saveCategoryMutation.mutate()} disabled={saveCategoryMutation.isPending}>
{saveCategoryMutation.isPending ? "保存中..." : editingCategoryId ? "保存分类" : "创建分类"}
</Button>
) : null}
</div>
{categoriesQuery.isLoading ? <TableSkeleton columns={3} rows={5} /> : null}
{categoriesQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{resolveError(categoriesQuery.error)}</p>
) : null}
{!categoriesQuery.isLoading && !categoriesQuery.isError ? (
<>
<div className="space-y-2 md:hidden">
{categoryItems.length ? (
categoryItems.map((item) => (
<button
key={item.id}
type="button"
className="w-full rounded-lg border border-zinc-200 bg-white p-3 text-left"
onClick={() => resetCategoryEditor(item)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="truncate text-sm font-semibold text-zinc-900" title={item.name}>
{formatTextWithCompactLongNumbers(item.name)}
</div>
<div className="mt-1 text-xs text-zinc-500" title={item.code}>
{formatTextWithCompactLongNumbers(item.code)}
</div>
</div>
<span className="shrink-0 rounded-full bg-zinc-100 px-2 py-1 text-xs text-zinc-600">
{item.enabled ? "启用" : "停用"}
</span>
</div>
<div className="mt-2 text-xs text-zinc-500">{item.documentCategory?.name ?? "系统默认"}</div>
</button>
))
) : (
<div className="rounded-lg border border-zinc-200 p-3 text-sm text-zinc-500">暂无资产分类</div>
)}
</div>
<PrimaryTable className="hidden md:block">
<Table>
<TableHeader>
<tr>
<TableHead>编码</TableHead>
<TableHead>名称</TableHead>
<TableHead>状态</TableHead>
</tr>
</TableHeader>
<TableBody>
{categoryItems.map((item) => (
<TableRow key={item.id} onClick={() => resetCategoryEditor(item)} className="cursor-pointer">
<TableCell className="font-medium text-zinc-900" title={item.code}>
{formatTextWithCompactLongNumbers(item.code)}
</TableCell>
<TableCell>
<div title={item.name}>{formatTextWithCompactLongNumbers(item.name)}</div>
<div className="text-xs text-zinc-500">{item.documentCategory?.name ?? "系统默认"}</div>
</TableCell>
<TableCell>{item.enabled ? "启用" : "停用"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</PrimaryTable>
</>
) : null}
</div>
) : null}
<div className="grid gap-4">
<BusinessListToolbar
actions={(
<>
{canViewAll ? (
<>
<Button type="button" size="sm" variant={mine ? "default" : "secondary"} onClick={() => setMine(true)}>
我相关
</Button>
<Button type="button" size="sm" variant={!mine ? "default" : "secondary"} onClick={() => setMine(false)}>
全范围
</Button>
</>
) : null}
<Button
type="button"
size="sm"
variant={showAssetAdvancedFilters ? "default" : "secondary"}
data-testid="asset-filter-toggle"
onClick={() => setShowAdvancedFilters((value) => !value)}
>
筛选
</Button>
</>
)}
advanced={showAssetAdvancedFilters ? (
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
<select className="select-std" value={sensitivityFilter} onChange={(event) => setSensitivityFilter(event.target.value as AssetSensitivityLevel | "") }>
{sensitivityOptions().map((item) => (
<option key={item.value || "all"} value={item.value}>
{item.label}
</option>
))}
</select>
<select className="select-std" value={categoryFilter} onChange={(event) => setCategoryFilter(event.target.value)}>
<option value="">全部分类</option>
{(categoriesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{formatTextWithCompactLongNumbers(item.name)}
</option>
))}
</select>
<select className="select-std" value={legalEntityFilter} onChange={(event) => {
setLegalEntityFilter(event.target.value);
setCostCenterFilter("");
}}>
<option value="">全部法体</option>
{(legalEntitiesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{formatTextWithCompactLongNumbers(item.name)}
</option>
))}
</select>
<select className="select-std" value={costCenterFilter} onChange={(event) => setCostCenterFilter(event.target.value)}>
<option value="">全部成本中心</option>
{filteredFilterCostCenters.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
<select className="select-std" value={assigneeFilter} onChange={(event) => setAssigneeFilter(event.target.value)} disabled={!canViewAll}>
<option value="">全部归属人</option>
{(assigneesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
<div className="flex items-center md:col-span-2 xl:col-span-5">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => {
setSensitivityFilter("");
setCategoryFilter("");
setLegalEntityFilter("");
setCostCenterFilter("");
setAssigneeFilter("");
setShowAdvancedFilters(false);
}}
>
重置筛选
</Button>
</div>
</div>
) : null}
>
<div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_180px_190px]">
<Input
placeholder="搜索编号/名称/hash/VER"
value={assetSearch}
onChange={(event) => setAssetSearch(event.target.value)}
/>
<select className="select-std" value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as AssetStatus | "") }>
{assetStatusOptions().map((item) => (
<option key={item.value || "all"} value={item.value}>
{item.label}
</option>
))}
</select>
<select className="select-std" value={assetTypeFilter} onChange={(event) => setAssetTypeFilter(event.target.value as AssetType | "") }>
{assetTypeOptions().map((item) => (
<option key={item.value || "all"} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
</BusinessListToolbar>
{assetsQuery.isLoading ? <TableSkeleton columns={4} rows={6} /> : null}
{assetsQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{resolveError(assetsQuery.error)}</p>
) : null}
{!assetsQuery.isLoading && !assetsQuery.isError ? (
<>
<BusinessMobileList>
{orderedAssetItems.length ? (
orderedAssetItems.map((item) => (
<button
data-testid="asset-mobile-row"
type="button"
key={item.id}
onClick={() => selectAsset(item.id)}
className="w-full rounded-lg border border-zinc-200 bg-white p-3 text-left"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="truncate text-sm font-semibold text-zinc-900">
<CompactAssetNo copyable={false} value={item.assetNo} />
</div>
<div className="mt-1 truncate text-xs text-zinc-500" title={item.name}>
{formatTextWithCompactLongNumbers(item.name)}
</div>
</div>
<StatusBadge status={item.status} />
</div>
<div className="mt-3 grid grid-cols-2 gap-2 text-xs text-zinc-600">
<div>
<div className="text-zinc-400">分类</div>
<div className="mt-0.5 truncate text-zinc-700" title={item.category?.name ?? undefined}>
{formatTextWithCompactLongNumbers(item.category?.name ?? "-")}
</div>
</div>
<div>
<div className="text-zinc-400">类型</div>
<div className="mt-0.5 truncate text-zinc-700">{assetTypeLabel(item.assetType)}</div>
</div>
<div>
<div className="text-zinc-400">归属人</div>
<div className="mt-0.5 truncate text-zinc-700">{item.assignee?.name ?? "-"}</div>
</div>
<div>
<div className="text-zinc-400">位置</div>
<div className="mt-0.5 truncate text-zinc-700">{item.location ?? "-"}</div>
</div>
</div>
<div className="mt-3 text-sm font-medium text-primary">查看详情</div>
</button>
))
) : (
<div className="rounded-lg border border-zinc-200 p-4 text-sm text-zinc-500">暂无资产卡片</div>
)}
</BusinessMobileList>
<BusinessTable testId="assets-table">
<thead className="table-header">
<tr>
<th className="table-th">资产</th>
<th className="table-th">状态</th>
<th className="table-th">责任人</th>
<th className="table-th">保管/位置</th>
<th className="table-th">盘点</th>
<th className="table-th w-24">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-50">
{orderedAssetItems.length ? (
orderedAssetItems.map((item) => (
<tr className="table-row" data-testid="asset-row" key={item.id}>
<td className="table-td">
<div className="font-semibold text-zinc-900">
<CompactAssetNo value={item.assetNo} />
</div>
<div className="text-xs text-zinc-500" title={item.name}>
{formatTextWithCompactLongNumbers(item.name)}
</div>
<div className="text-xs text-zinc-500">{assetTypeLabel(item.assetType)}</div>
</td>
<td className="table-td">
<StatusBadge status={item.status} />
</td>
<td className="table-td">
<div className="font-medium text-zinc-900">{formatEmployeeSummary(item.owner ?? item.assignee)}</div>
<div className="text-xs text-zinc-500">归属 {formatEmployeeSummary(item.assignee)}</div>
</td>
<td className="table-td" title={item.location ?? undefined}>
<div className="font-medium text-zinc-900">{formatEmployeeSummary(item.keeper)}</div>
<div className="text-xs text-zinc-500">{formatTextWithCompactLongNumbers(item.location ?? "-")}</div>
</td>
<td className="table-td">
{item.lastVerifiedAt ? formatDisplayDateTime(item.lastVerifiedAt) : "未登记"}
</td>
<td className="table-td">
<Button type="button" size="sm" variant="secondary" onClick={() => selectAsset(item.id)}>
查看详情
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan={6} className="py-8 text-center text-sm text-zinc-500">
暂无资产卡片
</td>
</tr>
)}
</tbody>
</BusinessTable>
</>
) : null}
</div>
</div>
) : (
<BusinessDetailWorkspace>
<BusinessDetailMain>
<div className="card-std space-y-4 p-4 md:p-5">
{selectedAssetId && !isCreatingAsset && assetDetailQuery.isLoading ? <TableSkeleton columns={2} rows={8} /> : null}
{selectedAssetId && !isCreatingAsset && assetDetailQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{resolveError(assetDetailQuery.error)}</p>
) : null}
{(isCreatingAsset || currentAsset) && !assetDetailQuery.isLoading ? (
<>
<div className="flex items-center justify-between gap-3">
<div>
<h3 className="text-lg font-semibold text-zinc-900">
{isCreatingAsset ? "新建资产卡片" : currentAsset ? <CompactAssetNo value={currentAsset.assetNo} /> : "资产卡片"}
</h3>
{!isCreatingAsset ? (
<p className="text-sm text-zinc-500" title={currentAsset?.name ?? undefined}>
{formatTextWithCompactLongNumbers(currentAsset?.name)}
</p>
) : null}
</div>
{!isCreatingAsset && currentAsset ? <StatusBadge status={currentAsset.status} /> : null}
</div>
{!isCreatingAsset && currentAsset?.sensitiveFieldsRedacted ? (
<p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
当前资产包含敏感字段,你可查看摘要;归档位置、外部引用、hash 和扩展元数据仅管理员或相关责任人可见。
</p>
) : null}
{assetFormError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{assetFormError}</p>
) : null}
{!isCreatingAsset && currentAsset ? (
<BusinessDetailFactGrid className="xl:grid-cols-4" testId="asset-detail-summary">
<BusinessDetailFact label="责任人">
{formatEmployeeSummary(currentAsset.owner ?? currentAsset.assignee)}
</BusinessDetailFact>
<BusinessDetailFact label="保管/位置">
{currentAsset.keeper ? formatEmployeeSummary(currentAsset.keeper) : currentAsset.location ?? "待确认"}
</BusinessDetailFact>
<BusinessDetailFact label={isElectronicAssetType(currentAsset.assetType) ? "最近验证" : "最近盘点"}>
{currentAsset.lastVerifiedAt ? formatDisplayDateTime(currentAsset.lastVerifiedAt) : "未登记"}
</BusinessDetailFact>
<BusinessDetailFact label="状态">
<StatusBadge status={currentAsset.status} />
</BusinessDetailFact>
</BusinessDetailFactGrid>
) : null}
<div className="space-y-6">
<section className="space-y-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">基础信息</h4>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">资产名称</label>
<Input data-testid="asset-name" value={assetForm.name} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, name: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">资产类型</label>
<select data-testid="asset-type" className="select-std" value={assetForm.assetType} disabled={!canEditCurrent || !isCreatingAsset} onChange={(event) => setAssetForm((current) => ({ ...current, assetType: event.target.value as AssetType }))}>
{assetTypeOptions().filter((item) => item.value).map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">资产状态</label>
<select data-testid="asset-status" className="select-std" value={assetForm.status} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, status: event.target.value as AssetStatus }))}>
{assetStatusOptions().filter((item) => item.value).map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">敏感级别</label>
<select data-testid="asset-sensitivity" className="select-std" value={assetForm.sensitivityLevel} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, sensitivityLevel: event.target.value as AssetSensitivityLevel }))}>
{sensitivityOptions().filter((item) => item.value).map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">资产分类</label>
<select data-testid="asset-category" className="select-std" value={assetForm.categoryId} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, categoryId: event.target.value }))}>
<option value="">请选择资产分类</option>
{(categoriesQuery.data?.items ?? []).filter((item) => item.enabled).map((item) => (
<option key={item.id} value={item.id}>
{formatTextWithCompactLongNumbers(item.name)}
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">法体</label>
<select data-testid="asset-legal-entity" className="select-std" value={assetForm.legalEntityId} disabled={!canEditCurrent} onChange={(event) => {
const legalEntityId = event.target.value;
setAssetForm((current) => ({
...current,
legalEntityId,
costCenterId: current.costCenterId && filteredAssetCostCenters.some((item) => item.id === current.costCenterId && item.legalEntityId === legalEntityId)
? current.costCenterId
: "",
}));
}}>
<option value="">请选择法体</option>
{(legalEntitiesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">成本中心</label>
<select data-testid="asset-cost-center" className="select-std" value={assetForm.costCenterId} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, costCenterId: event.target.value }))}>
<option value="">请选择成本中心</option>
{filteredAssetCostCenters.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">采购来源</label>
<select className="select-std" value={assetForm.purchaseRequestId} disabled={!canEditCurrent || !canReadProcurementSources || !isCreatingAsset} onChange={(event) => setAssetForm((current) => ({ ...current, purchaseRequestId: event.target.value }))}>
<option value="">无采购来源</option>
{purchaseOptions.map((item) => (
<option key={item.id} value={item.id}>
{formatTextWithCompactLongNumbers(item.requestNo ?? item.id)} · {formatTextWithCompactLongNumbers(item.title)}
</option>
))}
</select>
</div>
</div>
</section>
<section className="space-y-4 border-t border-zinc-200 pt-5">
<div>
<h4 className="text-sm font-semibold text-zinc-900">责任与归档</h4>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">归属人</label>
<select data-testid="asset-assignee" className="select-std" value={assetForm.assigneeEmployeeId} disabled={!canManage || !isCreatingAsset} onChange={(event) => setAssetForm((current) => ({ ...current, assigneeEmployeeId: event.target.value }))}>
<option value="">暂不分配</option>
{(assigneesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name} ({item.employeeNo})
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">负责人</label>
<select data-testid="asset-owner" className="select-std" value={assetForm.ownerEmployeeId} disabled={!canManage} onChange={(event) => setAssetForm((current) => ({ ...current, ownerEmployeeId: event.target.value }))}>
<option value="">未指定</option>
{(assigneesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name} ({item.employeeNo})
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">保管人/管理员</label>
<select data-testid="asset-keeper" className="select-std" value={assetForm.keeperEmployeeId} disabled={!canManage} onChange={(event) => setAssetForm((current) => ({ ...current, keeperEmployeeId: event.target.value }))}>
<option value="">未指定</option>
{(assigneesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name} ({item.employeeNo})
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">序列号</label>
<Input data-testid="asset-serial-no" value={assetForm.serialNo} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, serialNo: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">存放位置</label>
<Input data-testid="asset-location" value={assetForm.location} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, location: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">归档位置/备份位置</label>
<Input data-testid="asset-archive-location" placeholder="填归档位置摘要或离线档案号,不填 /home 或盘符完整路径" value={assetForm.archiveLocation} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, archiveLocation: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">最近盘点/恢复验证日期</label>
<DateTextInput value={assetForm.lastVerifiedAt} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, lastVerifiedAt: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">到期/续费日期</label>
<DateTextInput value={assetForm.expiresAt} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, expiresAt: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">启用日期</label>
<DateTextInput value={assetForm.activatedAt} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, activatedAt: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">退役日期</label>
<DateTextInput value={assetForm.retiredAt} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, retiredAt: event.target.value }))} />
</div>
</div>
</section>
{isElectronicAssetType(assetForm.assetType) ? (
<section className="space-y-4 border-t border-zinc-200 pt-5">
<div>
<h4 className="text-sm font-semibold text-zinc-900">电子资产安全字段</h4>
<p className="text-xs text-zinc-500">不填写密码、密钥、源码包、原始正文或完整路径。</p>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">外部引用/仓库地址</label>
<Input data-testid="asset-external-ref" placeholder="填系统入口或仓库主页,不填带 token 的链接或完整配置" value={assetForm.externalRef} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, externalRef: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">文件 hash / 校验摘要</label>
<Input data-testid="asset-source-hash" value={assetForm.sourceHash} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, sourceHash: event.target.value }))} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">历史验证编号</label>
<Input data-testid="asset-verification-no" placeholder="VER-00001" value={assetForm.verificationNo} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, verificationNo: event.target.value }))} />
</div>
<div className="space-y-2 md:col-span-2">
<label className="text-sm font-medium text-zinc-700">保密/回收要求</label>
<textarea className="textarea-std min-h-20" placeholder="写回收要求、保管要求或脱敏说明,不写密码、密钥、原文片段" value={assetForm.confidentialityNote} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, confidentialityNote: event.target.value }))} />
</div>
<details className="rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 md:col-span-2">
<summary className="cursor-pointer list-none text-sm font-medium text-zinc-700">
扩展元数据 JSON
<span className="ml-2 text-xs font-normal text-zinc-500">按需展开</span>
</summary>
<div className="mt-3 space-y-2">
<textarea className="textarea-std min-h-24 font-mono text-xs" placeholder='例如 {"backupPolicy":"monthly"};不要粘贴 .env、源码配置、原始 payload 或密钥' value={assetForm.metadataText} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, metadataText: event.target.value }))} />
</div>
</details>
</div>
</section>
) : null}
</div>
</>
) : null}
</div>
</BusinessDetailMain>
{(isCreatingAsset || currentAsset) && !assetDetailQuery.isLoading ? (
<BusinessDetailAside>
<BusinessDetailActionPanel
status={!isCreatingAsset && currentAsset ? <StatusBadge status={currentAsset.status} /> : null}
primaryAction={canManage ? (
<Button
className="w-full justify-center"
type="button"
data-testid="asset-save"
disabled={saveAssetMutation.isPending || !canEditCurrent}
onClick={() => saveAssetMutation.mutate()}
>
{saveAssetMutation.isPending ? "保存中..." : isCreatingAsset ? "创建资产卡片" : "保存资产卡片"}
</Button>
) : null}
summary={(
<>
<div>状态:{isCreatingAsset ? "新建中" : assetStatusLabel(currentAsset?.status)}</div>
<div>类型:{assetTypeLabel(assetForm.assetType)}</div>
<div>责任人:{formatEmployeeSummary(currentAsset?.owner ?? currentAsset?.assignee)}</div>
<div>归属人:{formatEmployeeSummary(currentAsset?.assignee)}</div>
<div>保管人:{formatEmployeeSummary(currentAsset?.keeper)}</div>
<div>位置:{(currentAsset?.location ?? assetForm.location) || "-"}</div>
<div>
{isElectronicAssetType(assetForm.assetType) ? "最近验证" : "最近盘点"}:
{currentAsset?.lastVerifiedAt ? formatDisplayDateTime(currentAsset.lastVerifiedAt) : assetForm.lastVerifiedAt || "-"}
</div>
<div>
采购来源:
{currentAsset?.purchaseRequest
? formatTextWithCompactLongNumbers(currentAsset.purchaseRequest.requestNo ?? currentAsset.purchaseRequest.id)
: "-"}
</div>
</>
)}
testId="asset-detail-action-panel"
>
{currentAsset && canTransfer && !isCreatingAsset && currentAsset.assetType === "fixed_asset" ? (
<div className="space-y-3">
<div className="text-sm font-semibold text-zinc-900">资产流转</div>
<div className="rounded-lg bg-zinc-50 px-3 py-2 text-xs text-zinc-600">
归属人:{formatEmployeeSummary(currentAsset.assignee)} · 位置:{currentAsset.location ?? "未设置"}
</div>
{movementError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{movementError}</p>
) : null}
<div className="space-y-3">
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">目标归属人</label>
<select
data-testid="asset-movement-assignee"
className="select-std"
value={movementEmployeeId}
onChange={(event) => setMovementEmployeeId(event.target.value)}
>
<option value="">保持当前归属人</option>
{(assigneesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name} ({item.employeeNo})
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">目标位置</label>
<Input
data-testid="asset-movement-location"
value={movementLocation}
onChange={(event) => setMovementLocation(event.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-zinc-700">备注</label>
<Input
data-testid="asset-movement-note"
value={movementNote}
onChange={(event) => setMovementNote(event.target.value)}
/>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
size="sm"
data-testid="asset-assign-submit"
disabled={assignAssetMutation.isPending || Boolean(currentAsset.assigneeEmployeeId) || !movementEmployeeId}
onClick={() => assignAssetMutation.mutate()}
>
{assignAssetMutation.isPending ? "领用中..." : "领用"}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
data-testid="asset-return-submit"
disabled={returnAssetMutation.isPending || !currentAsset.assigneeEmployeeId}
onClick={() => returnAssetMutation.mutate()}
>
{returnAssetMutation.isPending ? "归还中..." : "归还"}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
data-testid="asset-transfer-submit"
disabled={
transferAssetMutation.isPending ||
(!movementEmployeeId && movementLocation.trim() === (currentAsset.location ?? ""))
}
onClick={() => transferAssetMutation.mutate()}
>
{transferAssetMutation.isPending ? "调拨中..." : "调拨"}
</Button>
</div>
</div>
) : null}
</BusinessDetailActionPanel>
</BusinessDetailAside>
) : null}
</BusinessDetailWorkspace>
)}
</ListWorkspace>
);
}