Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+470
View File
@@ -0,0 +1,470 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出
// ─── 金额 ───────────────────────────────────────────────────────
// 货币统一显示人民币:额度 → CNY = quota / quota_per_unit × usd_exchange_rate
export const getCnyParams = () => {
let quotaPerUnit = parseFloat(localStorage.getItem('quota_per_unit'));
if (!quotaPerUnit || quotaPerUnit <= 0) quotaPerUnit = 500000;
let usdRate = 1;
try {
const s = JSON.parse(localStorage.getItem('status') || '{}');
usdRate = s?.usd_exchange_rate || 1;
} catch (e) {
usdRate = 1;
}
return { quotaPerUnit, usdRate };
};
export const quotaToCny = (quota, { quotaPerUnit, usdRate }) =>
((quota || 0) / quotaPerUnit) * usdRate;
export const formatCny = (quota, params, digits = 2) =>
`¥${quotaToCny(quota, params).toLocaleString(undefined, {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
})}`;
// 环比(%);对比期为 0 时无法计算返回 null
export const changeRate = (cur, prev) =>
prev > 0 ? (((cur || 0) - prev) / prev) * 100 : null;
export const formatRate = (rate) =>
rate === null || rate === undefined
? '—'
: `${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%`;
export const pct = (part, total) => (total > 0 ? (part / total) * 100 : 0);
// ─── 时间(报表口径统一为 UTC+8,与浏览器时区无关) ─────────────────
const pad = (n) => String(n).padStart(2, '0');
export const formatCst = (ts, withTime = true) => {
if (!ts) return '—';
const d = new Date((ts + 8 * 3600) * 1000);
const date = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
return withTime
? `${date} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`
: date;
};
export const daysSince = (ts, now = Date.now() / 1000) =>
ts > 0 ? Math.max(0, Math.floor((now - ts) / 86400)) : null;
// ─── 标签字典 ────────────────────────────────────────────────────
export const ORG_STATUS = {
1: { label: '正常', color: 'green' },
2: { label: '冻结', color: 'grey' },
3: { label: '欠费', color: 'red' },
4: { label: '待激活', color: 'blue' },
};
export const SEGMENTS = {
new: { label: '新客起量', color: 'cyan', desc: '本期首次使用' },
growing: { label: '增长', color: 'green', desc: '消耗环比增长 ≥ 20%' },
stable: { label: '稳定', color: 'blue', desc: '消耗环比波动 < 20%' },
recovered: { label: '回流', color: 'teal', desc: '对比期无使用,本期恢复' },
declining: { label: '下滑', color: 'orange', desc: '消耗环比下降 ≥ 20%' },
stopped: { label: '停用', color: 'red', desc: '对比期有使用,本期无使用' },
dormant: { label: '沉睡', color: 'grey', desc: '两期均无使用,历史用过' },
never_used: {
label: '从未使用',
color: 'violet',
desc: '开通后从未产生调用',
},
pending: { label: '待激活', color: 'light-blue', desc: '等待平台激活' },
frozen: { label: '冻结', color: 'grey', desc: '已被冻结' },
};
export const ALERT_LEVELS = {
exhausted: { label: '余额耗尽', color: 'red', rank: 0 },
critical: { label: '3 天内耗尽', color: 'orange', rank: 1 },
threshold: { label: '低于预警线', color: 'amber', rank: 2 },
warning: { label: '即将不足', color: 'yellow', rank: 3 },
};
export const TIERS = {
A: { label: 'A 类', color: 'red', desc: '累计贡献前 80% 消耗' },
B: { label: 'B 类', color: 'orange', desc: '累计贡献 80%~95%' },
C: { label: 'C 类', color: 'grey', desc: '其余长尾企业' },
};
// 行动原因 → 标签与建议动作(顺序即优先级)
export const REASONS = {
exhausted: {
label: '余额耗尽',
color: 'red',
action: '立即联系充值,避免业务中断',
},
critical: { label: '3 天内耗尽', color: 'orange', action: '3 天内跟进续费' },
expired: { label: '合同已到期', color: 'red', action: '确认续约方案' },
threshold: {
label: '低于预警线',
color: 'amber',
action: '提醒企业补充余额',
},
warning: { label: '即将不足', color: 'yellow', action: '本周内沟通续费计划' },
expiring: { label: '30 天内到期', color: 'orange', action: '推进续约' },
stopped: { label: '本期停用', color: 'red', action: '回访了解停用原因' },
sharp_decline: {
label: '近 7 日腰斩',
color: 'red',
action: '回访排查使用下降原因',
},
declining: {
label: '消耗下滑',
color: 'orange',
action: '回访排查使用下降原因',
},
dormant: {
label: '近期沉睡',
color: 'grey',
action: '唤醒沟通,推送新模型与新功能',
},
fast_growth: {
label: '高速增长',
color: 'green',
action: '跟进扩容与年度方案',
},
growing: { label: '稳步增长', color: 'green', action: '跟进扩容与年度方案' },
new: { label: '新客起量', color: 'cyan', action: '新客关怀,确认使用顺畅' },
recovered: { label: '回流', color: 'teal', action: '回流客户关怀,巩固使用' },
low_penetration: {
label: '成员渗透低',
color: 'violet',
action: '推动内部推广、组织培训',
},
pending: { label: '待激活', color: 'light-blue', action: '协助完成企业激活' },
never_used: {
label: '开通未使用',
color: 'violet',
action: '引导创建令牌、完成首次调用',
},
};
const isServing = (o) => !o.deleted && (o.status === 1 || o.status === 3);
// ─── 行动清单 ────────────────────────────────────────────────────
const withReasons = (o, reasons) => ({
...o,
reasons,
action: reasons.length ? REASONS[reasons[0]].action : '',
});
export const deriveActionLists = (orgs, meta) => {
const renewal = [];
const retention = [];
const growth = [];
const activation = [];
// 沉睡只关注「最近 60 天内还用过」的,太久远的不值得逐个跟进
const dormantCutoff = (meta?.start || 0) - 60 * 86400;
(orgs || []).forEach((o) => {
if (o.deleted) return;
const flags = o.flags || [];
// 续费跟进
if (isServing(o)) {
const r = [];
if (o.alert_level) r.push(o.alert_level);
if (flags.includes('expired')) r.push('expired');
if (flags.includes('expiring')) r.push('expiring');
if (r.length) {
r.sort(
(a, b) =>
Object.keys(REASONS).indexOf(a) - Object.keys(REASONS).indexOf(b),
);
renewal.push(withReasons(o, r));
}
}
// 流失挽回
if (isServing(o)) {
const r = [];
if (o.segment === 'stopped') r.push('stopped');
if (flags.includes('sharp_decline')) r.push('sharp_decline');
if (o.segment === 'declining') r.push('declining');
if (
o.segment === 'dormant' &&
o.last_active >= dormantCutoff &&
o.last_active > 0
)
r.push('dormant');
if (r.length) retention.push(withReasons(o, r));
}
// 增长机会
if (isServing(o)) {
const r = [];
const rate = changeRate(o.quota, o.prev_quota);
if (o.segment === 'growing')
r.push(rate !== null && rate >= 50 ? 'fast_growth' : 'growing');
if (o.segment === 'new') r.push('new');
if (o.segment === 'recovered') r.push('recovered');
if (flags.includes('low_penetration')) r.push('low_penetration');
if (r.length) growth.push(withReasons(o, r));
}
// 激活跟进
if (
o.segment === 'pending' ||
(o.segment === 'never_used' && isServing(o))
) {
activation.push(withReasons(o, [o.segment]));
}
});
const reasonRank = (o) => Object.keys(REASONS).indexOf(o.reasons[0]);
renewal.sort(
(a, b) =>
reasonRank(a) - reasonRank(b) ||
(a.days_left < 0) - (b.days_left < 0) ||
a.days_left - b.days_left ||
b.daily_avg - a.daily_avg,
);
const atRisk = (o) =>
Math.max(
(o.prev_quota || 0) - (o.quota || 0),
(o.prior7_quota || 0) - (o.recent7_quota || 0),
);
retention.sort((a, b) => atRisk(b) - atRisk(a));
growth.sort((a, b) => (b.quota || 0) - (a.quota || 0));
activation.sort((a, b) => (b.created_at || 0) - (a.created_at || 0));
return { renewal, retention, growth, activation, atRisk };
};
// ─── 跟进人视图 ──────────────────────────────────────────────────
export const deriveSalesReps = (orgs, lists) => {
const idsOf = (list) => new Set(list.map((o) => o.org_id));
const renewalIds = idsOf(lists.renewal);
const retentionIds = idsOf(lists.retention);
const growthIds = idsOf(lists.growth);
const map = new Map();
(orgs || []).forEach((o) => {
if (o.deleted) return;
const key = o.sales_rep || '';
if (!map.has(key)) {
map.set(key, {
sales_rep: key,
orgs: 0,
active: 0,
quota: 0,
prev_quota: 0,
renewal: 0,
retention: 0,
growth: 0,
balance: 0,
});
}
const r = map.get(key);
r.orgs += 1;
if (o.requests > 0) r.active += 1;
r.quota += o.quota || 0;
r.prev_quota += o.prev_quota || 0;
r.balance += o.balance || 0;
if (renewalIds.has(o.org_id)) r.renewal += 1;
if (retentionIds.has(o.org_id)) r.retention += 1;
if (growthIds.has(o.org_id)) r.growth += 1;
});
return Array.from(map.values()).sort((a, b) => b.quota - a.quota);
};
// ─── 本期要点(结论先行) ────────────────────────────────────────
// 返回 [{ level: 'danger'|'warning'|'success'|'info', text, target }],text 已翻译
export const deriveFindings = (report, lists, cny, t) => {
if (!report) return [];
const k = report.kpi || {};
const orgs = report.orgs || [];
const out = [];
const money = (q) => formatCny(q, cny, 0);
// 1. 消耗变化与主要贡献者
const rate = changeRate(k.org_quota, k.prev_org_quota);
const deltas = orgs
.filter((o) => !o.deleted)
.map((o) => ({ name: o.name, d: (o.quota || 0) - (o.prev_quota || 0) }));
const up = deltas
.filter((x) => x.d > 0)
.sort((a, b) => b.d - a.d)
.slice(0, 2);
const down = deltas
.filter((x) => x.d < 0)
.sort((a, b) => a.d - b.d)
.slice(0, 2);
if (rate !== null) {
const drivers = (rate >= 0 ? up : down)
.map((x) => `${x.name} (${x.d > 0 ? '+' : '-'}${money(Math.abs(x.d))})`)
.join(', ');
const params = {
amount: money(k.org_quota),
rate: formatRate(rate),
drivers,
};
let text;
if (!drivers) {
text = t('企业消耗 {{amount}},较对比期 {{rate}}', params);
} else if (rate >= 0) {
text = t(
'企业消耗 {{amount}},较对比期 {{rate}},增长主要来自 {{drivers}}',
params,
);
} else {
text = t(
'企业消耗 {{amount}},较对比期 {{rate}},下滑主要来自 {{drivers}}',
params,
);
}
out.push({
level: rate >= 0 ? 'success' : 'warning',
text,
target: 'attribution',
});
} else if (k.org_quota > 0) {
out.push({
level: 'info',
text: t('企业消耗 {{amount}},对比期无消耗数据', {
amount: money(k.org_quota),
}),
target: 'attribution',
});
}
// 2. 续费风险
const urgent = lists.renewal.filter((o) =>
['exhausted', 'critical'].includes(o.alert_level),
).length;
if (lists.renewal.length > 0) {
out.push({
level: urgent > 0 ? 'danger' : 'warning',
text: t(
'{{count}} 家企业需续费跟进({{urgent}} 家已耗尽或 3 天内耗尽),未来 30 天充值缺口约 {{gap}}',
{ count: lists.renewal.length, urgent, gap: money(k.topup_gap_30d) },
),
target: 'renewal',
});
}
// 3. 流失风险
if (lists.retention.length > 0) {
const exposure = lists.retention.reduce((s, o) => s + lists.atRisk(o), 0);
out.push({
level: 'warning',
text: t(
'{{count}} 家企业存在流失风险(停用 / 下滑 / 沉睡),涉及消耗减少约 {{amount}}',
{
count: lists.retention.length,
amount: money(exposure),
},
),
target: 'retention',
});
}
// 4. 本月预测
if (k.month_to_date > 0 || k.last_month_quota > 0) {
const mRate = changeRate(k.month_forecast, k.last_month_quota);
out.push({
level: mRate !== null && mRate < 0 ? 'warning' : 'info',
text: t(
'按近 7 日日均 {{runRate}} 推算,本月企业消耗预计 {{forecast}},上月 {{last}}({{rate}})',
{
runRate: money(k.run_rate_daily),
forecast: money(k.month_forecast),
last: money(k.last_month_quota),
rate: formatRate(mRate),
},
),
target: 'kpi',
});
}
// 5. 集中度
if (k.org_quota > 0 && k.active_orgs >= 5) {
out.push({
level: k.top5_share >= 60 ? 'warning' : 'info',
text:
k.top5_share >= 60
? t(
'头部依赖较高:Top5 企业贡献 {{share}} 的企业消耗,需关注大客户稳定性',
{
share: `${k.top5_share.toFixed(1)}%`,
},
)
: t('客户结构较分散:Top5 企业贡献 {{share}} 的企业消耗', {
share: `${k.top5_share.toFixed(1)}%`,
}),
target: 'tiers',
});
}
// 6. 渗透与激活
const lowPen = lists.growth.filter((o) =>
o.reasons.includes('low_penetration'),
).length;
const penetration = pct(k.active_members, k.total_members);
if (k.total_members > 0 && (penetration < 50 || lowPen > 0)) {
out.push({
level: 'info',
text: t(
'企业成员渗透率 {{rate}},{{count}} 家企业成员活跃率低于 30%,存在增量空间',
{
rate: `${Math.min(100, penetration).toFixed(1)}%`,
count: lowPen,
},
),
target: 'growth',
});
}
if (lists.activation.length > 0) {
out.push({
level: 'info',
text: t('{{count}} 家企业待激活或开通后从未使用,建议安排激活跟进', {
count: lists.activation.length,
}),
target: 'activation',
});
}
return out;
};
// ─── CSV 导出(带 BOM,Excel 直接打开不乱码) ─────────────────────
export const downloadCsv = (filename, headers, rows) => {
const escape = (v) => {
const s = v === null || v === undefined ? '' : String(v);
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
const lines = [headers.map(escape).join(',')];
rows.forEach((r) => lines.push(r.map(escape).join(',')));
const blob = new Blob(['' + lines.join('\r\n')], {
type: 'text/csv;charset=utf-8;',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
export const orgDisplayName = (o, t) =>
o.deleted ? `${t('已删除企业')} #${o.org_id}` : o.name || `#${o.org_id}`;