文件
hyb-oa/client/src/pages/AssetRegistryPage.tsx
T
2026-05-14 00:52:59 +08:00

1134 行
49 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,
fetchAssetErpTrack,
fetchAssets,
patchAsset,
patchAssetCategory,
requeueAssetErpSync,
returnAsset,
transferAsset,
type AssetCategoryItem,
type AssetErpStage,
type AssetErpTrack,
type AssetStatus,
} 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 { AiSuggestionCard } from "../components/ai/AiSuggestionCard";
import { StatusBadge } from "../components/common/StatusBadge";
import { TableSkeleton } from "../components/common/TableSkeleton";
import { FilterBar, ListWorkspace, PrimaryTable, WorkspaceHeader } from "../components/patterns/ListWorkspace";
import { SectionPanel } from "../components/patterns/SectionPanel";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
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: "",
categoryId: "",
legalEntityId: "",
costCenterId: "",
purchaseRequestId: "",
serialNo: "",
location: "",
status: "in_stock" as AssetStatus,
assigneeEmployeeId: "",
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 formatAssetErpReason(reason: string | null) {
switch (reason) {
case "erp_sync_disabled":
case "env_hard_off":
return "ERP 总闸当前关闭";
case "flag_force_off":
return "ERP 功能开关当前强制关闭";
case "missing_flag_record":
return "ERP 功能开关记录缺失";
default:
return reason ?? null;
}
}
function resolveAssetErpTimestamp(stage: AssetErpStage) {
return stage.outbox?.updatedAt ?? stage.outbox?.processedAt ?? stage.binding?.lastSyncedAt ?? null;
}
function resolveAssetErpActionLabel(actionHint: AssetErpTrack["stage"]["actionHint"]) {
switch (actionHint) {
case "backfill":
return "补发";
case "retry":
return "重试同步";
case "resync":
return "重新同步摘要";
default:
return null;
}
}
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 canIntegrationManage = hasPermission(permissions, "integration.manage");
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 [categoryFilter, setCategoryFilter] = useState("");
const [legalEntityFilter, setLegalEntityFilter] = useState("");
const [costCenterFilter, setCostCenterFilter] = useState("");
const [assigneeFilter, setAssigneeFilter] = useState("");
const [mine, setMine] = useState(!canViewAll);
const [selectedAssetId, setSelectedAssetId] = useState(searchParams.get("id") ?? "");
const [isCreatingAsset, setIsCreatingAsset] = useState(false);
const [assetForm, setAssetForm] = useState(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, categoryFilter, legalEntityFilter, costCenterFilter, assigneeFilter, mine, canViewAll],
queryFn: () =>
fetchAssets({
status: statusFilter || undefined,
categoryId: categoryFilter || undefined,
legalEntityId: legalEntityFilter || undefined,
costCenterId: costCenterFilter || undefined,
assigneeId: assigneeFilter || undefined,
mine: canViewAll ? mine : true,
}),
});
const assetDetailQuery = useQuery({
enabled: Boolean(selectedAssetId) && !isCreatingAsset,
queryKey: ["assets", "detail", selectedAssetId],
queryFn: () => fetchAssetDetail(selectedAssetId),
});
const assetErpTrackQuery = useQuery({
enabled: canIntegrationManage && Boolean(selectedAssetId) && !isCreatingAsset,
queryKey: ["assets", "erp-track", selectedAssetId],
queryFn: () => fetchAssetErpTrack(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(() => {
if (isCreatingAsset) {
return;
}
if (selectedAssetId) {
if (assetDetailQuery.isLoading) {
return;
}
if (!assetDetailQuery.isError) {
return;
}
}
const nextId = assetsQuery.data?.items?.[0]?.id ?? "";
if (nextId !== selectedAssetId) {
setSelectedAssetId(nextId);
}
}, [assetDetailQuery.isError, assetDetailQuery.isLoading, assetsQuery.data?.items, isCreatingAsset, 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;
setAssetForm({
name: asset.name,
categoryId: asset.categoryId,
legalEntityId: asset.legalEntityId,
costCenterId: asset.costCenterId,
purchaseRequestId: asset.purchaseRequestId ?? "",
serialNo: asset.serialNo ?? "",
location: asset.location ?? "",
status: asset.status,
assigneeEmployeeId: asset.assigneeEmployeeId ?? "",
activatedAt: asset.activatedAt ?? "",
retiredAt: asset.retiredAt ?? "",
});
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 assetErpTrack = assetErpTrackQuery.data ?? null;
const assetErpStage = assetErpTrack?.stage ?? null;
const assetErpActionLabel = assetErpStage ? resolveAssetErpActionLabel(assetErpStage.actionHint) : null;
const canEditCurrent = canManage && (isCreatingAsset || currentAsset?.permissions.canEdit);
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() {
setIsCreatingAsset(true);
setSelectedAssetId("");
setAssetForm(initialAssetForm());
setAssetFormError("");
}
function buildCreateAssetPayload() {
return {
name: assetForm.name.trim(),
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,
activatedAt: assetForm.activatedAt || null,
retiredAt: assetForm.retiredAt || null,
};
}
function buildPatchAssetPayload() {
return {
name: assetForm.name.trim(),
categoryId: assetForm.categoryId,
legalEntityId: assetForm.legalEntityId,
costCenterId: assetForm.costCenterId,
serialNo: assetForm.serialNo.trim() || null,
location: assetForm.location.trim() || null,
status: assetForm.status,
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("请选择成本中心");
}
}
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"] }),
queryClient.invalidateQueries({ queryKey: ["assets", "erp-track"] }),
]);
setAssetFormError("");
setSelectedAssetId(data.asset.id);
setIsCreatingAsset(false);
toast.success(isCreatingAsset ? "资产卡片已创建" : "资产卡片已更新");
},
onError: (error) => {
const message = resolveError(error);
setAssetFormError(message);
toast.error(message);
},
});
const requeueAssetErpMutation = useMutation({
mutationFn: async () => {
if (!currentAsset) {
throw new Error("请先选择资产卡片");
}
return requeueAssetErpSync(currentAsset.id, true);
},
onSuccess: async (data) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["assets", "erp-track"] }),
queryClient.invalidateQueries({ queryKey: ["assets", "detail"] }),
]);
const message = data.duplicated
? "ERP 摘要已是最新状态"
: data.requeued
? "资产 ERP 同步已重新入队"
: "资产 ERP 同步已入队";
toast.success(message);
},
onError: (error) => {
toast.error(resolveError(error));
},
});
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 selectAsset = (assetId: string) => {
setIsCreatingAsset(false);
setSelectedAssetId(assetId);
};
return (
<ListWorkspace>
<WorkspaceHeader
title="资产台账"
subtitle="维护资产分类与资产卡片,支持法体、成本中心和采购来源引用。"
actions={
<div className="flex flex-wrap gap-2">
<Button type="button" variant="secondary" onClick={() => navigate("/mobile/assets/scan") }>
移动扫码查找
</Button>
{canManage ? (
<Button type="button" data-testid="asset-create" onClick={resetAssetEditor}>
新建资产卡片
</Button>
) : null}
</div>
}
/>
<div className="grid gap-6 xl:grid-cols-[380px_minmax(0,1fr)]">
<div className="card-std space-y-4 p-4 md:p-5">
<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}>
{item.name} ({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">{item.name}</div>
<div className="mt-1 text-xs text-zinc-500">{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">{item.code}</TableCell>
<TableCell>
<div>{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>
<div className="space-y-6">
<FilterBar className="space-y-4">
<div className="grid gap-3 md:grid-cols-3 xl:grid-cols-6">
<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={categoryFilter} onChange={(event) => setCategoryFilter(event.target.value)}>
<option value="">全部分类</option>
{(categoriesQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{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}>
{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>
{canViewAll ? (
<div className="flex items-center gap-2">
<Button type="button" variant={mine ? "default" : "secondary"} onClick={() => setMine(true)}>
仅自己
</Button>
<Button type="button" variant={!mine ? "default" : "secondary"} onClick={() => setMine(false)}>
全范围
</Button>
</div>
) : null}
</div>
{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 ? (
<>
<div className="space-y-3 md:hidden">
{assetItems.length ? (
assetItems.map((item) => (
<button
data-testid="asset-mobile-row"
type="button"
key={item.id}
onClick={() => selectAsset(item.id)}
className={`w-full rounded-lg border p-3 text-left ${
item.id === selectedAssetId && !isCreatingAsset
? "border-zinc-400 bg-zinc-50"
: "border-zinc-200 bg-white"
}`}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="truncate text-sm font-semibold text-zinc-900">{item.assetNo}</div>
<div className="mt-1 truncate text-xs text-zinc-500">{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">{item.category?.name ?? "-"}</div>
</div>
<div>
<div className="text-zinc-400">归属人</div>
<div className="mt-0.5 truncate text-zinc-700">{item.assignee?.name ?? "-"}</div>
</div>
</div>
</button>
))
) : (
<div className="rounded-lg border border-zinc-200 p-4 text-sm text-zinc-500">暂无资产卡片</div>
)}
</div>
<PrimaryTable className="hidden md:block">
<Table>
<TableHeader>
<tr>
<TableHead>资产</TableHead>
<TableHead>分类</TableHead>
<TableHead>状态</TableHead>
<TableHead>归属人</TableHead>
</tr>
</TableHeader>
<TableBody>
{assetItems.length ? (
assetItems.map((item) => (
<TableRow data-testid="asset-row" key={item.id} onClick={() => {
selectAsset(item.id);
}} className={item.id === selectedAssetId && !isCreatingAsset ? "bg-zinc-50" : "cursor-pointer"}>
<TableCell>
<div className="font-medium text-zinc-900">{item.assetNo}</div>
<div className="text-xs text-zinc-500">{item.name}</div>
</TableCell>
<TableCell>{item.category?.name ?? "-"}</TableCell>
<TableCell><StatusBadge status={item.status} /></TableCell>
<TableCell>{item.assignee?.name ?? "-"}</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={4} className="py-4 text-zinc-500">
暂无资产卡片
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</PrimaryTable>
</>
) : null}
</FilterBar>
<div className="card-std space-y-4 p-4 md:p-5">
{!selectedAssetId && !isCreatingAsset ? (
<div className="rounded-lg border border-dashed border-zinc-300 p-8 text-center text-sm text-zinc-500">
请先从列表选择资产卡片,或点击“新建资产卡片”。
</div>
) : null}
{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?.assetNo ?? "资产卡片"}</h3>
<p className="text-sm text-zinc-500">{isCreatingAsset ? "创建新的资产台账卡片。" : currentAsset?.name}</p>
</div>
{!isCreatingAsset && currentAsset ? <StatusBadge status={currentAsset.status} /> : null}
</div>
{assetFormError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{assetFormError}</p>
) : null}
<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-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-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}>
{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 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 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}>
{(item.requestNo ?? item.id)} · {item.title}
</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 type="date" 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>
<Input type="date" value={assetForm.retiredAt} disabled={!canEditCurrent} onChange={(event) => setAssetForm((current) => ({ ...current, retiredAt: event.target.value }))} />
</div>
</div>
{currentAsset && canTransfer && !isCreatingAsset ? (
<div className="rounded-xl border border-zinc-200 bg-zinc-50 p-4">
<div className="mb-3 flex items-center justify-between gap-3">
<div>
<h4 className="text-sm font-semibold text-zinc-900">资产流转</h4>
<p className="text-xs text-zinc-500">通过受控动作执行领用、归还和调拨,并写入审计记录。</p>
</div>
<div className="text-xs text-zinc-500">
当前归属人:{currentAsset.assignee?.name ?? "未分配"} · 位置:{currentAsset.location ?? "未设置"}
</div>
</div>
{movementError ? (
<p className="mb-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{movementError}</p>
) : null}
<div className="grid gap-4 md:grid-cols-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="mt-4 flex flex-wrap items-center gap-2">
<Button
type="button"
data-testid="asset-assign-submit"
disabled={assignAssetMutation.isPending || Boolean(currentAsset.assigneeEmployeeId) || !movementEmployeeId}
onClick={() => assignAssetMutation.mutate()}
>
{assignAssetMutation.isPending ? "领用中..." : "资产领用"}
</Button>
<Button
type="button"
variant="secondary"
data-testid="asset-return-submit"
disabled={returnAssetMutation.isPending || !currentAsset.assigneeEmployeeId}
onClick={() => returnAssetMutation.mutate()}
>
{returnAssetMutation.isPending ? "归还中..." : "资产归还"}
</Button>
<Button
type="button"
variant="secondary"
data-testid="asset-transfer-submit"
disabled={
transferAssetMutation.isPending ||
(!movementEmployeeId && movementLocation.trim() === (currentAsset.location ?? ""))
}
onClick={() => transferAssetMutation.mutate()}
>
{transferAssetMutation.isPending ? "调拨中..." : "资产调拨"}
</Button>
</div>
</div>
) : null}
{selectedAssetId && !isCreatingAsset && canIntegrationManage ? (
<SectionPanel
title="ERP 同步状态"
description="仅同步资产法体、成本中心与退役/归档等财务台账摘要,不接管实物流转。"
>
{assetErpTrackQuery.isLoading ? (
<p className="rounded-lg bg-zinc-50 px-3 py-2 text-sm text-zinc-500">ERP 同步轨道加载中...</p>
) : assetErpTrackQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{resolveError(assetErpTrackQuery.error)}</p>
) : assetErpStage ? (
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<div className="space-y-1 text-xs text-zinc-500">
<div>
最近更新时间:{resolveAssetErpTimestamp(assetErpStage) ? new Date(resolveAssetErpTimestamp(assetErpStage) as string).toLocaleString() : "尚无同步记录"}
</div>
<div>变更来源:{assetErpStage.preview.sourceEventName ?? "-"}</div>
</div>
<StatusBadge status={assetErpStage.deliveryStatus} />
</div>
<div className="grid gap-2 rounded-lg bg-zinc-50 px-3 py-2 text-xs text-zinc-600 md:grid-cols-2">
<div>资产编号:{assetErpTrack?.asset.assetNo ?? currentAsset?.assetNo ?? "-"}</div>
<div>最近 changeType:{assetErpStage.preview.changeType ?? "-"}</div>
<div>分类:{assetErpStage.preview.categoryCode ?? "-"}</div>
<div>资产状态:{assetErpStage.preview.status ?? assetErpTrack?.asset.status ?? "-"}</div>
<div>法体:{assetErpStage.preview.legalEntityCode ?? "-"}</div>
<div>成本中心:{assetErpStage.preview.costCenterCode ?? "-"}</div>
</div>
{formatAssetErpReason(assetErpStage.reason) ? (
<div className="rounded bg-zinc-50 px-3 py-2 text-xs text-zinc-500">{formatAssetErpReason(assetErpStage.reason)}</div>
) : null}
{assetErpStage.outbox?.lastError ? (
<div className="rounded bg-red-50 px-3 py-2 text-xs text-red-600">{assetErpStage.outbox.lastError}</div>
) : null}
{assetErpTrack?.permissions.canSeeExternalRefs && (assetErpStage.binding?.externalCode || assetErpStage.binding?.externalId) ? (
<div className="rounded bg-zinc-50 px-3 py-2 text-xs text-zinc-600">
ERP 资产编号:{assetErpStage.binding?.externalCode ?? "-"}
{assetErpStage.binding?.externalId ? ` · ${assetErpStage.binding.externalId}` : ""}
</div>
) : null}
{assetErpTrack?.permissions.canRetry && assetErpActionLabel ? (
<div className="flex justify-end">
<Button
type="button"
size="sm"
variant="secondary"
disabled={requeueAssetErpMutation.isPending}
onClick={() => requeueAssetErpMutation.mutate()}
>
{requeueAssetErpMutation.isPending ? "处理中..." : assetErpActionLabel}
</Button>
</div>
) : null}
</div>
) : (
<p className="rounded-lg bg-zinc-50 px-3 py-2 text-sm text-zinc-500">暂无 ERP 轨道信息</p>
)}
</SectionPanel>
) : null}
{selectedAssetId && !isCreatingAsset && currentAsset ? (
<AiSuggestionCard targetType="asset_card" targetId={currentAsset.id} />
) : null}
<div className="flex items-center gap-2">
{canManage ? (
<Button type="button" data-testid="asset-save" disabled={saveAssetMutation.isPending || !canEditCurrent} onClick={() => saveAssetMutation.mutate()}>
{saveAssetMutation.isPending ? "保存中..." : isCreatingAsset ? "创建资产卡片" : "保存资产卡片"}
</Button>
) : null}
{currentAsset?.purchaseRequest ? (
<span className="text-sm text-zinc-500">采购来源:{currentAsset.purchaseRequest.requestNo ?? currentAsset.purchaseRequest.id}</span>
) : null}
</div>
</>
) : null}
</div>
</div>
</div>
</ListWorkspace>
);
}