WEB/src/views/storage/report/store.vue
2026-09-02 18:02:26 +08:00

634 lines
17 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.

<template>
<div class="storage-report-container" :style="{ height: containerHeight }">
<scan-box
ref="scanBox"
:width="reportScanBoxConfig.width"
:tree-props="reportScanBoxConfig.treeProps"
:auto-submit="reportScanBoxConfig.autoSubmit"
:preset-tree="presetTree"
:available-fields="availableFieldsRef"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
/>
<div class="main-content">
<div class="toolbar">
<div class="toolbar-left">
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
<el-divider direction="vertical" />
<WarehouseSelect
v-model="warehouseFilterId"
@change="handleWarehouseChange"
/>
<!-- <span class="toolbar-title">库存报表</span>
<el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag> -->
<template v-if="pagination.total > 0">
<el-tag size="small" effect="plain">入库合计 {{ formatNumber(sumInbound) }}</el-tag>
<el-tag size="small" effect="plain">出库合计 {{ formatNumber(sumOutbound) }}</el-tag>
</template>
</div>
</div>
<div class="split-stack" ref="splitStackRef">
<div class="upper-wrapper" :style="detailVisible ? upperPaneStyle : upperPaneFullStyle">
<upper-table
ref="upperTable"
row-key="__rid"
title="报表明细"
default-align="center"
table-id="storage-report-list"
:enable-column-config="true"
:data="list"
:columns="columns"
:table-size="tableSize"
:pagination="pagination"
:show-index="true"
:loading="loading"
:query-time="queryTime"
@current-change="handleRowClick"
@sort-change="handleSortChange"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadData"
>
<template #empty>
<div class="empty-tip">暂无数据,可在左侧调整筛选条件</div>
</template>
</upper-table>
</div>
<template v-if="detailVisible">
<div
class="pane-resizer"
title="拖动调整列表与详情区域高度"
@mousedown="beginSplitDrag"
/>
<div v-if="selectedRow" class="lower-level" :class="tableSize" :style="lowerPaneStyle">
<!-- <div class="detail-header">
<span class="detail-title">行明细</span>
<span class="detail-sub">字段与接口 <code>data.list[]</code> 单条对象一致</span>
</div> -->
<div class="detail-container">
<el-descriptions :column="2" border size="small">
<el-descriptions-item
v-for="key in detailKeys"
:key="key"
:label="fieldLabel(key)"
:span="isWideKey(key) ? 2 : 1"
>
{{ detailValue(key) }}
</el-descriptions-item>
</el-descriptions>
</div>
</div>
<div v-else class="no-selection" :style="lowerPaneStyle">
<div class="empty-tip">在表格中点击一行可查看该行完整字段</div>
</div>
</template>
</div>
</div>
<AsyncExportProgressDialog
v-model:visible="exportDialogVisible"
title="库存报表导出进度"
:loading="exportLoading"
:progress-percent="exportProgressPercent"
:progress-status="exportProgressStatus"
:status-label="exportStatusLabel"
:task-id="exportTaskProgress.taskId"
:message="exportTaskProgress.message"
:error="exportTaskProgress.error"
:update-time="exportTaskProgress.updateTime"
/>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import ExportModeDropdown from '@/components/ExportModeDropdown.vue'
import WarehouseSelect from '@/components/WarehouseSelect.vue'
import AsyncExportProgressDialog from '@/components/AsyncExportProgressDialog.vue'
import { useAsyncExportTask } from '@/composables/useAsyncExportTask'
import {
exportStoreReport,
getExportTaskProgress,
searchStoreReport,
type StockReportExportBody,
type StockReportSearchBody
} from '@/api/stock.report/stock.report'
import * as indexApi from '@/api/index/index'
import {
buildReportTableColumns,
formatReportCell,
formatReportDateTime,
formatReportNumber,
normalizeScanConditionToReportWhere,
reportFieldLabels,
reportScanBoxAvailableFields,
reportScanBoxConfig,
sortReportDetailKeys
} from './report-config'
import { useSettingsStore } from '@/stores/modules/settings'
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
const scanBox = ref<any>(null)
const upperTable = ref<any>(null)
const presetTree = ref<any[]>([])
const availableFieldsRef = reactive(
JSON.parse(JSON.stringify(reportScanBoxAvailableFields)).filter(
(f: any) => f.value !== 'store_id' && f.value !== 'by_space'
)
)
const settingsStore = useSettingsStore()
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
const containerHeight = computed(() =>
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
)
const {
splitStackRef,
beginSplitDrag,
lowerPaneStyle,
upperPaneStyle
} = useVerticalSplitPane({ defaultLowerPercent: 40 })
const upperPaneFullStyle = computed(() => ({
flex: '1 1 auto',
minHeight: '0',
overflow: 'hidden'
}))
const detailVisible = ref(true)
function toggleDetailVisible() {
detailVisible.value = !detailVisible.value
}
function openColumnConfigPanel() {
upperTable.value?.openColumnConfig?.()
}
const tableSize = ref<'small' | 'default' | 'large'>('small')
const loading = ref(false)
const queryTime = ref(0)
const {
exportLoading,
exportDialogVisible,
exportTaskProgress,
exportProgressPercent,
exportProgressStatus,
exportStatusLabel,
submitExportTaskWithMode,
resumeExportTaskFromStorage,
hasPendingExportTask
} = useAsyncExportTask({
storageKey: 'storage.report.export.taskId',
submitExport: (payload) => exportStoreReport(payload as StockReportExportBody),
queryProgress: (params) => getExportTaskProgress(params)
})
const fullList = ref<any[]>([])
const list = ref<any[]>([])
/** 货主侧不显示的列 */
const STORE_SIDE_HIDDEN_COLS = new Set(['store_id', 'store_name'])
function buildStoreReportColumns(rows: any[]) {
return buildReportTableColumns(rows).filter((col: any) => !STORE_SIDE_HIDDEN_COLS.has(col.prop))
}
const columns = ref(buildStoreReportColumns([]))
const pagination = reactive({
currentPage: 1,
pageSize: 20,
total: 0
})
const currentSort = reactive<{ prop: string; order: '' | 'ascending' | 'descending' }>({
prop: '',
order: ''
})
const selectedRid = ref<string | null>(null)
const currentConditionRaw = ref<any>({})
/** toolbar 全部仓库筛选值(独立于 scan-box 条件,空值=全部仓库) */
const warehouseFilterId = ref<number | string | null>(null)
const selectedRow = computed(() => fullList.value.find((r) => r.__rid === selectedRid.value) || null)
const detailKeys = computed(() => {
if (!selectedRow.value) return []
const keys = Object.keys(selectedRow.value).filter((k) => k !== '__rid' && !STORE_SIDE_HIDDEN_COLS.has(k))
return sortReportDetailKeys(keys)
})
const sumInbound = computed(() =>
fullList.value.reduce((a, r) => a + Number((r as any).inbound_total ?? 0), 0)
)
const sumOutbound = computed(() =>
fullList.value.reduce((a, r) => a + Number((r as any).outbound_total ?? 0), 0)
)
function formatNumber(n: number) {
return Number.isFinite(n) ? n.toLocaleString('zh-CN') : '--'
}
function fieldLabel(key: string) {
return reportFieldLabels[key] || key
}
function detailValue(key: string) {
if (!selectedRow.value) return '--'
const v = (selectedRow.value as any)[key]
if (key === 'start_time' || key === 'end_time') return formatReportDateTime(v)
if (key === 'stock_id') return formatReportCell(v)
if (
key === 'begin_total' ||
key === 'end_total' ||
key === 'inbound_total' ||
key === 'outbound_total' ||
key === 'store_id' ||
key === 'space_id'
) {
return formatReportNumber(v)
}
return formatReportCell(v)
}
function isWideKey(key: string) {
return detailValue(key).length > 80
}
function extractReportList(res: any): any[] {
if (!res) return []
if (res.data != null && Array.isArray(res.data.list)) return res.data.list
if (Array.isArray(res.list)) return res.list
return []
}
function withRowIds(rows: any[]) {
return rows.map((row, idx) => ({
...row,
__rid: `r-${idx}-${row.stock_id ?? ''}-${row.store_id ?? ''}-${row.item_code ?? ''}`
}))
}
function applyClientPage() {
const total = fullList.value.length
pagination.total = total
const start = (pagination.currentPage - 1) * pagination.pageSize
list.value = fullList.value.slice(start, start + pagination.pageSize)
}
const SORTABLE_FIELDS = new Set(['begin_total', 'inbound_total', 'outbound_total', 'end_total'])
function buildSortPayload(): StockReportSearchBody['sort'] | undefined {
if (!SORTABLE_FIELDS.has(currentSort.prop)) return undefined
if (!currentSort.order) return undefined
const sortOrder = currentSort.order === 'ascending' ? 'ASC' : 'DESC'
return {
sortField: currentSort.prop as any,
sort_field: currentSort.prop as any,
sortOrder,
sort_order: sortOrder
}
}
/** toolbar 全部仓库过滤:并入报表查询 where(直接值,与报表后端约定一致) */
function applyWarehouseToWhere(where: Record<string, any>) {
const v = warehouseFilterId.value
if (v === null || v === undefined || v === '') return
where.warehouse_id = v
}
/** toolbar 全部仓库切换:重置到第一页并刷新 */
function handleWarehouseChange() {
pagination.currentPage = 1
loadData()
}
function buildReportQueryPayload(): StockReportSearchBody {
const where = normalizeScanConditionToReportWhere(currentConditionRaw.value)
applyWarehouseToWhere(where)
const sort = buildSortPayload()
const body: StockReportSearchBody = {}
if (Object.keys(where).length > 0) {
body.where = where
}
if (sort) {
body.sort = sort
}
return body
}
async function handleExportWaybill() {
if (hasPendingExportTask()) {
ElMessage.warning('检测到未完成导出任务,请等待当前任务完成后再试')
resumeExportTaskFromStorage()
return
}
await submitExportTaskWithMode(buildReportQueryPayload() as Record<string, unknown>, 'waybill')
}
async function handleExportItem() {
if (hasPendingExportTask()) {
ElMessage.warning('检测到未完成导出任务,请等待当前任务完成后再试')
resumeExportTaskFromStorage()
return
}
await submitExportTaskWithMode(buildReportQueryPayload() as Record<string, unknown>, 'item')
}
function handleExportAction(action: string) {
if (action === 'handleExportItem') {
void handleExportItem()
return
}
void handleExportWaybill()
}
async function loadFilterData() {
try {
const presetRes: any = await indexApi.fastWhereTree('stock')
if (presetRes && presetRes.code === 200) {
presetTree.value = presetRes.presetTree || []
}
} catch (e) {
console.error('加载筛选配置失败', e)
}
}
function handleConditionChange(condition: any) {
currentConditionRaw.value = condition
pagination.currentPage = 1
loadData()
}
function handleConditionClear() {
currentConditionRaw.value = {}
pagination.currentPage = 1
loadData()
}
function handleConditionReset() {
currentConditionRaw.value = {}
pagination.currentPage = 1
if (scanBox.value?.reset) {
scanBox.value.reset()
} else if (scanBox.value?.clear) {
scanBox.value.clear()
}
loadData()
}
async function loadData() {
if (loading.value) return
loading.value = true
const started = Date.now()
selectedRid.value = null
const body = buildReportQueryPayload()
try {
const res: any = await searchStoreReport(
Object.keys(body).length > 0 ? body : undefined
)
if (res && (res.flag === 'success' || res.code === 200)) {
const raw = extractReportList(res)
fullList.value = withRowIds(raw)
columns.value = buildStoreReportColumns(raw)
pagination.currentPage = 1
applyClientPage()
queryTime.value = Date.now() - started
} else {
fullList.value = []
list.value = []
columns.value = buildStoreReportColumns([])
pagination.total = 0
ElMessage.error(res?.message || '查询失败')
}
} catch (e: any) {
fullList.value = []
list.value = []
columns.value = buildStoreReportColumns([])
pagination.total = 0
ElMessage.error(e?.message || '请求失败')
} finally {
loading.value = false
}
}
function handleSortChange({ prop, order }: { prop: string; order: '' | 'ascending' | 'descending' | null }) {
currentSort.prop = prop || ''
currentSort.order = (order || '') as '' | 'ascending' | 'descending'
pagination.currentPage = 1
loadData()
}
function handlePageChange(page: number) {
pagination.currentPage = page
applyClientPage()
}
function handlePageSizeChange(size: number) {
pagination.pageSize = size
pagination.currentPage = 1
applyClientPage()
}
function handleRowClick(row: any) {
selectedRid.value = row?.__rid ?? null
}
onMounted(() => {
loadFilterData()
loadData()
resumeExportTaskFromStorage()
})
</script>
<style lang="scss" scoped>
.storage-report-container {
display: flex;
width: 100%;
background-color: #f0f2f5;
.main-content {
flex: 1;
display: flex;
flex-direction: column;
padding: 10px;
overflow: hidden;
min-height: 0;
.toolbar {
padding: 5px;
border-bottom: 1px solid #ebeef5;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fff;
.toolbar-left {
display: flex;
gap: 8px;
align-items: center;
flex-wrap: wrap;
}
.toolbar-title {
font-size: 14px;
font-weight: 500;
color: #303133;
margin-left: 4px;
}
}
.filter-hint {
margin: 6px 0 0;
font-size: 12px;
color: #909399;
line-height: 1.5;
code {
font-size: 12px;
padding: 0 4px;
background: #f4f4f5;
border-radius: 2px;
}
}
.split-stack {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
margin-top: 8px;
}
.pane-resizer {
flex: 0 0 6px;
min-height: 6px;
background: #e4e7ed;
cursor: row-resize;
flex-shrink: 0;
position: relative;
z-index: 2;
&:hover {
background: #dcdfe6;
}
}
.upper-wrapper {
overflow: hidden;
}
.upper-wrapper :deep(.upper-table-container) {
height: 100%;
display: flex;
flex-direction: column;
}
.upper-wrapper :deep(.upper-table-container) :deep(.table-container) {
height: auto !important;
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
.upper-wrapper :deep(.el-table__header-wrapper) {
position: sticky;
top: 0;
z-index: 3;
background: #fff;
}
.upper-wrapper :deep(.el-table__body-wrapper) {
overflow: auto;
min-height: 0;
}
.lower-level {
display: flex;
flex-direction: column;
border-top: 1px solid #ebeef5;
overflow: hidden;
background-color: #fff;
.detail-header {
padding: 10px 12px;
border-bottom: 1px solid #ebeef5;
background: #fafafa;
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 8px;
}
.detail-title {
font-size: 14px;
font-weight: 500;
color: #303133;
}
.detail-sub {
font-size: 12px;
color: #909399;
code {
font-size: 12px;
padding: 0 4px;
background: #f4f4f5;
border-radius: 2px;
}
}
.detail-container {
flex: 1;
overflow: auto;
padding: 10px;
:deep(.el-descriptions__body) {
background: #fff;
}
:deep(.el-descriptions-item__cell) {
padding: 8px 12px;
}
}
}
.no-selection {
display: flex;
align-items: center;
justify-content: center;
color: #909399;
background-color: #fff;
border: 1px dashed #dcdfe6;
.empty-tip {
text-align: center;
font-size: 14px;
}
}
.empty-tip {
text-align: center;
font-size: 13px;
}
}
}
</style>