refactor file tree

This commit is contained in:
Timi
2026-08-11 15:24:36 +08:00
parent 575d41b2e2
commit 819c1623eb
42 changed files with 86 additions and 86 deletions
+690
View File
@@ -0,0 +1,690 @@
<template>
<div v-can="permissionCodes.stat.read" class="customer-data-charts-page">
<div class="header">
<div class="selector bg-white" :class="{ 'selected' : selectedCustomer }">
<div class="line buttons">
<t-button
v-if="selectedCustomer"
theme="primary"
@click="clearCustomerSelection"
>清除</t-button>
<t-button class="customer" block theme="primary" variant="outline" @click="selectorVisible = true">
<template #icon>
<t-icon name="user-search" />
</template>
<span v-text="selectedCustomer ? selectedCustomer.name : '选择客户'" />
</t-button>
<t-button theme="primary" @click="toggleScanner">
<template #icon>
<t-icon name="scan" />
</template>
<span>扫码</span>
</t-button>
</div>
<div v-if="scannerVisible" class="line scanner-wrapper">
<code-scanner
visible
:status-text="scanStatus"
active-text="正在识别客户编码,请将二维码移入取景框"
@decode="handleDecodedText"
@status-change="handleScanStatusChange"
/>
</div>
</div>
</div>
<section v-if="selectedCustomer" class="summary">
<div v-for="item in summaryList" :key="item.label" class="summary-item">
<span v-text="item.label" />
<strong v-text="item.value" />
</div>
</section>
<event-record-calendar
v-if="selectedCustomer"
v-model="monthCursor"
v-model:selected-event-id-list="selectedEventIdList"
class="calendar-section"
:event-list="eventList"
:customer-name="selectedCustomer.name"
:loading="calendarLoading"
:records="monthRecords"
/>
<section
v-for="item in chartList"
:key="item.id"
class="chart-section"
>
<h2 v-text="item.title" />
<div :ref="element => setChartRef(item.id, element)" class="chart" />
</section>
<customer-selector
v-model="selectedCustomerId"
v-model:visible="selectorVisible"
@change="handleCustomerSelected"
/>
</div>
</template>
<script setup lang="ts">
import type {ECharts, EChartsOption} from "echarts";
import {BarChart, LineChart} from "echarts/charts";
import {GridComponent, LegendComponent, TooltipComponent} from "echarts/components";
import {init, use} from "echarts/core";
import {CanvasRenderer} from "echarts/renderers";
import {Time} from "timi-web";
import CustomerAPI from "@/api/CustomerAPI";
import EventAPI from "@/api/EventAPI";
import EventRecordAPI from "@/api/EventRecordAPI";
import type {Customer} from "@/types/Customer";
import type {EventItem} from "@/types/EventItem";
import type {EventRecord} from "@/types/EventRecord";
import CodeScanner from "@/components/CodeScanner.vue";
import CustomerSelector from "@/components/CustomerSelector.vue";
import EventRecordCalendar from "@/components/EventRecordCalendar.vue";
import {useSettingStore} from "@/store/settingStore";
import {permissionCodes} from "@/utils/permission";
interface SummaryItem {
label: string;
value: string;
}
interface ChartProfile {
id: string;
title: string;
option: EChartsOption;
}
defineOptions({
name: "CustomerDataCharts"
});
use([
BarChart,
LineChart,
GridComponent,
LegendComponent,
TooltipComponent,
CanvasRenderer
]);
const settingStore = useSettingStore();
const router = useRouter();
const route = useRoute();
const chartRefs = new Map<string, HTMLElement>();
const chartInstances = new Map<string, ECharts>();
const routeCustomerId = computed(() => String(route.params.id || ""));
const routeCustomerCode = computed(() => String(route.query.customerCode || ""));
const customerCode = ref(routeCustomerCode.value);
const selectedCustomerId = ref(routeCustomerId.value);
const selectorVisible = ref(false);
const scannerVisible = ref(false);
const scanStatus = ref("点击扫码开始识别。");
const selectedCustomer = ref<Customer>();
const eventList = ref<EventItem[]>([]);
const selectedEventIdList = ref<string[]>([]);
const monthCursor = ref(getMonthStart(new Date()));
const monthRecords = ref<EventRecord[]>([]);
const calendarLoading = ref(false);
let latestDecodedText = "";
const eventNameMap = computed(() => {
const map = new Map<string, string>();
for (const item of eventList.value) {
if (item.id) {
map.set(item.id, item.name || "未命名事件");
}
}
return map;
});
const selectedEventIdSet = computed(() => new Set(selectedEventIdList.value));
const filteredMonthRecords = computed(() => {
if (!selectedEventIdList.value.length) {
return [];
}
return monthRecords.value.filter(item => {
if (!item.eventId || !selectedEventIdSet.value.has(item.eventId)) {
return false;
}
const recordDate = Time.toDateObject(item.registeredAt);
return !!recordDate && recordDate.getFullYear() === monthCursor.value.getFullYear() && recordDate.getMonth() === monthCursor.value.getMonth();
});
});
const monthDateTextList = computed(() => buildMonthDateTextList(monthCursor.value));
const summaryList = computed<SummaryItem[]>(() => [
{
label: "本月登记",
value: `${filteredMonthRecords.value.length} 次`
},
{
label: "转介绍",
value: `${selectedCustomer.value?.invitedCount || 0} 人`
},
{
label: "最近登记",
value: getRecordEventName(filteredMonthRecords.value[0]) || "暂无"
}
]);
const chartList = computed<ChartProfile[]>(() => {
if (!selectedCustomer.value) {
return [];
}
return [
{
id: "customer-record-trend",
title: "客户登记趋势",
option: buildRecordTrendOption()
},
{
id: "customer-event-structure",
title: "登记事件结构",
option: buildBehaviorStructureOption()
},
{
id: "customer-relation",
title: "客户关系数据",
option: buildRelationOption()
}
];
});
watch(chartList, async () => {
await nextTick();
renderCharts();
});
watch(routeCustomerCode, (value) => {
if (value) {
customerCode.value = value;
}
});
watch(routeCustomerId, async (value) => {
if (value) {
await loadCustomerById(value);
}
});
watch(customerCode, async (value) => {
await loadCustomer(value);
});
watch([selectedCustomer, monthCursor], async () => {
await loadMonthRecords();
});
onMounted(async () => {
await loadActions();
if (routeCustomerId.value) {
await loadCustomerById(routeCustomerId.value);
} else if (customerCode.value) {
await loadCustomer(customerCode.value);
}
await nextTick();
renderCharts();
window.addEventListener("resize", resizeCharts);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", resizeCharts);
chartInstances.forEach(item => item.dispose());
chartInstances.clear();
});
function setChartRef(id: string, element: Element | ComponentPublicInstance | null): void {
if (element instanceof HTMLElement) {
chartRefs.set(id, element);
}
}
function renderCharts(): void {
for (const item of chartList.value) {
const element = chartRefs.get(item.id);
if (!element) {
continue;
}
const chart = getChartInstance(item.id, element);
chart.setOption(item.option, true);
}
}
function getChartInstance(id: string, element: HTMLElement): ECharts {
const instance = chartInstances.get(id);
if (instance) {
return instance;
}
const chart = init(element);
chartInstances.set(id, chart);
return chart;
}
function resizeCharts(): void {
chartInstances.forEach(item => item.resize());
}
// ---------- 数据 ----------
async function loadActions(): Promise<void> {
eventList.value = await EventAPI.listValid();
selectedEventIdList.value = eventList.value.map(item => item.id).filter((item): item is string => Boolean(item));
}
async function loadCustomer(code: string): Promise<void> {
const normalizedCode = code.trim();
if (!normalizedCode) {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
monthRecords.value = [];
return;
}
const customer = await CustomerAPI.findByCode(normalizedCode);
if (!customer) {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
monthRecords.value = [];
return;
}
selectedCustomer.value = customer;
selectedCustomerId.value = customer.id || "";
}
async function loadCustomerById(id: string): Promise<void> {
const normalizedId = id.trim();
if (!normalizedId) {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
monthRecords.value = [];
return;
}
try {
selectedCustomer.value = await CustomerAPI.detail(normalizedId);
selectedCustomerId.value = selectedCustomer.value.id || "";
} catch (err) {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
monthRecords.value = [];
console.warn("客户详情加载失败", err);
}
}
async function handleCustomerSelected(id: string): Promise<void> {
await loadCustomerById(id);
}
async function clearCustomerSelection(): Promise<void> {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
customerCode.value = "";
monthRecords.value = [];
if (route.name !== "CustomerDataCharts" || Object.keys(route.query).length) {
await router.replace({name: "CustomerDataCharts"});
}
}
async function loadMonthRecords(): Promise<void> {
const customerId = selectedCustomer.value?.id;
if (!customerId) {
monthRecords.value = [];
return;
}
const beginDate = getCalendarBeginDate(monthCursor.value);
const endDate = getDateEnd(addDays(beginDate, 41));
calendarLoading.value = true;
try {
monthRecords.value = (await EventRecordAPI.list({
index: 0,
size: Number.MAX_SAFE_INTEGER,
customerId,
beginAt: Time.toTimestamp(beginDate),
endAt: Time.toTimestamp(endDate)
})).list;
} finally {
calendarLoading.value = false;
}
}
// ---------- 扫码 ----------
async function toggleScanner(): Promise<void> {
scannerVisible.value = !scannerVisible.value;
if (scannerVisible.value) {
latestDecodedText = "";
scanStatus.value = "正在启动扫码预览。";
}
}
async function handleDecodedText(rawText: string): Promise<void> {
const normalizedText = rawText.trim();
if (!normalizedText || normalizedText === latestDecodedText) {
return;
}
latestDecodedText = normalizedText;
await settingStore.playScanSuccessSound();
customerCode.value = normalizedText;
scanStatus.value = `已识别 ${normalizedText},正在加载客户档案。`;
scannerVisible.value = false;
}
function handleScanStatusChange(value: string): void {
scanStatus.value = value;
}
function getRecordDateText(record: EventRecord): string {
const date = Time.toDateObject(record.registeredAt);
return date ? Time.formatDate(date) : "";
}
function getRecordEventName(record?: EventRecord): string {
if (!record) {
return "";
}
return record.event?.name || (record.eventId ? eventNameMap.value.get(record.eventId) : "") || "未知事件";
}
// ---------- 图表 ----------
function buildBaseOption(): EChartsOption {
return {
color: ["#2563eb", "#0f766e", "#d97706", "#db2777", "#7c3aed"],
grid: {
top: 48,
left: 12,
right: 12,
bottom: 12,
containLabel: true
},
legend: {
top: 0,
icon: "roundRect",
textStyle: {
color: "#52607a"
}
},
tooltip: {
trigger: "axis"
},
xAxis: {
type: "category",
data: monthDateTextList.value.map(item => item.slice(5)),
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
yAxis: {
type: "value",
axisLabel: {
color: "#52607a"
},
splitLine: {
lineStyle: {
color: "rgba(148, 163, 184, .2)"
}
}
}
};
}
function buildRecordTrendOption(): EChartsOption {
return {
...buildBaseOption(),
series: [
{
name: "登记次数",
type: "line",
smooth: true,
data: monthDateTextList.value.map(date => filteredMonthRecords.value.filter(item => getRecordDateText(item) === date).length)
}
]
};
}
function buildBehaviorStructureOption(): EChartsOption {
return {
...buildBaseOption(),
xAxis: {
type: "category",
data: eventList.value.filter(item => item.id && selectedEventIdSet.value.has(item.id)).map(item => item.name || "未命名事件"),
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [
{
name: "登记次数",
type: "bar",
data: eventList.value
.filter(item => item.id && selectedEventIdSet.value.has(item.id))
.map(item => ({
value: filteredMonthRecords.value.filter(record => record.eventId === item.id).length,
itemStyle: getEventColor(item) ? {
color: getEventColor(item)
} : undefined
}))
}
]
};
}
function getEventColor(event: EventItem): string | undefined {
return event.color || undefined;
}
function buildRelationOption(): EChartsOption {
return {
...buildBaseOption(),
xAxis: {
type: "category",
data: ["介绍人", "转介绍客户"],
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [
{
name: "客户数",
type: "bar",
data: [selectedCustomer.value?.introducerCustomerId ? 1 : 0, selectedCustomer.value?.invitedCount || 0]
}
]
};
}
// ---------- 日期 ----------
function getMonthStart(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);
}
function getCalendarBeginDate(date: Date): Date {
const monthStart = getMonthStart(date);
return addDays(monthStart, -monthStart.getDay());
}
function buildMonthDateTextList(date: Date): string[] {
const monthStart = getMonthStart(date);
const nextMonthStart = addMonths(monthStart, 1);
const list: string[] = [];
for (let item = monthStart; item < nextMonthStart; item = addDays(item, 1)) {
list.push(Time.formatDate(item));
}
return list;
}
function addDays(date: Date, days: number): Date {
const value = new Date(date);
value.setDate(value.getDate() + days);
return value;
}
function addMonths(date: Date, months: number): Date {
return new Date(date.getFullYear(), date.getMonth() + months, 1, 0, 0, 0, 0);
}
function getDateEnd(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
}
</script>
<style scoped lang="less">
.customer-data-charts-page {
gap: 1rem;
padding: var(--app-nav-height) 0 1rem 0;
display: flex;
flex-direction: column;
.header {
top: var(--app-nav-height);
z-index: 10;
padding: 1rem 1rem .875rem 1rem;
position: sticky;
box-shadow: var(--td-shadow-1);
background: #F5F5F8;
.selector {
border: 1px solid rgba(148, 163, 184, .18);
display: flex;
overflow: hidden;
border-radius: .35rem .35rem 1rem 1rem;
flex-direction: column;
&.selected {
border: 1px solid transparent;
background: transparent;
border-radius: 0;
}
.line {
gap: .75rem;
display: flex;
&.buttons {
z-index: 1;
.customer {
flex: 1;
min-width: 0;
}
}
&.scanner-wrapper {
margin: 1rem .5rem;
}
}
}
}
.summary {
gap: .75rem;
margin: 0 1rem;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
.summary-item {
padding: .875rem .625rem;
display: flex;
min-width: 0;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
align-items: center;
border-radius: .75rem;
flex-direction: column;
span {
color: #52607a;
font-size: .75rem;
}
strong {
margin-top: .375rem;
color: #0f172a;
font-size: 1rem;
font-weight: 700;
}
}
}
.chart-section {
margin: 0 1rem;
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: .75rem;
h2 {
margin: 0;
color: #0f172a;
font-size: 1rem;
font-weight: 700;
}
}
.calendar-section {
margin: 0 1rem;
}
.chart-section {
h2 {
margin-bottom: .875rem;
}
.chart {
width: 100%;
height: 16rem;
}
}
}
:global(html.theme-dark) {
.customer-data-charts-page {
.selector {
background: #10161f;
}
.summary {
.summary-item {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
span {
color: #94a3b8;
}
strong {
color: #e2e8f0;
}
}
}
.calendar-section,
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
}
</style>