feat(crm): 新增独立潜客经营与漏斗统计中心(pages/owner/stats.uvue),解耦高频潜客管理并支持全渠道转化分析

这个提交包含在:
wikiboss
2026-09-21 14:52:56 +08:00
父节点 fabace7b07
当前提交 78a2f88158
共有 5 个文件被更改,包括 1147 次插入 和 0 次删除

查看文件

@@ -0,0 +1,189 @@
/**
* OmniCard AI (CRMmp) - 名片主独立数据统计与漏斗分析页测试套件 (TDD Red -> Green)
*
* 验证独立统计页面的数据计算、漏斗转化分析、渠道矩阵与界面规范
*/
import * as fs from 'fs';
import * as path from 'path';
const STATS_PAGE = path.resolve(
__dirname,
'../../../mpuniapp/pages/owner/stats.uvue'
);
const STATS_UTS = path.resolve(
__dirname,
'../../../mpuniapp/pages/owner/useStats.uts'
);
const PAGES_JSON = path.resolve(
__dirname,
'../../../mpuniapp/pages.json'
);
type StatsPeriod = 'today' | '7d' | '30d' | 'all';
type LeadEntity = {
id: string | number;
cardId: string | number;
name: string;
company?: string;
status: 'new' | 'contacted' | 'hot' | 'won' | 'archived';
intentScore: number;
source: 'nfc' | 'qr' | 'link' | 'ai_chat';
};
type FunnelStep = {
key: string;
label: string;
count: number;
rate: number;
};
type ChannelMetric = {
source: 'nfc' | 'qr' | 'link' | 'ai_chat';
label: string;
leadsCount: number;
wonCount: number;
conversionRate: number;
};
type StatsSummary = {
totalLeads: number;
hotLeads: number;
wonLeads: number;
overallRate: number;
};
type StatsState = {
period: StatsPeriod;
summary: StatsSummary;
funnel: FunnelStep[];
channels: ChannelMetric[];
loading: boolean;
errorMessage: string;
};
type UseStatsModule = {
createStatsState: () => StatsState;
calcConversionRate: (total: number, won: number) => number;
calcFunnelStepRate: (currentCount: number, baseCount: number) => number;
computeStatsFromLeads: (leads: LeadEntity[], period: StatsPeriod) => StatsState;
resolveStatsText: (key: string) => string;
};
const EMOJI_RE = /[\u2600-\u27BF\uFE0F]|[\uD83C-\uDBFF][\uDC00-\uDFFF]/;
function loadUseStats(): UseStatsModule {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require(STATS_UTS) as UseStatsModule;
}
describe('OmniCard AI 名片主独立统计与漏斗业务层 (useStats.uts)', () => {
beforeEach(() => {
jest.resetModules();
(global as { uni?: Record<string, unknown> }).uni = {
getLocale: () => 'zh-CN',
showToast: jest.fn(),
navigateTo: jest.fn(),
};
});
afterEach(() => {
delete (global as { uni?: Record<string, unknown> }).uni;
});
describe('1. 漏斗与转化率纯函数计算', () => {
it('1.1 calcConversionRate 在总数为0时返回0,正常时保留一位小数', () => {
const { calcConversionRate } = loadUseStats();
expect(calcConversionRate(0, 0)).toBe(0);
expect(calcConversionRate(0, 5)).toBe(0);
expect(calcConversionRate(10, 3)).toBe(30);
expect(calcConversionRate(3, 1)).toBe(33.3);
expect(calcConversionRate(7, 2)).toBe(28.6);
});
it('1.2 calcFunnelStepRate 计算阶梯相对率', () => {
const { calcFunnelStepRate } = loadUseStats();
expect(calcFunnelStepRate(0, 100)).toBe(0);
expect(calcFunnelStepRate(50, 100)).toBe(50);
expect(calcFunnelStepRate(80, 0)).toBe(0);
});
});
describe('2. computeStatsFromLeads 多维度聚合', () => {
it('2.1 从潜客样本计算出总数、高意向、成交数与漏斗4阶梯', () => {
const { computeStatsFromLeads } = loadUseStats();
const mockLeads: LeadEntity[] = [
{ id: 1, cardId: 1, name: 'Lead 1', status: 'new', intentScore: 40, source: 'nfc' },
{ id: 2, cardId: 1, name: 'Lead 2', status: 'hot', intentScore: 85, source: 'qr' },
{ id: 3, cardId: 1, name: 'Lead 3', status: 'contacted', intentScore: 70, source: 'link' },
{ id: 4, cardId: 1, name: 'Lead 4', status: 'won', intentScore: 92, source: 'ai_chat' },
];
const state = computeStatsFromLeads(mockLeads, 'all');
expect(state.summary.totalLeads).toBe(4);
expect(state.summary.wonLeads).toBe(1);
expect(state.summary.hotLeads).toBe(2); // intentScore >= 80 (Lead 2, Lead 4) or status === 'hot'
expect(state.summary.overallRate).toBe(25);
// 漏斗必须包含 new, hot, contacted, won 四个阶梯
expect(state.funnel).toHaveLength(4);
expect(state.funnel[0].key).toBe('new');
expect(state.funnel[3].key).toBe('won');
// 渠道分析必须覆盖 4 种渠道
expect(state.channels).toHaveLength(4);
const aiChannel = state.channels.find(c => c.source === 'ai_chat');
expect(aiChannel).toBeDefined();
expect(aiChannel?.leadsCount).toBe(1);
expect(aiChannel?.wonCount).toBe(1);
expect(aiChannel?.conversionRate).toBe(100);
});
});
});
describe('OmniCard AI 独立统计视图契约 (stats.uvue & pages.json)', () => {
it('1. pages.json 中已成功注册 pages/owner/stats 页面路由', () => {
expect(fs.existsSync(PAGES_JSON)).toBe(true);
const content = fs.readFileSync(PAGES_JSON, 'utf-8');
const cleanJson = content.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, '$1');
const config = JSON.parse(cleanJson);
const hasRoute = config.pages.some(
(p: { path: string }) => p.path === 'pages/owner/stats'
);
expect(hasRoute).toBe(true);
});
it('2. stats.uvue 包含完整的便当盒统计组件与设计 Token', () => {
expect(fs.existsSync(STATS_PAGE)).toBe(true);
expect(fs.existsSync(STATS_UTS)).toBe(true);
const pageSource = fs.readFileSync(STATS_PAGE, 'utf8');
const logicSource = fs.readFileSync(STATS_UTS, 'utf8');
expect(pageSource.includes('script setup lang="uts"')).toBe(true);
expect(pageSource.includes('#0B5CFF')).toBe(true);
expect(pageSource.includes('#F7F8FA')).toBe(true);
expect(pageSource.includes('#101828')).toBe(true);
expect(pageSource.includes('#667085')).toBe(true);
expect(pageSource.includes('#E3E7ED')).toBe(true);
expect(pageSource.includes('period-chip')).toBe(true);
expect(pageSource.includes('stats-funnel')).toBe(true);
expect(pageSource.includes('channel-grid')).toBe(true);
expect(logicSource.includes('resolveStatsText')).toBe(true);
});
it('3. stats.uvue 无 emoji、无 any、模板无硬编码中文', () => {
const pageSource = fs.readFileSync(STATS_PAGE, 'utf8');
const logicSource = fs.readFileSync(STATS_UTS, 'utf8');
const template = pageSource.split('<script')[0];
expect(EMOJI_RE.test(pageSource)).toBe(false);
expect(EMOJI_RE.test(logicSource)).toBe(false);
expect(pageSource.includes(': any') || pageSource.includes(' as any')).toBe(false);
expect(logicSource.includes(': any') || logicSource.includes(' as any')).toBe(false);
expect(/[\u4e00-\u9fff]/.test(template)).toBe(false);
});
});

