Files
zkxw/web-admin/src/views/quality-inspection/qc-material/QcMaterialStockCheckTab.vue
T
2026-06-16 07:38:27 +08:00

2214 lines
73 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!-- 质检物料库 · 库存盘点 Tab -->
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<div class="qc-material-stock-check-tab">
<div class="filter-block">
<el-form :model="searchForm" class="filter-form" @submit.prevent>
<div class="filter-grid">
<el-form-item label="关键词">
<el-input v-model="searchForm.keyword" placeholder="盘点标题" clearable />
</el-form-item>
<el-form-item label="状态">
<el-select v-model="searchForm.status" placeholder="全部" clearable>
<el-option label="进行中" value="draft" />
<el-option label="已完成" value="completed" />
<el-option label="已作废" value="cancelled" />
</el-select>
</el-form-item>
<el-form-item label="盘点时间">
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="YYYY-MM-DD"
clearable
style="width: 100%"
/>
</el-form-item>
</div>
<div class="filter-actions-row">
<span class="filter-hint">按标题、状态与盘点时间查询库存盘点单。</span>
<div class="filter-actions-end">
<el-button class="btn-ghost" @click="handleReset">
<el-icon><RefreshLeft /></el-icon>重置
</el-button>
<el-button class="btn-main" type="primary" @click="handleSearch">
<el-icon><Search /></el-icon>搜索
</el-button>
</div>
</div>
</el-form>
</div>
<div class="list-toolbar">
<div class="list-toolbar-row">
<div class="list-toolbar-selected">
已选 <span class="sel-num">{{ selectedRows.length }}</span> 项
</div>
<el-button class="btn-main" type="primary" @click="openCreateDialog">
<el-icon><Plus /></el-icon>新建盘点
</el-button>
</div>
</div>
<div class="list-body list-wrap">
<el-table
class="list-table"
:data="tableData"
v-loading="loading"
stripe
row-key="id"
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
min-width="68"
align="center"
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column prop="title" label="盘点标题" min-width="180" align="center" header-align="center" />
<el-table-column prop="checkTime" label="盘点时间" min-width="170" align="center" header-align="center" />
<el-table-column label="状态" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag :type="statusTagType(row.status)" size="small">{{ row.statusLabel }}</el-tag>
</template>
</el-table-column>
<el-table-column label="系统库存行" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ row.batchLineCount ?? 0 }}</template>
</el-table-column>
<el-table-column label="未用完登记" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ row.unusedLineCount ?? 0 }}</template>
</el-table-column>
<el-table-column label="创建人" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ row.createByName || row.createBy || '—' }}</template>
</el-table-column>
<el-table-column prop="completeTime" label="完成时间" min-width="170" align="center" header-align="center">
<template #default="{ row }">{{ row.completeTime || '—' }}</template>
</el-table-column>
<el-table-column
label="操作"
min-width="440"
fixed="right"
align="center"
header-align="center"
>
<template #default="{ row }">
<div class="table-op-btns">
<el-button class="btn-op-item" @click="handleView(row)">
<el-icon><View /></el-icon>查看
</el-button>
<el-button
class="btn-op-item"
:loading="exportLoadingId === row.id"
@click="handleExport(row)"
>
<el-icon><Download /></el-icon>导出
</el-button>
<el-button
v-if="row.status === 'draft'"
class="btn-op-item"
@click="openUnusedDialog(row)"
>
<el-icon><Edit /></el-icon>登记未用完
</el-button>
<el-button
v-if="row.status === 'draft'"
class="btn-op-item"
type="primary"
@click="handleComplete(row)"
>
<el-icon><Check /></el-icon>完成盘点
</el-button>
<el-button
v-if="row.status === 'draft'"
class="btn-op-item"
type="danger"
link
@click="handleCancel(row)"
>
<el-icon><Close /></el-icon>作废
</el-button>
</div>
</template>
</el-table-column>
</el-table>
<div class="pagination list-pager-bar">
<el-pagination
:current-page="pagination.page"
:page-size="pagination.pageSize"
:total="pagination.total"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next"
@size-change="(val) => ((pagination.page = 1), (pagination.pageSize = val), loadData())"
@current-change="(val) => ((pagination.page = val), loadData())"
/>
</div>
</div>
<!-- 新建盘点 -->
<el-dialog
v-model="createVisible"
title="新建盘点"
width="560px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<el-form ref="createFormRef" :model="createForm" :rules="createRules" label-position="top">
<el-form-item label="盘点标题" prop="title">
<el-input v-model="createForm.title" placeholder="如:2026年6月底盘存" />
</el-form-item>
<el-form-item label="盘点时间" prop="checkTime">
<el-date-picker
v-model="createForm.checkTime"
type="datetime"
placeholder="选择盘点时间"
value-format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="备注">
<el-input v-model="createForm.remark" type="textarea" :rows="2" placeholder="可选" />
</el-form-item>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="createVisible = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="createLoading" @click="handleCreate">
<el-icon><Check /></el-icon>创建
</el-button>
</template>
</el-dialog>
<!-- 登记未用完 -->
<el-dialog
v-model="unusedVisible"
title="登记未用完物料"
width="1120px"
class="dialog-form-layout unused-split-dialog"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<div class="unused-split-layout">
<aside class="unused-list-panel">
<div class="unused-list-panel__head">
<span class="unused-list-panel__title">领用记录</span>
<span class="stat-pill">共 {{ requisitionTotalCount }} · 已登记 {{ requisitionRegisteredCount }}</span>
</div>
<div class="unused-list-search-wrap">
<el-input
v-model="requisitionKeyword"
class="unused-list-search"
placeholder="搜索物料/批号/入库编号/领用人"
clearable
@input="debouncedLoadRequisitions"
/>
</div>
<div class="unused-line-list" :class="{ 'is-list-loading': requisitionLoading }">
<div
v-for="req in requisitionList"
:key="req.id"
class="unused-line-item"
:class="{ 'is-active': activeKey === `req:${req.id}` }"
@mousedown.left.prevent="onRequisitionBodyPointerDown(req, $event)"
@click="onRequisitionBodyClick(req, $event)"
>
<div class="unused-line-item__top">
<span class="unused-line-item__name">{{ req.materialName }}</span>
<span v-if="isRequisitionEntryRegistered(req.id)" class="unused-reg-tag">已登记</span>
</div>
<div class="unused-line-item__meta">
<span>{{ req.requisitionQty }}{{ req.unit || '' }}</span>
<span>{{ req.batchNo || '—' }}</span>
<span>{{ req.receiverName || req.receiver || '—' }}</span>
</div>
<div class="unused-line-item__actions">
<button
type="button"
class="unused-mark-btn"
:disabled="markFullyUsedLoadingId === req.id"
@mousedown.stop
@click.stop="onMarkFullyUsedClick(req.id, $event)"
>
<el-icon><CircleCheck /></el-icon>标记已使用完
</button>
</div>
</div>
<div v-if="!requisitionLoading && !requisitionList.length" class="unused-empty-hint">
暂无待登记领用记录
</div>
</div>
<div class="unused-manual-section">
<div class="unused-list-panel__head">
<span class="unused-list-panel__title">手工登记</span>
<span class="stat-pill">{{ manualLines.length }} 项</span>
</div>
<el-button class="btn-ghost btn-sm-block" @click="startManualEntry">
<el-icon><Plus /></el-icon>批次检索登记
</el-button>
<div v-if="manualLines.length" class="unused-manual-list">
<div
v-for="(line, idx) in manualLines"
:key="line._key || idx"
class="unused-line-item unused-line-item--manual"
:class="{ 'is-active': activeKey === `manual:${line._key}` }"
role="button"
tabindex="0"
@click="selectManualLine(line)"
@keydown.enter.prevent="selectManualLine(line)"
@keydown.space.prevent="selectManualLine(line)"
>
<div class="unused-line-item__top">
<span class="unused-line-item__name">{{ line.materialName || '未选批次' }}</span>
<el-tag type="warning" size="small">手工</el-tag>
</div>
<div class="unused-line-item__meta">
<span>{{ line.unusedQty }}{{ line.unit || '' }}</span>
<span>{{ line.batchNo || line.stockInNo || '—' }}</span>
</div>
<div class="unused-line-item__actions" @click.stop>
<el-button link type="danger" size="small" @click="removeManualLine(line._key)">
<el-icon><Delete /></el-icon>
</el-button>
</div>
</div>
</div>
</div>
</aside>
<section class="unused-detail-panel">
<div
v-if="editMode === 'requisition' && activeRequisition"
class="unused-detail-body"
>
<div class="unused-detail-head">
<div>
<h3 class="unused-detail-title">{{ activeRequisition.materialName }}</h3>
<p class="unused-detail-sub">
{{ activeRequisition.stockInNo || '—' }} · 批号 {{ activeRequisition.batchNo || '—' }} ·
领用 {{ activeRequisition.requisitionQty }}{{ activeRequisition.unit || '' }}
<template v-if="activeRequisition.taskConsumedQty > 0">
· 任务已消耗 {{ activeRequisition.taskConsumedQty }}{{ activeRequisition.unit || '' }}
</template>
</p>
</div>
</div>
<div class="unused-readonly-grid">
<div><span class="ro-label">领用人</span>{{ activeRequisition.receiverName || activeRequisition.receiver || '—' }}</div>
<div><span class="ro-label">领用时间</span>{{ activeRequisition.useTime || '—' }}</div>
<div><span class="ro-label">规格</span>{{ activeRequisition.specModel || '—' }}</div>
<div><span class="ro-label">厂家</span>{{ activeRequisition.manufacturer || '—' }}</div>
<div><span class="ro-label">单价</span>{{ displayMoney(activeRequisition.unitPrice) }}</div>
<div><span class="ro-label">过期日期</span>{{ activeRequisition.expireDate || '—' }}</div>
</div>
<el-form label-position="top" class="unused-edit-form">
<div class="form-grid-2">
<el-form-item label="未用完数量" required>
<el-input
:model-value="formatDraftQty(activeDraft.unusedQty)"
inputmode="decimal"
placeholder="请输入未用完数量"
@update:model-value="onActiveDraftQtyInput"
@focus="dbgQtyInputFocus"
@blur="dbgQtyInputBlur"
/>
</el-form-item>
<el-form-item label="剩余金额(元)">
<el-input
:model-value="displayMoney(calcLineAmount(activeDraft.unitPrice, activeDraft.unusedQty))"
disabled
/>
</el-form-item>
<el-form-item label="持有人">
<el-input v-model="activeDraft.holder" placeholder="默认领用人" />
</el-form-item>
<el-form-item label="备注" class="form-col-span-2">
<el-input v-model="activeDraft.remark" placeholder="可选" />
</el-form-item>
</div>
</el-form>
</div>
<div v-else-if="editMode === 'manual'" :key="manualDetailKey" class="unused-detail-body">
<div class="unused-detail-head">
<div>
<h3 class="unused-detail-title">手工登记</h3>
<p class="unused-detail-sub">检索入库批次带出物料信息,填写未用完数量、持有人与备注。</p>
</div>
</div>
<el-form label-position="top" class="unused-edit-form">
<el-form-item label="批次检索" required>
<el-select
v-model="manualDraft.batchPickId"
filterable
remote
clearable
placeholder="输入入库编号、物料名称、批号检索"
popper-class="batch-out-option-popper"
style="width: 100%"
:loading="batchOptionsLoading"
:remote-method="searchUnusedBatchOptions"
@change="onManualBatchPick"
>
<el-option v-for="opt in batchOptions" :key="opt.id" :label="opt.label" :value="opt.id">
<div class="batch-option-item">
<span class="batch-option-main">{{ opt.stockInNo }} · {{ opt.materialName }}</span>
<span class="batch-option-sub">
批号:{{ opt.batchNo || '—' }} · 剩余 {{ opt.remainingQty }}{{ opt.unit || '' }}
</span>
</div>
</el-option>
</el-select>
</el-form-item>
<div v-if="manualDraft.fromBatch" class="unused-readonly-grid">
<div><span class="ro-label">物料</span>{{ manualDraft.materialName || '—' }}</div>
<div><span class="ro-label">入库编号</span>{{ manualDraft.stockInNo || '—' }}</div>
<div><span class="ro-label">批号</span>{{ manualDraft.batchNo || '—' }}</div>
<div><span class="ro-label">规格</span>{{ manualDraft.specModel || '—' }}</div>
<div><span class="ro-label">厂家</span>{{ manualDraft.manufacturer || '—' }}</div>
<div><span class="ro-label">单价</span>{{ displayMoney(manualDraft.unitPrice) }}</div>
</div>
<div class="form-grid-2">
<el-form-item label="未用完数量" required>
<el-input-number
v-model="manualDraft.unusedQty"
:min="0.01"
:precision="2"
controls-position="right"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="剩余金额(元)">
<el-input
:model-value="displayMoney(calcLineAmount(manualDraft.unitPrice, manualDraft.unusedQty))"
disabled
/>
</el-form-item>
<el-form-item label="持有人">
<el-input v-model="manualDraft.holder" placeholder="可选" />
</el-form-item>
<el-form-item label="备注" class="form-col-span-2">
<el-input v-model="manualDraft.remark" placeholder="可选" />
</el-form-item>
</div>
<div class="unused-manual-actions">
<el-button class="btn-main" type="primary" @click="confirmManualLine">
<el-icon><Check /></el-icon>{{ editingManualKey ? '更新登记' : '加入登记' }}
</el-button>
</div>
</el-form>
</div>
<div v-else class="unused-detail-empty">
请从左侧选择领用记录,或点击「批次检索登记」进行手工登记
</div>
</section>
</div>
<template #footer>
<el-button class="btn-ghost" @click="unusedVisible = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="unusedLoading" @click="handleSaveUnused">
<el-icon><Check /></el-icon>保存
</el-button>
</template>
</el-dialog>
<!-- 查看 -->
<el-dialog
v-model="viewVisible"
:title="viewDetail?.title || '盘点详情'"
width="1400px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
>
<div v-if="viewDetail" class="stock-check-view">
<div class="view-head-grid">
<div><span class="view-label">盘点时间</span>{{ viewDetail.checkTime }}</div>
<div>
<span class="view-label">状态</span>
<el-tag :type="statusTagType(viewDetail.status)" size="small">{{ viewDetail.statusLabel }}</el-tag>
</div>
<div><span class="view-label">创建人</span>{{ viewDetail.createByName || viewDetail.createBy || '—' }}</div>
<div><span class="view-label">完成时间</span>{{ viewDetail.completeTime || '—' }}</div>
<div class="view-head-remark"><span class="view-label">备注</span>{{ viewDetail.remark || '—' }}</div>
</div>
<h3 class="view-section-title">系统库存快照({{ viewDetail.batchLines?.length || 0 }} 行)</h3>
<div class="inner-table-scroll">
<el-table
:data="viewDetail.batchLines || []"
stripe
:fit="false"
table-layout="auto"
class="list-table inner-table"
>
<el-table-column type="index" label="序号" min-width="52" align="center" header-align="center" />
<el-table-column label="入库编号" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.stockInNo) }}</template>
</el-table-column>
<el-table-column label="入库日期" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.stockInDate) }}</template>
</el-table-column>
<el-table-column label="过期日期" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.expireDate) }}</template>
</el-table-column>
<el-table-column label="物料编码" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.materialCode) }}</template>
</el-table-column>
<el-table-column label="物料名称" min-width="130" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.materialName) }}</template>
</el-table-column>
<el-table-column label="规格型号" min-width="100" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.specModel) }}</template>
</el-table-column>
<el-table-column label="单位" min-width="72" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.unit) }}</template>
</el-table-column>
<el-table-column label="货号" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.catalogNo) }}</template>
</el-table-column>
<el-table-column label="批号" min-width="90" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.batchNo) }}</template>
</el-table-column>
<el-table-column label="厂家" min-width="110" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.manufacturer) }}</template>
</el-table-column>
<el-table-column label="单价(元)" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ displayMoney(row.unitPrice) }}</template>
</el-table-column>
<el-table-column label="剩余金额(元)" min-width="120" align="center" header-align="center">
<template #default="{ row }">
{{ displayMoney(row.remainingAmount ?? calcLineAmount(row.unitPrice, row.remainingQty)) }}
</template>
</el-table-column>
<el-table-column label="剩余数量" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.remainingQty) }}</template>
</el-table-column>
</el-table>
</div>
<h3 class="view-section-title">领用未用完登记({{ viewDetail.unusedLines?.length || 0 }} 行)</h3>
<div class="inner-table-scroll">
<el-table
:data="viewDetail.unusedLines || []"
stripe
:fit="false"
table-layout="auto"
class="list-table inner-table"
>
<el-table-column type="index" label="序号" min-width="52" align="center" header-align="center" />
<el-table-column label="入库编号" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.stockInNo) }}</template>
</el-table-column>
<el-table-column label="入库日期" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.stockInDate) }}</template>
</el-table-column>
<el-table-column label="过期日期" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.expireDate) }}</template>
</el-table-column>
<el-table-column label="物料编码" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.materialCode) }}</template>
</el-table-column>
<el-table-column label="物料名称" min-width="130" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.materialName) }}</template>
</el-table-column>
<el-table-column label="规格型号" min-width="100" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.specModel) }}</template>
</el-table-column>
<el-table-column label="单位" min-width="72" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.unit) }}</template>
</el-table-column>
<el-table-column label="货号" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.catalogNo) }}</template>
</el-table-column>
<el-table-column label="批号" min-width="90" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.batchNo) }}</template>
</el-table-column>
<el-table-column label="厂家" min-width="110" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.manufacturer) }}</template>
</el-table-column>
<el-table-column label="单价(元)" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ displayMoney(row.unitPrice) }}</template>
</el-table-column>
<el-table-column label="剩余金额(元)" min-width="120" align="center" header-align="center">
<template #default="{ row }">
{{ displayMoney(row.remainingAmount ?? calcLineAmount(row.unitPrice, row.unusedQty)) }}
</template>
</el-table-column>
<el-table-column label="未用完数量" min-width="110" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.unusedQty) }}</template>
</el-table-column>
<el-table-column label="持有人" min-width="100" align="center" header-align="center">
<template #default="{ row }">{{ displayText(row.holder) }}</template>
</el-table-column>
<el-table-column label="备注" min-width="120" align="center" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ displayText(row.remark) }}</template>
</el-table-column>
</el-table>
</div>
</div>
<template #footer>
<el-button class="btn-ghost" @click="viewVisible = false">
<el-icon><Close /></el-icon>关闭
</el-button>
<el-button
class="btn-ghost"
:loading="exportLoadingId === viewDetail?.id"
:disabled="!viewDetail"
@click="handleExportFromView"
>
<el-icon><Download /></el-icon>导出 Excel
</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
Search,
RefreshLeft,
Plus,
View,
Edit,
Check,
Close,
Delete,
Download,
CircleCheck
} from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { formatMoneyDisplay } from '@/utils/money-format'
import { fetchQcMaterialBatchOptions, type QcMaterialBatchOption } from '@/api/qc-material'
import { fetchMarkQcMaterialUsageFullyUsed } from '@/api/qc-material-usage'
import {
fetchQcMaterialStockCheckList,
fetchCreateQcMaterialStockCheck,
fetchQcMaterialStockCheckDetail,
fetchSaveQcMaterialStockCheckUnusedLines,
fetchCompleteQcMaterialStockCheck,
fetchCancelQcMaterialStockCheck,
fetchQcMaterialStockCheckRequisitions
} from '@/api/qc-material-stock-check'
import type {
QcMaterialStockCheck,
QcMaterialStockCheckDetail,
QcMaterialStockCheckUnusedLine,
QcMaterialStockCheckRequisition
} from '@/api/qc-material-stock-check'
defineOptions({ name: 'QcMaterialStockCheckTab' })
const searchForm = reactive({ keyword: '', status: '' })
const dateRange = ref<[string, string] | null>(null)
const tableData = ref<QcMaterialStockCheck[]>([])
const selectedRows = ref<QcMaterialStockCheck[]>([])
const loading = ref(false)
const pagination = reactive({ page: 1, pageSize: 10, total: 0 })
function handleSelectionChange(rows: QcMaterialStockCheck[]) {
selectedRows.value = rows
}
function statusTagType(status: string) {
if (status === 'completed') return 'success'
if (status === 'cancelled') return 'info'
return 'warning'
}
function formatNowDatetime() {
const d = new Date()
const p = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
}
function displayText(v?: string | number | null) {
if (v == null || v === '') return '—'
return String(v)
}
function displayMoney(v?: number | null) {
if (v == null || Number.isNaN(Number(v))) return '—'
return formatMoneyDisplay(v)
}
function calcLineAmount(unitPrice?: number | null, qty?: number | null) {
const p = Number(unitPrice) || 0
const q = Number(qty) || 0
if (!p || !q) return null
return Math.round(p * q * 100) / 100
}
const batchOptions = ref<QcMaterialBatchOption[]>([])
const batchOptionsLoading = ref(false)
async function searchUnusedBatchOptions(query: string) {
batchOptionsLoading.value = true
try {
batchOptions.value =
(await fetchQcMaterialBatchOptions({
keyword: query?.trim() || undefined,
onlyAvailable: false
})) || []
} catch {
batchOptions.value = []
} finally {
batchOptionsLoading.value = false
}
}
function clearUnusedLineBatchFields(row: QcMaterialStockCheckUnusedLine) {
row.fromBatch = false
row.batchPickId = ''
row.batchId = ''
row.materialCode = ''
row.materialName = ''
row.specModel = ''
row.unit = ''
row.stockInNo = ''
row.stockInDate = ''
row.expireDate = ''
row.catalogNo = ''
row.batchNo = ''
row.manufacturer = ''
row.unitPrice = null
}
function fillUnusedLineFromBatch(row: QcMaterialStockCheckUnusedLine, opt: QcMaterialBatchOption) {
row.fromBatch = true
row.batchPickId = opt.id
row.batchId = opt.id
row.materialCode = opt.materialCode || ''
row.materialName = opt.materialName || ''
row.specModel = opt.specModel || ''
row.unit = opt.unit || ''
row.stockInNo = opt.stockInNo || ''
row.stockInDate = opt.stockInDate || ''
row.expireDate = opt.expireDate || ''
row.catalogNo = opt.catalogNo || ''
row.batchNo = opt.batchNo || ''
row.manufacturer = opt.manufacturer || ''
row.unitPrice = opt.unitPrice ?? null
}
async function loadData() {
loading.value = true
try {
const params: Record<string, any> = {
page: pagination.page,
pageSize: pagination.pageSize
}
if (searchForm.keyword) params.keyword = searchForm.keyword
if (searchForm.status) params.status = searchForm.status
if (dateRange.value?.[0]) {
params.startTime = dateRange.value[0]
params.endTime = dateRange.value[1]
}
const res = await fetchQcMaterialStockCheckList(params)
tableData.value = res.list || []
pagination.total = res.total ?? 0
} finally {
loading.value = false
}
}
function handleSearch() {
pagination.page = 1
loadData()
}
function handleReset() {
searchForm.keyword = ''
searchForm.status = ''
dateRange.value = null
pagination.page = 1
loadData()
}
const createVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref()
const createForm = reactive({ title: '', checkTime: '', remark: '' })
const createRules = {
title: [{ required: true, message: '请输入盘点标题', trigger: 'blur' }],
checkTime: [{ required: true, message: '请选择盘点时间', trigger: 'change' }]
}
function openCreateDialog() {
createForm.title = ''
createForm.checkTime = formatNowDatetime()
createForm.remark = ''
createVisible.value = true
createFormRef.value?.clearValidate?.()
}
async function handleCreate() {
await createFormRef.value?.validate?.()
createLoading.value = true
try {
const res = await fetchCreateQcMaterialStockCheck({
title: createForm.title.trim(),
checkTime: createForm.checkTime,
remark: createForm.remark?.trim() || undefined
})
ElMessage.success(`盘点单创建成功,已快照 ${res.batchLineCount ?? 0} 条系统库存`)
createVisible.value = false
loadData()
} finally {
createLoading.value = false
}
}
type ManualUnusedLine = QcMaterialStockCheckUnusedLine & { _key: string }
const unusedVisible = ref(false)
const unusedLoading = ref(false)
const unusedCheckId = ref('')
const requisitionList = ref<QcMaterialStockCheckRequisition[]>([])
const requisitionLoading = ref(false)
const requisitionKeyword = ref('')
const requisitionDrafts = ref<Record<string, QcMaterialStockCheckUnusedLine>>({})
const manualLines = ref<ManualUnusedLine[]>([])
const editMode = ref<'requisition' | 'manual' | 'none'>('none')
const activeKey = ref('')
const activeRequisition = ref<QcMaterialStockCheckRequisition | null>(null)
const activeDraft = ref<QcMaterialStockCheckUnusedLine>({
materialName: '',
unusedQty: 1,
holder: '',
remark: ''
})
const manualDraft = ref<QcMaterialStockCheckUnusedLine>(newManualLine())
const editingManualKey = ref('')
const markFullyUsedLoadingId = ref('')
const registeredUsageMap = reactive<Record<string, boolean>>({})
const requisitionTotalCount = computed(() => requisitionList.value.length)
const requisitionRegisteredCount = computed(() => {
return requisitionList.value.filter((r) => isRequisitionEntryRegistered(r.id)).length
})
function isRequisitionEntryRegistered(reqId: string) {
if (registeredUsageMap[reqId]) return true
if (
editMode.value === 'requisition' &&
activeRequisition.value?.id === reqId &&
(activeDraft.value.unusedQty ?? 0) > 0
) {
return true
}
return false
}
/** 登记弹窗调试:Console 过滤 [QcUnusedDialog] */
const UNUSED_DIALOG_DEBUG = false
const DBG = '[QcUnusedDialog]'
let dbgSeq = 0
let dbgSession = 0
let dbgLastTs = performance.now()
let dbgLastPointerDownTs = 0
let dbgLongTaskObserver: PerformanceObserver | null = null
function dbgActiveEl() {
const el = document.activeElement as HTMLElement | null
if (!el) return 'none'
return `${el.tagName}.${(el.className || '').toString().slice(0, 40)}`
}
function dbgLog(event: string, payload?: Record<string, unknown>) {
if (!UNUSED_DIALOG_DEBUG) return
dbgSeq += 1
const now = performance.now()
const delta = (now - dbgLastTs).toFixed(1)
dbgLastTs = now
console.log(`${DBG} s${dbgSession} #${dbgSeq} +${delta}ms | ${event}`, payload ?? '')
}
function dbgSnapshot(label: string) {
dbgLog(label, {
unusedVisible: unusedVisible.value,
requisitionLoading: requisitionLoading.value,
editMode: editMode.value,
activeKey: activeKey.value,
activeReqId: activeRequisition.value?.id,
activeReqName: activeRequisition.value?.materialName,
activeDraftQty: activeDraft.value.unusedQty,
activeDraftName: activeDraft.value.materialName,
draftKeys: Object.keys(requisitionDrafts.value),
listCount: requisitionList.value.length,
activeElement: dbgActiveEl()
})
}
function dbgEventTarget(evt: Event) {
const t = evt.target as HTMLElement | null
const c = evt.currentTarget as HTMLElement | null
return {
type: evt.type,
target: t ? `${t.tagName}.${(t.className || '').toString().slice(0, 48)}` : 'null',
currentTarget: c ? `${c.tagName}.${(c.className || '').toString().slice(0, 48)}` : 'null',
activeElement: dbgActiveEl()
}
}
function dbgStartLongTaskObserver() {
if (!UNUSED_DIALOG_DEBUG || dbgLongTaskObserver) return
try {
dbgLongTaskObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
dbgLog('⚠️ LONG TASK (main thread blocked)', {
durationMs: Number(entry.duration.toFixed(1)),
startMs: Number(entry.startTime.toFixed(1))
})
}
})
dbgLongTaskObserver.observe({ type: 'longtask', buffered: true } as PerformanceObserverInit)
dbgLog('longtask observer started')
} catch (err) {
dbgLog('longtask observer unavailable', { err })
}
}
function dbgStopLongTaskObserver() {
if (dbgLongTaskObserver) {
dbgLongTaskObserver.disconnect()
dbgLongTaskObserver = null
dbgLog('longtask observer stopped')
}
}
function dbgSincePointerDown() {
if (!dbgLastPointerDownTs) return 'n/a'
return `${(performance.now() - dbgLastPointerDownTs).toFixed(1)}ms`
}
function onRequisitionBodyPointerDown(req: QcMaterialStockCheckRequisition, evt: MouseEvent) {
const t0 = performance.now()
dbgLastPointerDownTs = t0
dbgLog('▶ CARD pointerdown START', {
reqId: req.id,
reqName: req.materialName,
fromId: activeRequisition.value?.id,
...dbgEventTarget(evt)
})
selectRequisition(req, 'pointerdown')
dbgLog('▶ CARD pointerdown AFTER select sync', {
reqId: req.id,
syncMs: (performance.now() - t0).toFixed(2),
activeReqId: activeRequisition.value?.id,
activeDraftName: activeDraft.value.materialName
})
requestAnimationFrame(() => {
dbgLog('▶ CARD pointerdown rAF#1', {
reqId: req.id,
sincePointerdown: dbgSincePointerDown(),
activeElement: dbgActiveEl()
})
requestAnimationFrame(() => {
dbgLog('▶ CARD pointerdown rAF#2 (paint)', {
reqId: req.id,
sincePointerdown: dbgSincePointerDown()
})
dbgSnapshot('after paint')
})
})
}
function onRequisitionBodyClick(req: QcMaterialStockCheckRequisition, evt: MouseEvent) {
dbgLog('CARD click (info only)', {
reqId: req.id,
sincePointerdown: dbgSincePointerDown(),
...dbgEventTarget(evt)
})
}
function dbgQtyInputFocus() {
dbgLog('qty-input focus', {
activeReqId: activeRequisition.value?.id,
unusedQty: activeDraft.value.unusedQty
})
}
function dbgQtyInputBlur() {
dbgLog('qty-input blur', {
activeReqId: activeRequisition.value?.id,
unusedQty: activeDraft.value.unusedQty,
sincePointerdown: dbgSincePointerDown(),
nextActiveElement: dbgActiveEl()
})
}
const manualDetailKey = computed(
() => `manual-detail-${editingManualKey.value || 'new'}-${manualDraft.value.batchPickId || 'empty'}`
)
function rebuildRegisteredUsageMap() {
for (const key of Object.keys(registeredUsageMap)) {
delete registeredUsageMap[key]
}
for (const [id, draft] of Object.entries(requisitionDrafts.value)) {
if ((draft?.unusedQty ?? 0) > 0) registeredUsageMap[id] = true
}
}
function updateRegisteredUsageMap(usageId: string, unusedQty?: number | null) {
if ((unusedQty ?? 0) > 0) registeredUsageMap[usageId] = true
else delete registeredUsageMap[usageId]
}
function applyActiveDraft(line: QcMaterialStockCheckUnusedLine) {
const t0 = performance.now()
const beforeQty = activeDraft.value.unusedQty
for (const key of Object.keys(activeDraft.value)) {
if (!(key in line)) delete (activeDraft.value as Record<string, unknown>)[key]
}
Object.assign(activeDraft.value, line)
dbgLog('applyActiveDraft', {
usageId: line.usageId,
materialName: line.materialName,
beforeQty,
afterQty: activeDraft.value.unusedQty,
ms: (performance.now() - t0).toFixed(2)
})
}
function onActiveDraftQtyInput(val: string) {
const prev = activeDraft.value.unusedQty
const trimmed = val.trim()
if (!trimmed) {
activeDraft.value.unusedQty = 0
} else {
const num = Number(trimmed)
if (Number.isFinite(num)) activeDraft.value.unusedQty = num
}
dbgLog('qty-input update', { prev, input: val, next: activeDraft.value.unusedQty })
}
function formatDraftQty(qty?: number | null) {
if (qty == null || Number.isNaN(qty)) return ''
return String(qty)
}
let requisitionSearchTimer: ReturnType<typeof setTimeout> | null = null
function newManualLine(): QcMaterialStockCheckUnusedLine {
return {
fromBatch: false,
batchPickId: '',
batchId: '',
materialCode: '',
materialName: '',
specModel: '',
unit: '',
stockInNo: '',
stockInDate: '',
expireDate: '',
catalogNo: '',
batchNo: '',
manufacturer: '',
unitPrice: null,
unusedQty: 1,
holder: '',
remark: ''
}
}
function newManualLineWithKey(): ManualUnusedLine {
return { ...newManualLine(), _key: `m_${Date.now()}_${Math.random().toString(36).slice(2, 8)}` }
}
function lineFromRequisition(req: QcMaterialStockCheckRequisition): QcMaterialStockCheckUnusedLine {
return {
usageId: req.id,
batchId: req.batchId || '',
materialCode: req.materialCode || '',
materialName: req.materialName || '',
specModel: req.specModel || '',
unit: req.unit || '',
stockInNo: req.stockInNo || '',
stockInDate: req.stockInDate || '',
expireDate: req.expireDate || '',
catalogNo: req.catalogNo || '',
batchNo: req.batchNo || '',
manufacturer: req.manufacturer || '',
unitPrice: req.unitPrice ?? null,
unusedQty: 1,
holder: req.receiverName || req.receiver || '',
remark: ''
}
}
function persistActiveRequisitionDraft() {
if (editMode.value !== 'requisition' || !activeRequisition.value) return
const usageId = activeRequisition.value.id
requisitionDrafts.value[usageId] = { ...activeDraft.value, usageId }
updateRegisteredUsageMap(usageId, activeDraft.value.unusedQty)
}
function debouncedLoadRequisitions() {
dbgLog('debouncedLoadRequisitions scheduled', { keyword: requisitionKeyword.value })
if (requisitionSearchTimer) clearTimeout(requisitionSearchTimer)
requisitionSearchTimer = setTimeout(() => {
dbgLog('debouncedLoadRequisitions fire')
void loadRequisitions('debounced-search')
}, 300)
}
async function loadRequisitions(source = 'unknown') {
const t0 = performance.now()
dbgLog('loadRequisitions START', { source, keyword: requisitionKeyword.value })
requisitionLoading.value = true
try {
const res = await fetchQcMaterialStockCheckRequisitions({
page: 1,
pageSize: 200,
keyword: requisitionKeyword.value.trim() || undefined
})
requisitionList.value = res.list || []
dbgLog('loadRequisitions OK', {
source,
count: requisitionList.value.length,
ids: requisitionList.value.map((r) => r.id),
ms: (performance.now() - t0).toFixed(2)
})
} catch (err) {
requisitionList.value = []
dbgLog('loadRequisitions FAIL', { source, ms: (performance.now() - t0).toFixed(2), err })
} finally {
requisitionLoading.value = false
dbgLog('loadRequisitions END loading=false', { source })
}
}
function selectRequisition(req: QcMaterialStockCheckRequisition, trigger = 'direct') {
const t0 = performance.now()
const fromId = activeRequisition.value?.id
const fromName = activeRequisition.value?.materialName
const isSame = editMode.value === 'requisition' && activeRequisition.value?.id === req.id
dbgLog('selectRequisition START', {
trigger,
fromId,
fromName,
toId: req.id,
toName: req.materialName,
isSame,
editMode: editMode.value,
fromDraftQty: activeDraft.value.unusedQty
})
let prevUsageId: string | null = null
let prevDraft: QcMaterialStockCheckUnusedLine | null = null
if (editMode.value === 'requisition' && activeRequisition.value && !isSame) {
prevUsageId = activeRequisition.value.id
prevDraft = { ...activeDraft.value, usageId: prevUsageId }
dbgLog('selectRequisition will persist prev draft', {
prevUsageId,
prevDraftQty: prevDraft.unusedQty
})
}
editMode.value = 'requisition'
activeKey.value = `req:${req.id}`
activeRequisition.value = req
applyActiveDraft(
requisitionDrafts.value[req.id] ? { ...requisitionDrafts.value[req.id] } : lineFromRequisition(req)
)
if (prevUsageId && prevDraft) {
queueMicrotask(() => {
const tPersist = performance.now()
requisitionDrafts.value[prevUsageId!] = prevDraft!
updateRegisteredUsageMap(prevUsageId!, prevDraft!.unusedQty)
dbgLog('selectRequisition deferred persist prev draft', {
prevUsageId,
prevDraftQty: prevDraft!.unusedQty,
sincePointerdown: dbgSincePointerDown(),
ms: (performance.now() - tPersist).toFixed(2)
})
})
}
dbgLog('selectRequisition SYNC DONE', {
trigger,
activeKey: activeKey.value,
activeReqId: activeRequisition.value?.id,
activeDraftQty: activeDraft.value.unusedQty,
activeDraftName: activeDraft.value.materialName,
ms: (performance.now() - t0).toFixed(2)
})
void nextTick(() => {
dbgLog('selectRequisition nextTick', {
trigger,
domTitle: activeRequisition.value?.materialName,
totalMs: (performance.now() - t0).toFixed(2)
})
dbgSnapshot('selectRequisition nextTick snapshot')
})
}
function selectManualLine(line: ManualUnusedLine) {
persistActiveRequisitionDraft()
editMode.value = 'manual'
activeKey.value = `manual:${line._key}`
editingManualKey.value = line._key
manualDraft.value = {
...line,
batchPickId: line.batchId || line.batchPickId || ''
}
}
function startManualEntry() {
persistActiveRequisitionDraft()
editMode.value = 'manual'
activeKey.value = ''
editingManualKey.value = ''
manualDraft.value = newManualLine()
void searchUnusedBatchOptions('')
}
function onManualBatchPick(batchId: string) {
if (!batchId) {
clearUnusedLineBatchFields(manualDraft.value)
return
}
const opt = batchOptions.value.find((o) => o.id === batchId)
if (opt) {
fillUnusedLineFromBatch(manualDraft.value, opt)
manualDraft.value.batchId = opt.id
}
}
function confirmManualLine() {
if (!manualDraft.value.fromBatch || !manualDraft.value.batchId) {
ElMessage.warning('请先检索并选择入库批次')
return
}
if (!manualDraft.value.unusedQty || manualDraft.value.unusedQty <= 0) {
ElMessage.warning('未用完数量必须大于0')
return
}
if (editingManualKey.value) {
const idx = manualLines.value.findIndex((l) => l._key === editingManualKey.value)
if (idx >= 0) {
manualLines.value[idx] = {
...manualDraft.value,
_key: editingManualKey.value
} as ManualUnusedLine
}
} else {
manualLines.value.push({
...manualDraft.value,
_key: `m_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
} as ManualUnusedLine)
}
ElMessage.success(editingManualKey.value ? '已更新手工登记' : '已加入手工登记')
editingManualKey.value = ''
manualDraft.value = newManualLine()
editMode.value = 'none'
activeKey.value = ''
}
function removeManualLine(key?: string) {
if (!key) return
manualLines.value = manualLines.value.filter((l) => l._key !== key)
if (activeKey.value === `manual:${key}`) {
editMode.value = 'none'
activeKey.value = ''
editingManualKey.value = ''
}
}
async function handleMarkFullyUsed(usageId: string) {
dbgLog('handleMarkFullyUsed START', { usageId })
try {
await ElMessageBox.confirm('确认该领用记录已全部使用完?标记后将不再出现在待登记列表。', '标记已使用完', {
type: 'warning',
confirmButtonText: '确认',
cancelButtonText: '取消'
})
} catch {
return
}
markFullyUsedLoadingId.value = usageId
try {
await fetchMarkQcMaterialUsageFullyUsed(usageId)
requisitionList.value = requisitionList.value.filter((r) => r.id !== usageId)
delete requisitionDrafts.value[usageId]
delete registeredUsageMap[usageId]
if (activeRequisition.value?.id === usageId) {
editMode.value = 'none'
activeKey.value = ''
activeRequisition.value = null
}
ElMessage.success('已标记为使用完')
} finally {
markFullyUsedLoadingId.value = ''
}
}
function onMarkFullyUsedClick(usageId: string, evt: MouseEvent) {
dbgLog('mark-fully-used button click', {
usageId,
...dbgEventTarget(evt)
})
void handleMarkFullyUsed(usageId)
}
function buildSaveItems(): QcMaterialStockCheckUnusedLine[] {
const reqItems = Object.values(requisitionDrafts.value).filter(
(l) => l.usageId && l.unusedQty > 0 && (l.materialName || '').trim()
)
const manualItems = manualLines.value.filter(
(l) => l.unusedQty > 0 && (l.materialName || '').trim() && (l.batchId || l.fromBatch)
)
return [...reqItems, ...manualItems]
}
async function openUnusedDialog(row: QcMaterialStockCheck) {
dbgSession += 1
dbgSeq = 0
dbgLastTs = performance.now()
dbgLastPointerDownTs = 0
console.info(
`${DBG} 调试已开启 | 复现:点A → 改数量 → 点B卡片任意区域(标记按钮除外)| 复制 ▶ 与 ⚠️ 日志`
)
dbgLog('openUnusedDialog START', { checkId: row.id, title: row.title })
unusedCheckId.value = row.id
requisitionKeyword.value = ''
requisitionDrafts.value = {}
for (const key of Object.keys(registeredUsageMap)) {
delete registeredUsageMap[key]
}
manualLines.value = []
editMode.value = 'none'
activeKey.value = ''
activeRequisition.value = null
editingManualKey.value = ''
manualDraft.value = newManualLine()
try {
const detail = await fetchQcMaterialStockCheckDetail(row.id)
for (const l of detail.unusedLines || []) {
if (l.usageId) {
requisitionDrafts.value[l.usageId] = { ...l }
} else {
manualLines.value.push({
...l,
fromBatch: !!l.batchId,
batchPickId: l.batchId || '',
_key: l.id || `m_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
} as ManualUnusedLine)
}
}
} catch {
/* ignore */
}
rebuildRegisteredUsageMap()
unusedVisible.value = true
await loadRequisitions('open-dialog')
void searchUnusedBatchOptions('')
dbgSnapshot('openUnusedDialog READY')
}
async function handleSaveUnused() {
persistActiveRequisitionDraft()
const items = buildSaveItems()
for (const line of items) {
if (!(line.materialName || '').trim()) {
ElMessage.warning('登记行缺少物料名称')
return
}
if (!line.unusedQty || line.unusedQty <= 0) {
ElMessage.warning('未用完数量必须大于0')
return
}
}
unusedLoading.value = true
try {
await fetchSaveQcMaterialStockCheckUnusedLines(
unusedCheckId.value,
items.map((l) => ({
usageId: l.usageId || undefined,
batchId: l.batchId || undefined,
materialName: l.materialName.trim(),
materialCode: l.materialCode?.trim() || undefined,
specModel: l.specModel?.trim() || undefined,
unit: l.unit?.trim() || undefined,
stockInNo: l.stockInNo?.trim() || undefined,
stockInDate: l.stockInDate || undefined,
expireDate: l.expireDate || undefined,
catalogNo: l.catalogNo?.trim() || undefined,
batchNo: l.batchNo?.trim() || undefined,
manufacturer: l.manufacturer?.trim() || undefined,
unitPrice: l.unitPrice != null ? Number(l.unitPrice) : undefined,
holder: l.holder?.trim() || undefined,
unusedQty: l.unusedQty,
remark: l.remark?.trim() || undefined
}))
)
ElMessage.success('登记保存成功')
unusedVisible.value = false
loadData()
} finally {
unusedLoading.value = false
}
}
const viewVisible = ref(false)
const viewDetail = ref<QcMaterialStockCheckDetail | null>(null)
const exportLoadingId = ref('')
const MERGED_EXPORT_HEADERS = [
'序号',
'入库编号',
'入库日期',
'过期日期',
'物料编码',
'物料名称',
'规格型号',
'单位',
'货号',
'批号',
'厂家',
'单价(元)',
'数量',
'剩余金额(元)',
'备注'
]
type StockCheckExportLine = {
groupKey: string
stockInNo: string
stockInDate: string
expireDate: string
materialCode: string
materialName: string
specModel: string
unit: string
catalogNo: string
batchNo: string
manufacturer: string
unitPrice: number | null
qty: number
amount: number
remark: string
}
function exportCell(v?: string | number | null) {
if (v == null || v === '') return ''
return v
}
function exportMoney(v?: number | null) {
if (v == null || Number.isNaN(Number(v))) return ''
return Number(v)
}
function lineAmount(unitPrice?: number | null, qty?: number | null, remainingAmount?: number | null) {
if (remainingAmount != null && !Number.isNaN(Number(remainingAmount))) {
return Number(remainingAmount)
}
return calcLineAmount(unitPrice, qty) ?? 0
}
function sanitizeSheetName(name: string) {
return name.replace(/[\\/*?:[\]]/g, '_').slice(0, 31)
}
function sanitizeFileName(name: string) {
return name.replace(/[\\/:*?"<>|]/g, '_').trim() || '库存盘点'
}
function buildMergedExportRows(detail: QcMaterialStockCheckDetail) {
const normalized: StockCheckExportLine[] = []
let rowIndex = 0
for (const row of detail.batchLines || []) {
const stockInNo = (row.stockInNo || '').trim()
normalized.push({
groupKey: stockInNo || `__empty_${rowIndex}__`,
stockInNo,
stockInDate: row.stockInDate || '',
expireDate: row.expireDate || '',
materialCode: row.materialCode || '',
materialName: row.materialName || '',
specModel: row.specModel || '',
unit: row.unit || '',
catalogNo: row.catalogNo || '',
batchNo: row.batchNo || '',
manufacturer: row.manufacturer || '',
unitPrice: row.unitPrice ?? null,
qty: Number(row.remainingQty) || 0,
amount: lineAmount(row.unitPrice, row.remainingQty, row.remainingAmount),
remark: (row.remark || '').trim()
})
rowIndex += 1
}
for (const row of detail.unusedLines || []) {
const stockInNo = (row.stockInNo || '').trim()
normalized.push({
groupKey: stockInNo || `__empty_${rowIndex}__`,
stockInNo,
stockInDate: row.stockInDate || '',
expireDate: row.expireDate || '',
materialCode: row.materialCode || '',
materialName: row.materialName || '',
specModel: row.specModel || '',
unit: row.unit || '',
catalogNo: row.catalogNo || '',
batchNo: row.batchNo || '',
manufacturer: row.manufacturer || '',
unitPrice: row.unitPrice ?? null,
qty: Number(row.unusedQty) || 0,
amount: lineAmount(row.unitPrice, row.unusedQty, row.remainingAmount),
remark: (row.remark || '').trim()
})
rowIndex += 1
}
const groups = new Map<
string,
{
meta: StockCheckExportLine
totalQty: number
totalAmount: number
remarks: string[]
}
>()
for (const line of normalized) {
const existing = groups.get(line.groupKey)
if (!existing) {
groups.set(line.groupKey, {
meta: line,
totalQty: line.qty,
totalAmount: line.amount,
remarks: line.remark ? [line.remark] : []
})
continue
}
existing.totalQty += line.qty
existing.totalAmount += line.amount
if (line.remark && !existing.remarks.includes(line.remark)) {
existing.remarks.push(line.remark)
}
}
return Array.from(groups.values()).map((group, index) => {
const { meta, totalQty, totalAmount, remarks } = group
return {
序号: index + 1,
入库编号: exportCell(meta.stockInNo),
入库日期: exportCell(meta.stockInDate),
过期日期: exportCell(meta.expireDate),
物料编码: exportCell(meta.materialCode),
物料名称: exportCell(meta.materialName),
规格型号: exportCell(meta.specModel),
单位: exportCell(meta.unit),
货号: exportCell(meta.catalogNo),
批号: exportCell(meta.batchNo),
厂家: exportCell(meta.manufacturer),
'单价(元)': exportMoney(meta.unitPrice),
数量: exportCell(totalQty),
'剩余金额(元)': exportMoney(Math.round(totalAmount * 100) / 100),
备注: remarks.join(';')
}
})
}
function buildExportWorksheet(headers: string[], rows: Record<string, unknown>[]) {
if (!rows.length) {
return XLSX.utils.aoa_to_sheet([headers])
}
return XLSX.utils.json_to_sheet(rows, { header: headers })
}
function downloadStockCheckExcel(detail: QcMaterialStockCheckDetail) {
const workbook = XLSX.utils.book_new()
const mergedRows = buildMergedExportRows(detail)
XLSX.utils.book_append_sheet(
workbook,
buildExportWorksheet(MERGED_EXPORT_HEADERS, mergedRows),
sanitizeSheetName('库存盘点')
)
const excelBuffer = XLSX.write(workbook, {
bookType: 'xlsx',
type: 'array',
compression: true
})
const blob = new Blob([excelBuffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const dateStr = detail.checkTime?.slice(0, 10) || new Date().toISOString().slice(0, 10)
FileSaver.saveAs(blob, `${sanitizeFileName(detail.title)}_库存盘点_${dateStr}.xlsx`)
}
async function handleExport(row: QcMaterialStockCheck) {
exportLoadingId.value = row.id
try {
const detail =
viewDetail.value?.id === row.id
? viewDetail.value
: await fetchQcMaterialStockCheckDetail(row.id)
downloadStockCheckExcel(detail)
ElMessage.success('导出成功')
} catch {
ElMessage.error('导出失败,请重试')
} finally {
exportLoadingId.value = ''
}
}
async function handleExportFromView() {
if (!viewDetail.value) return
exportLoadingId.value = viewDetail.value.id
try {
downloadStockCheckExcel(viewDetail.value)
ElMessage.success('导出成功')
} catch {
ElMessage.error('导出失败,请重试')
} finally {
exportLoadingId.value = ''
}
}
async function handleView(row: QcMaterialStockCheck) {
viewDetail.value = await fetchQcMaterialStockCheckDetail(row.id)
viewVisible.value = true
}
async function handleComplete(row: QcMaterialStockCheck) {
await ElMessageBox.confirm(`确定完成盘点「${row.title}」吗?完成后不可再修改登记。`, '完成盘点', {
type: 'warning'
})
await fetchCompleteQcMaterialStockCheck(row.id)
ElMessage.success('盘点已完成')
loadData()
}
async function handleCancel(row: QcMaterialStockCheck) {
await ElMessageBox.confirm(`确定作废盘点「${row.title}」吗?`, '作废盘点', { type: 'warning' })
await fetchCancelQcMaterialStockCheck(row.id)
ElMessage.success('盘点已作废')
loadData()
}
watch(unusedVisible, (visible) => {
if (!UNUSED_DIALOG_DEBUG) return
dbgLog('watch unusedVisible', { visible })
if (visible) dbgStartLongTaskObserver()
else dbgStopLongTaskObserver()
})
watch(requisitionLoading, (loading) => {
if (!UNUSED_DIALOG_DEBUG || !unusedVisible.value) return
dbgLog('watch requisitionLoading', { loading })
})
watch(
() => [activeKey.value, editMode.value, activeRequisition.value?.id] as const,
([key, mode, reqId], [prevKey, prevMode, prevReqId]) => {
if (!UNUSED_DIALOG_DEBUG || !unusedVisible.value) return
dbgLog('watch selection', {
prev: { key: prevKey, mode: prevMode, reqId: prevReqId },
next: { key, mode, reqId }
})
}
)
watch(
() => activeDraft.value.unusedQty,
(next, prev) => {
if (!UNUSED_DIALOG_DEBUG || !unusedVisible.value) return
dbgLog('watch activeDraft.unusedQty', {
prev,
next,
activeReqId: activeRequisition.value?.id
})
}
)
watchDebounced(
searchForm,
() => {
pagination.page = 1
loadData()
},
{ debounce: 300, deep: true }
)
watch(dateRange, () => {
pagination.page = 1
loadData()
})
onMounted(() => loadData())
</script>
<style scoped lang="scss">
.table-op-btns {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px;
}
.material-batch-stock-dialog,
.unused-split-dialog {
.unused-split-layout {
display: grid;
grid-template-columns: minmax(0, 340px) minmax(0, 1fr);
gap: 20px;
min-height: 480px;
> aside,
> section {
min-width: 0;
max-width: 100%;
}
}
.unused-list-panel {
border: 1px solid var(--mint-border, #e2e8f0);
border-radius: 8px;
background: #fafafa;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
box-sizing: border-box;
}
.unused-list-panel__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 12px;
border-bottom: 1px solid var(--mint-border, #e2e8f0);
background: #fff;
}
.unused-list-panel__title {
font-size: 13px;
font-weight: 600;
color: var(--mint-text, #0f172a);
min-width: 0;
}
.stat-pill {
display: inline-flex;
align-items: center;
flex-shrink: 0;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
background: var(--primary-bg, #ecfdf5);
color: var(--primary-dark, #059669);
}
.unused-list-search-wrap {
padding: 6px 12px 8px;
box-sizing: border-box;
max-width: 100%;
}
.unused-list-search {
width: 100%;
max-width: 100%;
:deep(.el-input) {
width: 100%;
max-width: 100%;
}
}
.unused-line-list {
flex: 0 0 auto;
overflow-y: auto;
max-height: 200px;
padding: 6px 12px;
&.is-list-loading {
opacity: 0.65;
pointer-events: auto;
}
}
.unused-line-item {
display: flex;
flex-direction: column;
width: 100%;
text-align: left;
padding: 7px 8px;
margin-bottom: 4px;
border: 1px solid var(--mint-border, #e2e8f0);
border-radius: 6px;
background: #fff;
cursor: pointer;
transition: border-color 0.12s, background 0.12s;
&:hover {
border-color: #a7f3d0;
background: #f0fdf4;
}
&.is-active {
border-color: var(--primary, #10b981);
background: var(--primary-bg, #ecfdf5);
}
}
.unused-line-item__actions {
margin-top: 4px;
display: flex;
justify-content: flex-end;
}
.unused-line-item--manual {
display: block;
padding: 7px 8px;
cursor: pointer;
outline: none;
&:focus-visible {
box-shadow: 0 0 0 2px rgb(16 185 129 / 35%);
}
}
.unused-line-item__top {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 2px;
}
.unused-line-item__name {
flex: 1;
font-size: 12px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.unused-reg-tag {
flex-shrink: 0;
display: inline-flex;
align-items: center;
height: 18px;
padding: 0 6px;
border-radius: 4px;
font-size: 10px;
font-weight: 600;
background: var(--primary-bg, #ecfdf5);
color: var(--primary-dark, #059669);
}
.unused-line-item__meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
font-size: 10px;
color: var(--mint-text-muted, #64748b);
}
.unused-mark-btn {
display: inline-flex;
align-items: center;
gap: 4px;
height: 26px;
padding: 0 8px;
font-size: 11px;
border: 1px solid var(--mint-border, #e2e8f0);
border-radius: 6px;
background: #fff;
color: var(--mint-text, #0f172a);
cursor: pointer;
&:hover:not(:disabled) {
border-color: var(--primary, #10b981);
color: var(--primary-dark, #059669);
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.el-icon {
font-size: 12px;
}
}
.unused-empty-hint {
padding: 16px 10px;
text-align: center;
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
.unused-manual-section {
border-top: 1px solid var(--mint-border, #e2e8f0);
padding: 10px 12px 12px;
background: #fff;
}
.btn-sm-block {
width: 100%;
margin-top: 8px;
}
.unused-manual-list {
margin-top: 8px;
max-height: 140px;
overflow-y: auto;
}
.unused-detail-panel {
border: 1px solid var(--mint-border, #e2e8f0);
border-radius: 8px;
padding: 16px;
background: #fff;
min-height: 480px;
}
.unused-detail-head {
margin-bottom: 14px;
padding-bottom: 12px;
border-bottom: 1px solid var(--mint-border, #e2e8f0);
}
.unused-detail-title {
margin: 0;
font-size: 15px;
font-weight: 600;
}
.unused-detail-sub {
margin: 4px 0 0;
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
.unused-readonly-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px 16px;
margin-bottom: 16px;
padding: 12px;
background: #f8fafc;
border-radius: 8px;
font-size: 13px;
.ro-label {
display: block;
font-size: 11px;
color: var(--mint-text-muted, #64748b);
margin-bottom: 2px;
}
}
.unused-edit-form {
:deep(.el-form-item) {
margin-bottom: 12px;
}
}
.unused-manual-actions {
margin-top: 8px;
}
.unused-detail-empty {
display: flex;
align-items: center;
justify-content: center;
min-height: 360px;
color: var(--mint-text-muted, #64748b);
font-size: 13px;
}
.batch-option-item {
display: flex;
flex-direction: column;
gap: 2px;
line-height: 1.3;
padding: 2px 0;
}
.batch-option-main {
font-size: 13px;
font-weight: 500;
}
.batch-option-sub {
font-size: 11px;
color: var(--mint-text-muted, #64748b);
}
}
@media (max-width: 960px) {
.unused-split-dialog .unused-split-layout {
grid-template-columns: 1fr;
}
}
.material-batch-stock-dialog {
.batch-stock-move-lines-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
margin-bottom: 10px;
}
.batch-stock-move-lines-head-left {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.batch-stock-move-lines-title {
font-size: 14px;
font-weight: 600;
color: var(--mint-text, #0f172a);
}
.batch-stock-move-lines-hint {
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
.batch-in-line-list {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 460px;
overflow-y: auto;
padding-right: 2px;
}
.batch-in-line-card {
display: grid;
grid-template-columns: 28px 1fr;
gap: 0 6px;
align-items: start;
border: 1px solid var(--mint-border, #e2e8f0);
border-radius: 6px;
padding: 6px 8px;
background: #fff;
&:nth-child(even) {
background: var(--el-fill-color-lighter, #f8fafc);
}
}
.batch-in-line-card-head {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding-top: 18px;
}
.batch-in-line-card-index {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
color: var(--primary-dark, #065f46);
background: var(--primary-bg, #e8f4ee);
}
.batch-in-line-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 4px 8px;
min-width: 0;
}
.batch-in-col-span-2 {
grid-column: span 2;
}
.batch-in-line-card-body {
--batch-in-control-h: 28px;
:deep(.el-form-item) {
margin-bottom: 0;
}
:deep(.el-form-item__label) {
margin-bottom: 0;
padding-bottom: 2px;
font-size: 11px;
line-height: 1.2;
color: var(--mint-text-muted, #64748b);
}
:deep(.el-select),
:deep(.el-input),
:deep(.el-date-editor),
:deep(.el-input-number) {
width: 100%;
}
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
min-height: var(--batch-in-control-h);
height: var(--batch-in-control-h);
padding-top: 0;
padding-bottom: 0;
box-sizing: border-box;
}
:deep(.el-input__inner) {
height: calc(var(--batch-in-control-h) - 2px);
line-height: calc(var(--batch-in-control-h) - 2px);
}
:deep(.el-date-editor.el-input) {
height: var(--batch-in-control-h);
--el-input-height: var(--batch-in-control-h);
}
:deep(.el-input-number--small) {
width: 100%;
line-height: var(--batch-in-control-h);
.el-input__wrapper {
min-height: var(--batch-in-control-h);
height: var(--batch-in-control-h);
}
.el-input-number__decrease,
.el-input-number__increase {
height: calc((var(--batch-in-control-h) - 2px) / 2);
}
}
}
}
/*
* 弹窗内宽表横向滚动(对齐 order/index.vue order-detail-items-scroll):
* OpenSpec 列 min-width + :fit="false" + body-wrapper overflow-x,覆盖全局 width:100%!important
*/
.inner-table-scroll {
width: 100%;
max-width: 100%;
overflow-x: hidden;
overflow-y: visible;
-webkit-overflow-scrolling: touch;
}
.inner-table-scroll :deep(.el-table.inner-table) {
width: 100% !important;
min-width: 100%;
}
.inner-table-scroll :deep(.el-table.inner-table .el-table__inner-wrapper) {
width: 100% !important;
min-width: 100%;
}
.inner-table-scroll :deep(.el-table.inner-table .el-table__body-wrapper) {
overflow-x: auto !important;
}
.inner-table-scroll :deep(.el-table.inner-table .el-table__header-wrapper) {
overflow-x: hidden !important;
}
.inner-cell-input {
width: 100%;
}
.batch-option-item {
display: flex;
flex-direction: column;
gap: 4px;
line-height: 1.4;
padding: 0;
}
.batch-option-main {
font-size: 13px;
color: var(--mint-text, #0f172a);
}
.batch-option-sub {
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
:global(.batch-out-option-popper .el-select-dropdown__item) {
height: auto;
min-height: 52px;
line-height: 1.45;
white-space: normal;
padding-top: 8px;
padding-bottom: 8px;
}
.stock-check-view {
.view-head-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px 24px;
margin-bottom: 16px;
font-size: 14px;
}
.view-head-remark {
grid-column: 1 / -1;
}
.view-label {
display: inline-block;
min-width: 72px;
margin-right: 8px;
color: var(--mint-text-muted, #64748b);
}
.view-section-title {
margin: 16px 0 8px;
font-size: 14px;
font-weight: 600;
color: var(--mint-text, #0f172a);
}
}
</style>