This commit is contained in:
zlwu committed 2026-08-17 09:22:31 +08:00
1 parent 42ad896456
commit 6b2147aa46
66 files changed
+617071 -28046

No files matched your search

@@ -147,6 +147,7 @@
</div>
<div class="list-body list-wrap"> <!-- 操作按钮栏 + 数据表格 -->
<div ref="contractTableWrapRef" class="contract-table-wrap">
<ListTable table-key="crm-contract"
v-loading="loading"
class="list-table"
@@ -156,6 +157,7 @@
@selection-change="handleSelectionChange"
@expand-change="handleExpandChange"
@row-dblclick="handleView"
@header-dragend="onContractHeaderDragEnd"
>
<el-table-column type="expand" width="55">
<template #default="scope">
@@ -456,6 +458,16 @@
<el-table-column v-if="isColumnVisible('remark')" label="备注" align="center" prop="remark" min-width="200" show-overflow-tooltip />
</ListTable>
<ListColumnStatsRow
ref="contractStatsRowRef"
storage-key="crm-contract-column-stats"
:columns="contractStatsRowColumns"
:data="contractList"
:table-wrap-el="contractTableWrapRef"
:get-cell-value="getContractStatCellValue"
/>
</div>
<div class="pagination list-pager-bar">
<div class="list-pager-selected">
已选 <span class="sel-num">{{ selectedRows.length }}</span> 项
@@ -551,7 +563,9 @@ import {
} from '@/utils/crm-attachment'
import ListToolbarDateShortcuts from '@/components/core/list-toolbar-date-shortcuts/index.vue'
import ListToolbarEndActions from '@/components/business/list-toolbar-end-actions/index.vue'
import ListColumnStatsRow from '@/components/business/list-column-stats-row/index.vue'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import { buildStatsRowColumns } from '@/utils/list-column-stats'
const props = withDefaults(
defineProps<{
@@ -991,6 +1005,45 @@ const formatContractProductInfoLines = (row: ContractVO): string[] => {
.filter((line) => line.length > 0)
}
const CONTRACT_MONEY_STAT_PROPS = new Set([
'totalContractAmount',
'amount',
'freight',
'barrelDeposit',
'unreceivedAmount',
'invoiceAmount',
'uninvoiceAmount'
])
const contractTableWrapRef = ref<HTMLElement | null>(null)
const contractStatsRowRef = ref<{ resync?: () => void } | null>(null)
const contractStatsRowColumns = computed(() =>
buildStatsRowColumns({
leadingSpacers: 2,
alwaysColumns: [
{ prop: 'contractNo' },
{ prop: 'contractName' }
],
optionalDefs: listColumnDefs,
isColumnVisible,
moneyProps: CONTRACT_MONEY_STAT_PROPS
})
)
function getContractStatCellValue(row: ContractVO, prop: string): unknown {
if (prop === 'totalContractAmount') return getContractTotalAmount(row)
if (prop === 'productInfo') {
const lines = formatContractProductInfoLines(row)
return lines.length ? lines.join('\n') : null
}
return (row as Record<string, unknown>)[prop]
}
function onContractHeaderDragEnd() {
contractStatsRowRef.value?.resync?.()
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: ContractVO[]) => {
selectedRows.value = selection;
@@ -1501,4 +1554,8 @@ onMounted(() => {
}
}
.contract-table-wrap {
min-width: 0;
}
</style>
+235 -77
View File
@@ -383,42 +383,51 @@
</ListTable>
<div
ref="quoteStatsScrollRef"
class="quote-list-stats-row"
aria-label="列表列统计"
@scroll="onStatsRowScroll"
>
<div class="quote-list-stats-row__fixed">
<div class="quote-list-stats-row__cell is-fixed" style="width: 55px" />
<div class="quote-list-stats-row__cell is-fixed" style="width: 55px" />
</div>
<div
ref="quoteStatsScrollRef"
class="quote-list-stats-row__scroll"
@scroll="onStatsRowScroll"
>
<div class="quote-list-stats-row__inner">
<div
v-for="col in statsBusinessColumns"
:key="col.prop"
class="quote-list-stats-row__cell is-stat"
v-for="col in statsRowColumns"
:key="col.key"
class="quote-list-stats-row__cell"
:class="{ 'is-stat': col.interactive, 'is-spacer': !col.interactive }"
>
<el-dropdown trigger="click" @command="(cmd: string | number) => onStatCommand(col.prop, cmd)">
<span
class="quote-list-stats-row__trigger"
:class="{ 'is-empty': !statsCellText(col.prop, col.money) }"
>
{{ statsCellText(col.prop, col.money) || '统计' }}
</span>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
v-for="opt in COLUMN_STAT_METHOD_OPTIONS"
:key="opt.label"
:command="opt.value"
>
{{ opt.label }}
</el-dropdown-item>
</el-dropdown-menu>
<el-popover
v-if="col.interactive && col.prop"
:visible="statsMenuOpenProp === col.prop"
placement="top-start"
:width="132"
:teleported="true"
trigger="click"
:hide-after="0"
popper-class="quote-list-stats-dropdown"
@update:visible="(v: boolean) => setStatsMenuOpen(col.prop!, v)"
>
<template #reference>
<button
type="button"
class="quote-list-stats-row__trigger"
:class="{ 'is-empty': !statsCellText(col.prop, !!col.money) }"
>
{{ statsCellText(col.prop, !!col.money) || '\u00a0' }}
</button>
</template>
</el-dropdown>
<div class="quote-list-stats-menu">
<button
v-for="opt in COLUMN_STAT_METHOD_OPTIONS"
:key="opt.label"
type="button"
class="quote-list-stats-menu__item"
:class="{ 'is-active': (columnStatConfig[col.prop!] || '') === opt.value }"
@click="pickColumnStat(col.prop!, opt.value)"
>
{{ opt.label }}
</button>
</div>
</el-popover>
</div>
</div>
</div>
@@ -863,8 +872,11 @@ import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import {
COLUMN_STAT_METHOD_OPTIONS,
QUOTE_MONEY_STAT_PROPS,
applyStatsCellAlignStyles,
formatColumnStatDisplay,
getTableColumnTextAligns,
loadColumnStatConfig,
resolveStatsCellAlign,
saveColumnStatConfig,
setColumnStatMethod,
type ColumnStatConfigMap,
@@ -1899,16 +1911,29 @@ const formatQuoteProductInfoLines = (row: QuoteVO): string[] => {
const columnStatConfig = ref<ColumnStatConfigMap>(loadColumnStatConfig())
const statsBusinessColumns = computed(() => {
const cols: { prop: string; money: boolean }[] = [
{ prop: 'quoteNo', money: false },
{ prop: 'quoteTitle', money: false }
type StatsRowColumn = {
key: string
interactive: boolean
prop?: string
money?: boolean
}
/** 与主表列顺序一致:展开、勾选占位 + 业务列 */
const statsRowColumns = computed((): StatsRowColumn[] => {
const cols: StatsRowColumn[] = [
{ key: '__expand', interactive: false },
{ key: '__selection', interactive: false },
{ key: 'quoteNo', interactive: true, prop: 'quoteNo', money: false },
{ key: 'quoteTitle', interactive: true, prop: 'quoteTitle', money: false }
]
for (const def of listColumnDefs) {
if (!isColumnVisible(def.prop)) continue
cols.push({
key: def.prop,
interactive: true,
prop: def.prop,
money: QUOTE_MONEY_STAT_PROPS.has(def.prop)
money: QUOTE_MONEY_STAT_PROPS.has(def.prop),
...(QUOTE_MONEY_STAT_PROPS.has(def.prop) ? { align: 'right' as const } : {})
})
}
return cols
@@ -1935,24 +1960,30 @@ function onSelectColumnStat(prop: string, method: ColumnStatMethod | '') {
saveColumnStatConfig(columnStatConfig.value)
}
function onStatCommand(prop: string, cmd: string | number) {
onSelectColumnStat(
prop,
(cmd === '' || cmd === 'sum' || cmd === 'avg' || cmd === 'max' || cmd === 'min'
? cmd
: '') as ColumnStatMethod | ''
)
const statsMenuOpenProp = ref<string | null>(null)
function setStatsMenuOpen(prop: string, visible: boolean) {
statsMenuOpenProp.value = visible ? prop : statsMenuOpenProp.value === prop ? null : statsMenuOpenProp.value
}
function pickColumnStat(prop: string, method: ColumnStatMethod | '') {
onSelectColumnStat(prop, method)
statsMenuOpenProp.value = null
}
const quoteTableWrapRef = ref<HTMLElement | null>(null)
const quoteStatsScrollRef = ref<HTMLElement | null>(null)
let quoteStatsScrollSyncing = false
let quoteHeaderResizeObserver: ResizeObserver | null = null
let quoteTableScrollElBound: HTMLElement | null = null
function getQuoteMainTableEl(): Element | null {
function getQuoteMainTableEl(): HTMLElement | null {
const wrap = quoteTableWrapRef.value
if (!wrap) return null
return wrap.querySelector(':scope > .el-table') || wrap.querySelector('.el-table')
return (
(wrap.querySelector(':scope > .el-table') as HTMLElement | null) ||
(wrap.querySelector('.el-table') as HTMLElement | null)
)
}
function getQuoteTableScrollEl(): HTMLElement | null {
@@ -1964,22 +1995,67 @@ function getQuoteTableScrollEl(): HTMLElement | null {
)
}
function syncStatsColumnWidths() {
function getQuoteHeaderWidthSources(): number[] {
const table = getQuoteMainTableEl()
if (!table) return
const headerCells = table.querySelectorAll('.el-table__header-wrapper th')
const cells = quoteTableWrapRef.value?.querySelectorAll(
'.quote-list-stats-row__scroll .quote-list-stats-row__cell'
)
if (!cells) return
const offset = 2
cells.forEach((el, i) => {
const th = headerCells[i + offset] as HTMLElement | undefined
if (!th) return
;(el as HTMLElement).style.flex = 'none'
;(el as HTMLElement).style.width = `${th.offsetWidth}px`
;(el as HTMLElement).style.minWidth = `${th.offsetWidth}px`
if (!table) return []
// 优先用 header colgroup(与实际列宽一致,并跳过 gutter)
const cols = table.querySelectorAll('.el-table__header colgroup col')
const fromCols: number[] = []
cols.forEach((col) => {
const el = col as HTMLElement
if (el.getAttribute('name') === 'gutter') return
const w = el.getBoundingClientRect().width || Number.parseFloat(el.getAttribute('width') || '') || 0
if (w > 0) fromCols.push(w)
})
if (fromCols.length >= statsRowColumns.value.length) return fromCols
const ths = table.querySelectorAll('.el-table__header-wrapper th.el-table__cell')
const fromThs: number[] = []
ths.forEach((th) => {
const el = th as HTMLElement
if (el.classList.contains('gutter')) return
const w = el.getBoundingClientRect().width
if (w > 0) fromThs.push(w)
})
return fromThs
}
function syncStatsColumnWidths() {
const widths = getQuoteHeaderWidthSources()
const aligns = getTableColumnTextAligns(getQuoteMainTableEl())
const inner = quoteStatsScrollRef.value?.querySelector(
'.quote-list-stats-row__inner'
) as HTMLElement | null
const cells = quoteStatsScrollRef.value?.querySelectorAll('.quote-list-stats-row__cell')
if (!inner || !cells?.length || !widths.length) return
const cols = statsRowColumns.value
const count = Math.min(cells.length, widths.length, cols.length)
let total = 0
for (let i = 0; i < count; i++) {
const w = Math.round(widths[i])
total += w
const el = cells[i] as HTMLElement
el.style.flex = 'none'
el.style.width = `${w}px`
el.style.minWidth = `${w}px`
el.style.maxWidth = `${w}px`
applyStatsCellAlignStyles(
el,
resolveStatsCellAlign(cols[i], aligns[i]),
'.quote-list-stats-row__trigger'
)
}
inner.style.width = `${total}px`
inner.style.minWidth = `${total}px`
bindQuoteTableScrollListener()
const tableScroll = getQuoteTableScrollEl()
const statsScroll = quoteStatsScrollRef.value
if (tableScroll && statsScroll) {
statsScroll.scrollLeft = tableScroll.scrollLeft
}
}
function scheduleSyncStatsColumnWidths() {
@@ -2000,11 +2076,22 @@ function ensureQuoteHeaderResizeObserver() {
syncStatsColumnWidths()
})
quoteHeaderResizeObserver.observe(header)
header.querySelectorAll('th').forEach((th) => {
header.querySelectorAll('th.el-table__cell').forEach((th) => {
if ((th as HTMLElement).classList.contains('gutter')) return
quoteHeaderResizeObserver?.observe(th)
})
}
function bindQuoteTableScrollListener() {
const el = getQuoteTableScrollEl()
if (!el || el === quoteTableScrollElBound) return
if (quoteTableScrollElBound) {
quoteTableScrollElBound.removeEventListener('scroll', onQuoteTableScroll)
}
quoteTableScrollElBound = el
el.addEventListener('scroll', onQuoteTableScroll, { passive: true })
}
function onQuoteHeaderDragEnd() {
scheduleSyncStatsColumnWidths()
}
@@ -2036,7 +2123,7 @@ function onStatsRowScroll() {
}
watch(
[statsBusinessColumns, quoteList, visibleColumns],
[statsRowColumns, quoteList, visibleColumns],
() => {
scheduleSyncStatsColumnWidths()
},
@@ -2963,8 +3050,9 @@ watchDebounced(
onMounted(() => {
getList();
scheduleSyncStatsColumnWidths();
// ListTable 会在挂载后异步回写持久化列宽,补一次对齐
// ListTable 会在挂载后异步回写持久化列宽,补几次对齐
setTimeout(() => scheduleSyncStatsColumnWidths(), 150);
setTimeout(() => scheduleSyncStatsColumnWidths(), 400);
window.addEventListener('resize', scheduleSyncStatsColumnWidths);
});
@@ -2972,6 +3060,10 @@ onUnmounted(() => {
window.removeEventListener('resize', scheduleSyncStatsColumnWidths);
quoteHeaderResizeObserver?.disconnect();
quoteHeaderResizeObserver = null;
if (quoteTableScrollElBound) {
quoteTableScrollElBound.removeEventListener('scroll', onQuoteTableScroll);
quoteTableScrollElBound = null;
}
});
</script>
@@ -3285,50 +3377,76 @@ onUnmounted(() => {
}
.quote-list-stats-row {
display: flex;
align-items: stretch;
position: relative;
z-index: 5;
overflow-x: auto;
overflow-y: hidden;
border-top: 2px solid var(--el-color-primary, #10b981);
background: var(--mint-primary-bg, #ecfdf5);
font-weight: 600;
color: var(--mint-text, #1e293b);
min-height: 44px;
overflow: hidden;
/* 隐藏自身滚动条,横向位置跟主表同步 */
scrollbar-width: none;
}
.quote-list-stats-row__fixed {
display: flex;
flex-shrink: 0;
.quote-list-stats-row::-webkit-scrollbar {
display: none;
}
.quote-list-stats-row__scroll {
.quote-list-stats-row__inner {
display: flex;
flex: 1;
min-width: 0;
overflow-x: auto;
align-items: stretch;
min-height: 44px;
box-sizing: border-box;
}
.quote-list-stats-row__cell {
display: flex;
align-items: center;
justify-content: center;
padding: 8px 10px;
justify-content: flex-start;
padding: 0 8px;
box-sizing: border-box;
border-right: 1px solid var(--mint-border, #e2e8f0);
flex: none;
overflow: hidden;
}
.quote-list-stats-row__cell.is-stat {
flex: 1 1 120px;
min-width: 120px;
.quote-list-stats-row__cell.is-align-left {
justify-content: flex-start;
}
.quote-list-stats-row__cell.is-align-center {
justify-content: center;
}
.quote-list-stats-row__cell.is-align-right {
justify-content: flex-end;
}
.quote-list-stats-row__cell.is-spacer {
pointer-events: none;
}
.quote-list-stats-row__trigger {
cursor: pointer;
display: block;
box-sizing: border-box;
width: 100%;
min-height: 28px;
margin: 0;
padding: 4px 0;
border: 0;
background: transparent;
cursor: pointer;
text-align: left;
line-height: 1.4;
font-size: 13px;
font-weight: inherit;
color: inherit;
outline: none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.quote-list-stats-row__trigger.is-empty {
@@ -3336,3 +3454,43 @@ onUnmounted(() => {
font-weight: 500;
}
</style>
<style lang="scss">
/* teleported 到 body,需非 scoped */
.quote-list-stats-dropdown {
z-index: 4000 !important;
padding: 6px !important;
}
.quote-list-stats-menu {
display: flex;
flex-direction: column;
gap: 2px;
}
.quote-list-stats-menu__item {
display: block;
width: 100%;
margin: 0;
padding: 8px 10px;
border: 0;
border-radius: 6px;
background: transparent;
color: #1e293b;
font-size: 13px;
text-align: left;
cursor: pointer;
line-height: 1.3;
}
.quote-list-stats-menu__item:hover {
background: #ecfdf5;
color: #059669;
}
.quote-list-stats-menu__item.is-active {
background: #d1fae5;
color: #059669;
font-weight: 600;
}
</style>
@@ -56,3 +56,15 @@ describe('setColumnStatMethod', () => {
assert.deepEqual(b, {})
})
})
describe('resolveStatsCellAlign', () => {
it('prefers explicit align, then money right, then column align', async () => {
const { resolveStatsCellAlign } = await import('./quoteListColumnStats')
assert.equal(resolveStatsCellAlign({ align: 'right' }, 'left'), 'right')
assert.equal(resolveStatsCellAlign({ money: true }, 'center'), 'right')
assert.equal(resolveStatsCellAlign({}, 'right'), 'right')
assert.equal(resolveStatsCellAlign({}, 'center'), 'center')
assert.equal(resolveStatsCellAlign({ money: true }), 'right')
assert.equal(resolveStatsCellAlign({}), 'left')
})
})
@@ -1,23 +1,27 @@
export type ColumnStatMethod = 'sum' | 'avg' | 'max' | 'min'
/** @deprecated 请优先使用 `@/utils/list-column-stats`;本文件保留 quote 兼容导出 */
export {
aggregateColumnValues,
applyStatsCellAlignStyles,
buildStatsRowColumns,
COLUMN_STAT_METHOD_LABEL,
COLUMN_STAT_METHOD_OPTIONS,
formatColumnStatDisplay,
formatStatNumberResult,
getTableColumnTextAligns,
loadColumnStatConfig,
normalizeCssTextAlign,
parseStatNumber,
resolveStatsCellAlign,
saveColumnStatConfig,
setColumnStatMethod,
type ColumnStatConfigMap,
type ColumnStatMethod,
type StatsCellAlign,
type StatsRowColumn
} from '@/utils/list-column-stats'
export const COLUMN_STAT_STORAGE_KEY = 'crm-quote-column-stats'
export const COLUMN_STAT_METHOD_OPTIONS: { value: ColumnStatMethod | ''; label: string }[] = [
{ value: '', label: '无' },
{ value: 'sum', label: '求和' },
{ value: 'avg', label: '平均' },
{ value: 'max', label: '最大值' },
{ value: 'min', label: '最小值' }
]
export const COLUMN_STAT_METHOD_LABEL: Record<ColumnStatMethod, string> = {
sum: '求和',
avg: '平均',
max: '最大值',
min: '最小值'
}
/** 列表中按金额格式展示的列 prop */
export const QUOTE_MONEY_STAT_PROPS = new Set([
'discountAmount',
'finalAmount',
@@ -25,128 +29,3 @@ export const QUOTE_MONEY_STAT_PROPS = new Set([
'freight',
'barrelDeposit'
])
export function parseStatNumber(raw: unknown): number | null {
if (raw == null || raw === '') return null
if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null
let s = String(raw).trim()
if (!s) return null
s = s.replace(/^¥/, '').replace(/%$/, '').replace(/,/g, '')
const n = Number(s)
return Number.isFinite(n) ? n : null
}
function nonEmptyString(raw: unknown): string | null {
if (raw == null) return null
const s = String(raw).trim()
return s ? s : null
}
export function aggregateColumnValues(
values: unknown[],
method: ColumnStatMethod
): number | string | null {
const nums: number[] = []
const strs: string[] = []
for (const v of values) {
const n = parseStatNumber(v)
if (n != null) nums.push(n)
else {
const s = nonEmptyString(v)
if (s != null) strs.push(s)
}
}
if (method === 'sum') {
if (!nums.length) return null
return nums.reduce((a, b) => a + b, 0)
}
if (method === 'avg') {
if (!nums.length) return null
return nums.reduce((a, b) => a + b, 0) / nums.length
}
if (method === 'max') {
if (nums.length) return Math.max(...nums)
if (strs.length) return strs.reduce((a, b) => (a >= b ? a : b))
return null
}
// min
if (nums.length) return Math.min(...nums)
if (strs.length) return strs.reduce((a, b) => (a <= b ? a : b))
return null
}
export function formatStatNumberResult(
value: number,
opts: { money?: boolean } = {}
): string {
if (opts.money) {
return value.toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
}
if (Number.isInteger(value)) return String(value)
return value.toLocaleString('zh-CN', { maximumFractionDigits: 4 })
}
/**
* 生成合计格展示文案。method 为空则返回 ''。
* 聚合结果为 null →「{标签} -」
*/
export function formatColumnStatDisplay(
method: ColumnStatMethod | '' | null | undefined,
values: unknown[],
opts: { money?: boolean } = {}
): string {
if (!method) return ''
const label = COLUMN_STAT_METHOD_LABEL[method]
const agg = aggregateColumnValues(values, method)
if (agg == null) return `${label} -`
if (typeof agg === 'number') {
return `${label} ${formatStatNumberResult(agg, opts)}`
}
return `${label} ${agg}`
}
export type ColumnStatConfigMap = Partial<Record<string, ColumnStatMethod>>
export function loadColumnStatConfig(
storageKey: string = COLUMN_STAT_STORAGE_KEY
): ColumnStatConfigMap {
try {
const raw = localStorage.getItem(storageKey)
if (!raw) return {}
const parsed = JSON.parse(raw) as Record<string, unknown>
if (!parsed || typeof parsed !== 'object') return {}
const out: ColumnStatConfigMap = {}
for (const [k, v] of Object.entries(parsed)) {
if (v === 'sum' || v === 'avg' || v === 'max' || v === 'min') out[k] = v
}
return out
} catch {
return {}
}
}
export function saveColumnStatConfig(
config: ColumnStatConfigMap,
storageKey: string = COLUMN_STAT_STORAGE_KEY
): void {
const cleaned: ColumnStatConfigMap = {}
for (const [k, v] of Object.entries(config)) {
if (v === 'sum' || v === 'avg' || v === 'max' || v === 'min') cleaned[k] = v
}
localStorage.setItem(storageKey, JSON.stringify(cleaned))
}
export function setColumnStatMethod(
config: ColumnStatConfigMap,
prop: string,
method: ColumnStatMethod | ''
): ColumnStatConfigMap {
const next = { ...config }
if (!method) delete next[prop]
else next[prop] = method
return next
}