查看文件

@@ -72,6 +72,13 @@
"backgroundColorContent": "#F7F8FA"
}
},
{
"path": "pages/owner/stats",
"style": {
"navigationBarTitleText": "统计看板",
"backgroundColorContent": "#F7F8FA"
}
},
{
"path": "pages/owner/profile/index",
"style": {

查看文件

@@ -18,6 +18,9 @@
<view class="radar-hot-dot"></view>
<text class="radar-hot-text">{{ hotUnreadText }}</text>
</view>
<view class="header-stats-btn" @click="openStats">
<text class="header-stats-text">{{ statsLabel }}</text>
</view>
<view class="header-refresh-btn" @click="handleSearch">
<text class="header-refresh-text">{{ refreshText }}</text>
</view>
@@ -285,6 +288,10 @@ const hotUnreadText = computed((): string => {
return formatHotUnread(state.hotUnread);
});
const statsLabel = computed((): string => {
return getCurrentLocale() === 'zh-CN' ? '统计' : 'Stats';
});
const leadsCountSummary = computed((): string => {
const count = state.total > 0 ? state.total : state.list.length;
return `${count}`;
@@ -423,6 +430,12 @@ function openRadar(): void {
openRadarPage();
}
function openStats(): void {
uni.navigateTo({
url: '/pages/owner/stats',
});
}
async function handleSearch(): Promise<void> {
await refreshLeads(state);
}
@@ -541,6 +554,28 @@ onShow(() => {
color: var(--oc-error, #F04438);
}
.header-stats-btn {
min-height: 32px;
padding-inline: 10px;
background-color: var(--oc-primary-soft, #EBF5FF);
border: 1px solid #B2DDFF;
border-radius: var(--oc-radius-btn, 14px);
display: flex;
align-items: center;
justify-content: center;
transition: opacity 150ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.header-stats-btn:active {
opacity: 0.85;
}
.header-stats-text {
font-size: 12px;
color: var(--oc-primary, #0B5CFF);
font-weight: 600;
}
.header-refresh-btn {
min-height: 32px;
padding-inline: 10px;

查看文件

@@ -0,0 +1,646 @@
<template>
<view class="stats-page" :class="pageRtlClass" :style="pageTheme">
<!-- Slim Cockpit Header -->
<view class="stats-header">
<view class="stats-header-top">
<view class="stats-title-group">
<text class="stats-title">{{ pageTitle }}</text>
<text class="stats-subtitle">{{ pageSubtitle }}</text>
</view>
<view class="stats-refresh-btn" @click="handleRefresh">
<text class="stats-refresh-text">{{ refreshText }}</text>
</view>
</view>
<!-- Period Filter Chips -->
<view class="period-row">
<view
class="period-chip"
:class="{ 'period-chip-active': state.period === 'today' }"
@click="changePeriod('today')"
>
<text class="period-chip-text">{{ t('periodToday') }}</text>
</view>
<view
class="period-chip"
:class="{ 'period-chip-active': state.period === '7d' }"
@click="changePeriod('7d')"
>
<text class="period-chip-text">{{ t('period7d') }}</text>
</view>
<view
class="period-chip"
:class="{ 'period-chip-active': state.period === '30d' }"
@click="changePeriod('30d')"
>
<text class="period-chip-text">{{ t('period30d') }}</text>
</view>
<view
class="period-chip"
:class="{ 'period-chip-active': state.period === 'all' }"
@click="changePeriod('all')"
>
<text class="period-chip-text">{{ t('periodAll') }}</text>
</view>
</view>
</view>
<!-- Skeleton Loading -->
<view v-if="state.loading" class="stats-skeleton">
<view class="skeleton-metric-row">
<view class="skeleton-card"></view>
<view class="skeleton-card"></view>
</view>
<view class="skeleton-funnel"></view>
<view class="skeleton-grid"></view>
</view>
<!-- Feedback Error Banner -->
<view v-else-if="state.errorMessage !== ''" class="stats-feedback">
<text class="feedback-title">{{ t('error') }}</text>
<text class="feedback-desc">{{ state.errorMessage }}</text>
</view>
<!-- Stats Scrollable Body -->
<scroll-view v-else class="stats-body" :scroll-y="true">
<!-- 2x2 Executive Bento Grid -->
<view class="kpi-grid">
<!-- KPI 1: Total Leads -->
<view class="metric-card">
<text class="metric-label">{{ t('metricTotal') }}</text>
<text class="metric-value text-brand">{{ state.summary.totalLeads }}</text>
<text class="metric-sub">{{ t('stepNew') }}</text>
</view>
<!-- KPI 2: Hot Opportunities -->
<view class="metric-card metric-card-hot">
<view class="metric-hot-header">
<text class="metric-label text-hot">{{ t('metricHot') }}</text>
<view class="metric-hot-dot"></view>
</view>
<text class="metric-value text-hot">{{ state.summary.hotLeads }}</text>
<text class="metric-sub">{{ t('stepHot') }}</text>
</view>
<!-- KPI 3: Won Deals -->
<view class="metric-card">
<text class="metric-label">{{ t('metricWon') }}</text>
<text class="metric-value text-won">{{ state.summary.wonLeads }}</text>
<text class="metric-sub">{{ t('stepWon') }}</text>
</view>
<!-- KPI 4: Overall Conversion Rate -->
<view class="metric-card metric-card-rate">
<text class="metric-label">{{ t('metricRate') }}</text>
<text class="metric-value text-primary">{{ state.summary.overallRate }}%</text>
<text class="metric-sub">{{ t('stepContacted') }}</text>
</view>
</view>
<!-- Conversion Funnel Section -->
<view class="stats-card stats-funnel">
<view class="card-header">
<text class="card-title">{{ t('funnelTitle') }}</text>
</view>
<view class="funnel-list">
<view v-for="step in state.funnel" :key="step.key" class="funnel-step-item">
<view class="funnel-step-header">
<text class="funnel-step-label">{{ step.label }}</text>
<view class="funnel-step-values">
<text class="funnel-step-count">{{ step.count }}</text>
<text class="funnel-step-rate">{{ step.rate }}%</text>
</view>
</view>
<view class="funnel-track">
<view
class="funnel-fill"
:class="'funnel-fill-' + step.key"
:style="{ width: step.rate + '%' }"
></view>
</view>
</view>
</view>
</view>
<!-- Acquisition Channels Matrix -->
<view class="stats-card stats-channels">
<view class="card-header">
<text class="card-title">{{ t('channelTitle') }}</text>
</view>
<view class="channel-grid">
<view v-for="ch in state.channels" :key="ch.source" class="channel-card">
<view class="channel-header">
<text class="channel-name">{{ ch.label }}</text>
<text class="channel-rate">{{ ch.conversionRate }}%</text>
</view>
<view class="channel-data-row">
<view class="channel-data-col">
<text class="channel-num">{{ ch.leadsCount }}</text>
<text class="channel-tag">{{ t('metricTotal') }}</text>
</view>
<view class="channel-data-divider"></view>
<view class="channel-data-col">
<text class="channel-num text-won">{{ ch.wonCount }}</text>
<text class="channel-tag">{{ t('metricWon') }}</text>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
</view>
</template>
<script setup lang="uts">
import { getCurrentLocale, isRtl } from '../../common/locale.uts';
import { utsLightColors, utsRadius, utsSpacing, utsTypography } from '../../common/tokens.uts';
import {
createStatsState,
loadStatsData,
resolveStatsText,
StatsPeriod,
} from './useStats.uts';
const pageTheme: Record<string, string> = {
'--oc-primary': utsLightColors.primary,
'--oc-primary-gradient': utsLightColors.primaryGradient,
'--oc-primary-soft': utsLightColors.primarySoft,
'--oc-ai': utsLightColors.ai,
'--oc-bg': utsLightColors.bg,
'--oc-surface': utsLightColors.surface,
'--oc-border': utsLightColors.border,
'--oc-text': utsLightColors.text,
'--oc-text-2': utsLightColors.text2,
'--oc-success': utsLightColors.success,
'--oc-warning': utsLightColors.warning,
'--oc-error': utsLightColors.error,
'--oc-radius-btn': utsRadius.button,
'--oc-radius-card': utsRadius.card,
'--oc-radius-modal': utsRadius.modal,
'--oc-radius-pill': utsRadius.pill,
'--oc-shadow-card': utsTypography.shadowCard,
'--oc-shadow-cta': utsTypography.shadowCta,
'--oc-shadow': utsTypography.shadow,
'--oc-space-4': utsSpacing.space4,
'--oc-space-8': utsSpacing.space8,
'--oc-space-12': utsSpacing.space12,
'--oc-space-16': utsSpacing.space16,
'--oc-space-20': utsSpacing.space20,
'--oc-space-24': utsSpacing.space24,
};
const state = reactive(createStatsState());
const pageTitle = ref(resolveStatsText('title'));
const pageSubtitle = ref(resolveStatsText('subtitle'));
const refreshText = ref(resolveStatsText('retry'));
const pageRtlClass = computed((): string => {
return isRtl(getCurrentLocale()) ? 'stats-rtl' : '';
});
function t(key: string): string {
return resolveStatsText(key);
}
function changePeriod(period: StatsPeriod): void {
state.period = period;
loadStatsData(state);
}
function handleRefresh(): void {
loadStatsData(state);
}
onLoad(() => {
loadStatsData(state);
});
onShow(() => {
loadStatsData(state);
});
</script>
<style scoped>
/* Page Container */
.stats-page {
display: flex;
flex-direction: column;
height: 100%;
background-color: var(--oc-bg, #F5F8FC);
}
.stats-rtl {
direction: rtl;
}
/* Header & Filter Area */
.stats-header {
padding-inline: var(--oc-space-16, 16px);
padding-block-start: var(--oc-space-16, 16px);
padding-block-end: var(--oc-space-12, 12px);
background-color: var(--oc-surface, #FFFFFF);
border-bottom: 1px solid var(--oc-border, #E3E7ED);
flex-shrink: 0;
}
.stats-header-top {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
margin-block-end: var(--oc-space-12, 12px);
}
.stats-title-group {
display: flex;
flex-direction: column;
}
.stats-title {
font-size: 20px;
font-weight: 700;
color: var(--oc-text, #101828);
line-height: 1.25;
}
.stats-subtitle {
font-size: 12px;
color: var(--oc-text-2, #667085);
margin-block-start: 2px;
}
.stats-refresh-btn {
min-height: 32px;
padding-inline: 12px;
background-color: var(--oc-surface, #F7F8FA);
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-btn, 14px);
display: flex;
align-items: center;
justify-content: center;
transition: opacity 150ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.stats-refresh-btn:active {
opacity: 0.85;
}
.stats-refresh-text {
font-size: 12px;
color: var(--oc-text-2, #667085);
font-weight: 500;
}
/* Period Filter Chips */
.period-row {
display: flex;
flex-direction: row;
gap: 8px;
}
.period-chip {
flex: 1;
height: 32px;
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-btn, 14px);
background-color: var(--oc-surface, #F7F8FA);
display: flex;
align-items: center;
justify-content: center;
transition: all 150ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.period-chip:active {
opacity: 0.85;
}
.period-chip-active {
background-color: var(--oc-primary-soft, #EBF5FF);
border-color: var(--oc-primary, #0B5CFF);
}
.period-chip-text {
font-size: 12px;
color: var(--oc-text-2, #667085);
font-weight: 500;
}
.period-chip-active .period-chip-text {
color: var(--oc-primary, #0B5CFF);
font-weight: 600;
}
/* Skeleton Loading */
.stats-skeleton {
flex: 1;
padding: 16px;
}
.skeleton-metric-row {
display: flex;
flex-direction: row;
gap: 10px;
margin-block-end: 12px;
}
.skeleton-card {
flex: 1;
height: 80px;
background-color: var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-card, 20px);
}
.skeleton-funnel {
height: 140px;
background-color: var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-card, 20px);
margin-block-end: 12px;
}
.skeleton-grid {
height: 120px;
background-color: var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-card, 20px);
}
/* Feedback Error */
.stats-feedback {
flex: 1;
margin: 24px 16px;
padding: 24px;
background-color: var(--oc-surface, #FFFFFF);
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-card, 20px);
display: flex;
flex-direction: column;
align-items: center;
}
.feedback-title {
font-size: 16px;
font-weight: 600;
color: var(--oc-text, #101828);
margin-block-end: 6px;
}
.feedback-desc {
font-size: 13px;
color: var(--oc-text-2, #667085);
text-align: center;
}
/* Stats Body */
.stats-body {
flex: 1;
padding: 16px;
}
/* 2x2 Bento Grid KPI Cards */
.kpi-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-block-end: 12px;
}
.metric-card {
background-color: var(--oc-surface, #FFFFFF);
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-card, 20px);
box-shadow: var(--oc-shadow-card, 0 8px 30px rgba(0, 0, 0, 0.04));
padding: 12px 14px;
display: flex;
flex-direction: column;
}
.metric-card-hot {
background: linear-gradient(145deg, #FFFFFF 0%, #FFF8F6 100%);
}
.metric-hot-header {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.metric-hot-dot {
width: 6px;
height: 6px;
border-radius: 3px;
background-color: var(--oc-error, #F04438);
}
.metric-card-rate {
background: linear-gradient(145deg, #FFFFFF 0%, #F5F9FF 100%);
}
.metric-label {
font-size: 11px;
font-weight: 600;
color: var(--oc-text-2, #667085);
margin-block-end: 4px;
}
.metric-value {
font-size: 24px;
font-weight: 800;
color: var(--oc-text, #101828);
line-height: 1.15;
margin-block-end: 2px;
}
.text-brand {
color: var(--oc-primary, #0B5CFF);
}
.text-hot {
color: var(--oc-error, #F04438);
}
.text-won {
color: var(--oc-success, #12B76A);
}
.text-primary {
color: var(--oc-primary, #0B5CFF);
}
.metric-sub {
font-size: 10px;
color: var(--oc-text-2, #667085);
}
/* Generic Stats Card */
.stats-card {
background-color: var(--oc-surface, #FFFFFF);
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: var(--oc-radius-card, 20px);
box-shadow: var(--oc-shadow-card, 0 8px 30px rgba(0, 0, 0, 0.04));
padding: 14px 16px;
margin-block-end: 12px;
}
.card-header {
margin-block-end: 12px;
}
.card-title {
font-size: 14px;
font-weight: 700;
color: var(--oc-text, #101828);
}
/* Funnel Step List */
.funnel-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.funnel-step-item {
display: flex;
flex-direction: column;
}
.funnel-step-header {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
margin-block-end: 6px;
}
.funnel-step-label {
font-size: 12px;
font-weight: 600;
color: var(--oc-text, #101828);
}
.funnel-step-values {
display: flex;
flex-direction: row;
align-items: center;
gap: 8px;
}
.funnel-step-count {
font-size: 13px;
font-weight: 700;
color: var(--oc-text, #101828);
}
.funnel-step-rate {
font-size: 11px;
font-weight: 600;
color: var(--oc-primary, #0B5CFF);
background-color: var(--oc-primary-soft, #EBF5FF);
padding-inline: 6px;
padding-block: 1px;
border-radius: 9999px;
}
.funnel-track {
height: 8px;
background-color: var(--oc-surface, #F7F8FA);
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: 4px;
overflow: hidden;
}
.funnel-fill {
height: 100%;
border-radius: 4px;
transition: width 300ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.funnel-fill-new {
background-color: var(--oc-primary, #0B5CFF);
}
.funnel-fill-hot {
background-color: var(--oc-error, #F04438);
}
.funnel-fill-contacted {
background-color: var(--oc-warning, #F79009);
}
.funnel-fill-won {
background-color: var(--oc-success, #12B76A);
}
/* Channel Matrix Grid */
.channel-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.channel-card {
background-color: var(--oc-surface, #F7F8FA);
border: 1px solid var(--oc-border, #E3E7ED);
border-radius: 14px;
padding: 10px 12px;
display: flex;
flex-direction: column;
}
.channel-header {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
margin-block-end: 8px;
}
.channel-name {
font-size: 12px;
font-weight: 600;
color: var(--oc-text, #101828);
}
.channel-rate {
font-size: 11px;
font-weight: 700;
color: var(--oc-primary, #0B5CFF);
}
.channel-data-row {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
}
.channel-data-col {
display: flex;
flex-direction: column;
align-items: center;
}
.channel-num {
font-size: 14px;
font-weight: 700;
color: var(--oc-text, #101828);
}
.channel-tag {
font-size: 9px;
color: var(--oc-text-2, #667085);
margin-block-start: 1px;
}
.channel-data-divider {
width: 1px;
height: 18px;
background-color: var(--oc-border, #E3E7ED);
}
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}
</style>

查看文件

@@ -0,0 +1,270 @@
/**
* OmniCard AI (CRMmp) - 名片主独立数据统计与销售漏斗业务驱动层
* 纯函数计算转化率、漏斗阶段折损、渠道成效矩阵与国际化
*/
import { LeadEntity, OwnerPageQuery } from '../../common/types.uts';
import { fetchOwnerLeadPage } from '../../common/api.uts';
import { getCurrentLocale, getOmniText } from '../../common/locale.uts';
export type StatsPeriod = 'today' | '7d' | '30d' | 'all';
export type FunnelStep = {
key: string;
label: string;
count: number;
rate: number;
};
export type ChannelMetric = {
source: 'nfc' | 'qr' | 'link' | 'ai_chat';
label: string;
leadsCount: number;
wonCount: number;
conversionRate: number;
};
export type StatsSummary = {
totalLeads: number;
hotLeads: number;
wonLeads: number;
overallRate: number;
};
export type StatsState = {
period: StatsPeriod;
summary: StatsSummary;
funnel: FunnelStep[];
channels: ChannelMetric[];
loading: boolean;
errorMessage: string;
};
function isZhLocale(): boolean {
return getCurrentLocale() === 'zh-CN';
}
export function calcConversionRate(total: number, won: number): number {
if (total <= 0 || won <= 0) {
return 0;
}
const rate = (won / total) * 100;
return Math.round(rate * 10) / 10;
}
export function calcFunnelStepRate(currentCount: number, baseCount: number): number {
if (baseCount <= 0 || currentCount <= 0) {
return 0;
}
const rate = (currentCount / baseCount) * 100;
return Math.round(rate * 10) / 10;
}
export function resolveStatsText(key: string): string {
const locale = getCurrentLocale();
if (key === 'title') {
return isZhLocale() ? '经营与漏斗统计' : 'Pipeline & Analytics';
}
if (key === 'subtitle') {
return isZhLocale() ? '全渠道商机转化与意向大盘' : 'Full-funnel lead insights & radar score';
}
if (key === 'empty') {
return getOmniText(locale, 'common.empty');
}
if (key === 'error') {
return getOmniText(locale, 'common.error');
}
if (key === 'loading') {
return getOmniText(locale, 'common.loading');
}
if (key === 'retry') {
return getOmniText(locale, 'portal.retry');
}
// Periods
if (key === 'periodToday') {
return isZhLocale() ? '今日' : 'Today';
}
if (key === 'period7d') {
return isZhLocale() ? '近7天' : '7 Days';
}
if (key === 'period30d') {
return isZhLocale() ? '近30天' : '30 Days';
}
if (key === 'periodAll') {
return isZhLocale() ? '全部' : 'All Time';
}
// Funnel & Metrics
if (key === 'metricTotal') {
return isZhLocale() ? '潜客总量' : 'Total Leads';
}
if (key === 'metricHot') {
return isZhLocale() ? '高意向商机' : 'High Intent';
}
if (key === 'metricWon') {
return isZhLocale() ? '签约成交' : 'Deals Won';
}
if (key === 'metricRate') {
return isZhLocale() ? '综合转化率' : 'Conversion';
}
if (key === 'funnelTitle') {
return isZhLocale() ? '商机转化漏斗' : 'Pipeline Funnel';
}
if (key === 'channelTitle') {
return isZhLocale() ? '获客渠道成效' : 'Acquisition Channels';
}
if (key === 'stepNew') {
return isZhLocale() ? '新建线索' : 'New Leads';
}
if (key === 'stepHot') {
return isZhLocale() ? '高意向' : 'Hot Intent';
}
if (key === 'stepContacted') {
return isZhLocale() ? '已接洽' : 'Contacted';
}
if (key === 'stepWon') {
return isZhLocale() ? '赢单成单' : 'Deals Won';
}
if (key === 'sourceNfc') {
return isZhLocale() ? 'NFC 贴卡' : 'NFC Touch';
}
if (key === 'sourceQr') {
return isZhLocale() ? '海报码' : 'Poster QR';
}
if (key === 'sourceLink') {
return isZhLocale() ? '直链分享' : 'Direct Link';
}
if (key === 'sourceAi') {
return isZhLocale() ? 'AI顾问' : 'AI Concierge';
}
return key;
}
export function createStatsState(): StatsState {
return {
period: 'all',
summary: {
totalLeads: 0,
hotLeads: 0,
wonLeads: 0,
overallRate: 0,
},
funnel: [
{ key: 'new', label: resolveStatsText('stepNew'), count: 0, rate: 0 },
{ key: 'hot', label: resolveStatsText('stepHot'), count: 0, rate: 0 },
{ key: 'contacted', label: resolveStatsText('stepContacted'), count: 0, rate: 0 },
{ key: 'won', label: resolveStatsText('stepWon'), count: 0, rate: 0 },
],
channels: [
{ source: 'nfc', label: resolveStatsText('sourceNfc'), leadsCount: 0, wonCount: 0, conversionRate: 0 },
{ source: 'qr', label: resolveStatsText('sourceQr'), leadsCount: 0, wonCount: 0, conversionRate: 0 },
{ source: 'link', label: resolveStatsText('sourceLink'), leadsCount: 0, wonCount: 0, conversionRate: 0 },
{ source: 'ai_chat', label: resolveStatsText('sourceAi'), leadsCount: 0, wonCount: 0, conversionRate: 0 },
],
loading: false,
errorMessage: '',
};
}
export function computeStatsFromLeads(leads: LeadEntity[], period: StatsPeriod): StatsState {
const state = createStatsState();
state.period = period;
let totalCount = 0;
let hotCount = 0;
let newCount = 0;
let contactedCount = 0;
let wonCount = 0;
const channelMap: Record<string, { leads: number; won: number }> = {
nfc: { leads: 0, won: 0 },
qr: { leads: 0, won: 0 },
link: { leads: 0, won: 0 },
ai_chat: { leads: 0, won: 0 },
};
for (let i = 0; i < leads.length; i++) {
const item = leads[i];
totalCount++;
if (item.status === 'hot' || item.intentScore >= 80) {
hotCount++;
}
if (item.status === 'new') {
newCount++;
} else if (item.status === 'contacted') {
contactedCount++;
} else if (item.status === 'won') {
wonCount++;
}
const src = item.source != null ? item.source : 'link';
if (channelMap[src] != null) {
channelMap[src].leads++;
if (item.status === 'won') {
channelMap[src].won++;
}
}
}
state.summary.totalLeads = totalCount;
state.summary.hotLeads = hotCount;
state.summary.wonLeads = wonCount;
state.summary.overallRate = calcConversionRate(totalCount, wonCount);
// 漏斗阶梯与转化率
state.funnel[0].count = totalCount;
state.funnel[0].rate = totalCount > 0 ? 100 : 0;
state.funnel[1].count = hotCount;
state.funnel[1].rate = calcFunnelStepRate(hotCount, totalCount);
state.funnel[2].count = contactedCount;
state.funnel[2].rate = calcFunnelStepRate(contactedCount, totalCount);
state.funnel[3].count = wonCount;
state.funnel[3].rate = calcFunnelStepRate(wonCount, totalCount);
// 渠道成效
state.channels[0].leadsCount = channelMap['nfc'].leads;
state.channels[0].wonCount = channelMap['nfc'].won;
state.channels[0].conversionRate = calcConversionRate(channelMap['nfc'].leads, channelMap['nfc'].won);
state.channels[1].leadsCount = channelMap['qr'].leads;
state.channels[1].wonCount = channelMap['qr'].won;
state.channels[1].conversionRate = calcConversionRate(channelMap['qr'].leads, channelMap['qr'].won);
state.channels[2].leadsCount = channelMap['link'].leads;
state.channels[2].wonCount = channelMap['link'].won;
state.channels[2].conversionRate = calcConversionRate(channelMap['link'].leads, channelMap['link'].won);
state.channels[3].leadsCount = channelMap['ai_chat'].leads;
state.channels[3].wonCount = channelMap['ai_chat'].won;
state.channels[3].conversionRate = calcConversionRate(channelMap['ai_chat'].leads, channelMap['ai_chat'].won);
return state;
}
export async function loadStatsData(state: StatsState): Promise<void> {
state.loading = true;
state.errorMessage = '';
try {
const query: OwnerPageQuery = {
page: 1,
size: 100,
};
const res = await fetchOwnerLeadPage(query);
const computed = computeStatsFromLeads(res.list, state.period);
state.summary = computed.summary;
state.funnel = computed.funnel;
state.channels = computed.channels;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
state.errorMessage = msg !== '' ? msg : resolveStatsText('error');
} finally {
state.loading = false;
}
}