Просмотр исходного кода

feat(crm): add quote list column stats helpers

Pure aggregation, display formatting, and localStorage helpers
for the quote list configurable summary row.

Co-authored-by: Cursor <cursoragent@cursor.com>
zlwu 3 месяцев назад
Родитель
Сommit
6ce7554557

+ 58 - 0
web-admin/src/views/crm/quote/quoteListColumnStats.test.ts

@@ -0,0 +1,58 @@
+import assert from 'node:assert/strict'
+import { describe, it } from 'node:test'
+import {
+  aggregateColumnValues,
+  formatColumnStatDisplay,
+  parseStatNumber,
+  setColumnStatMethod
+} from './quoteListColumnStats'
+
+describe('parseStatNumber', () => {
+  it('parses plain and money-like strings', () => {
+    assert.equal(parseStatNumber(12.5), 12.5)
+    assert.equal(parseStatNumber('¥1,234.50'), 1234.5)
+    assert.equal(parseStatNumber('10%'), 10)
+    assert.equal(parseStatNumber('abc'), null)
+    assert.equal(parseStatNumber(''), null)
+  })
+})
+
+describe('aggregateColumnValues', () => {
+  it('sum and avg over numbers only', () => {
+    assert.equal(aggregateColumnValues([1, 2, 'x', null], 'sum'), 3)
+    assert.equal(aggregateColumnValues([1, 3], 'avg'), 2)
+    assert.equal(aggregateColumnValues(['a', 'b'], 'sum'), null)
+  })
+
+  it('max/min prefer numbers then lexicographic strings', () => {
+    assert.equal(aggregateColumnValues([1, 9, 3], 'max'), 9)
+    assert.equal(aggregateColumnValues([1, 9, 3], 'min'), 1)
+    assert.equal(aggregateColumnValues(['张三', '李四'], 'max'), '李四')
+    assert.equal(aggregateColumnValues(['张三', '李四'], 'min'), '张三')
+    assert.equal(aggregateColumnValues([null, ''], 'max'), null)
+  })
+})
+
+describe('formatColumnStatDisplay', () => {
+  it('empty method yields empty string', () => {
+    assert.equal(formatColumnStatDisplay('', [1, 2]), '')
+  })
+
+  it('formats money sum and dash for non-numeric sum', () => {
+    assert.equal(
+      formatColumnStatDisplay('sum', [1000, 234.5], { money: true }),
+      '求和 1,234.50'
+    )
+    assert.equal(formatColumnStatDisplay('sum', ['甲', '乙']), '求和 -')
+    assert.equal(formatColumnStatDisplay('max', ['甲', '乙']), '最大值 甲')
+  })
+})
+
+describe('setColumnStatMethod', () => {
+  it('sets and clears props', () => {
+    const a = setColumnStatMethod({}, 'totalAmount', 'sum')
+    assert.deepEqual(a, { totalAmount: 'sum' })
+    const b = setColumnStatMethod(a, 'totalAmount', '')
+    assert.deepEqual(b, {})
+  })
+})

+ 152 - 0
web-admin/src/views/crm/quote/quoteListColumnStats.ts

@@ -0,0 +1,152 @@
+export type ColumnStatMethod = 'sum' | 'avg' | 'max' | 'min'
+
+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',
+  'totalAmount',
+  '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
+}