Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/services/maintenance_chat_service.py
#	backend/tests/test_maintenance_chat_service.py
#	frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
hugo committed 2026-07-08 16:23:30 +08:00
commit 2ce1aca023
25 files changed
+1609 -304

No files matched your search

@@ -1,6 +1,7 @@
/**
* features/chat/components/ChatInputBar.vue
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
* 逻辑:设备维保助手的管理入口(设备台账、登记维修)与语音按钮同侧排列,发送按钮独占右侧。
*/
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -259,27 +260,6 @@ watch(
<span>点发送开始处理</span>
</div>
<div
v-if="isMaintenanceAgent && canManageMaintenance"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
>
<button
type="button"
class="rounded-full border border-brand-200 bg-brand-50 px-3 py-1 font-medium text-brand-700 transition-colors hover:bg-brand-100"
@click="emit('maintenance-ledger-config')"
>
▦ {{ $t('maintenance.panel.ledgerTitle') }}
</button>
<button
type="button"
class="rounded-full border border-brand-200 bg-brand-50 px-3 py-1 font-medium text-brand-700 transition-colors hover:bg-brand-100"
@click="emit('maintenance-create-record')"
>
{{ $t('maintenance.panel.recordTitle') }}
</button>
<span>{{ $t('maintenance.panel.adminOnly') }}</span>
</div>
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
<div class="flex items-center gap-3">
<button
@@ -359,7 +339,7 @@ watch(
</div>
</div>
<div ref="kbMenuRef" class="relative">
<div v-if="!isMaintenanceAgent" ref="kbMenuRef" class="relative">
<button
type="button"
:disabled="kbDropdownDisabled"
@@ -386,6 +366,27 @@ watch(
</button>
</div>
</div>
<div
v-if="isMaintenanceAgent && canManageMaintenance"
class="flex flex-wrap items-center gap-2"
:title="$t('maintenance.panel.adminOnly')"
>
<button
type="button"
class="rounded-lg border border-brand-300 bg-brand-50 px-3 py-1.5 text-xs font-semibold text-brand-700 transition-colors hover:bg-brand-100"
@click="emit('maintenance-ledger-config')"
>
{{ $t('maintenance.chat.manageLedger') }}
</button>
<button
type="button"
class="rounded-lg border border-brand-300 bg-brand-50 px-3 py-1.5 text-xs font-semibold text-brand-700 transition-colors hover:bg-brand-100"
@click="emit('maintenance-create-record')"
>
{{ $t('maintenance.chat.logRepair') }}
</button>
</div>
</div>
<button
@@ -402,7 +403,7 @@ watch(
v-else
type="button"
:disabled="!canSendMessage"
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
:class="!canSendMessage
? 'border-default bg-slate-100 text-muted'
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
@@ -13,6 +13,8 @@ import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappin
import type { TrainingHandlers } from './messages/TrainingExamQuestionMessage.vue';
import type { ChatMessage } from '../types/chat.types';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
const {
messages,
@@ -55,6 +57,9 @@ const emit = defineEmits<{
'open-feedback': [index: number];
'select-question': [question: string];
'scroll-to-bottom': [];
'maintenance-edit-record': [record: MaintenanceRecord];
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
}>();
const bindScrollContainer = (node: unknown) => {
@@ -122,6 +127,9 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
@resend="emit('resend', $event)"
@regenerate="emit('regenerate')"
@open-feedback="emit('open-feedback', index)"
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
/>
<ToolRunProgressCard
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
@@ -21,6 +21,19 @@ import MaintenanceRecordManagerPanel from '@/features/maintenance/components/Mai
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
import {
MAINTENANCE_PANEL_DEFAULT_WIDTH,
buildMaintenancePanelWidthStyle,
clampMaintenancePanelWidth,
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
type MaintenanceRecordPanelCommand = {
mode: 'list' | 'create';
device: MaintenanceDevice;
nonce: number;
};
const page = useChatPageContext();
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
@@ -35,18 +48,16 @@ const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].inc
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
const maintenancePanelWidth = ref(560);
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
const isMaintenancePanelFullscreen = ref(false);
const isMaintenancePanelResizing = ref(false);
const maintenancePanelStyle = computed(() => {
if (isMaintenancePanelFullscreen.value) {
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
}
return {
width: `${maintenancePanelWidth.value}px`,
minWidth: '420px',
maxWidth: '82vw',
};
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
});
/**
@@ -61,8 +72,7 @@ const startMaintenancePanelResize = (event: MouseEvent): void => {
const startWidth = maintenancePanelWidth.value;
const handleMove = (moveEvent: MouseEvent) => {
const nextWidth = startWidth + (startX - moveEvent.clientX);
const maxWidth = Math.max(420, Math.floor(window.innerWidth * 0.82));
maintenancePanelWidth.value = Math.min(maxWidth, Math.max(420, nextWidth));
maintenancePanelWidth.value = clampMaintenancePanelWidth(nextWidth, window.innerWidth);
};
const stopResize = () => {
isMaintenancePanelResizing.value = false;
@@ -73,6 +83,42 @@ const startMaintenancePanelResize = (event: MouseEvent): void => {
window.addEventListener('mouseup', stopResize);
};
/**
* 打开右侧维修记录面板并进入指定记录的编辑表单。
* @param record - 会话结果表格中选中的维修记录。
*/
const openMaintenanceRecordEdit = (record: MaintenanceRecord): void => {
maintenanceEditRecord.value = record;
maintenanceRecordPanelCommand.value = null;
maintenancePanel.value = 'record';
};
/**
* 鎵撳紑鍙充晶缁翠慨璁板綍鍒楄〃锛屽苟鎸夊綋鍓嶈澶囩紪鍙风瓫閫夊巻鍙茶褰曘€?
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
*/
const openMaintenanceRecordHistory = (device: MaintenanceDevice): void => {
maintenanceEditRecord.value = null;
maintenanceRecordPanelCommand.value = { mode: 'list', device, nonce: Date.now() };
maintenancePanel.value = 'record';
};
/**
* 鎵撳紑鍙充晶缁翠慨璁板綍鏂板琛ㄥ崟锛屽苟棰勫~褰撳墠璁惧缂栧彿銆?
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
*/
const openMaintenanceRecordCreate = (device: MaintenanceDevice): void => {
maintenanceEditRecord.value = null;
maintenanceRecordPanelCommand.value = { mode: 'create', device, nonce: Date.now() };
maintenancePanel.value = 'record';
};
const openBlankMaintenanceRecordCreate = (): void => {
maintenanceEditRecord.value = null;
maintenanceRecordPanelCommand.value = null;
maintenancePanel.value = 'record';
};
// 切换 Agent 时,重置工作区展开状态,确保每次进入都是收起状态(聊天优先)
watch(() => page.currentAgentId, () => {
isTrainingWorkspaceExpanded.value = false;
@@ -207,6 +253,9 @@ watch(() => page.currentAgentId, () => {
@open-feedback="page.handleOpenFeedback($event)"
@select-question="page.handleSend"
@scroll-to-bottom="page.scrollToBottom"
@maintenance-edit-record="openMaintenanceRecordEdit"
@maintenance-view-record-history="openMaintenanceRecordHistory"
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
/>
<ChatInputBar
@@ -241,7 +290,7 @@ watch(() => page.currentAgentId, () => {
@shipping-inventory-selected="page.handleShippingInventorySelected"
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
@maintenance-ledger-config="maintenancePanel = 'ledger'"
@maintenance-create-record="maintenancePanel = 'record'"
@maintenance-create-record="openBlankMaintenanceRecordCreate"
@clear-shipping-focus="page.clearShippingFocus"
/>
</div>
@@ -293,7 +342,11 @@ watch(() => page.currentAgentId, () => {
</div>
<div class="min-h-0 flex-1 overflow-auto p-4">
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
<MaintenanceRecordManagerPanel v-else />
<MaintenanceRecordManagerPanel
v-else
:edit-record="maintenanceEditRecord"
:command="maintenanceRecordPanelCommand"
/>
</div>
</aside>
@@ -19,6 +19,8 @@ import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
import TrainingResultCard from './TrainingResultCard.vue';
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
@@ -76,6 +78,9 @@ const emit = defineEmits<{
resend: [content: string];
regenerate: [];
'open-feedback': [];
'maintenance-edit-record': [record: MaintenanceRecord];
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
}>();
const authStore = useAuthStore();
@@ -693,6 +698,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
<MaintenanceDeviceResultCard
v-else-if="message.type === 'maintenance-device-result'"
:message="message"
@edit-record="emit('maintenance-edit-record', $event)"
@view-record-history="emit('maintenance-view-record-history', $event)"
@create-record="emit('maintenance-create-record-for-device', $event)"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
@@ -1,31 +1,51 @@
/**
* features/chat/components/messages/MaintenanceDeviceResultCard.vue
* 用途:设备维保助手会话中的设备台账查询结果卡片。
* 依赖:chat.types、ledger/record 类型、vue-i18n。
* 逻辑:后端返回 maintenance-device-result payload 后,本组件按原型展示设备基础信息、匹配状态和快捷操作。
* 用途:设备维保助手会话中的设备信息与维修记录结果卡片。
* 依赖:auth.store、chat.types、maintenance ledger/record 类型、repair-status-display.utils、maintenance-panel-layout.utils、vue-i18n。
* 逻辑:后端返回 queryMode=device 时按台账配置表单同序展示设备信息;queryMode=records 时按维修记录配置字段展示记录列表。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import type { ChatMessage } from '../../types/chat.types';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
import { repairStatusBadgeClass } from '@/features/maintenance/utils/repair-status-display.utils';
import { buildMaintenancePanelWidthStyle } from '@/features/maintenance/utils/maintenance-panel-layout.utils';
interface MaintenanceDeviceResultPayload {
matched?: boolean;
queryMode?: 'device' | 'records';
keyword?: string;
device?: MaintenanceDevice;
records?: MaintenanceRecord[];
summary?: {
recentRecordCount?: number;
statusCounts?: Record<string, number>;
ledgerMatched?: boolean;
};
actions?: Array<{ id: string; label: string }>;
}
type DisplayCell = {
label: string;
value: string | number | null | undefined;
};
const props = defineProps<{
message: ChatMessage;
}>();
const emit = defineEmits<{
'edit-record': [record: MaintenanceRecord];
'view-record-history': [device: MaintenanceDevice];
'create-record': [device: MaintenanceDevice];
}>();
const { t } = useI18n();
const authStore = useAuthStore();
const recordDetailPanelStyle = buildMaintenancePanelWidthStyle();
const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
const raw = props.message.payload;
@@ -35,21 +55,39 @@ const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
const device = computed(() => payload.value?.device || null);
const records = computed(() => payload.value?.records || []);
const queryMode = computed(() => payload.value?.queryMode === 'records' ? 'records' : 'device');
const hasResult = computed(() => Boolean(device.value || records.value.length));
const ledgerMatched = computed(() => payload.value?.summary?.ledgerMatched !== false);
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(authStore.user?.role || '')));
const selectedRecord = ref<MaintenanceRecord | null>(null);
const statusLabel = computed(() => {
const status = device.value?.deviceStatus;
const deviceStatusLabel = (status?: string | null) => {
if (status === 'in_use') return t('maintenance.ledger.status.inUse');
if (status === 'disabled') return t('maintenance.ledger.status.disabled');
if (status === 'scrapped') return t('maintenance.ledger.status.scrapped');
if (status === 'sold') return t('maintenance.ledger.status.sold');
return status || '-';
});
};
const rows = computed(() => {
const recordStatusLabel = (status?: string | null) => {
if (status === 'pending') return t('maintenance.record.status.pending');
if (status === 'processing') return t('maintenance.record.status.processing');
if (status === 'done') return t('maintenance.record.status.done');
if (status === 'cancelled') return t('maintenance.record.status.cancelled');
return status || '-';
};
const displayValue = (value: DisplayCell['value']) => {
if (value === null || value === undefined || value === '') return '-';
return String(value);
};
const firstCell = (row: DisplayCell[]): DisplayCell => row[0] || { label: '', value: '' };
const deviceRows = computed<DisplayCell[][]>(() => {
const item = device.value;
if (!item) return [];
// 字段顺序与 LedgerConfigPanel 设备配置表单保持一致(左列优先、逐行两列)。
return [
[
{ label: t('maintenance.ledger.fields.deviceCode'), value: item.deviceCode },
@@ -57,76 +95,244 @@ const rows = computed(() => {
],
[
{ label: t('maintenance.ledger.fields.modelSpec'), value: item.modelSpec },
{ label: t('maintenance.ledger.fields.department'), value: item.department },
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
],
[
{ label: t('maintenance.ledger.fields.devicePosition'), value: item.installLocation },
{ label: t('maintenance.ledger.fields.deviceStatus'), value: statusLabel.value },
{ label: t('maintenance.ledger.fields.deviceStatus'), value: deviceStatusLabel(item.deviceStatus) },
],
[
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
{ label: t('maintenance.ledger.fields.startDate'), value: item.startDate },
{ label: t('maintenance.ledger.fields.department'), value: item.department },
{ label: t('maintenance.ledger.fields.responsibleUser'), value: item.responsibleUser },
],
[
{ label: t('maintenance.ledger.fields.productionDate'), value: item.productionDate },
{ label: t('maintenance.ledger.fields.entryDate'), value: item.entryDate },
],
[
{ label: t('maintenance.ledger.fields.originalValue'), value: item.originalValue },
{ label: t('maintenance.ledger.fields.residualValue'), value: item.residualValue },
],
[
{ label: t('maintenance.ledger.fields.accountSet'), value: item.accountSet },
],
[
{ label: t('maintenance.ledger.fields.remark'), value: item.remark },
],
];
});
const latestRepairDate = computed(() => records.value[0]?.reportDate || '-');
const totalCost = computed(() => records.value.reduce((sum, item) => {
const value = Number(String(item.repairCost || '').replace(/[^\d.-]/g, ''));
return Number.isFinite(value) ? sum + value : sum;
}, 0));
const summaryCards = computed(() => [
{ label: t('maintenance.record.fields.deviceCode'), value: device.value?.deviceCode || payload.value?.keyword || '-' },
{ label: t('maintenance.chat.latestRepair'), value: latestRepairDate.value },
{ label: t('maintenance.chat.totalCount'), value: String(records.value.length) },
{ label: t('maintenance.chat.totalCost'), value: totalCost.value ? String(totalCost.value) : '-' },
]);
const recordDetailRows = (record: MaintenanceRecord): DisplayCell[] => [
{ label: t('maintenance.record.fields.deviceCode'), value: record.deviceCode },
{ label: t('maintenance.ledger.fields.deviceName'), value: record.deviceName },
{ label: t('maintenance.record.fields.reportDate'), value: record.reportDate },
{ label: t('maintenance.record.fields.repairCategory'), value: record.repairCategory },
{ label: t('maintenance.record.fields.repairStatus'), value: recordStatusLabel(record.repairStatus) },
{ label: t('maintenance.record.fields.faultDescription'), value: record.faultDescription },
{ label: t('maintenance.record.fields.repairDescription'), value: record.repairDescription },
{ label: t('maintenance.record.fields.reporter'), value: record.reporter },
{ label: t('maintenance.record.fields.repairDate'), value: record.repairDate },
{ label: t('maintenance.record.fields.repairUnit'), value: record.repairUnit },
{ label: t('maintenance.record.fields.repairer'), value: record.repairer },
{ label: t('maintenance.record.fields.approver'), value: record.approver },
{ label: t('maintenance.record.fields.repairCost'), value: record.repairCost },
{ label: t('maintenance.record.fields.repairHours'), value: record.repairHours },
{ label: t('maintenance.record.fields.sourceOrderNo'), value: record.sourceOrderNo },
{ label: t('maintenance.ledger.fields.devicePosition'), value: record.installLocation },
];
</script>
<template>
<section v-if="hasResult" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
<div class="flex items-center justify-between gap-3 rounded-t-lg border border-slate-200 bg-slate-50 px-3 py-2">
<h3 class="font-semibold">
{{ device ? t('maintenance.chat.deviceLedgerInfo') : t('maintenance.chat.recordInfo') }}
<section
v-if="hasResult"
class="mt-3 w-full max-w-[760px] overflow-hidden rounded-lg border border-slate-300 bg-white text-sm text-slate-800 shadow-sm"
>
<div class="flex items-center justify-between gap-3 border-b border-slate-200 bg-slate-50 px-3 py-2.5">
<h3 class="font-semibold text-slate-900">
{{ queryMode === 'records' ? t('maintenance.chat.recordQueryResult') : t('maintenance.chat.deviceLedgerInfo') }}
</h3>
<span
class="rounded-full px-2.5 py-0.5 text-xs font-semibold"
class="shrink-0 rounded-full px-2.5 py-0.5 text-xs font-semibold"
:class="ledgerMatched ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
>
{{ ledgerMatched ? t('maintenance.chat.matched') : t('maintenance.chat.recordMatched') }}
{{ queryMode === 'records' ? t('maintenance.chat.returnedRecords', { count: records.length }) : t('maintenance.chat.matched') }}
</span>
</div>
<div v-if="device" class="overflow-hidden border-x border-b border-slate-200">
<table class="w-full table-fixed text-sm">
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex" class="border-t border-slate-200 first:border-t-0">
<template v-for="cell in row" :key="cell.label">
<th class="w-[16%] bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">{{ cell.label }}</th>
<td class="w-[34%] px-3 py-2 text-slate-800">{{ cell.value || '-' }}</td>
</template>
</tr>
</tbody>
</table>
</div>
<div v-if="records.length" class="mt-3 overflow-hidden rounded-lg border border-slate-200">
<div class="bg-slate-50 px-3 py-2 text-xs font-semibold text-slate-600">
{{ t('maintenance.chat.recentRecords', { count: records.length }) }}
<template v-if="queryMode === 'device'">
<div v-if="device" class="overflow-x-auto p-3">
<table class="w-full min-w-[680px] border-collapse text-sm">
<tbody>
<tr v-for="(row, rowIndex) in deviceRows" :key="rowIndex">
<template v-if="row.length === 1">
<th class="w-[16%] border border-slate-200 bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">
{{ firstCell(row).label }}
</th>
<td colspan="3" class="border border-slate-200 px-3 py-2 text-slate-900">
{{ displayValue(firstCell(row).value) }}
</td>
</template>
<template v-else>
<template v-for="cell in row" :key="cell.label">
<th class="w-[16%] border border-slate-200 bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">
{{ cell.label }}
</th>
<td class="w-[34%] border border-slate-200 px-3 py-2 text-slate-900">
{{ displayValue(cell.value) }}
</td>
</template>
</template>
</tr>
</tbody>
</table>
</div>
<table class="w-full text-left text-xs">
<thead class="bg-slate-50 text-slate-500">
<tr>
<th class="px-3 py-2">{{ t('maintenance.record.fields.reportDate') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.faultDescription') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairer') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="record in records.slice(0, 3)" :key="record.id" class="border-t border-slate-200">
<td class="px-3 py-2">{{ record.reportDate || '-' }}</td>
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription || '-' }}</td>
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
</tr>
</tbody>
</table>
</div>
<div class="mt-3 flex flex-wrap gap-2">
<button type="button" class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white">
{{ t('maintenance.chat.viewRepairHistory') }}
</button>
<button type="button" class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700">
{{ t('maintenance.chat.addRepairRecord') }}
</button>
</div>
<div v-if="canManageMaintenance" class="flex flex-wrap gap-2 px-3 pb-3">
<button
v-if="device"
type="button"
class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white transition-colors hover:bg-brand-700"
@click="emit('view-record-history', device)"
>
{{ t('maintenance.chat.viewRepairHistory') }}
</button>
<button
v-if="device"
type="button"
class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50"
@click="emit('create-record', device)"
>
{{ t('maintenance.chat.addRepairRecord') }}
</button>
</div>
<p v-else class="px-3 pb-3 text-xs text-slate-500">
{{ t('maintenance.chat.adminActionsHidden') }}
</p>
</template>
<template v-else>
<div class="grid gap-2 p-3 sm:grid-cols-2 lg:grid-cols-4">
<div v-for="card in summaryCards" :key="card.label" class="rounded-lg border border-dashed border-slate-300 bg-white px-3 py-2">
<div class="text-xs text-slate-500">{{ card.label }}</div>
<div class="mt-1 text-lg font-bold text-slate-900">{{ card.value }}</div>
</div>
</div>
<div class="px-3 pb-3">
<div class="overflow-hidden border border-slate-200">
<table class="w-full table-fixed border-collapse text-left text-xs">
<thead class="bg-slate-100 text-slate-700">
<tr>
<th class="w-[13%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.reportDate') }}</th>
<th class="w-[29%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.faultDescription') }}</th>
<th class="w-[29%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.repairDescription') }}</th>
<th class="w-[11%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.repairStatus') }}</th>
<th class="w-[18%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.chat.operation') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="record in records" :key="record.id" class="bg-white">
<td class="whitespace-nowrap border border-slate-200 px-2 py-2">{{ displayValue(record.reportDate) }}</td>
<td class="border border-slate-200 px-2 py-2 align-top" :title="displayValue(record.faultDescription)">
<span class="line-clamp-2 break-words leading-relaxed">{{ displayValue(record.faultDescription) }}</span>
</td>
<td class="border border-slate-200 px-2 py-2 align-top" :title="displayValue(record.repairDescription)">
<span class="line-clamp-2 break-words leading-relaxed">{{ displayValue(record.repairDescription) }}</span>
</td>
<td class="border border-slate-200 px-2 py-2">
<span
class="inline-flex whitespace-nowrap rounded-full border px-2 py-0.5 text-xs font-semibold"
:class="repairStatusBadgeClass(record.repairStatus)"
>
{{ recordStatusLabel(record.repairStatus) }}
</span>
</td>
<td class="border border-slate-200 px-2 py-2">
<div class="flex items-center gap-1.5">
<button
type="button"
class="inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md border border-brand-200 bg-brand-50 px-2 py-1 text-xs font-semibold leading-none text-brand-700 transition-colors hover:bg-brand-100"
@click="selectedRecord = record"
>
{{ t('maintenance.chat.viewRecordDetail') }}
</button>
<button
v-if="canManageMaintenance"
type="button"
class="inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md border border-brand-200 bg-brand-50 px-2 py-1 text-xs font-semibold leading-none text-brand-700 transition-colors hover:bg-brand-100"
@click="emit('edit-record', record)"
>
{{ t('maintenance.record.actions.edit') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div
v-if="selectedRecord"
class="fixed inset-y-0 right-0 z-50 flex flex-col border-l border-slate-200 bg-white shadow-2xl"
:style="recordDetailPanelStyle"
>
<div class="flex items-start justify-between gap-3 border-b border-slate-200 px-5 py-4">
<div>
<h3 class="text-base font-semibold text-slate-900">{{ t('maintenance.chat.recordDetailTitle') }}</h3>
<p class="mt-1 text-xs text-slate-500">{{ t('maintenance.chat.recordDetailHint') }}</p>
</div>
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-700"
@click="selectedRecord = null"
>
×
</button>
</div>
<div class="flex-1 overflow-y-auto px-4 py-4">
<div class="mb-4 rounded-lg border border-dashed border-brand-300 bg-brand-50 px-3 py-2 text-xs text-brand-700">
{{ t('maintenance.chat.recordDetailPermissionHint') }}
</div>
<dl class="overflow-hidden border border-slate-200 text-sm">
<div
v-for="detail in recordDetailRows(selectedRecord)"
:key="detail.label"
class="grid grid-cols-[118px_minmax(0,1fr)] border-b border-slate-200 last:border-b-0"
>
<dt class="bg-slate-100 px-3 py-2 font-semibold text-slate-700">{{ detail.label }}</dt>
<dd class="min-w-0 break-words px-3 py-2 text-slate-900">{{ displayValue(detail.value) }}</dd>
</div>
</dl>
</div>
</div>
</div>
<div v-if="canManageMaintenance" class="flex flex-wrap gap-2 px-3 pb-3">
<button
v-if="device"
type="button"
class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50"
@click="emit('create-record', device)"
>
{{ t('maintenance.chat.addRepairRecord') }}
</button>
</div>
<p v-else class="px-3 pb-3 text-xs text-slate-500">
{{ t('maintenance.chat.adminActionsHidden') }}
</p>
</template>
</section>
</template>
@@ -19,6 +19,8 @@ export interface ListMaintenanceRecordsParams {
keyword?: string;
deviceCode?: string;
status?: string;
reportDateFrom?: string;
reportDateTo?: string;
page?: number;
pageSize?: number;
}
@@ -28,13 +30,19 @@ const jsonHeaders = () => ({
'Content-Type': 'application/json',
});
export const listMaintenanceRecords = (params: ListMaintenanceRecordsParams = {}) => {
const sp = new URLSearchParams();
const appendListQueryParams = (sp: URLSearchParams, params: ListMaintenanceRecordsParams = {}) => {
if (params.keyword) sp.set('keyword', params.keyword);
if (params.deviceCode) sp.set('deviceCode', params.deviceCode);
if (params.status) sp.set('status', params.status);
if (params.reportDateFrom) sp.set('reportDateFrom', params.reportDateFrom);
if (params.reportDateTo) sp.set('reportDateTo', params.reportDateTo);
if (params.page) sp.set('page', String(params.page));
if (params.pageSize) sp.set('page_size', String(params.pageSize));
};
export const listMaintenanceRecords = (params: ListMaintenanceRecordsParams = {}) => {
const sp = new URLSearchParams();
appendListQueryParams(sp, params);
const qs = sp.toString();
return requestJson<MaintenanceRecordListResult>(`${API_BASE}${qs ? `?${qs}` : ''}`, {
headers: getAuthHeaders(),
@@ -72,9 +80,7 @@ export const deleteMaintenanceRecord = (id: number) => {
export const exportMaintenanceRecords = async (params: ListMaintenanceRecordsParams = {}) => {
const sp = new URLSearchParams();
if (params.keyword) sp.set('keyword', params.keyword);
if (params.deviceCode) sp.set('deviceCode', params.deviceCode);
if (params.status) sp.set('status', params.status);
appendListQueryParams(sp, params);
const qs = sp.toString();
const response = await fetch(`${API_BASE}/export${qs ? `?${qs}` : ''}`, {
headers: getAuthHeaders(),
@@ -106,12 +112,25 @@ export const downloadMaintenanceRecordImportTemplate = async (): Promise<Blob> =
return response.blob();
};
export const importMaintenanceRecords = (file: File) => {
export const importMaintenanceRecords = async (file: File) => {
const form = new FormData();
form.append('file', file);
return requestJson<MaintenanceRecordImportResult>(`${API_BASE}/import`, {
const response = await fetch(`${API_BASE}/import`, {
method: 'POST',
headers: getAuthHeaders(),
body: form,
});
const data = await response.json().catch(() => null);
if (!response.ok) {
const message = data?.error?.message || data?.message || `HTTP ${response.status}`;
const code = data?.error?.code || data?.code || 'SYSTEM.HTTP_ERROR';
throw new BusinessError({
message,
code,
details: data?.error?.details || data?.details || {},
requestId: data?.request_id,
status: response.status,
});
}
return (data?.success === true ? data.data : data) as MaintenanceRecordImportResult;
};
@@ -3,7 +3,7 @@
* features/maintenance/components/LedgerConfigPanel.vue
* 用途:设备维保助手右侧固定面板中的“台账配置”页面,包含设备列表与设备配置两个 Tab。
* 依赖:maintenanceLedger.api、PaginationBar、useMessage。
* 逻辑:列表 Tab 负责查询/导入/选择设备;配置 Tab 负责新增或编辑设备台账,保存后刷新列表。
* 逻辑:列表 Tab 负责查询/导入/选择设备;配置 Tab 负责新增或编辑设备台账,保存后刷新列表;启用日期与维护周期仅保留后端字段,不在 UI 展示。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -83,8 +83,33 @@ const formatStatus = (value: string): string => {
return item?.label ? t(item.label) : value || '-';
};
/**
* 根据设备状态返回列表标签颜色,帮助管理员快速区分设备可用性。
* @param value - 设备状态枚举值。
* @returns Tailwind class 字符串。
*/
const statusBadgeClass = (value: string): string => {
if (value === 'in_use') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
if (value === 'disabled') return 'border-slate-200 bg-slate-100 text-slate-600';
if (value === 'scrapped') return 'border-rose-200 bg-rose-50 text-rose-700';
if (value === 'sold') return 'border-sky-200 bg-sky-50 text-sky-700';
return 'border-slate-200 bg-slate-50 text-slate-600';
};
/**
* 将金额输入统一转为可提交字符串,兼容 type=number 绑定产生的 number 值。
* @param value - 表单中的原值/残值。
* @returns 裁剪后的字符串;空值返回 undefined。
*/
const normalizeAmountField = (value: string | number | null | undefined): string | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const text = String(value).trim();
return text || undefined;
};
/**
* 从表单状态生成 API payload,集中裁剪字符串。
* 核心逻辑:startDate / maintenanceCycle 虽不在 UI 展示,编辑时仍随 payload 回传,避免保存其他字段时清空库内已有值。
* @returns 设备保存入参。
*/
const buildPayload = (): MaintenanceDevicePayload => ({
@@ -100,8 +125,8 @@ const buildPayload = (): MaintenanceDevicePayload => ({
startDate: form.startDate || undefined,
responsibleUser: form.responsibleUser?.trim(),
maintenanceCycle: form.maintenanceCycle?.trim(),
originalValue: form.originalValue?.trim(),
residualValue: form.residualValue?.trim(),
originalValue: normalizeAmountField(form.originalValue),
residualValue: normalizeAmountField(form.residualValue),
accountSet: form.accountSet?.trim(),
remark: form.remark?.trim(),
});
@@ -350,7 +375,7 @@ onMounted(loadDevices);
<th class="px-3 py-2">{{ t('maintenance.ledger.table.modelSpec') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.manufacturer') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.status') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.operation') }}</th>
<th class="px-3 py-2 text-right">{{ t('maintenance.ledger.table.operation') }}</th>
</tr>
</thead>
<tbody>
@@ -365,11 +390,24 @@ onMounted(loadDevices);
<td class="px-3 py-2">{{ device.deviceName }}</td>
<td class="px-3 py-2">{{ device.modelSpec || '-' }}</td>
<td class="px-3 py-2">{{ device.manufacturer || '-' }}</td>
<td class="px-3 py-2">{{ formatStatus(device.deviceStatus) }}</td>
<td class="px-3 py-2">
<button type="button" class="admin-report-page-btn" @click="startEdit(device)">
{{ t('maintenance.ledger.actions.edit') }}
</button>
<span
class="inline-flex min-w-14 items-center justify-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="statusBadgeClass(device.deviceStatus)"
>
{{ formatStatus(device.deviceStatus) }}
</span>
</td>
<td class="px-3 py-2">
<div class="flex justify-end">
<button
type="button"
class="admin-report-page-btn admin-report-page-btn--edit"
@click="startEdit(device)"
>
{{ t('maintenance.ledger.actions.edit') }}
</button>
</div>
</td>
</tr>
</tbody>
@@ -437,14 +475,6 @@ onMounted(loadDevices);
{{ t('maintenance.ledger.fields.entryDate') }}
<input v-model="form.entryDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.startDate') }}
<input v-model="form.startDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.maintenanceCycle') }}
<input v-model="form.maintenanceCycle" class="admin-table-filter-input" :placeholder="t('maintenance.ledger.placeholder.maintenanceCycle')" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.originalValue') }}
<input v-model="form.originalValue" type="number" min="0" step="0.01" class="admin-table-filter-input" />
@@ -0,0 +1,129 @@
<script setup lang="ts">
/**
* features/maintenance/components/MaintenanceDeviceSnapshotCard.vue
* 用途:维修记录表单中展示已匹配的设备台账快照卡片。
* 依赖:device-status-display.utils、maintenance ledger 类型、vue-i18n。
* 逻辑:MaintenanceRecordManagerPanel / MaintenanceRecordPanel 在设备编号下方引用;按加载、匹配、未找到、空态四种状态渲染。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { BadgeCheck, BriefcaseBusiness, Building2, MapPin, UserRound } from 'lucide-vue-next';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import { deviceStatusBadgeClass, deviceStatusLabelKey } from '@/features/maintenance/utils/device-status-display.utils';
const props = defineProps<{
device: MaintenanceDevice | null;
loading?: boolean;
deviceCode?: string;
}>();
const { t } = useI18n();
const trimmedCode = computed(() => props.deviceCode?.trim() || '');
/**
* 根据加载态、匹配结果与是否已输入编号,计算快照卡片展示状态。
* @returns loading | matched | notFound | empty
*/
const displayState = computed(() => {
if (props.loading) return 'loading';
if (props.device) return 'matched';
if (trimmedCode.value) return 'notFound';
return 'empty';
});
/**
* 将设备状态枚举转为当前语言的展示文案。
* @param value - 设备状态枚举。
* @returns 本地化状态文案。
*/
const formatDeviceStatus = (value: string): string => {
const key = deviceStatusLabelKey(value);
return key ? t(key) : value || '-';
};
const infoCells = computed(() => {
if (!props.device) return [];
return [
{ label: t('maintenance.ledger.fields.modelSpec'), value: props.device.modelSpec, icon: BriefcaseBusiness },
{ label: t('maintenance.record.deviceSnapshot.position'), value: props.device.installLocation, icon: MapPin },
{ label: t('maintenance.record.deviceSnapshot.department'), value: props.device.department, icon: Building2 },
{ label: t('maintenance.record.deviceSnapshot.responsibleUser'), value: props.device.responsibleUser, icon: UserRound },
];
});
</script>
<template>
<div v-if="displayState === 'loading'" class="rounded-xl border border-sky-100 bg-gradient-to-r from-sky-50/90 to-white p-4 shadow-sm">
<div class="animate-pulse space-y-3">
<div class="flex items-center justify-between gap-3">
<div class="h-4 w-28 rounded bg-sky-100" />
<div class="h-6 w-14 rounded-full bg-sky-100" />
</div>
<div class="h-6 w-40 rounded bg-sky-100" />
<div class="h-4 w-28 rounded bg-sky-50" />
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<div v-for="index in 4" :key="index" class="h-14 rounded-lg bg-white/80 ring-1 ring-sky-100" />
</div>
</div>
<p class="mt-3 text-xs text-secondary">{{ t('maintenance.record.deviceSnapshot.loading') }}</p>
</div>
<div
v-else-if="displayState === 'matched' && device"
class="rounded-xl border border-sky-100 border-l-4 border-l-brand-500 bg-gradient-to-r from-sky-50/90 to-white p-4 shadow-sm"
>
<div class="flex flex-wrap items-center gap-2">
<span class="text-xs font-semibold text-sky-800">{{ t('maintenance.record.deviceSnapshot.title') }}</span>
<span class="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700">
<BadgeCheck class="h-3.5 w-3.5" />
{{ t('maintenance.record.deviceSnapshot.matched') }}
</span>
</div>
<div class="mt-3 flex flex-wrap items-start justify-between gap-3">
<div class="min-w-0">
<div class="text-lg font-semibold text-primary">{{ device.deviceName || '-' }}</div>
<div class="mt-1 font-mono text-sm text-secondary">{{ device.deviceCode }}</div>
</div>
<span
class="inline-flex shrink-0 items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="deviceStatusBadgeClass(device.deviceStatus)"
>
{{ formatDeviceStatus(device.deviceStatus) }}
</span>
</div>
<div class="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<div
v-for="cell in infoCells"
:key="cell.label"
class="rounded-lg bg-white/85 px-3 py-2 ring-1 ring-sky-100"
>
<div class="flex items-start gap-2">
<component :is="cell.icon" class="mt-0.5 h-4 w-4 shrink-0 text-brand-600" />
<div class="min-w-0">
<div class="text-[11px] text-secondary">{{ cell.label }}</div>
<div class="mt-0.5 truncate text-xs font-medium text-primary" :title="cell.value || '-'">
{{ cell.value || '-' }}
</div>
</div>
</div>
</div>
</div>
</div>
<div
v-else-if="displayState === 'notFound'"
class="rounded-xl border border-dashed border-amber-300 bg-amber-50/60 px-4 py-3 text-sm text-amber-900"
>
{{ t('maintenance.record.deviceSnapshot.notFound') }}
</div>
<div
v-else
class="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-4 py-3 text-sm text-secondary"
>
{{ t('maintenance.record.deviceSnapshot.empty') }}
</div>
</template>
@@ -1,15 +1,16 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* features/maintenance/components/MaintenanceRecordManagerPanel.vue
* 用途:设备维保助手右侧固定面板中的维修记录管理页,覆盖查询、新增、编辑和删除。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、PaginationBar、useMessage。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、MaintenanceDeviceSnapshotCard、repair-status-display.utils、PaginationBar、useMessage。
* 逻辑:列表 Tab 按设备编号/名称和维修状态筛选;配置 Tab 复用同一表单新增或修改记录。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import MaintenanceDeviceSnapshotCard from '@/features/maintenance/components/MaintenanceDeviceSnapshotCard.vue';
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
import {
createMaintenanceRecord,
@@ -24,12 +25,29 @@ import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.type
import type {
MaintenanceRecord,
MaintenanceRecordImportResult,
MaintenanceRecordListStatus,
MaintenanceRecordPayload,
MaintenanceRepairStatus,
} from '@/features/maintenance/types/record.types';
import { repairStatusBadgeClass } from '@/features/maintenance/utils/repair-status-display.utils';
import {
DEFAULT_MAINTENANCE_RECORD_TIME_RANGE,
resolveMaintenanceRecordReportDateRange,
type MaintenanceRecordTimeRange,
} from '@/features/maintenance/utils/record-list-filter.utils';
type TabName = 'list' | 'form';
interface MaintenanceRecordPanelCommand {
mode: 'list' | 'create';
device?: MaintenanceDevice | null;
nonce?: number;
}
const props = defineProps<{
editRecord?: MaintenanceRecord | null;
command?: MaintenanceRecordPanelCommand | null;
}>();
const msg = useMessage();
const { t } = useI18n();
const activeTab = ref<TabName>('list');
@@ -46,7 +64,8 @@ const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const keyword = ref('');
const status = ref('');
const status = ref<MaintenanceRecordListStatus>('active');
const timeRange = ref<MaintenanceRecordTimeRange>(DEFAULT_MAINTENANCE_RECORD_TIME_RANGE);
const editingId = ref<number | null>(null);
const importResult = ref<MaintenanceRecordImportResult | null>(null);
const deleteDialogOpen = ref(false);
@@ -71,14 +90,25 @@ const form = reactive<MaintenanceRecordPayload>({
sourceOrderNo: '',
});
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
const statusOptions: Array<{ value: MaintenanceRecordListStatus; label: string }> = [
{ value: '', label: 'maintenance.record.status.all' },
{ value: 'active', label: 'maintenance.record.status.active' },
{ value: 'pending', label: 'maintenance.record.status.pending' },
{ value: 'processing', label: 'maintenance.record.status.processing' },
{ value: 'done', label: 'maintenance.record.status.done' },
{ value: 'cancelled', label: 'maintenance.record.status.cancelled' },
];
const timeRangeOptions: Array<{ value: MaintenanceRecordTimeRange; label: string }> = [
{ value: '3m', label: 'maintenance.record.filters.timeRange3m' },
{ value: '1y', label: 'maintenance.record.filters.timeRange1y' },
{ value: 'all', label: 'maintenance.record.filters.timeRangeAll' },
];
const isDefaultScopedFilter = computed(
() => status.value === 'active' && timeRange.value === '1y' && !keyword.value.trim(),
);
const formTitle = computed(() => t(editingId.value ? 'maintenance.record.formTitle.edit' : 'maintenance.record.formTitle.create'));
const deleteConfirmMessage = computed(() =>
pendingDeleteRecord.value
@@ -118,17 +148,24 @@ const buildPayload = (): MaintenanceRecordPayload => ({
});
/**
* 查询维修记录列表,仅按设备编号/设备名称和状态筛选。
* 组装当前列表筛选参数,供查询与导出共用。
* @returns 维修记录列表 API 入参。
*/
const buildListQueryParams = () => ({
keyword: keyword.value.trim(),
status: status.value,
...resolveMaintenanceRecordReportDateRange(timeRange.value),
page: page.value,
pageSize: pageSize.value,
});
/**
* 查询维修记录列表,默认聚焦近一年内未完成记录。
*/
const loadRecords = async (): Promise<void> => {
loading.value = true;
try {
const result = await listMaintenanceRecords({
keyword: keyword.value.trim(),
status: status.value,
page: page.value,
pageSize: pageSize.value,
});
const result = await listMaintenanceRecords(buildListQueryParams());
records.value = result.items;
total.value = result.total;
} catch (error: any) {
@@ -147,6 +184,7 @@ const exportRecords = async (): Promise<void> => {
const blob = await exportMaintenanceRecords({
keyword: keyword.value.trim(),
status: status.value,
...resolveMaintenanceRecordReportDateRange(timeRange.value),
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -237,7 +275,7 @@ const loadDeviceSnapshot = async (): Promise<void> => {
deviceLoading.value = true;
try {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || result.items[0] || null;
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
} finally {
@@ -245,6 +283,31 @@ const loadDeviceSnapshot = async (): Promise<void> => {
}
};
/**
* 保存维修记录前精确校验设备编号,避免把记录挂到不存在的设备上。
* @returns 台账中是否存在当前设备编号。
*/
const ensureDeviceExists = async (): Promise<boolean> => {
const code = form.deviceCode.trim();
if (!code) return false;
if (matchedDevice.value?.deviceCode === code) return true;
deviceLoading.value = true;
try {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
if (!matchedDevice.value) {
msg.warning(t('maintenance.record.messages.deviceNotFound'));
return false;
}
return true;
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
return false;
} finally {
deviceLoading.value = false;
}
};
/**
* 重置表单并进入新增模式。
*/
@@ -270,6 +333,49 @@ const startCreate = (): void => {
activeTab.value = 'form';
};
/**
* 从会话结果里的设备卡片进入新增时,预填设备编号并复用设备快照,减少管理员重复录入。
* @param device - 当前会话结果命中的设备。
*/
const startCreateForDevice = (device: MaintenanceDevice): void => {
startCreate();
form.deviceCode = device.deviceCode || '';
matchedDevice.value = device;
};
/**
* 从会话结果里的设备卡片进入历史时,按设备编号筛选维修记录列表。
* @param device - 当前会话结果命中的设备。
*/
const showHistoryForDevice = async (device: MaintenanceDevice): Promise<void> => {
keyword.value = device.deviceCode || '';
status.value = '';
timeRange.value = 'all';
page.value = 1;
activeTab.value = 'list';
await loadRecords();
};
/**
* 切换报修日期快捷范围并刷新列表。
* @param range - 近 3 个月 / 近 1 年 / 全部时间。
*/
const applyTimeRange = async (range: MaintenanceRecordTimeRange): Promise<void> => {
timeRange.value = range;
page.value = 1;
await loadRecords();
};
/**
* 一键查看全部历史记录,取消默认的未完成与时间限制。
*/
const viewAllHistory = async (): Promise<void> => {
status.value = '';
timeRange.value = 'all';
page.value = 1;
await loadRecords();
};
/**
* 将选中的维修记录带入表单并进入编辑模式。
* @param record - 列表中选中的维修记录。
@@ -314,6 +420,9 @@ const saveRecord = async (): Promise<void> => {
msg.warning(t('maintenance.record.messages.required'));
return;
}
if (!await ensureDeviceExists()) {
return;
}
saving.value = true;
try {
if (editingId.value) {
@@ -366,6 +475,27 @@ const cancelDeleteDialog = (): void => {
};
onMounted(loadRecords);
watch(
() => props.editRecord,
(record) => {
if (record) startEdit(record);
},
{ immediate: true },
);
watch(
() => props.command,
async (command) => {
if (!command?.device) return;
if (command.mode === 'create') {
startCreateForDevice(command.device);
return;
}
await showHistoryForDevice(command.device);
},
{ immediate: true },
);
</script>
<template>
@@ -396,6 +526,10 @@ onMounted(loadRecords);
</div>
<div v-if="activeTab === 'list'" class="flex min-h-0 flex-1 flex-col gap-4">
<div class="rounded-xl border border-brand-100 bg-brand-50/70 px-3 py-2 text-sm text-brand-900">
{{ t('maintenance.record.filters.defaultHint') }}
</div>
<div class="flex flex-wrap gap-3">
<input
v-model="keyword"
@@ -410,6 +544,20 @@ onMounted(loadRecords);
</select>
</div>
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm text-secondary">{{ t('maintenance.record.filters.timeRangeLabel') }}</span>
<button
v-for="item in timeRangeOptions"
:key="item.value"
type="button"
class="admin-report-page-btn"
:class="{ 'admin-report-page-btn--active': timeRange === item.value }"
@click="applyTimeRange(item.value)"
>
{{ t(item.label) }}
</button>
</div>
<div class="flex flex-wrap gap-2">
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="page = 1; loadRecords()">
{{ t('maintenance.record.actions.search') }}
@@ -439,34 +587,75 @@ onMounted(loadRecords);
</div>
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
<table class="w-full table-fixed text-left text-sm">
<thead class="bg-muted/50 text-secondary">
<table class="w-full min-w-[1040px] table-fixed border-separate border-spacing-0 text-left text-sm">
<colgroup>
<col style="width: 140px" />
<col style="width: 150px" />
<col />
<col style="width: 120px" />
<col style="width: 120px" />
<col style="width: 110px" />
<col style="width: 110px" />
<col style="width: 150px" />
</colgroup>
<thead class="bg-surface-soft text-secondary">
<tr>
<th class="w-[24%] px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="w-[22%] px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.faultDescription') }}</th>
<th class="w-[14%] px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="w-[18%] px-3 py-2 text-right">{{ t('maintenance.record.table.operation') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairDate') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairer') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairCost') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="admin-table-sticky-right-head px-3 py-2 text-center">
{{ t('maintenance.record.table.operation') }}
</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
<td colspan="8" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
</tr>
<tr v-else-if="!records.length">
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
<td colspan="8" class="px-3 py-8 text-center text-secondary">
<div>{{ t(isDefaultScopedFilter ? 'maintenance.record.table.emptyActive' : 'maintenance.record.table.empty') }}</div>
<button
v-if="isDefaultScopedFilter"
type="button"
class="admin-report-page-btn admin-report-page-btn--active mt-3"
@click="viewAllHistory"
>
{{ t('maintenance.record.actions.viewAllHistory') }}
</button>
</td>
</tr>
<tr v-for="record in records" v-else :key="record.id" class="border-t border-default">
<td class="truncate px-3 py-2 font-semibold" :title="record.deviceCode">{{ record.deviceCode }}</td>
<td class="truncate px-3 py-2" :title="record.deviceName || '-'">{{ record.deviceName || '-' }}</td>
<td class="truncate px-3 py-2" :title="record.faultDescription">{{ record.faultDescription }}</td>
<td class="px-3 py-2">{{ formatStatus(record.repairStatus) }}</td>
<td class="px-3 py-2">
<div class="flex justify-end gap-2">
<button type="button" class="admin-report-page-btn" @click="startEdit(record)">{{ t('maintenance.record.actions.edit') }}</button>
<tr v-for="record in records" v-else :key="record.id">
<td class="border-t border-default px-3 py-2 font-semibold" :title="record.deviceCode">{{ record.deviceCode }}</td>
<td class="truncate border-t border-default px-3 py-2" :title="record.deviceName || '-'">{{ record.deviceName || '-' }}</td>
<td class="truncate border-t border-default px-3 py-2" :title="record.faultDescription">{{ record.faultDescription }}</td>
<td class="whitespace-nowrap border-t border-default px-3 py-2">{{ record.repairDate || '-' }}</td>
<td class="truncate border-t border-default px-3 py-2" :title="record.repairer || '-'">{{ record.repairer || '-' }}</td>
<td class="truncate border-t border-default px-3 py-2" :title="record.repairCost || '-'">{{ record.repairCost || '-' }}</td>
<td class="border-t border-default px-3 py-2">
<span
class="inline-flex min-w-14 items-center justify-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="repairStatusBadgeClass(record.repairStatus)"
>
{{ formatStatus(record.repairStatus) }}
</span>
</td>
<td class="admin-table-sticky-right-cell border-t border-default px-3 py-2">
<div class="relative z-[1] flex justify-center gap-2">
<button
type="button"
class="admin-report-page-btn"
class="admin-report-page-btn admin-report-page-btn--edit"
@click="startEdit(record)"
>
{{ t('maintenance.record.actions.edit') }}
</button>
<button
type="button"
class="admin-report-page-btn admin-report-page-btn--danger"
:disabled="deletingId === record.id"
@click="openDeleteDialog(record)"
>
@@ -509,6 +698,17 @@ onMounted(loadRecords);
{{ t('maintenance.record.fields.reportDate') }} *
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
</label>
</div>
<div class="mt-3">
<MaintenanceDeviceSnapshotCard
:device="matchedDevice"
:loading="deviceLoading"
:device-code="form.deviceCode"
/>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairCategory') }}
<input v-model="form.repairCategory" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairCategory')" />
@@ -524,16 +724,6 @@ onMounted(loadRecords);
</label>
</div>
<div class="mt-3 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm">
<div v-if="deviceLoading" class="text-secondary">{{ t('maintenance.record.deviceSnapshot.loading') }}</div>
<div v-else-if="matchedDevice" class="grid gap-1 text-secondary">
<div class="font-semibold text-primary">{{ matchedDevice.deviceName }}({{ matchedDevice.deviceCode }})</div>
<div>{{ t('maintenance.record.deviceSnapshot.position') }}:{{ matchedDevice.installLocation || '-' }} | {{ t('maintenance.record.deviceSnapshot.department') }}:{{ matchedDevice.department || '-' }}</div>
<div>{{ t('maintenance.record.deviceSnapshot.responsibleUser') }}:{{ matchedDevice.responsibleUser || '-' }} | {{ t('maintenance.record.deviceSnapshot.status') }}:{{ matchedDevice.deviceStatus }}</div>
</div>
<div v-else class="text-secondary">{{ t('maintenance.record.deviceSnapshot.empty') }}</div>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
{{ t('maintenance.record.fields.faultDescription') }} *
@@ -2,11 +2,12 @@
/**
* features/maintenance/components/MaintenanceRecordPanel.vue
* 用途:设备维保助手右侧固定面板中的“新增维修记录”页面。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、useMessage。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、MaintenanceDeviceSnapshotCard、useMessage。
* 逻辑:管理员通过按钮进入固定面板后填写维修记录;设备编号失焦时查询台账快照,保存后刷新最近记录用于确认。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { useMessage } from '@/shared/composables/useMessage';
import MaintenanceDeviceSnapshotCard from '@/features/maintenance/components/MaintenanceDeviceSnapshotCard.vue';
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
import {
createMaintenanceRecord,
@@ -100,7 +101,7 @@ const loadDeviceSnapshot = async (): Promise<void> => {
deviceLoading.value = true;
try {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || result.items[0] || null;
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
} catch (error: any) {
msg.error(error?.message || '查询设备台账失败');
} finally {
@@ -108,6 +109,30 @@ const loadDeviceSnapshot = async (): Promise<void> => {
}
};
/**
* 保存前精确校验设备编号必须存在于台账,避免产生无设备归属的维修记录。
*/
const ensureDeviceExists = async (): Promise<boolean> => {
const code = form.deviceCode.trim();
if (!code) return false;
if (matchedDevice.value?.deviceCode === code) return true;
deviceLoading.value = true;
try {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
if (!matchedDevice.value) {
msg.warning('设备不存在,不能新增维修记录');
return false;
}
return true;
} catch (error: any) {
msg.error(error?.message || '鏌ヨ璁惧鍙拌处澶辫触');
return false;
} finally {
deviceLoading.value = false;
}
};
/**
* 查询最近维修记录,作为保存后的确认列表和轻量筛选入口。
*/
@@ -160,6 +185,9 @@ const saveRecord = async (): Promise<void> => {
msg.warning('设备编号、报修日期和故障描述不能为空');
return;
}
if (!await ensureDeviceExists()) {
return;
}
saving.value = true;
try {
await createMaintenanceRecord(payload);
@@ -199,6 +227,17 @@ onMounted(loadRecentRecords);
报修日期 *
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
</label>
</div>
<div class="mt-3">
<MaintenanceDeviceSnapshotCard
:device="matchedDevice"
:loading="deviceLoading"
:device-code="form.deviceCode"
/>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
维修类别
<input v-model="form.repairCategory" class="admin-table-filter-input" placeholder="日常维修 / 保养 / 点检" />
@@ -214,16 +253,6 @@ onMounted(loadRecentRecords);
</label>
</div>
<div class="mt-3 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm">
<div v-if="deviceLoading" class="text-secondary">正在查询设备台账...</div>
<div v-else-if="matchedDevice" class="grid gap-1 text-secondary">
<div class="font-semibold text-primary">{{ matchedDevice.deviceName }}({{ matchedDevice.deviceCode }})</div>
<div>位置:{{ matchedDevice.installLocation || '-' }} | 部门:{{ matchedDevice.department || '-' }}</div>
<div>负责人:{{ matchedDevice.responsibleUser || '-' }} | 状态:{{ matchedDevice.deviceStatus }}</div>
</div>
<div v-else class="text-secondary">输入设备编号后可自动匹配设备台账快照。</div>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
故障描述 *
@@ -7,6 +7,9 @@
export type MaintenanceRepairStatus = 'pending' | 'processing' | 'done' | 'cancelled';
/** 列表筛选状态:active 表示待维修 + 维修中。 */
export type MaintenanceRecordListStatus = MaintenanceRepairStatus | 'active' | '';
export interface MaintenanceRecord {
id: number;
deviceId?: number | null;
@@ -0,0 +1,33 @@
/**
* features/maintenance/utils/device-status-display.utils.ts
* 用途:设备台账状态在列表、快照卡片中的标签配色映射。
* 依赖:MaintenanceDeviceStatus 类型。
* 逻辑:LedgerConfigPanel、MaintenanceDeviceSnapshotCard 等组件统一引用,保证设备状态色一致。
*/
import type { MaintenanceDeviceStatus } from '@/features/maintenance/types/ledger.types';
/**
* 根据设备状态返回 Tailwind 标签配色,帮助用户快速区分在用、停用与报废设备。
* @param value - 设备状态枚举值。
* @returns Tailwind class 字符串(border / background / text)。
*/
export function deviceStatusBadgeClass(value: MaintenanceDeviceStatus | string): string {
if (value === 'in_use') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
if (value === 'disabled') return 'border-slate-200 bg-slate-100 text-slate-600';
if (value === 'scrapped') return 'border-rose-200 bg-rose-50 text-rose-700';
if (value === 'sold') return 'border-sky-200 bg-sky-50 text-sky-700';
return 'border-slate-200 bg-slate-50 text-slate-600';
}
/**
* 返回设备状态对应的 i18n 文案 key,供组件内 t() 翻译。
* @param value - 设备状态枚举值。
* @returns maintenance.ledger.status.* 的 key 路径。
*/
export function deviceStatusLabelKey(value: MaintenanceDeviceStatus | string): string {
if (value === 'in_use') return 'maintenance.ledger.status.inUse';
if (value === 'disabled') return 'maintenance.ledger.status.disabled';
if (value === 'scrapped') return 'maintenance.ledger.status.scrapped';
if (value === 'sold') return 'maintenance.ledger.status.sold';
return '';
}
@@ -0,0 +1,37 @@
/**
* features/maintenance/utils/maintenance-panel-layout.utils.ts
* 用途:设备维保助手右侧管理面板与会话维修记录明细面板的统一宽度约束。
* 依赖:无运行时依赖。
* 逻辑:ChatViewContent 管理面板与 MaintenanceDeviceResultCard 明细抽屉共用同一组默认值。
*/
export const MAINTENANCE_PANEL_MIN_WIDTH = 520;
export const MAINTENANCE_PANEL_DEFAULT_WIDTH = 760;
export const MAINTENANCE_PANEL_MAX_WIDTH_RATIO = 0.82;
/**
* 生成维保右侧面板宽度样式,默认与管理面板初始宽度一致。
* @param width - 当前面板宽度,默认 760px。
* @returns 可直接绑定到 style 的宽度对象。
*/
export function buildMaintenancePanelWidthStyle(width = MAINTENANCE_PANEL_DEFAULT_WIDTH): Record<string, string> {
return {
width: `${width}px`,
minWidth: `${MAINTENANCE_PANEL_MIN_WIDTH}px`,
maxWidth: `${Math.round(MAINTENANCE_PANEL_MAX_WIDTH_RATIO * 100)}vw`,
};
}
/**
* 计算拖拽调整后的面板宽度,保持与管理面板相同上下限。
* @param nextWidth - 拖拽后的目标宽度。
* @param viewportWidth - 当前视口宽度。
* @returns 合法宽度像素值。
*/
export function clampMaintenancePanelWidth(nextWidth: number, viewportWidth: number): number {
const maxWidth = Math.max(
MAINTENANCE_PANEL_MIN_WIDTH,
Math.floor(viewportWidth * MAINTENANCE_PANEL_MAX_WIDTH_RATIO),
);
return Math.min(maxWidth, Math.max(MAINTENANCE_PANEL_MIN_WIDTH, nextWidth));
}
@@ -0,0 +1,44 @@
/**
* features/maintenance/utils/record-list-filter.utils.ts
* 用途:维修记录管理列表的默认筛选与时间范围计算。
* 依赖:无运行时依赖。
* 逻辑:MaintenanceRecordManagerPanel 进入时默认「未完成 + 近一年」;本工具负责把 UI 选项转为 API 报修日期参数。
*/
export type MaintenanceRecordTimeRange = '3m' | '1y' | 'all';
export const DEFAULT_MAINTENANCE_RECORD_TIME_RANGE: MaintenanceRecordTimeRange = '1y';
export interface MaintenanceRecordReportDateRange {
reportDateFrom?: string;
reportDateTo?: string;
}
/**
* 将时间快捷选项转为报修日期闭区间参数。
* 核心逻辑:3m/1y 以 referenceDate 为结束日倒推;all 不传日期参数表示不限时间。
* @param range - 近 3 个月 / 近 1 年 / 全部时间。
* @param referenceDate - 计算基准日期,默认当天。
* @returns API 可用的 reportDateFrom/reportDateTo。
*/
export function resolveMaintenanceRecordReportDateRange(
range: MaintenanceRecordTimeRange,
referenceDate: Date = new Date(),
): MaintenanceRecordReportDateRange {
if (range === 'all') {
return {};
}
const reportDateTo = referenceDate.toISOString().slice(0, 10);
const fromDate = new Date(referenceDate);
if (range === '3m') {
fromDate.setMonth(fromDate.getMonth() - 3);
} else {
fromDate.setFullYear(fromDate.getFullYear() - 1);
}
return {
reportDateFrom: fromDate.toISOString().slice(0, 10),
reportDateTo,
};
}
@@ -0,0 +1,20 @@
/**
* features/maintenance/utils/repair-status-display.utils.ts
* 用途:维修记录状态在列表、卡片中的标签配色映射。
* 依赖:MaintenanceRepairStatus 类型。
* 逻辑:MaintenanceRecordManagerPanel、MaintenanceDeviceResultCard 等组件统一引用,保证状态色一致。
*/
import type { MaintenanceRepairStatus } from '@/features/maintenance/types/record.types';
/**
* 根据维修状态返回 Tailwind 标签配色,帮助用户快速区分待办、进行中与已完成。
* @param value - 维修状态枚举值。
* @returns Tailwind class 字符串(border / background / text)。
*/
export function repairStatusBadgeClass(value: MaintenanceRepairStatus | string): string {
if (value === 'pending') return 'border-amber-200 bg-amber-50 text-amber-700';
if (value === 'processing') return 'border-sky-200 bg-sky-50 text-sky-700';
if (value === 'done') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
if (value === 'cancelled') return 'border-slate-200 bg-slate-100 text-slate-600';
return 'border-slate-200 bg-slate-50 text-slate-600';
}