feat: 优化工作台kpi卡片

This commit is contained in:
2026-08-12 22:35:02 +08:00
parent 4e343bd83c
commit 055367bbd4
5 changed files with 636 additions and 331 deletions
@@ -1,30 +1,30 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { WorkbenchVO } from '#/api/ecommerce/workbench/types'; import type { WorkbenchVO } from '#/api/ecommerce/workbench/types';
import type { FinanceKpiCardId } from '../kpi-catalog';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'; import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { Tooltip } from 'ant-design-vue'; import { Popover, Tooltip } from 'ant-design-vue';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue'; import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import { formatYuanDetail, yuanToWanNum } from '../../../utils/money'; import { formatYuanDetail, yuanToWanNum } from '../../../utils/money';
import { getFinanceKpiHint } from '../finance-kpi-hints';
import { import {
catalogLabels, cardById,
clampFinanceKpiColsPerRow, clampFinanceKpiColsPerRow,
kpiMetaByLabel, kpiMetaByLabel,
sortLabelsByCatalog, normalizePrimary,
sortCardIdsByCatalog,
} from '../kpi-catalog'; } from '../kpi-catalog';
import { getFinanceKpiHint } from '../finance-kpi-hints';
defineOptions({ name: 'WorkbenchFinanceKpiGrid' }); defineOptions({ name: 'WorkbenchFinanceKpiGrid' });
const props = defineProps<{ const props = defineProps<{
kpis: WorkbenchVO.KpiItem[]; kpis: WorkbenchVO.KpiItem[];
/** 用户勾选的 KPI label 列表 */ visibleCardIds: string[];
visibleLabels: string[]; primaryByCardId: Record<string, string>;
/** 与汇总表一致,用于「税额」列说明 */
taxRate?: number; taxRate?: number;
/** 每行卡片数(来自用户设置) */
colsPerRow?: number; colsPerRow?: number;
momCompareDateStart?: string | null; momCompareDateStart?: string | null;
momCompareDateEnd?: string | null; momCompareDateEnd?: string | null;
@@ -32,32 +32,50 @@ const props = defineProps<{
yoyCompareDateEnd?: string | null; yoyCompareDateEnd?: string | null;
}>(); }>();
const displayOrder = computed(() => { const emit = defineEmits<{
const fromPrefs = sortLabelsByCatalog(props.visibleLabels); (e: 'set-primary', payload: { cardId: FinanceKpiCardId; metricLabel: string }): void;
if (fromPrefs.length > 0) return fromPrefs; }>();
return catalogLabels();
const kpiByLabel = computed(() => {
const map = new Map<string, WorkbenchVO.KpiItem>();
for (const k of props.kpis) {
if (k.label) map.set(k.label, k);
}
return map;
}); });
const orderedKpiRows = computed(() => { const orderedCards = computed(() => {
const byLabel = new Map(props.kpis.map((k) => [k.label, k])); const ids = sortCardIdsByCatalog(props.visibleCardIds);
const visibleSet = new Set(displayOrder.value); return ids
const ordered: WorkbenchVO.KpiItem[] = []; .map((id) => cardById(id))
for (const label of displayOrder.value) { .filter((c): c is NonNullable<typeof c> => !!c)
const k = byLabel.get(label); .map((card) => {
if (k) ordered.push(k); const primaryLabel = normalizePrimary(
} card,
for (const k of props.kpis) { props.primaryByCardId[card.id],
if (!visibleSet.has(k.label)) continue; );
if (!ordered.some((o) => o.label === k.label)) ordered.push(k); const primaryKpi = kpiByLabel.value.get(primaryLabel);
} const members = card.metrics
return ordered.map((kpi) => ({ .map((label) => ({
kpi, label,
meta: kpiMetaByLabel(kpi.label), kpi: kpiByLabel.value.get(label),
})); meta: kpiMetaByLabel(label),
isPrimary: label === primaryLabel,
}))
.filter((m) => m.kpi != null);
return {
card,
primaryLabel,
primaryKpi,
primaryMeta: kpiMetaByLabel(primaryLabel),
members,
};
})
.filter((row) => row.primaryKpi != null);
}); });
const showEmptyPrefsHint = computed( const showEmptyPrefsHint = computed(
() => props.kpis.length > 0 && props.visibleLabels.length === 0, () => props.kpis.length > 0 && props.visibleCardIds.length === 0,
); );
const MIN_CARD_WIDTH = 285; const MIN_CARD_WIDTH = 285;
@@ -87,8 +105,7 @@ onMounted(() => {
ensureObserving(); ensureObserving();
}); });
/** 数据加载后网格才可见,补上 ResizeObserver */ watch(orderedCards, () => {
watch(orderedKpiRows, () => {
nextTick(() => ensureObserving()); nextTick(() => ensureObserving());
}); });
@@ -99,7 +116,10 @@ onUnmounted(() => {
const effectiveCols = computed(() => { const effectiveCols = computed(() => {
const pref = gridColumnCount.value; const pref = gridColumnCount.value;
const maxFit = Math.max(1, Math.floor((containerWidth.value + GRID_GAP) / (MIN_CARD_WIDTH + GRID_GAP))); const maxFit = Math.max(
1,
Math.floor((containerWidth.value + GRID_GAP) / (MIN_CARD_WIDTH + GRID_GAP)),
);
return Math.min(pref, maxFit); return Math.min(pref, maxFit);
}); });
@@ -112,7 +132,6 @@ function compareRangeHint(start?: string | null, end?: string | null): string {
return '对比区间未返回'; return '对比区间未返回';
} }
/** 主数字与单位分开展示,便于单位、环比胶囊紧跟数字 */
function primaryLine(kpi: WorkbenchVO.KpiItem): { function primaryLine(kpi: WorkbenchVO.KpiItem): {
display: string; display: string;
unitText: string; unitText: string;
@@ -141,6 +160,11 @@ function primaryLine(kpi: WorkbenchVO.KpiItem): {
}; };
} }
function compactValue(kpi: WorkbenchVO.KpiItem): string {
const line = primaryLine(kpi);
return line.unitText ? `${line.display}${line.unitText}` : line.display;
}
function trendIsGood(kpi: WorkbenchVO.KpiItem, up: boolean): boolean { function trendIsGood(kpi: WorkbenchVO.KpiItem, up: boolean): boolean {
const meta = kpiMetaByLabel(kpi.label); const meta = kpiMetaByLabel(kpi.label);
return meta.upIsGood ? up : !up; return meta.upIsGood ? up : !up;
@@ -160,6 +184,10 @@ function deltaTextClass(good: boolean): string {
: 'text-rose-600 dark:text-rose-400'; : 'text-rose-600 dark:text-rose-400';
} }
function onPickPrimary(cardId: FinanceKpiCardId, metricLabel: string) {
emit('set-primary', { cardId, metricLabel });
}
const cardShellClass = const cardShellClass =
'group flex min-h-[6.75rem] min-w-0 flex-col rounded-xl border border-slate-200/90 bg-gradient-to-b from-white to-slate-50/80 p-3.5 shadow-sm transition-[border-color,box-shadow] duration-200 hover:border-slate-300 hover:shadow-md dark:border-[hsl(240deg_3.7%_22%)] dark:from-[hsl(222.34deg_10.43%_12.27%)] dark:to-[hsl(222.34deg_10.43%_10%)] dark:shadow-none dark:hover:border-[hsl(240deg_3.7%_32%)]'; 'group flex min-h-[6.75rem] min-w-0 flex-col rounded-xl border border-slate-200/90 bg-gradient-to-b from-white to-slate-50/80 p-3.5 shadow-sm transition-[border-color,box-shadow] duration-200 hover:border-slate-300 hover:shadow-md dark:border-[hsl(240deg_3.7%_22%)] dark:from-[hsl(222.34deg_10.43%_12.27%)] dark:to-[hsl(222.34deg_10.43%_10%)] dark:shadow-none dark:hover:border-[hsl(240deg_3.7%_32%)]';
const labelClass = const labelClass =
@@ -181,10 +209,10 @@ const trendChipClass =
v-else-if="showEmptyPrefsHint" v-else-if="showEmptyPrefsHint"
class="rounded-xl border border-dashed border-amber-200 bg-amber-50/60 px-4 py-8 text-center text-sm text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300" class="rounded-xl border border-dashed border-amber-200 bg-amber-50/60 px-4 py-8 text-center text-sm text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300"
> >
未选择任何 KPI,请点击上方「KPI 显示设置」勾选要展示的指标。 未选择任何 KPI 卡片,请点击上方「KPI 显示设置」勾选要展示的卡片。
</div> </div>
<div <div
v-else-if="orderedKpiRows.length === 0" v-else-if="orderedCards.length === 0"
class="rounded-xl border border-dashed border-slate-200 bg-white/60 px-4 py-8 text-center text-sm text-slate-400 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:text-[hsl(240deg_5%_64.9%)]" class="rounded-xl border border-dashed border-slate-200 bg-white/60 px-4 py-8 text-center text-sm text-slate-400 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:text-[hsl(240deg_5%_64.9%)]"
> >
当前筛选下暂无已选 KPI 数据 当前筛选下暂无已选 KPI 数据
@@ -195,78 +223,164 @@ const trendChipClass =
class="grid gap-3" class="grid gap-3"
:style="gridStyle" :style="gridStyle"
> >
<div <Popover
v-for="{ kpi, meta } in orderedKpiRows" v-for="row in orderedCards"
:key="kpi.label" :key="row.card.id"
:class="cardShellClass" trigger="hover"
placement="bottom"
:mouse-enter-delay="0.15"
overlay-class-name="workbench-kpi-card-popover"
> >
<!-- 顶栏:左标题 / 右上角环比同比 --> <template #content>
<div class="mb-2 flex items-start justify-between gap-2"> <div class="w-[min(18rem,80vw)] space-y-1 py-0.5">
<div class="flex min-w-0 flex-1 items-center gap-1.5"> <p class="mb-1.5 px-1 text-[11px] text-slate-400">
<component 点击切换优先显示
:is="meta.icon" </p>
class="size-4 shrink-0 text-slate-400 dark:text-[hsl(240deg_5%_55%)]" <button
/> v-for="m in row.members"
<OverviewColumnHint :key="m.label"
class="min-w-0" type="button"
:title="getFinanceKpiHint(kpi.label, taxRate ?? 0.04)" class="flex w-full items-center justify-between gap-3 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-slate-100 dark:hover:bg-[hsl(240deg_3.7%_18%)]"
:class="
m.isPrimary
? 'bg-slate-100/80 dark:bg-[hsl(240deg_3.7%_16%)]'
: ''
"
@click="onPickPrimary(row.card.id, m.label)"
> >
<span :class="labelClass">{{ kpi.label }}</span> <span class="min-w-0 flex-1">
</OverviewColumnHint>
</div>
<div class="flex shrink-0 items-center gap-1">
<Tooltip
:title="compareRangeHint(momCompareDateStart, momCompareDateEnd)"
>
<span :class="trendChipClass">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_55%)]">环</span>
<span :class="deltaTextClass(trendIsGood(kpi, kpi.up === true))">
{{ formatDelta(kpi, kpi.changePct) }}
</span>
</span>
</Tooltip>
<Tooltip
v-if="kpi.yoyChangePct != null && kpi.yoyUp != null"
:title="compareRangeHint(yoyCompareDateStart, yoyCompareDateEnd)"
>
<span :class="trendChipClass">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_55%)]">同</span>
<span <span
:class="deltaTextClass(trendIsGood(kpi, kpi.yoyUp === true))" class="block truncate text-xs font-semibold text-slate-700 dark:text-[hsl(0deg_0%_90%)]"
> >
{{ formatDelta(kpi, kpi.yoyChangePct) }} {{ m.label }}
<span
v-if="m.isPrimary"
class="ml-1 text-[10px] font-medium text-blue-500"
>
当前
</span>
</span>
<span
v-if="m.kpi"
class="mt-0.5 block text-[11px] tabular-nums text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ compactValue(m.kpi) }}
<span
v-if="m.kpi.changePct != null"
class="ml-1"
:class="deltaTextClass(trendIsGood(m.kpi, m.kpi.up === true))"
>
环 {{ formatDelta(m.kpi, m.kpi.changePct) }}
</span>
</span> </span>
</span> </span>
</Tooltip> </button>
</div> </div>
</div> </template>
<!-- 主数字 + 单位紧跟 --> <div :class="cardShellClass">
<span class="inline-flex max-w-full items-baseline whitespace-nowrap"> <div class="mb-2 flex items-start justify-between gap-2">
<Tooltip v-if="primaryLine(kpi).hover" :title="primaryLine(kpi).hover"> <div class="flex min-w-0 flex-1 items-center gap-1.5">
<span <component
class="cursor-default tabular-nums text-2xl font-bold leading-none tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]" :is="row.primaryMeta.icon"
class="size-4 shrink-0 text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
/>
<OverviewColumnHint
class="min-w-0"
:title="getFinanceKpiHint(row.primaryLabel, taxRate ?? 0.04)"
>
<span :class="labelClass">
{{ row.card.title }}
<span class="font-normal text-slate-400">· {{ row.primaryLabel }}</span>
</span>
</OverviewColumnHint>
</div>
<div
v-if="row.primaryKpi"
class="flex shrink-0 items-center gap-1"
> >
{{ primaryLine(kpi).display }} <Tooltip
</span> :title="compareRangeHint(momCompareDateStart, momCompareDateEnd)"
</Tooltip> >
<span <span :class="trendChipClass">
v-else <span class="text-slate-400 dark:text-[hsl(240deg_5%_55%)]">环</span>
class="tabular-nums text-2xl font-bold leading-none tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]" <span
> :class="
{{ primaryLine(kpi).display }} deltaTextClass(
</span> trendIsGood(row.primaryKpi, row.primaryKpi.up === true),
<span v-if="primaryLine(kpi).unitText" :class="valueUnitClass"> )
{{ primaryLine(kpi).unitText }} "
</span> >
</span> {{ formatDelta(row.primaryKpi, row.primaryKpi.changePct) }}
</span>
</span>
</Tooltip>
<Tooltip
v-if="
row.primaryKpi.yoyChangePct != null &&
row.primaryKpi.yoyUp != null
"
:title="compareRangeHint(yoyCompareDateStart, yoyCompareDateEnd)"
>
<span :class="trendChipClass">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_55%)]">同</span>
<span
:class="
deltaTextClass(
trendIsGood(
row.primaryKpi,
row.primaryKpi.yoyUp === true,
),
)
"
>
{{ formatDelta(row.primaryKpi, row.primaryKpi.yoyChangePct) }}
</span>
</span>
</Tooltip>
</div>
</div>
<p <template v-if="row.primaryKpi">
v-if="kpi.sub" <span class="inline-flex max-w-full items-baseline whitespace-nowrap">
class="mt-1.5 w-full truncate text-right text-[11px] leading-snug text-slate-400 dark:text-[hsl(240deg_5%_55%)]" <Tooltip
> v-if="primaryLine(row.primaryKpi).hover"
{{ kpi.sub }} :title="primaryLine(row.primaryKpi).hover"
</p> >
</div> <span
class="cursor-default tabular-nums text-2xl font-bold leading-none tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
>
{{ primaryLine(row.primaryKpi).display }}
</span>
</Tooltip>
<span
v-else
class="tabular-nums text-2xl font-bold leading-none tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
>
{{ primaryLine(row.primaryKpi).display }}
</span>
<span
v-if="primaryLine(row.primaryKpi).unitText"
:class="valueUnitClass"
>
{{ primaryLine(row.primaryKpi).unitText }}
</span>
</span>
<p
v-if="row.primaryKpi.sub"
class="mt-1.5 w-full truncate text-right text-[11px] leading-snug text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
{{ row.primaryKpi.sub }}
</p>
<p
v-else-if="row.members.length > 1"
class="mt-1.5 w-full truncate text-right text-[11px] leading-snug text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
悬停查看同组 {{ row.members.length }} 项指标
</p>
</template>
</div>
</Popover>
</div> </div>
</template> </template>
@@ -1,17 +1,18 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { FinanceKpiGroupId } from '../kpi-catalog'; import type { FinanceKpiCardId } from '../kpi-catalog';
import { computed, ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { Button, Checkbox, message, Modal, Slider } from 'ant-design-vue'; import { Button, Checkbox, message, Modal, Radio, RadioGroup, Slider } from 'ant-design-vue';
import { import {
allCardIds,
clampFinanceKpiColsPerRow, clampFinanceKpiColsPerRow,
FINANCE_KPI_CATALOG, FINANCE_KPI_CARDS,
FINANCE_KPI_DEFAULT_COLS_PER_ROW, FINANCE_KPI_DEFAULT_COLS_PER_ROW,
FINANCE_KPI_DEFAULT_VISIBLE, FINANCE_KPI_DEFAULT_VISIBLE_CARDS,
FINANCE_KPI_GROUP_ORDER, normalizePrimary,
type FinanceKpiColsPerRow, type FinanceKpiColsPerRow,
} from '../kpi-catalog'; } from '../kpi-catalog';
@@ -19,96 +20,88 @@ defineOptions({ name: 'WorkbenchFinanceKpiSettingsModal' });
const props = defineProps<{ const props = defineProps<{
open: boolean; open: boolean;
visibleLabels: string[]; visibleCardIds: string[];
primaryByCardId: Record<string, string>;
colsPerRow: number; colsPerRow: number;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'update:open', v: boolean): void; (e: 'update:open', v: boolean): void;
(e: 'save', payload: { labels: string[]; colsPerRow: number }): void; (
e: 'save',
payload: {
visibleCardIds: string[];
primaryByCardId: Record<string, string>;
colsPerRow: number;
},
): void;
}>(); }>();
const IconSettings = createIconifyIcon('lucide:settings-2'); const IconSettings = createIconifyIcon('lucide:settings-2');
const draft = ref<string[]>([]); const draftVisible = ref<string[]>([]);
const draftPrimary = ref<Record<string, string>>({});
const draftColsPerRow = ref<FinanceKpiColsPerRow>(FINANCE_KPI_DEFAULT_COLS_PER_ROW); const draftColsPerRow = ref<FinanceKpiColsPerRow>(FINANCE_KPI_DEFAULT_COLS_PER_ROW);
function syncDraftFromProps() {
draftVisible.value = [...props.visibleCardIds];
draftPrimary.value = { ...props.primaryByCardId };
for (const card of FINANCE_KPI_CARDS) {
draftPrimary.value[card.id] = normalizePrimary(
card,
draftPrimary.value[card.id],
);
}
draftColsPerRow.value = clampFinanceKpiColsPerRow(props.colsPerRow);
}
watch( watch(
() => props.open, () => props.open,
(isOpen) => { (isOpen) => {
if (isOpen) { if (isOpen) syncDraftFromProps();
draft.value = [...props.visibleLabels];
draftColsPerRow.value = clampFinanceKpiColsPerRow(props.colsPerRow);
}
}, },
{ immediate: true }, { immediate: true },
); );
const grouped = computed(() => { function isChecked(id: string): boolean {
const map = new Map<FinanceKpiGroupId, { title: string; labels: string[] }>(); return draftVisible.value.includes(id);
for (const g of FINANCE_KPI_GROUP_ORDER) {
map.set(g, { title: '', labels: [] });
}
for (const item of FINANCE_KPI_CATALOG) {
const bucket = map.get(item.group)!;
if (!bucket.title) bucket.title = item.groupTitle;
bucket.labels.push(item.label);
}
return FINANCE_KPI_GROUP_ORDER.map((id) => ({
id,
title: map.get(id)!.title,
labels: map.get(id)!.labels,
})).filter((g) => g.labels.length > 0);
});
function isGroupAllChecked(labels: string[]): boolean {
return labels.every((l) => draft.value.includes(l));
} }
function isGroupIndeterminate(labels: string[]): boolean { function onCardCheck(id: FinanceKpiCardId, e: { target: { checked: boolean } }) {
const n = labels.filter((l) => draft.value.includes(l)).length; const set = new Set(draftVisible.value);
return n > 0 && n < labels.length; if (e.target.checked) set.add(id);
else set.delete(id);
draftVisible.value = [...set];
} }
function toggleGroup(labels: string[], checked: boolean) { function onPrimaryChange(cardId: FinanceKpiCardId, label: string) {
const set = new Set(draft.value); draftPrimary.value = { ...draftPrimary.value, [cardId]: label };
for (const l of labels) {
if (checked) set.add(l);
else set.delete(l);
}
draft.value = [...set];
}
function onCheckboxChange(label: string, checked: boolean) {
const set = new Set(draft.value);
if (checked) set.add(label);
else set.delete(label);
draft.value = [...set];
}
function onGroupCheckboxChange(labels: string[], e: { target: { checked: boolean } }) {
toggleGroup(labels, e.target.checked);
}
function onItemCheckboxChange(label: string, e: { target: { checked: boolean } }) {
onCheckboxChange(label, e.target.checked);
} }
function applyDefaultCore() { function applyDefaultCore() {
draft.value = [...FINANCE_KPI_DEFAULT_VISIBLE]; draftVisible.value = [...FINANCE_KPI_DEFAULT_VISIBLE_CARDS];
const primaries: Record<string, string> = {};
for (const card of FINANCE_KPI_CARDS) {
primaries[card.id] = card.defaultPrimary;
}
draftPrimary.value = primaries;
draftColsPerRow.value = FINANCE_KPI_DEFAULT_COLS_PER_ROW; draftColsPerRow.value = FINANCE_KPI_DEFAULT_COLS_PER_ROW;
} }
function applySelectAll() { function applySelectAll() {
draft.value = FINANCE_KPI_CATALOG.map((c) => c.label); draftVisible.value = allCardIds();
} }
function handleOk() { function handleOk() {
if (draft.value.length === 0) { if (draftVisible.value.length === 0) {
message.warning('请至少选择一项 KPI'); message.warning('请至少选择一张 KPI 卡片');
return; return;
} }
emit('save', { labels: draft.value, colsPerRow: draftColsPerRow.value }); emit('save', {
visibleCardIds: draftVisible.value,
primaryByCardId: draftPrimary.value,
colsPerRow: draftColsPerRow.value,
});
emit('update:open', false); emit('update:open', false);
} }
@@ -128,13 +121,16 @@ function handleCancel() {
> >
<template #title> <template #title>
<span class="inline-flex flex-nowrap items-center gap-2 whitespace-nowrap"> <span class="inline-flex flex-nowrap items-center gap-2 whitespace-nowrap">
<component :is="IconSettings" class="size-[1.125rem] shrink-0 text-slate-500" /> <component
:is="IconSettings"
class="size-[1.125rem] shrink-0 text-slate-500"
/>
<span class="shrink-0">KPI 显示设置</span> <span class="shrink-0">KPI 显示设置</span>
</span> </span>
</template> </template>
<p class="mb-4 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"> <p class="mb-4 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
勾选要在经营概览中展示的指标,并可调整最多列数;设置保存在本浏览器。 勾选要展示的卡片,并为每张卡选择优先显示的指标;悬停卡片可临时切换。设置保存在本浏览器。
</p> </p>
<div <div
@@ -152,52 +148,69 @@ function handleCancel() {
:marks="{ 3: '3', 4: '4', 5: '5', 6: '6' }" :marks="{ 3: '3', 4: '4', 5: '5', 6: '6' }"
class="flex-1" class="flex-1"
/> />
<span class="min-w-[3ch] text-center text-sm font-bold text-slate-700 dark:text-[hsl(0deg_0%_90%)]"> <span
class="min-w-[3ch] text-center text-sm font-bold text-slate-700 dark:text-[hsl(0deg_0%_90%)]"
>
{{ draftColsPerRow }} 列 {{ draftColsPerRow }} 列
</span> </span>
</div> </div>
</div> </div>
<div class="mb-4 flex flex-wrap gap-2"> <div class="mb-4 flex flex-wrap gap-2">
<Button size="small" @click="applySelectAll">全选</Button> <Button size="small" @click="applySelectAll">全选卡片</Button>
<Button size="small" @click="applyDefaultCore">恢复默认(8 项)</Button> <Button size="small" @click="applyDefaultCore">恢复默认</Button>
</div> </div>
<div class="max-h-[min(60vh,28rem)] space-y-5 overflow-y-auto pr-1"> <div class="max-h-[min(60vh,32rem)] space-y-3 overflow-y-auto pr-1">
<section <section
v-for="group in grouped" v-for="card in FINANCE_KPI_CARDS"
:key="group.id" :key="card.id"
class="rounded-xl border border-slate-100 bg-slate-50/80 p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_12%)]" class="rounded-xl border border-slate-100 bg-slate-50/80 p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_12%)]"
> >
<div class="mb-3 flex items-center gap-2"> <div class="mb-3 flex items-center gap-2">
<Checkbox <Checkbox
:checked="isGroupAllChecked(group.labels)" :checked="isChecked(card.id)"
:indeterminate="isGroupIndeterminate(group.labels)" @change="(e) => onCardCheck(card.id, e)"
@change="(e) => onGroupCheckboxChange(group.labels, e)"
> >
<span class="font-semibold text-slate-700 dark:text-[hsl(0deg_0%_90%)]"> <span
{{ group.title }} class="inline-flex items-center gap-1.5 font-semibold text-slate-700 dark:text-[hsl(0deg_0%_90%)]"
>
<component
:is="card.icon"
class="size-4 text-slate-400"
/>
{{ card.title }}
</span> </span>
</Checkbox> </Checkbox>
</div> </div>
<div class="grid grid-cols-2 gap-x-4 gap-y-2 sm:grid-cols-3"> <div
<Checkbox class="pl-6"
v-for="label in group.labels" :class="isChecked(card.id) ? 'opacity-100' : 'pointer-events-none opacity-45'"
:key="label" >
:checked="draft.includes(label)" <p class="mb-2 text-[11px] text-slate-400">优先显示</p>
@change="(e) => onItemCheckboxChange(label, e)" <RadioGroup
:value="draftPrimary[card.id]"
size="small"
class="flex flex-wrap gap-x-3 gap-y-2"
@update:value="(v: string) => onPrimaryChange(card.id, v)"
> >
<span class="text-sm">{{ label }}</span> <Radio
</Checkbox> v-for="label in card.metrics"
:key="label"
:value="label"
>
<span class="text-sm">{{ label }}</span>
</Radio>
</RadioGroup>
</div> </div>
</section> </section>
</div> </div>
<p <p
v-if="draft.length === 0" v-if="draftVisible.length === 0"
class="mt-3 text-sm text-amber-600 dark:text-amber-400" class="mt-3 text-sm text-amber-600 dark:text-amber-400"
> >
请至少选择一项指标,否则概览区将无 KPI 卡片。 请至少选择一张卡片,否则概览区将无 KPI。
</p> </p>
</Modal> </Modal>
</template> </template>
@@ -13,8 +13,8 @@ import FinanceKpiSettingsModal from './components/FinanceKpiSettingsModal.vue';
import FinanceTrendChart from './components/FinanceTrendChart.vue'; import FinanceTrendChart from './components/FinanceTrendChart.vue';
import OverviewTables from './components/OverviewTables.vue'; import OverviewTables from './components/OverviewTables.vue';
import { sortLabelsByCatalog } from './kpi-catalog';
import { useFinanceKpiPreferences } from './useFinanceKpiPreferences'; import { useFinanceKpiPreferences } from './useFinanceKpiPreferences';
import type { FinanceKpiCardId } from './kpi-catalog';
import { import {
buildCategoryOverviewFromDimRows, buildCategoryOverviewFromDimRows,
@@ -61,21 +61,34 @@ const productOverview = computed(
const IconSliders = createIconifyIcon('lucide:sliders-horizontal'); const IconSliders = createIconifyIcon('lucide:sliders-horizontal');
const { visibleLabels, colsPerRow, applySettings } = useFinanceKpiPreferences(); const {
visibleCardIds,
primaryByCardId,
colsPerRow,
applySettings,
setCardPrimary,
} = useFinanceKpiPreferences();
const kpiSettingsOpen = ref(false); const kpiSettingsOpen = ref(false);
const visibleKpiCount = computed(() => visibleLabels.value.length); const visibleKpiCount = computed(() => visibleCardIds.value.length);
function onKpiSettingsSave(payload: { labels: string[]; colsPerRow: number }) { function onKpiSettingsSave(payload: {
const normalized = sortLabelsByCatalog(payload.labels); visibleCardIds: string[];
if (normalized.length === 0) { primaryByCardId: Record<string, string>;
message.warning('请至少选择一项 KPI'); colsPerRow: number;
}) {
if (payload.visibleCardIds.length === 0) {
message.warning('请至少选择一张 KPI 卡片');
return; return;
} }
applySettings(normalized, payload.colsPerRow); applySettings(payload);
message.success('KPI 显示已更新'); message.success('KPI 显示已更新');
} }
function onSetPrimary(payload: { cardId: FinanceKpiCardId; metricLabel: string }) {
setCardPrimary(payload.cardId, payload.metricLabel);
}
const trendChartRef = ref<InstanceType< const trendChartRef = ref<InstanceType<
typeof FinanceTrendChart typeof FinanceTrendChart
> | null>(null); > | null>(null);
@@ -98,7 +111,7 @@ defineExpose({ redraw });
<span class="text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"> <span class="text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
经营 KPI 经营 KPI
<span v-if="visibleKpiCount > 0" class="ml-1 text-slate-400"> <span v-if="visibleKpiCount > 0" class="ml-1 text-slate-400">
(已选 {{ visibleKpiCount }} 项 · 最多 {{ colsPerRow }} 列) (已选 {{ visibleKpiCount }} 张卡片 · 最多 {{ colsPerRow }} 列)
</span> </span>
</span> </span>
<Button <Button
@@ -115,18 +128,21 @@ defineExpose({ redraw });
<FinanceKpiSettingsModal <FinanceKpiSettingsModal
v-model:open="kpiSettingsOpen" v-model:open="kpiSettingsOpen"
:cols-per-row="colsPerRow" :cols-per-row="colsPerRow"
:visible-labels="visibleLabels" :visible-card-ids="visibleCardIds"
:primary-by-card-id="primaryByCardId"
@save="onKpiSettingsSave" @save="onKpiSettingsSave"
/> />
<FinanceKpiGrid <FinanceKpiGrid
:kpis="finance.kpis" :kpis="finance.kpis"
:cols-per-row="colsPerRow" :cols-per-row="colsPerRow"
:tax-rate="taxRate" :tax-rate="taxRate"
:visible-labels="visibleLabels" :visible-card-ids="visibleCardIds"
:primary-by-card-id="primaryByCardId"
:mom-compare-date-start="finance.momCompareDateStart" :mom-compare-date-start="finance.momCompareDateStart"
:mom-compare-date-end="finance.momCompareDateEnd" :mom-compare-date-end="finance.momCompareDateEnd"
:yoy-compare-date-start="finance.yoyCompareDateStart" :yoy-compare-date-start="finance.yoyCompareDateStart"
:yoy-compare-date-end="finance.yoyCompareDateEnd" :yoy-compare-date-end="finance.yoyCompareDateEnd"
@set-primary="onSetPrimary"
/> />
<div class="grid grid-cols-1 gap-6 xl:grid-cols-3"> <div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
<FinanceTrendChart <FinanceTrendChart
@@ -2,13 +2,14 @@ import type { Component } from 'vue';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
/** localStorage 键(本机浏览器) */ /** 旧版扁平偏好(迁移用) */
export const FINANCE_KPI_PREFS_KEY = 'workbench-finance-kpi-visible-v1'; export const FINANCE_KPI_PREFS_KEY_V1 = 'workbench-finance-kpi-visible-v1';
/** 每行 KPI 卡片数默认值 */ /** 复合卡偏好 */
export const FINANCE_KPI_DEFAULT_COLS_PER_ROW = 5; export const FINANCE_KPI_PREFS_KEY = 'workbench-finance-kpi-cards-v2';
export const FINANCE_KPI_DEFAULT_COLS_PER_ROW = 4;
/** 设置里可选的每行卡片数 */
export const FINANCE_KPI_COLS_PER_ROW_OPTIONS = [3, 4, 5, 6] as const; export const FINANCE_KPI_COLS_PER_ROW_OPTIONS = [3, 4, 5, 6] as const;
export type FinanceKpiColsPerRow = (typeof FINANCE_KPI_COLS_PER_ROW_OPTIONS)[number]; export type FinanceKpiColsPerRow = (typeof FINANCE_KPI_COLS_PER_ROW_OPTIONS)[number];
@@ -21,22 +22,15 @@ export function clampFinanceKpiColsPerRow(value: unknown): FinanceKpiColsPerRow
return FINANCE_KPI_DEFAULT_COLS_PER_ROW; return FINANCE_KPI_DEFAULT_COLS_PER_ROW;
} }
export type FinanceKpiGroupId = export type FinanceKpiCardId =
| 'gmv' | 'revenue'
| 'sales' | 'orders'
| 'net' | 'qty'
| 'aov'
| 'refund'
| 'cost' | 'cost'
| 'profit' | 'profit'
| 'ops'; | 'ads';
export type FinanceKpiCatalogItem = {
label: string;
group: FinanceKpiGroupId;
groupTitle: string;
/** 涨跌颜色:true=涨绿跌红,false=涨红跌绿(如退款率) */
upIsGood: boolean;
icon: Component;
};
const IconGmv = createIconifyIcon('lucide:layers'); const IconGmv = createIconifyIcon('lucide:layers');
const IconSales = createIconifyIcon('lucide:wallet'); const IconSales = createIconifyIcon('lucide:wallet');
@@ -57,78 +51,181 @@ const IconScale = createIconifyIcon('lucide:scale');
const IconReceipt = createIconifyIcon('lucide:receipt'); const IconReceipt = createIconifyIcon('lucide:receipt');
const IconDefault = createIconifyIcon('lucide:bar-chart-3'); const IconDefault = createIconifyIcon('lucide:bar-chart-3');
const G = { /** 单指标元数据(图标、涨跌语义);label 与后端 buildKpis 一致 */
gmv: 'GMV 口径', export type FinanceKpiMetricMeta = {
sales: '实际销售', label: string;
net: '净收与退款', upIsGood: boolean;
cost: '成本', icon: Component;
profit: '利润与费用', };
ops: '运营效率',
} as const;
/** 与后端 buildKpis 顺序一致,用于默认排序 */ export const FINANCE_KPI_METRIC_META: Record<string, FinanceKpiMetricMeta> = {
export const FINANCE_KPI_CATALOG: FinanceKpiCatalogItem[] = [ 总GMV: { label: '总GMV', upIsGood: true, icon: IconGmv },
{ label: '总GMV', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconGmv }, GMV单量: { label: 'GMV单量', upIsGood: true, icon: IconOrders },
{ label: 'GMV单量', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconOrders }, GMV销量: { label: 'GMV销量', upIsGood: true, icon: IconPackage },
{ label: 'GMV销量', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconPackage }, GMV客单价: { label: 'GMV客单价', upIsGood: true, icon: IconAov },
{ label: 'GMV客单价', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconAov }, GMV件单价: { label: 'GMV件单价', upIsGood: true, icon: IconReceipt },
{ label: 'GMV件单价', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconReceipt }, 实际销售额: { label: '实际销售额', upIsGood: true, icon: IconSales },
{ label: '实际销售额', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconSales }, 销售单量: { label: '销售单量', upIsGood: true, icon: IconOrders },
{ label: '销售单量', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconOrders }, 实际销量: { label: '实际销量', upIsGood: true, icon: IconPackage },
{ label: '实际销量', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconPackage }, 客单价: { label: '客单价', upIsGood: true, icon: IconAov },
{ label: '客单价', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconAov }, 销售件单价: { label: '销售件单价', upIsGood: true, icon: IconReceipt },
{ label: '销售件单价', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconReceipt }, 净销售额: { label: '净销售额', upIsGood: true, icon: IconNet },
{ label: '净销售额', group: 'net', groupTitle: G.net, upIsGood: true, icon: IconNet }, 退款额: { label: '退款额', upIsGood: false, icon: IconRefund },
{ label: '退款额', group: 'net', groupTitle: G.net, upIsGood: false, icon: IconRefund }, 退款率: { label: '退款率', upIsGood: false, icon: IconPercent },
{ label: '退款率', group: 'net', groupTitle: G.net, upIsGood: false, icon: IconPercent }, 'GMV与销售差额': { label: 'GMV与销售差额', upIsGood: true, icon: IconScale },
{ label: 'GMV与销售差额', group: 'net', groupTitle: G.net, upIsGood: true, icon: IconScale }, 订单成本: { label: '订单成本', upIsGood: false, icon: IconCost },
{ label: '订单成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconCost }, 商品成本: { label: '商品成本', upIsGood: false, icon: IconPackage },
{ label: '商品成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconPackage }, 运费成本: { label: '运费成本', upIsGood: false, icon: IconTruck },
{ label: '运费成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconTruck }, 其他成本: { label: '其他成本', upIsGood: false, icon: IconCost },
{ label: '其他成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconCost }, 毛利润: { label: '毛利润', upIsGood: true, icon: IconGross },
{ label: '毛利润', group: 'profit', groupTitle: G.profit, upIsGood: true, icon: IconGross }, 推广费: { label: '推广费', upIsGood: false, icon: IconMegaphone },
{ label: '推广费', group: 'profit', groupTitle: G.profit, upIsGood: false, icon: IconMegaphone }, 刷单费: { label: '刷单费', upIsGood: false, icon: IconBrush },
{ label: '刷单费', group: 'profit', groupTitle: G.profit, upIsGood: false, icon: IconBrush }, 税额: { label: '税额', upIsGood: false, icon: IconTax },
{ label: '税额', group: 'profit', groupTitle: G.profit, upIsGood: false, icon: IconTax }, 净利润: { label: '净利润', upIsGood: true, icon: IconNet },
{ label: '净利润', group: 'profit', groupTitle: G.profit, upIsGood: true, icon: IconNet }, 广告ROI: { label: '广告ROI', upIsGood: true, icon: IconRoi },
{ label: '广告ROI', group: 'ops', groupTitle: G.ops, upIsGood: true, icon: IconRoi }, };
export type FinanceKpiCardDef = {
id: FinanceKpiCardId;
title: string;
/** 可作主指标的后端 KPI label,顺序即悬停列表顺序 */
metrics: string[];
defaultPrimary: string;
icon: Component;
};
/** 复合卡目录(展示顺序) */
export const FINANCE_KPI_CARDS: FinanceKpiCardDef[] = [
{
id: 'revenue',
title: '销售额',
metrics: ['实际销售额', '总GMV', '净销售额', 'GMV与销售差额'],
defaultPrimary: '实际销售额',
icon: IconSales,
},
{
id: 'orders',
title: '单量',
metrics: ['销售单量', 'GMV单量'],
defaultPrimary: '销售单量',
icon: IconOrders,
},
{
id: 'qty',
title: '销量',
metrics: ['实际销量', 'GMV销量'],
defaultPrimary: '实际销量',
icon: IconPackage,
},
{
id: 'aov',
title: '客单价',
metrics: ['客单价', 'GMV客单价', '销售件单价', 'GMV件单价'],
defaultPrimary: '客单价',
icon: IconAov,
},
{
id: 'refund',
title: '退款',
metrics: ['退款率', '退款额'],
defaultPrimary: '退款率',
icon: IconRefund,
},
{
id: 'cost',
title: '成本',
metrics: ['订单成本', '商品成本', '运费成本', '其他成本'],
defaultPrimary: '订单成本',
icon: IconCost,
},
{
id: 'profit',
title: '利润',
metrics: ['净利润', '毛利润'],
defaultPrimary: '净利润',
icon: IconGross,
},
{
id: 'ads',
title: '投放',
metrics: ['广告ROI', '推广费', '刷单费', '税额'],
defaultPrimary: '广告ROI',
icon: IconRoi,
},
]; ];
/** 首次进入默认展示(与改版前 8 卡接近,订单量→销售单量) */ /** 默认展示的卡片(不含成本,减少噪音) */
export const FINANCE_KPI_DEFAULT_VISIBLE: string[] = [ export const FINANCE_KPI_DEFAULT_VISIBLE_CARDS: FinanceKpiCardId[] = [
'总GMV', 'revenue',
'实际销售额', 'orders',
'毛利润', 'aov',
'净利润', 'refund',
'销售单量',
'客单价',
'退款率',
'广告ROI',
];
export const FINANCE_KPI_GROUP_ORDER: FinanceKpiGroupId[] = [
'gmv',
'sales',
'net',
'cost',
'profit', 'profit',
'ops', 'ads',
]; ];
export function cardById(id: string): FinanceKpiCardDef | undefined {
return FINANCE_KPI_CARDS.find((c) => c.id === id);
}
export function allCardIds(): FinanceKpiCardId[] {
return FINANCE_KPI_CARDS.map((c) => c.id);
}
export function sortCardIdsByCatalog(ids: string[]): FinanceKpiCardId[] {
const set = new Set(ids);
return FINANCE_KPI_CARDS.map((c) => c.id).filter((id) => set.has(id));
}
export function normalizePrimary(
card: FinanceKpiCardDef,
primary: string | undefined | null,
): string {
if (primary && card.metrics.includes(primary)) return primary;
return card.defaultPrimary;
}
export function kpiMetaByLabel(label: string): Pick< export function kpiMetaByLabel(label: string): Pick<
FinanceKpiCatalogItem, FinanceKpiMetricMeta,
'icon' | 'upIsGood' 'icon' | 'upIsGood'
> { > {
const item = FINANCE_KPI_CATALOG.find((c) => c.label === label); const item = FINANCE_KPI_METRIC_META[label];
return item ?? { icon: IconDefault, upIsGood: true }; return item ?? { icon: IconDefault, upIsGood: true };
} }
export function catalogLabels(): string[] { /** 旧 v1 勾选 label → 应打开的卡片 id */
return FINANCE_KPI_CATALOG.map((c) => c.label); export function migrateV1LabelsToCardIds(labels: string[]): FinanceKpiCardId[] {
const mapped = new Set<FinanceKpiCardId>();
const labelSet = new Set(
labels.map((l) => (l === '订单量' ? '销售单量' : l)),
);
for (const card of FINANCE_KPI_CARDS) {
if (card.metrics.some((m) => labelSet.has(m))) {
mapped.add(card.id);
}
}
if (mapped.size === 0) {
return [...FINANCE_KPI_DEFAULT_VISIBLE_CARDS];
}
return sortCardIdsByCatalog([...mapped]);
} }
/** 按目录顺序排列可见 label */ /** 旧 v1:若勾选了某卡下多个指标,优先用「实际销售额」等默认偏好,否则取第一个命中的成员 */
export function sortLabelsByCatalog(visible: string[]): string[] { export function migrateV1PrimaryByCard(
const set = new Set(visible); labels: string[],
return FINANCE_KPI_CATALOG.map((c) => c.label).filter((l) => set.has(l)); ): Partial<Record<FinanceKpiCardId, string>> {
const labelSet = new Set(
labels.map((l) => (l === '订单量' ? '销售单量' : l)),
);
const out: Partial<Record<FinanceKpiCardId, string>> = {};
for (const card of FINANCE_KPI_CARDS) {
const hit = card.metrics.filter((m) => labelSet.has(m));
if (hit.length === 0) continue;
if (hit.includes(card.defaultPrimary)) {
out[card.id] = card.defaultPrimary;
} else {
out[card.id] = hit[0];
}
}
return out;
} }
@@ -1,96 +1,161 @@
import { ref } from 'vue'; import { ref } from 'vue';
import { import {
catalogLabels, allCardIds,
cardById,
clampFinanceKpiColsPerRow, clampFinanceKpiColsPerRow,
FINANCE_KPI_DEFAULT_COLS_PER_ROW, FINANCE_KPI_DEFAULT_COLS_PER_ROW,
FINANCE_KPI_DEFAULT_VISIBLE, FINANCE_KPI_DEFAULT_VISIBLE_CARDS,
FINANCE_KPI_PREFS_KEY, FINANCE_KPI_PREFS_KEY,
sortLabelsByCatalog, FINANCE_KPI_PREFS_KEY_V1,
migrateV1LabelsToCardIds,
migrateV1PrimaryByCard,
normalizePrimary,
sortCardIdsByCatalog,
type FinanceKpiCardId,
} from './kpi-catalog'; } from './kpi-catalog';
type PrefsPayload = { type PrefsV2 = {
version: 2;
visibleCardIds: string[];
primaryByCardId: Record<string, string>;
colsPerRow?: number;
};
type PrefsV1 = {
visibleLabels: string[]; visibleLabels: string[];
colsPerRow?: number; colsPerRow?: number;
}; };
function parseStored(): PrefsPayload | null { function defaultPrimaries(): Record<string, string> {
try { const out: Record<string, string> = {};
const raw = localStorage.getItem(FINANCE_KPI_PREFS_KEY); for (const id of allCardIds()) {
if (!raw) return null; const card = cardById(id)!;
const parsed = JSON.parse(raw) as PrefsPayload; out[id] = card.defaultPrimary;
if (!Array.isArray(parsed.visibleLabels)) return null;
return {
visibleLabels: parsed.visibleLabels
.filter((x) => typeof x === 'string')
.map((l) => (l === '订单量' ? '销售单量' : l)),
colsPerRow: parsed.colsPerRow,
};
} catch {
return null;
}
}
function normalizeVisible(labels: string[]): string[] {
const catalog = new Set(catalogLabels());
const seen = new Set<string>();
const out: string[] = [];
for (const label of labels) {
if (!catalog.has(label) || seen.has(label)) continue;
seen.add(label);
out.push(label);
} }
return out; return out;
} }
function normalizeVisibleCards(ids: string[]): FinanceKpiCardId[] {
return sortCardIdsByCatalog(ids);
}
function normalizePrimaries(
raw: Record<string, string> | undefined,
): Record<string, string> {
const base = defaultPrimaries();
if (!raw) return base;
for (const id of allCardIds()) {
const card = cardById(id)!;
base[id] = normalizePrimary(card, raw[id]);
}
return base;
}
function loadFromStorage(): {
visibleCardIds: FinanceKpiCardId[];
primaryByCardId: Record<string, string>;
colsPerRow: number;
} {
try {
const rawV2 = localStorage.getItem(FINANCE_KPI_PREFS_KEY);
if (rawV2) {
const parsed = JSON.parse(rawV2) as PrefsV2;
if (Array.isArray(parsed.visibleCardIds)) {
return {
visibleCardIds: normalizeVisibleCards(parsed.visibleCardIds),
primaryByCardId: normalizePrimaries(parsed.primaryByCardId),
colsPerRow: clampFinanceKpiColsPerRow(
parsed.colsPerRow ?? FINANCE_KPI_DEFAULT_COLS_PER_ROW,
),
};
}
}
} catch {
// fall through
}
try {
const rawV1 = localStorage.getItem(FINANCE_KPI_PREFS_KEY_V1);
if (rawV1) {
const parsed = JSON.parse(rawV1) as PrefsV1;
if (Array.isArray(parsed.visibleLabels)) {
const visibleCardIds = migrateV1LabelsToCardIds(parsed.visibleLabels);
const migratedPrimary = migrateV1PrimaryByCard(parsed.visibleLabels);
return {
visibleCardIds,
primaryByCardId: normalizePrimaries(migratedPrimary),
colsPerRow: clampFinanceKpiColsPerRow(
parsed.colsPerRow ?? FINANCE_KPI_DEFAULT_COLS_PER_ROW,
),
};
}
}
} catch {
// fall through
}
return {
visibleCardIds: [...FINANCE_KPI_DEFAULT_VISIBLE_CARDS],
primaryByCardId: defaultPrimaries(),
colsPerRow: FINANCE_KPI_DEFAULT_COLS_PER_ROW,
};
}
export function useFinanceKpiPreferences() { export function useFinanceKpiPreferences() {
const stored = parseStored(); const initial = loadFromStorage();
const visibleLabels = ref<string[]>( const visibleCardIds = ref<FinanceKpiCardId[]>(initial.visibleCardIds);
normalizeVisible(stored?.visibleLabels ?? [...FINANCE_KPI_DEFAULT_VISIBLE]), const primaryByCardId = ref<Record<string, string>>(initial.primaryByCardId);
); const colsPerRow = ref(initial.colsPerRow);
const colsPerRow = ref(
clampFinanceKpiColsPerRow(stored?.colsPerRow ?? FINANCE_KPI_DEFAULT_COLS_PER_ROW),
);
function persist() { function persist() {
const payload: PrefsPayload = { const payload: PrefsV2 = {
visibleLabels: visibleLabels.value, version: 2,
visibleCardIds: visibleCardIds.value,
primaryByCardId: primaryByCardId.value,
colsPerRow: colsPerRow.value, colsPerRow: colsPerRow.value,
}; };
localStorage.setItem(FINANCE_KPI_PREFS_KEY, JSON.stringify(payload)); localStorage.setItem(FINANCE_KPI_PREFS_KEY, JSON.stringify(payload));
} }
function setVisibleLabels(labels: string[]) { // 首次从 v1 / 默认加载后立刻写 v2,便于后续只读 v2
visibleLabels.value = sortLabelsByCatalog(normalizeVisible(labels)); persist();
function applySettings(payload: {
visibleCardIds: string[];
primaryByCardId: Record<string, string>;
colsPerRow: number;
}) {
visibleCardIds.value = normalizeVisibleCards(payload.visibleCardIds);
primaryByCardId.value = normalizePrimaries(payload.primaryByCardId);
colsPerRow.value = clampFinanceKpiColsPerRow(payload.colsPerRow);
persist(); persist();
} }
function setColsPerRow(cols: number) { function setCardPrimary(cardId: FinanceKpiCardId, metricLabel: string) {
colsPerRow.value = clampFinanceKpiColsPerRow(cols); const card = cardById(cardId);
persist(); if (!card) return;
} primaryByCardId.value = {
...primaryByCardId.value,
function applySettings(labels: string[], cols: number) { [cardId]: normalizePrimary(card, metricLabel),
visibleLabels.value = sortLabelsByCatalog(normalizeVisible(labels)); };
colsPerRow.value = clampFinanceKpiColsPerRow(cols);
persist(); persist();
} }
function resetToDefault() { function resetToDefault() {
applySettings([...FINANCE_KPI_DEFAULT_VISIBLE], FINANCE_KPI_DEFAULT_COLS_PER_ROW); applySettings({
} visibleCardIds: [...FINANCE_KPI_DEFAULT_VISIBLE_CARDS],
primaryByCardId: defaultPrimaries(),
function selectAll() { colsPerRow: FINANCE_KPI_DEFAULT_COLS_PER_ROW,
setVisibleLabels(catalogLabels()); });
} }
return { return {
visibleLabels, visibleCardIds,
primaryByCardId,
colsPerRow, colsPerRow,
setVisibleLabels,
setColsPerRow,
applySettings, applySettings,
setCardPrimary,
resetToDefault, resetToDefault,
selectAll,
}; };
} }