update chart

This commit is contained in:
Timi
2026-08-12 00:24:12 +08:00
parent 9c30891f2c
commit 171aee1602
17 changed files with 1554 additions and 697 deletions
+19
View File
@@ -0,0 +1,19 @@
import { axios } from "timi-web";
import type { CustomerChartReq } from "@/types/Customer";
import type { StoreEventRecordCalendarView, StoreEventRecordDailyStatView } from "@/types/Store";
import { withCurrentStoreId } from "@/utils/store";
const BASE_URI = "/gao/customer/chart";
async function eventRecordDailyStat(req: CustomerChartReq): Promise<StoreEventRecordDailyStatView[]> {
return await axios.post(`${BASE_URI}/event/record/daily`, withCurrentStoreId(req));
}
async function eventRecordCalendar(req: CustomerChartReq): Promise<StoreEventRecordCalendarView[]> {
return await axios.post(`${BASE_URI}/event/record/calendar`, withCurrentStoreId(req));
}
export default {
eventRecordDailyStat,
eventRecordCalendar
};
+31
View File
@@ -0,0 +1,31 @@
import { axios } from "timi-web";
import type { CustomerDailyStatView, CustomerGenderStatView } from "@/types/Customer";
import type { StoreChartReq, StoreEventRecordCalendarView, StoreEventRecordDailyStatView } from "@/types/Store";
import { getCurrentStoreId, withCurrentStoreId } from "@/utils/store";
const BASE_URI = "/gao/store/chart";
async function customerDailyStat(req: StoreChartReq): Promise<CustomerDailyStatView[]> {
return await axios.post(`${BASE_URI}/customer/daily`, withCurrentStoreId(req));
}
async function customerGenderStat(): Promise<CustomerGenderStatView[]> {
return await axios.post(`${BASE_URI}/customer/gender`, undefined, {
params: { storeId: getCurrentStoreId() }
});
}
async function eventRecordDailyStat(req: StoreChartReq): Promise<StoreEventRecordDailyStatView[]> {
return await axios.post(`${BASE_URI}/event/record/daily`, withCurrentStoreId(req));
}
async function eventRecordCalendar(req: StoreChartReq): Promise<StoreEventRecordCalendarView[]> {
return await axios.post(`${BASE_URI}/event/record/calendar`, withCurrentStoreId(req));
}
export default {
customerDailyStat,
customerGenderStat,
eventRecordDailyStat,
eventRecordCalendar
};
+247
View File
@@ -0,0 +1,247 @@
<template>
<div class="chart-range-slider">
<div ref="trackRef" class="track" @pointerdown="handleTrackPointerDown">
<div
class="selection"
:style="selectionStyle"
@pointerdown.stop="handleSelectionPointerDown"
/>
<button
class="thumb start"
:style="startThumbStyle"
type="button"
aria-label="调整开始日期"
@pointerdown.stop="event => handleThumbPointerDown('start', event)"
/>
<button
class="thumb end"
:style="endThumbStyle"
type="button"
aria-label="调整结束日期"
@pointerdown.stop="event => handleThumbPointerDown('end', event)"
/>
</div>
<div class="label" v-text="label" />
</div>
</template>
<script setup lang="ts">
type DragMode = "start" | "end" | "range";
const props = withDefaults(defineProps<{
label?: string;
max: number;
min?: number;
minRange?: number;
modelValue: number[];
}>(), {
label: "",
minRange: 0,
min: 0
});
const emit = defineEmits<{
"update:modelValue": [value: number[]];
change: [value: number[]];
}>();
const trackRef = ref<HTMLElement>();
const draggingMode = ref<DragMode>();
const dragStartX = ref(0);
const dragStartValue = ref<[number, number]>([0, 0]);
const safeMin = computed(() => Math.min(props.min, props.max));
const safeMax = computed(() => Math.max(props.min, props.max));
const valueRange = computed(() => Math.max(1, safeMax.value - safeMin.value));
const safeMinRange = computed(() => Math.min(Math.max(0, Math.round(props.minRange)), valueRange.value));
const normalizedValue = computed<[number, number]>(() => normalizeRange(props.modelValue));
const startPercent = computed(() => valueToPercent(normalizedValue.value[0]));
const endPercent = computed(() => valueToPercent(normalizedValue.value[1]));
const selectionStyle = computed(() => ({
left: `${startPercent.value}%`,
width: `${Math.max(0, endPercent.value - startPercent.value)}%`
}));
const startThumbStyle = computed(() => ({
left: `${startPercent.value}%`
}));
const endThumbStyle = computed(() => ({
left: `${endPercent.value}%`
}));
onBeforeUnmount(() => {
stopDocumentDrag();
});
function handleThumbPointerDown(mode: "start" | "end", event: PointerEvent): void {
startDocumentDrag(mode, event);
}
function handleSelectionPointerDown(event: PointerEvent): void {
startDocumentDrag("range", event);
}
function handleTrackPointerDown(event: PointerEvent): void {
const value = pointToValue(event.clientX);
const [start, end] = normalizedValue.value;
const targetMode: DragMode = Math.abs(value - start) <= Math.abs(value - end) ? "start" : "end";
updateByMode(targetMode, value);
startDocumentDrag(targetMode, event);
}
function startDocumentDrag(mode: DragMode, event: PointerEvent): void {
draggingMode.value = mode;
dragStartX.value = event.clientX;
dragStartValue.value = normalizedValue.value;
window.addEventListener("pointermove", handleDocumentPointerMove);
window.addEventListener("pointerup", handleDocumentPointerUp);
window.addEventListener("pointercancel", handleDocumentPointerUp);
}
function handleDocumentPointerMove(event: PointerEvent): void {
const mode = draggingMode.value;
if (!mode) {
return;
}
if (mode === "range") {
const nextValue = dragStartValue.value[0] + pointDeltaToStep(event.clientX - dragStartX.value);
const width = dragStartValue.value[1] - dragStartValue.value[0];
const start = clamp(nextValue, safeMin.value, safeMax.value - width);
commitRange([start, start + width]);
return;
}
updateByMode(mode, pointToValue(event.clientX));
}
function handleDocumentPointerUp(): void {
stopDocumentDrag();
}
function stopDocumentDrag(): void {
window.removeEventListener("pointermove", handleDocumentPointerMove);
window.removeEventListener("pointerup", handleDocumentPointerUp);
window.removeEventListener("pointercancel", handleDocumentPointerUp);
draggingMode.value = undefined;
}
function updateByMode(mode: "start" | "end", value: number): void {
const [start, end] = normalizedValue.value;
if (mode === "start") {
commitRange([Math.min(value, end - safeMinRange.value), end]);
return;
}
commitRange([start, Math.max(start + safeMinRange.value, value)]);
}
function commitRange(value: [number, number]): void {
const normalized = normalizeRange(value);
emit("update:modelValue", normalized);
emit("change", normalized);
}
function normalizeRange(value: number[]): [number, number] {
const rawStart = value[0] ?? safeMin.value;
const rawEnd = value[1] ?? rawStart;
const start = clamp(Math.round(Math.min(rawStart, rawEnd)), safeMin.value, safeMax.value);
const end = clamp(Math.round(Math.max(rawStart, rawEnd)), start + safeMinRange.value, safeMax.value);
if (safeMax.value < start + safeMinRange.value) {
return [safeMin.value, safeMax.value];
}
return [Math.min(start, end - safeMinRange.value), end];
}
function pointToValue(clientX: number): number {
const rect = trackRef.value?.getBoundingClientRect();
if (!rect || rect.width <= 0) {
return safeMin.value;
}
const percent = clamp((clientX - rect.left) / rect.width, 0, 1);
return Math.round(safeMin.value + percent * valueRange.value);
}
function pointDeltaToStep(deltaX: number): number {
const rect = trackRef.value?.getBoundingClientRect();
if (!rect || rect.width <= 0) {
return 0;
}
return Math.round(deltaX / rect.width * valueRange.value);
}
function valueToPercent(value: number): number {
return (clamp(value, safeMin.value, safeMax.value) - safeMin.value) / valueRange.value * 100;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
</script>
<style scoped lang="less">
.chart-range-slider {
padding: .25rem .25rem 0 .25rem;
.track {
height: 2.25rem;
display: flex;
position: relative;
align-items: center;
touch-action: none;
&::before {
left: 0;
right: 0;
height: .25rem;
content: "";
position: absolute;
background: rgba(148, 163, 184, .24);
border-radius: 999rem;
}
}
.selection {
height: .25rem;
position: absolute;
background: var(--td-brand-color);
border-radius: 999rem;
touch-action: none;
}
.thumb {
top: 50%;
margin: 0;
padding: 0;
width: 1.25rem;
height: 1.25rem;
border: .125rem solid var(--td-brand-color);
position: absolute;
background: #fff;
transform: translate(-50%, -50%);
box-shadow: 0 .125rem .5rem rgba(15, 23, 42, .18);
border-radius: 999rem;
touch-action: none;
}
.label {
color: #52607a;
font-size: .75rem;
text-align: center;
white-space: nowrap;
}
}
:global(html.theme-dark) {
.chart-range-slider {
.track::before {
background: rgba(148, 163, 184, .28);
}
.thumb {
background: #10161f;
box-shadow: 0 .125rem .5rem rgba(2, 6, 23, .38);
}
.label {
color: #94a3b8;
}
}
}
</style>
+119 -298
View File
@@ -38,24 +38,28 @@
<strong v-text="item.value" /> <strong v-text="item.value" />
</div> </div>
</section> </section>
<event-record-calendar <customer-event-record-calendar-section
v-if="selectedCustomer" v-if="selectedCustomer"
v-model="monthCursor" v-model="monthCursor"
v-model:selected-event-id-list="selectedEventIdList" v-model:selected-event-id-list="selectedEventIdList"
class="calendar-section"
:event-list="eventList"
:customer-name="selectedCustomer.name" :customer-name="selectedCustomer.name"
:event-list="eventList"
:loading="calendarLoading" :loading="calendarLoading"
:records="monthRecords" :records="monthRecords"
/> />
<section <customer-record-trend-chart
v-for="item in chartList" v-if="selectedCustomer"
:key="item.id" :date-text-list="chartDateTextList"
class="chart-section" :selected-event-id-list="selectedEventIdList"
> :stat-map="recordDailyStatMap"
<h2 v-text="item.title" /> />
<div :ref="element => setChartRef(item.id, element)" class="chart" /> <customer-event-structure-chart
</section> v-if="selectedCustomer"
:date-text-list="monthDateTextList"
:event-list="eventList"
:selected-event-id-list="selectedEventIdList"
:stat-map="recordDailyStatMap"
/>
<customer-selector <customer-selector
v-model="selectedCustomerId" v-model="selectedCustomerId"
v-model:visible="selectorVisible" v-model:visible="selectorVisible"
@@ -65,53 +69,34 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type {ECharts, EChartsOption} from "echarts"; import { Time } from "timi-web";
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 CustomerAPI from "@/api/CustomerAPI";
import CustomerChartAPI from "@/api/CustomerChartAPI";
import EventAPI from "@/api/EventAPI"; 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 CodeScanner from "@/components/CodeScanner.vue";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import EventRecordCalendar from "@/components/EventRecordCalendar.vue"; import CustomerEventRecordCalendarSection from "@/pages/customer/component/CustomerEventRecordCalendarSection.vue";
import {useSettingStore} from "@/store/settingStore"; import CustomerEventStructureChart from "@/pages/customer/component/CustomerEventStructureChart.vue";
import {permissionCodes} from "@/utils/permission"; import CustomerRecordTrendChart from "@/pages/customer/component/CustomerRecordTrendChart.vue";
import { useSettingStore } from "@/store/settingStore";
import type { Customer } from "@/types/Customer";
import type { EventItem } from "@/types/EventItem";
import type { EventRecord } from "@/types/EventRecord";
import type { StoreEventRecordCalendarView, StoreEventRecordDailyStatView } from "@/types/Store";
import { permissionCodes } from "@/utils/permission";
interface SummaryItem { interface SummaryItem {
label: string; label: string;
value: string; value: string;
} }
interface ChartProfile {
id: string;
title: string;
option: EChartsOption;
}
defineOptions({ defineOptions({
name: "CustomerDataCharts" name: "CustomerDataCharts"
}); });
use([
BarChart,
LineChart,
GridComponent,
LegendComponent,
TooltipComponent,
CanvasRenderer
]);
const settingStore = useSettingStore(); const settingStore = useSettingStore();
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
const chartRefs = new Map<string, HTMLElement>();
const chartInstances = new Map<string, ECharts>();
const routeCustomerId = computed(() => String(route.params.id || "")); const routeCustomerId = computed(() => String(route.params.id || ""));
const routeCustomerCode = computed(() => String(route.query.customerCode || "")); const routeCustomerCode = computed(() => String(route.query.customerCode || ""));
const customerCode = ref(routeCustomerCode.value); const customerCode = ref(routeCustomerCode.value);
@@ -125,7 +110,12 @@ const selectedEventIdList = ref<string[]>([]);
const monthCursor = ref(getMonthStart(new Date())); const monthCursor = ref(getMonthStart(new Date()));
const monthRecords = ref<EventRecord[]>([]); const monthRecords = ref<EventRecord[]>([]);
const calendarLoading = ref(false); const calendarLoading = ref(false);
const recordDailyStatMap = ref<Record<string, StoreEventRecordDailyStatView[]>>({});
const chartBeginDate = getDateStart(addMonths(new Date(), -1));
const chartEndDate = getDateEnd(new Date());
const chartDateTextList = buildDateTextList(chartBeginDate, chartEndDate);
let latestDecodedText = ""; let latestDecodedText = "";
let monthDataRequestId = 0;
const eventNameMap = computed(() => { const eventNameMap = computed(() => {
const map = new Map<string, string>(); const map = new Map<string, string>();
@@ -165,33 +155,6 @@ const summaryList = computed<SummaryItem[]>(() => [
value: getRecordEventName(filteredMonthRecords.value[0]) || "暂无" 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) => { watch(routeCustomerCode, (value) => {
if (value) { if (value) {
@@ -210,81 +173,35 @@ watch(customerCode, async (value) => {
}); });
watch([selectedCustomer, monthCursor], async () => { watch([selectedCustomer, monthCursor], async () => {
await loadMonthRecords(); await loadMonthData();
}); });
onMounted(async () => { onMounted(async () => {
await loadActions(); await loadEvents();
if (routeCustomerId.value) { if (routeCustomerId.value) {
await loadCustomerById(routeCustomerId.value); await loadCustomerById(routeCustomerId.value);
} else if (customerCode.value) { } else if (customerCode.value) {
await loadCustomer(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> { async function loadEvents(): Promise<void> {
eventList.value = await EventAPI.listValid(); eventList.value = await EventAPI.listValid();
selectedEventIdList.value = eventList.value.map(item => item.id).filter((item): item is string => Boolean(item)); selectedEventIdList.value = getEventIdList();
} }
async function loadCustomer(code: string): Promise<void> { async function loadCustomer(code: string): Promise<void> {
const normalizedCode = code.trim(); const normalizedCode = code.trim();
if (!normalizedCode) { if (!normalizedCode) {
selectedCustomer.value = undefined; clearLoadedCustomer();
selectedCustomerId.value = "";
monthRecords.value = [];
return; return;
} }
const customer = await CustomerAPI.findByCode(normalizedCode); const customer = await CustomerAPI.findByCode(normalizedCode);
if (!customer) { if (!customer) {
selectedCustomer.value = undefined; clearLoadedCustomer();
selectedCustomerId.value = "";
monthRecords.value = [];
return; return;
} }
@@ -295,9 +212,7 @@ async function loadCustomer(code: string): Promise<void> {
async function loadCustomerById(id: string): Promise<void> { async function loadCustomerById(id: string): Promise<void> {
const normalizedId = id.trim(); const normalizedId = id.trim();
if (!normalizedId) { if (!normalizedId) {
selectedCustomer.value = undefined; clearLoadedCustomer();
selectedCustomerId.value = "";
monthRecords.value = [];
return; return;
} }
@@ -305,9 +220,7 @@ async function loadCustomerById(id: string): Promise<void> {
selectedCustomer.value = await CustomerAPI.detail(normalizedId); selectedCustomer.value = await CustomerAPI.detail(normalizedId);
selectedCustomerId.value = selectedCustomer.value.id || ""; selectedCustomerId.value = selectedCustomer.value.id || "";
} catch (err) { } catch (err) {
selectedCustomer.value = undefined; clearLoadedCustomer();
selectedCustomerId.value = "";
monthRecords.value = [];
console.warn("客户详情加载失败", err); console.warn("客户详情加载失败", err);
} }
} }
@@ -317,36 +230,63 @@ async function handleCustomerSelected(id: string): Promise<void> {
} }
async function clearCustomerSelection(): Promise<void> { async function clearCustomerSelection(): Promise<void> {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
customerCode.value = ""; customerCode.value = "";
monthRecords.value = []; clearLoadedCustomer();
if (route.name !== "CustomerDataCharts" || Object.keys(route.query).length) { if (route.name !== "CustomerDataCharts" || Object.keys(route.query).length) {
await router.replace({name: "CustomerDataCharts"}); await router.replace({ name: "CustomerDataCharts" });
} }
} }
async function loadMonthRecords(): Promise<void> { function clearLoadedCustomer(): void {
selectedCustomer.value = undefined;
selectedCustomerId.value = "";
monthRecords.value = [];
recordDailyStatMap.value = {};
}
async function loadMonthData(): Promise<void> {
const customerId = selectedCustomer.value?.id; const customerId = selectedCustomer.value?.id;
if (!customerId) { if (!customerId) {
monthRecords.value = []; monthRecords.value = [];
recordDailyStatMap.value = {};
return; return;
} }
const beginDate = getCalendarBeginDate(monthCursor.value); const eventIdList = getEventIdList();
const endDate = getDateEnd(addDays(beginDate, 41)); if (!eventIdList.length) {
monthRecords.value = [];
recordDailyStatMap.value = {};
return;
}
const requestId = ++monthDataRequestId;
const calendarBeginDate = getCalendarBeginDate(monthCursor.value);
const calendarEndDate = getDateEnd(addDays(calendarBeginDate, 41));
calendarLoading.value = true; calendarLoading.value = true;
try { try {
monthRecords.value = (await EventRecordAPI.list({ const [dailyStatList, calendarRecordList] = await Promise.all([
index: 0, CustomerChartAPI.eventRecordDailyStat({
size: Number.MAX_SAFE_INTEGER, customerId,
customerId, beginAt: Time.toTimestamp(chartBeginDate),
beginAt: Time.toTimestamp(beginDate), endAt: Time.toTimestamp(chartEndDate),
endAt: Time.toTimestamp(endDate) eventIdList
})).list; }),
CustomerChartAPI.eventRecordCalendar({
customerId,
beginAt: Time.toTimestamp(calendarBeginDate),
endAt: Time.toTimestamp(calendarEndDate),
eventIdList
})
]);
if (requestId === monthDataRequestId) {
recordDailyStatMap.value = groupRecordDailyStatByEventId(dailyStatList);
monthRecords.value = calendarRecordList.map(buildCalendarRecord);
}
} finally { } finally {
calendarLoading.value = false; if (requestId === monthDataRequestId) {
calendarLoading.value = false;
}
} }
} }
@@ -377,9 +317,20 @@ function handleScanStatusChange(value: string): void {
scanStatus.value = value; scanStatus.value = value;
} }
function getRecordDateText(record: EventRecord): string { // ---------- 统计 ----------
const date = Time.toDateObject(record.registeredAt);
return date ? Time.formatDate(date) : ""; function groupRecordDailyStatByEventId(list: StoreEventRecordDailyStatView[]): Record<string, StoreEventRecordDailyStatView[]> {
const map: Record<string, StoreEventRecordDailyStatView[]> = {};
for (const item of list) {
if (!item.eventId) {
continue;
}
if (!map[item.eventId]) {
map[item.eventId] = [];
}
map[item.eventId].push(item);
}
return map;
} }
function getRecordEventName(record?: EventRecord): string { function getRecordEventName(record?: EventRecord): string {
@@ -390,120 +341,21 @@ function getRecordEventName(record?: EventRecord): string {
return record.event?.name || (record.eventId ? eventNameMap.value.get(record.eventId) : "") || "未知事件"; return record.event?.name || (record.eventId ? eventNameMap.value.get(record.eventId) : "") || "未知事件";
} }
// ---------- 图表 ---------- function getEventIdList(): string[] {
return eventList.value.map(item => item.id).filter((item): item is string => Boolean(item));
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 { function buildCalendarRecord(record: StoreEventRecordCalendarView): EventRecord {
return { return {
...buildBaseOption(), id: record.id,
series: [ customerId: record.customerId,
{ eventId: record.eventId,
name: "登记次数", registeredAt: record.registeredAt,
type: "line", customer: record.customerId || record.customerCode || record.customerName ? {
smooth: true, id: record.customerId,
data: monthDateTextList.value.map(date => filteredMonthRecords.value.filter(item => getRecordDateText(item) === date).length) code: record.customerCode,
} name: record.customerName
] } : undefined
};
}
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]
}
]
}; };
} }
@@ -513,6 +365,10 @@ function getMonthStart(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0); return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);
} }
function getDateStart(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
}
function getCalendarBeginDate(date: Date): Date { function getCalendarBeginDate(date: Date): Date {
const monthStart = getMonthStart(date); const monthStart = getMonthStart(date);
return addDays(monthStart, -monthStart.getDay()); return addDays(monthStart, -monthStart.getDay());
@@ -528,6 +384,14 @@ function buildMonthDateTextList(date: Date): string[] {
return list; return list;
} }
function buildDateTextList(begin: Date, end: Date): string[] {
const list: string[] = [];
for (let item = getDateStart(begin); item <= end; item = addDays(item, 1)) {
list.push(Time.formatDate(item));
}
return list;
}
function addDays(date: Date, days: number): Date { function addDays(date: Date, days: number): Date {
const value = new Date(date); const value = new Date(date);
value.setDate(value.getDate() + days); value.setDate(value.getDate() + days);
@@ -541,7 +405,6 @@ function addMonths(date: Date, months: number): Date {
function getDateEnd(date: Date): Date { function getDateEnd(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999); return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
} }
</script> </script>
<style scoped lang="less"> <style scoped lang="less">
@@ -621,37 +484,6 @@ function getDateEnd(date: Date): Date {
} }
} }
} }
.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) { :global(html.theme-dark) {
@@ -674,17 +506,6 @@ function getDateEnd(date: Date): Date {
} }
} }
} }
.calendar-section,
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
} }
} }
</style> </style>
@@ -0,0 +1,58 @@
<template>
<event-record-calendar
v-model="monthCursorProxy"
v-model:selected-event-id-list="selectedEventIdListProxy"
class="calendar-section"
:event-list="eventList"
:customer-name="customerName"
:loading="loading"
:records="records"
/>
</template>
<script setup lang="ts">
import EventRecordCalendar from "@/components/EventRecordCalendar.vue";
import type { EventItem } from "@/types/EventItem";
import type { EventRecord } from "@/types/EventRecord";
const props = defineProps<{
customerName?: string;
eventList: EventItem[];
loading?: boolean;
modelValue: Date;
records: EventRecord[];
selectedEventIdList: string[];
}>();
const emit = defineEmits<{
"update:modelValue": [value: Date];
"update:selectedEventIdList": [value: string[]];
}>();
const monthCursorProxy = computed({
get: () => props.modelValue,
set: value => emit("update:modelValue", value)
});
const selectedEventIdListProxy = computed({
get: () => props.selectedEventIdList,
set: value => emit("update:selectedEventIdList", value)
});
</script>
<style scoped lang="less">
.calendar-section {
margin: 0 1rem;
}
:global(html.theme-dark) {
.calendar-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
@@ -0,0 +1,91 @@
<template>
<section class="chart-section">
<h2>登记事件结构</h2>
<div ref="chartElement" class="chart" />
</section>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import type { EventItem } from "@/types/EventItem";
import type { StoreEventRecordDailyStatView } from "@/types/Store";
import { buildCustomerBaseChartOption, useCustomerChart } from "@/pages/customer/component/useCustomerChart";
const props = defineProps<{
dateTextList: string[];
eventList: EventItem[];
selectedEventIdList: string[];
statMap: Record<string, StoreEventRecordDailyStatView[]>;
}>();
const selectedEventIdSet = computed(() => new Set(props.selectedEventIdList));
const visibleEventList = computed(() => props.eventList.filter(item => item.id && selectedEventIdSet.value.has(item.id)));
const chartOption = computed<EChartsOption>(() => ({
...buildCustomerBaseChartOption(props.dateTextList),
xAxis: {
type: "category",
data: visibleEventList.value.map(item => item.name || "未命名事件"),
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [
{
name: "登记次数",
type: "bar",
data: visibleEventList.value.map(item => ({
value: countRecordByEvent(item.id || ""),
itemStyle: getEventColor(item) ? {
color: getEventColor(item)
} : undefined
}))
}
]
}));
const { chartElement } = useCustomerChart(chartOption);
function countRecordByEvent(eventId: string): number {
return (props.statMap[eventId] || []).reduce((sum, item) => sum + (item.dailyCount || 0), 0);
}
function getEventColor(event: EventItem): string | undefined {
return event.color || undefined;
}
</script>
<style scoped lang="less">
.chart-section {
margin: 0 1rem;
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: .75rem;
h2 {
color: #0f172a;
margin: 0 0 .875rem 0;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
:global(html.theme-dark) {
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
@@ -0,0 +1,88 @@
<template>
<section class="chart-section">
<h2>客户登记趋势</h2>
<div ref="chartElement" class="chart" />
<chart-range-slider
v-if="showSlider"
:model-value="sliderValue"
:max="maxSliderValue"
:min-range="5"
:label="rangeText"
@change="handleSliderChange"
/>
</section>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import ChartRangeSlider from "@/components/ChartRangeSlider.vue";
import type { StoreEventRecordDailyStatView } from "@/types/Store";
import { buildCustomerBaseChartOption, useCustomerChart, useCustomerChartWindow } from "@/pages/customer/component/useCustomerChart";
const props = defineProps<{
dateTextList: string[];
selectedEventIdList: string[];
statMap: Record<string, StoreEventRecordDailyStatView[]>;
}>();
const dateTextList = computed(() => props.dateTextList);
const {
rangeText,
showSlider,
sliderValue,
maxSliderValue,
visibleDateTextList,
handleSliderChange
} = useCustomerChartWindow(dateTextList);
const chartOption = computed<EChartsOption>(() => ({
...buildCustomerBaseChartOption(visibleDateTextList.value),
series: [
{
name: "登记次数",
type: "line",
smooth: true,
data: visibleDateTextList.value.map(dateText => countRecordByDate(dateText))
}
]
}));
const { chartElement } = useCustomerChart(chartOption);
function countRecordByDate(dateText: string): number {
const dateValue = Number(dateText.replaceAll("-", ""));
return props.selectedEventIdList.reduce((sum, eventId) => sum + (props.statMap[eventId]?.find(item => item.dateValue === dateValue)?.dailyCount || 0), 0);
}
</script>
<style scoped lang="less">
.chart-section {
margin: 0 1rem;
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: .75rem;
h2 {
color: #0f172a;
margin: 0 0 .875rem 0;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
:global(html.theme-dark) {
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
@@ -0,0 +1,164 @@
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 type { ComputedRef, Ref } from "vue";
use([
BarChart,
LineChart,
GridComponent,
LegendComponent,
TooltipComponent,
CanvasRenderer
]);
export function buildCustomerBaseChartOption(dateTextList: string[]): 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: dateTextList.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)"
}
}
}
};
}
export function useCustomerChart(option: ComputedRef<EChartsOption> | Ref<EChartsOption>) {
const chartElement = ref<HTMLElement>();
let chart: ECharts | undefined;
watch(option, async () => {
await nextTick();
renderChart();
}, {
deep: true
});
onMounted(async () => {
await nextTick();
renderChart();
window.addEventListener("resize", resizeChart);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", resizeChart);
chart?.dispose();
chart = undefined;
});
function renderChart(): void {
if (!chartElement.value) {
return;
}
chart = chart || init(chartElement.value);
chart.setOption(option.value, true);
}
function resizeChart(): void {
chart?.resize();
}
return {
chartElement
};
}
export function useCustomerChartWindow(dateTextList: ComputedRef<string[]>) {
const sliderValue = ref<number[]>([0, 0]);
const viewportWidth = ref(window.innerWidth);
let isSliderInitialized = false;
const visibleDayCount = computed(() => Math.max(6, Math.floor(viewportWidth.value / 64)));
const maxSliderValue = computed(() => Math.max(0, dateTextList.value.length - 1));
const visibleDateTextList = computed(() => dateTextList.value.slice(sliderValue.value[0], sliderValue.value[1] + 1));
const showSlider = computed(() => visibleDayCount.value < dateTextList.value.length);
const rangeText = computed(() => {
const list = visibleDateTextList.value;
const beginText = list[0]?.slice(5) || "";
const endText = list[list.length - 1]?.slice(5) || "";
return beginText && endText ? `${beginText} 至 ${endText}` : "";
});
watch(maxSliderValue, value => {
if (!isSliderInitialized) {
sliderValue.value = getLatestSliderRange();
isSliderInitialized = true;
return;
}
const [start, end] = sliderValue.value;
if (value < end) {
sliderValue.value = [Math.max(0, value - Math.max(0, end - start)), value];
}
}, {
immediate: true
});
onMounted(() => {
window.addEventListener("resize", updateViewportWidth);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", updateViewportWidth);
});
function handleSliderChange(value: number | number[]): void {
if (!Array.isArray(value)) {
return;
}
const [start = 0, end = start] = value;
sliderValue.value = [start, Math.max(start, end)];
}
function updateViewportWidth(): void {
viewportWidth.value = window.innerWidth;
}
function getLatestSliderRange(): number[] {
const end = maxSliderValue.value;
const start = Math.max(0, end - visibleDayCount.value + 1);
return [start, end];
}
return {
rangeText,
showSlider,
sliderValue,
maxSliderValue,
visibleDateTextList,
handleSliderChange
};
}
+59 -399
View File
@@ -7,38 +7,25 @@
</div> </div>
</section> </section>
<event-record-calendar <store-event-record-calendar-section :event-list="eventList" />
v-model="monthCursor" <store-customer-growth-chart :date-text-list="dateTextList" :stat-list="customerDailyStatList" />
v-model:selected-event-id-list="selectedEventIdList" <store-event-record-trend-chart :date-text-list="dateTextList" :event-list="eventList" :stat-map="recordDailyStatMap" />
:event-list="eventList" <store-event-structure-chart :date-text-list="dateTextList" :event-list="eventList" :stat-map="recordDailyStatMap" />
empty-text="当前月份暂无登记事件记录" <store-customer-gender-chart :date-text-list="dateTextList" :stat-list="customerGenderStatList" />
:loading="isCalendarLoading"
: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>
</div> </div>
</template> </template>
<script setup lang="ts"> <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 CustomerAPI from "@/api/CustomerAPI";
import EventAPI from "@/api/EventAPI"; import EventAPI from "@/api/EventAPI";
import EventRecordCalendar from "@/components/EventRecordCalendar.vue"; import StoreChartAPI from "@/api/StoreChartAPI";
import StoreCustomerGenderChart from "@/pages/store/component/StoreCustomerGenderChart.vue";
import StoreCustomerGrowthChart from "@/pages/store/component/StoreCustomerGrowthChart.vue";
import StoreEventRecordCalendarSection from "@/pages/store/component/StoreEventRecordCalendarSection.vue";
import StoreEventRecordTrendChart from "@/pages/store/component/StoreEventRecordTrendChart.vue";
import StoreEventStructureChart from "@/pages/store/component/StoreEventStructureChart.vue";
import type { CustomerDailyStatView, CustomerGenderStatView } from "@/types/Customer"; import type { CustomerDailyStatView, CustomerGenderStatView } from "@/types/Customer";
import type { EventItem } from "@/types/EventItem"; import type { EventItem } from "@/types/EventItem";
import type { EventRecord, EventRecordCalendarView, EventRecordDailyStatView } from "@/types/EventRecord"; import type { StoreEventRecordDailyStatView } from "@/types/Store";
import { Time } from "timi-web"; import { Time } from "timi-web";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
@@ -47,45 +34,18 @@ interface SummaryItem {
value: string; value: string;
} }
interface ChartProfile {
id: string;
title: string;
option: EChartsOption;
}
defineOptions({ defineOptions({
name: "StoreDataCharts" name: "StoreDataCharts"
}); });
use([
BarChart,
LineChart,
GridComponent,
LegendComponent,
TooltipComponent,
CanvasRenderer
]);
const chartRefs = new Map<string, HTMLElement>();
const chartInstances = new Map<string, ECharts>();
// ---------- 数据源 ---------- // ---------- 数据源 ----------
const eventList = ref<EventItem[]>([]); const eventList = ref<EventItem[]>([]);
const selectedEventIdList = ref<string[]>([]);
const customerDailyStatList = ref<CustomerDailyStatView[]>([]); const customerDailyStatList = ref<CustomerDailyStatView[]>([]);
const customerGenderStatList = ref<CustomerGenderStatView[]>([]); const customerGenderStatList = ref<CustomerGenderStatView[]>([]);
const recordDailyStatMap = ref<Record<string, EventRecordDailyStatView[]>>({}); const recordDailyStatMap = ref<Record<string, StoreEventRecordDailyStatView[]>>({});
const monthRecords = ref<EventRecord[]>([]); const weekBeginDate = getDateStart(addDays(new Date(), -6));
const isLoading = ref(false); const beginDate = getDateStart(addMonths(new Date(), -1));
const isCalendarLoading = ref(false);
const monthCursor = ref(getMonthStart(new Date()));
const genderColorMap = {
MALE: "#2563eb",
FEMALE: "#db2777",
UNKNOWN: "#64748b"
} as const;
const beginDate = getDateStart(addDays(new Date(), -6));
const endDate = getDateEnd(new Date()); const endDate = getDateEnd(new Date());
const dateTextList = buildDateTextList(beginDate, endDate); const dateTextList = buildDateTextList(beginDate, endDate);
const timestampRange = { const timestampRange = {
@@ -110,286 +70,31 @@ const summaryList = computed<SummaryItem[]>(() => [
} }
]); ]);
// ---------- 图表配置 ----------
const chartList = computed<ChartProfile[]>(() => [
{
id: "customer-growth",
title: "客户增长趋势",
option: buildCustomerGrowthOption()
},
{
id: "record-trend",
title: "登记量趋势",
option: buildRecordTrendOption()
},
{
id: "customer-value",
title: "事件结构",
option: buildEventStructureOption()
},
{
id: "customer-gender",
title: "性别统计",
option: buildGenderStatOption()
}
]);
watch(chartList, async () => {
await nextTick();
renderCharts();
});
// ---------- 日历 ----------
watch(monthCursor, async () => {
await loadMonthRecords();
});
onMounted(async () => { onMounted(async () => {
await loadChartsData(); await loadChartsData();
await loadMonthRecords();
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 loadChartsData(): Promise<void> { async function loadChartsData(): Promise<void> {
isLoading.value = true; eventList.value = await EventAPI.listValid();
try { const valideventList = eventList.value.filter((item): item is EventItem & { id: string } => Boolean(item.id));
eventList.value = await EventAPI.listValid(); const eventIdList = valideventList.map(item => item.id);
const valideventList = eventList.value.filter((item): item is EventItem & { id: string } => Boolean(item.id)); const [customerStatList, genderStatList, recordDailyStatList] = await Promise.all([
selectedEventIdList.value = valideventList.map(item => item.id); StoreChartAPI.customerDailyStat({
const [customerStatList, genderStatList, recordDailyStatList] = await Promise.all([ beginAt: timestampRange.beginAt,
CustomerAPI.dailyStat({ endAt: timestampRange.endAt
beginCreatedAt: timestampRange.beginAt, }),
endCreatedAt: timestampRange.endAt StoreChartAPI.customerGenderStat(),
}), eventIdList.length ? StoreChartAPI.eventRecordDailyStat({
CustomerAPI.genderStat(), beginAt: timestampRange.beginAt,
Promise.all(valideventList.map(async item => ({ endAt: timestampRange.endAt,
eventId: item.id, eventIdList
stats: [] }) : Promise.resolve([])
}))) ]);
]); customerDailyStatList.value = customerStatList;
customerDailyStatList.value = customerStatList; customerGenderStatList.value = genderStatList;
customerGenderStatList.value = genderStatList; recordDailyStatMap.value = groupRecordDailyStatByEventId(recordDailyStatList);
recordDailyStatMap.value = Object.fromEntries(recordDailyStatList.map(item => [item.eventId, item.stats]));
} finally {
isLoading.value = false;
}
}
async function loadMonthRecords(): Promise<void> {
const begin = getCalendarBeginDate(monthCursor.value);
const end = getDateEnd(addDays(begin, 41));
isCalendarLoading.value = true;
try {
await Promise.resolve({
beginAt: Time.toTimestamp(begin),
endAt: Time.toTimestamp(end)
});
const calendarRecordList: EventRecordCalendarView[] = [];
monthRecords.value = calendarRecordList.map(buildCalendarRecord);
} finally {
isCalendarLoading.value = false;
}
}
// ---------- 图表构建 ----------
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: dateTextList.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 buildCustomerGrowthOption(): EChartsOption {
return {
...buildBaseOption(),
series: [
{
name: "客户总量",
type: "line",
smooth: true,
data: dateTextList.map(dateText => getCustomerDailyStat(dateText)?.totalCustomerCount || 0)
},
{
name: "新客户量",
type: "bar",
data: dateTextList.map(dateText => getCustomerDailyStat(dateText)?.newCustomerCount || 0)
}
]
};
}
function buildRecordTrendOption(): EChartsOption {
return {
...buildBaseOption(),
series: eventList.value.map(action => ({
name: action.name || "未命名事件",
type: "bar",
stack: "record",
itemStyle: getEventColor(action) ? {
color: getEventColor(action)
} : undefined,
data: dateTextList.map(dateText => countRecordByEventAndDate(action.id || "", dateText))
}))
};
}
function buildEventStructureOption(): EChartsOption {
return {
...buildBaseOption(),
legend: {
show: false
},
xAxis: {
type: "category",
data: eventList.value.map(item => item.name || "未命名事件"),
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [{
name: "登记次数",
type: "bar",
data: eventList.value.map(item => ({
value: countRecordByEvent(item.id || ""),
itemStyle: getEventColor(item) ? {
color: getEventColor(item)
} : undefined
}))
}]
};
}
function buildGenderStatOption(): EChartsOption {
return {
...buildBaseOption(),
tooltip: {
trigger: "item"
},
xAxis: {
type: "category",
data: ["男", "女", "未知"],
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [
{
name: "男",
type: "bar",
itemStyle: {
color: genderColorMap.MALE
},
data: [getGenderCount("MALE"), 0, 0]
},
{
name: "女",
type: "bar",
itemStyle: {
color: genderColorMap.FEMALE
},
data: [0, getGenderCount("FEMALE"), 0]
},
{
name: "未知",
type: "bar",
itemStyle: {
color: genderColorMap.UNKNOWN
},
data: [0, 0, getGenderCount("UNKNOWN")]
}
]
};
} }
// ---------- 统计计算 ---------- // ---------- 统计计算 ----------
@@ -400,49 +105,33 @@ function getLatestTotalCustomerCount(): number {
} }
function sumCustomerNewCount(): number { function sumCustomerNewCount(): number {
return customerDailyStatList.value.reduce((sum, item) => sum + (item.newCustomerCount || 0), 0); return customerDailyStatList.value.filter(isRecentWeekStat).reduce((sum, item) => sum + (item.newCustomerCount || 0), 0);
} }
function sumActionDailyCount(): number { function sumActionDailyCount(): number {
return eventList.value.reduce((sum, item) => sum + countRecordByEvent(item.id || ""), 0); return eventList.value.reduce((sum, item) => sum + countRecentWeekRecordByEvent(item.id || ""), 0);
} }
function getCustomerDailyStat(dateText: string): CustomerDailyStatView | undefined { function countRecentWeekRecordByEvent(eventId: string): number {
const dateValue = Number(dateText.replaceAll("-", "")); return (recordDailyStatMap.value[eventId] || []).filter(isRecentWeekStat).reduce((sum, item) => sum + (item.dailyCount || 0), 0);
return customerDailyStatList.value.find(item => item.dateValue === dateValue);
} }
function countRecordByEventAndDate(eventId: string, dateText: string): number { function isRecentWeekStat(item: { dateValue?: number }): boolean {
const dateValue = Number(dateText.replaceAll("-", "")); return toDateValue(weekBeginDate) <= (item.dateValue || 0);
return recordDailyStatMap.value[eventId]?.find(item => item.dateValue === dateValue)?.dailyCount || 0;
} }
function countRecordByEvent(eventId: string): number { function groupRecordDailyStatByEventId(list: StoreEventRecordDailyStatView[]): Record<string, StoreEventRecordDailyStatView[]> {
return (recordDailyStatMap.value[eventId] || []).reduce((sum, item) => sum + (item.dailyCount || 0), 0); const map: Record<string, StoreEventRecordDailyStatView[]> = {};
} for (const item of list) {
if (!item.eventId) {
function getEventColor(event: EventItem): string | undefined { continue;
return event.color || undefined; }
} if (!map[item.eventId]) {
map[item.eventId] = [];
function getGenderCount(genderCode: "MALE" | "FEMALE" | "UNKNOWN"): number { }
return customerGenderStatList.value.find(item => item.genderCode === genderCode)?.count || 0; map[item.eventId].push(item);
} }
return map;
// ---------- 日历转换 ----------
function buildCalendarRecord(record: EventRecordCalendarView): EventRecord {
return {
id: record.id,
customerId: record.customerId,
eventId: record.eventId,
registeredAt: record.registeredAt,
customer: record.customerId || record.customerCode || record.customerName ? {
id: record.customerId,
code: record.customerCode,
name: record.customerName
} : undefined
};
} }
// ---------- 日期工具 ---------- // ---------- 日期工具 ----------
@@ -451,15 +140,6 @@ function getDateStart(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0); return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 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 getDateEnd(date: Date): Date { function getDateEnd(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999); return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
} }
@@ -470,6 +150,14 @@ function addDays(date: Date, days: number): Date {
return value; return value;
} }
function addMonths(date: Date, months: number): Date {
return new Date(date.getFullYear(), date.getMonth() + months, date.getDate(), 0, 0, 0, 0);
}
function toDateValue(date: Date): number {
return Number(Time.formatDate(date).replaceAll("-", ""));
}
function buildDateTextList(begin: Date, end: Date): string[] { function buildDateTextList(begin: Date, end: Date): string[] {
const list: string[] = []; const list: string[] = [];
for (let item = getDateStart(begin); item <= end; item = addDays(item, 1)) { for (let item = getDateStart(begin); item <= end; item = addDays(item, 1)) {
@@ -515,25 +203,6 @@ function buildDateTextList(begin: Date, end: Date): string[] {
} }
} }
} }
.chart-section {
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: 1.25rem;
h2 {
margin: 0 0 .875rem 0;
color: #0f172a;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
} }
:global(html.theme-dark) { :global(html.theme-dark) {
@@ -552,15 +221,6 @@ function buildDateTextList(begin: Date, end: Date): string[] {
} }
} }
} }
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
} }
} }
</style> </style>
@@ -0,0 +1,108 @@
<template>
<section class="chart-section">
<h2>性别统计</h2>
<div ref="chartElement" class="chart" />
</section>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import type { CustomerGenderStatView } from "@/types/Customer";
import { buildStoreBaseChartOption, useStoreChart } from "@/pages/store/component/useStoreChart";
const props = defineProps<{
dateTextList: string[];
statList: CustomerGenderStatView[];
}>();
const genderColorMap = {
MALE: "#2563eb",
FEMALE: "#db2777",
UNKNOWN: "#64748b"
} as const;
const chartOption = computed<EChartsOption>(() => ({
...buildStoreBaseChartOption(props.dateTextList),
tooltip: {
trigger: "item"
},
xAxis: {
type: "category",
data: ["男", "女", "未知"],
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [
{
name: "客户数",
type: "bar",
barWidth: 24,
data: [
{
name: "男",
value: getGenderCount("MALE"),
itemStyle: {
color: genderColorMap.MALE
}
},
{
name: "女",
value: getGenderCount("FEMALE"),
itemStyle: {
color: genderColorMap.FEMALE
}
},
{
name: "未知",
value: getGenderCount("UNKNOWN"),
itemStyle: {
color: genderColorMap.UNKNOWN
}
}
]
}
]
}));
const { chartElement } = useStoreChart(chartOption);
function getGenderCount(genderCode: "MALE" | "FEMALE" | "UNKNOWN"): number {
return props.statList.find(item => item.genderCode === genderCode)?.count || 0;
}
</script>
<style scoped lang="less">
.chart-section {
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: 1.25rem;
h2 {
color: #0f172a;
margin: 0 0 .875rem 0;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
:global(html.theme-dark) {
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
@@ -0,0 +1,91 @@
<template>
<section class="chart-section">
<h2>客户增长趋势</h2>
<div ref="chartElement" class="chart" />
<chart-range-slider
v-if="showSlider"
:model-value="sliderValue"
:max="maxSliderValue"
:min-range="5"
:label="rangeText"
@change="handleSliderChange"
/>
</section>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import ChartRangeSlider from "@/components/ChartRangeSlider.vue";
import type { CustomerDailyStatView } from "@/types/Customer";
import { buildStoreBaseChartOption, useStoreChart, useStoreChartWindow } from "@/pages/store/component/useStoreChart";
const props = defineProps<{
dateTextList: string[];
statList: CustomerDailyStatView[];
}>();
const dateTextList = computed(() => props.dateTextList);
const {
rangeText,
showSlider,
sliderValue,
maxSliderValue,
visibleDateTextList,
handleSliderChange
} = useStoreChartWindow(dateTextList);
const chartOption = computed<EChartsOption>(() => ({
...buildStoreBaseChartOption(visibleDateTextList.value),
series: [
{
name: "客户总量",
type: "line",
smooth: true,
data: visibleDateTextList.value.map(dateText => getDailyStat(dateText)?.totalCustomerCount || 0)
},
{
name: "新客户量",
type: "bar",
data: visibleDateTextList.value.map(dateText => getDailyStat(dateText)?.newCustomerCount || 0)
}
]
}));
const { chartElement } = useStoreChart(chartOption);
function getDailyStat(dateText: string): CustomerDailyStatView | undefined {
const dateValue = Number(dateText.replaceAll("-", ""));
return props.statList.find(item => item.dateValue === dateValue);
}
</script>
<style scoped lang="less">
.chart-section {
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: 1.25rem;
h2 {
color: #0f172a;
margin: 0 0 .875rem 0;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
:global(html.theme-dark) {
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
@@ -0,0 +1,104 @@
<template>
<event-record-calendar
v-model="monthCursor"
v-model:selected-event-id-list="selectedEventIdList"
:event-list="eventList"
empty-text="当前月份暂无登记事件记录"
:loading="isCalendarLoading"
:records="monthRecords"
/>
</template>
<script setup lang="ts">
import StoreChartAPI from "@/api/StoreChartAPI";
import EventRecordCalendar from "@/components/EventRecordCalendar.vue";
import type { EventItem } from "@/types/EventItem";
import type { EventRecord } from "@/types/EventRecord";
import type { StoreEventRecordCalendarView } from "@/types/Store";
import { Time } from "timi-web";
const props = defineProps<{
eventList: EventItem[];
}>();
const selectedEventIdList = ref<string[]>([]);
const monthRecords = ref<EventRecord[]>([]);
const isCalendarLoading = ref(false);
const monthCursor = ref(getMonthStart(new Date()));
let calendarRequestId = 0;
watch(monthCursor, async () => {
await loadMonthRecords();
});
watch(() => props.eventList, async () => {
const eventIdList = getEventIdList();
selectedEventIdList.value = selectedEventIdList.value.length ? selectedEventIdList.value.filter(item => eventIdList.includes(item)) : eventIdList;
await loadMonthRecords();
}, {
immediate: true
});
async function loadMonthRecords(): Promise<void> {
const requestId = ++calendarRequestId;
const begin = getCalendarBeginDate(monthCursor.value);
const end = getDateEnd(addDays(begin, 41));
const eventIdList = getEventIdList();
if (!eventIdList.length) {
monthRecords.value = [];
return;
}
isCalendarLoading.value = true;
try {
const calendarRecordList = await StoreChartAPI.eventRecordCalendar({
beginAt: Time.toTimestamp(begin),
endAt: Time.toTimestamp(end),
eventIdList
});
if (requestId === calendarRequestId) {
monthRecords.value = calendarRecordList.map(buildCalendarRecord);
}
} finally {
if (requestId === calendarRequestId) {
isCalendarLoading.value = false;
}
}
}
function getEventIdList(): string[] {
return props.eventList.map(item => item.id).filter((id): id is string => Boolean(id));
}
function buildCalendarRecord(record: StoreEventRecordCalendarView): EventRecord {
return {
id: record.id,
customerId: record.customerId,
eventId: record.eventId,
registeredAt: record.registeredAt,
customer: record.customerId || record.customerCode || record.customerName ? {
id: record.customerId,
code: record.customerCode,
name: record.customerName
} : undefined
};
}
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 getDateEnd(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
}
function addDays(date: Date, days: number): Date {
const value = new Date(date);
value.setDate(value.getDate() + days);
return value;
}
</script>
@@ -0,0 +1,93 @@
<template>
<section class="chart-section">
<h2>登记量趋势</h2>
<div ref="chartElement" class="chart" />
<chart-range-slider
v-if="showSlider"
:model-value="sliderValue"
:max="maxSliderValue"
:min-range="5"
:label="rangeText"
@change="handleSliderChange"
/>
</section>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import ChartRangeSlider from "@/components/ChartRangeSlider.vue";
import type { EventItem } from "@/types/EventItem";
import type { StoreEventRecordDailyStatView } from "@/types/Store";
import { buildStoreBaseChartOption, useStoreChart, useStoreChartWindow } from "@/pages/store/component/useStoreChart";
const props = defineProps<{
dateTextList: string[];
eventList: EventItem[];
statMap: Record<string, StoreEventRecordDailyStatView[]>;
}>();
const dateTextList = computed(() => props.dateTextList);
const {
rangeText,
showSlider,
sliderValue,
maxSliderValue,
visibleDateTextList,
handleSliderChange
} = useStoreChartWindow(dateTextList);
const chartOption = computed<EChartsOption>(() => ({
...buildStoreBaseChartOption(visibleDateTextList.value),
series: props.eventList.map(event => ({
name: event.name || "未命名事件",
type: "bar",
stack: "record",
itemStyle: getEventColor(event) ? {
color: getEventColor(event)
} : undefined,
data: visibleDateTextList.value.map(dateText => countRecordByEventAndDate(event.id || "", dateText))
}))
}));
const { chartElement } = useStoreChart(chartOption);
function countRecordByEventAndDate(eventId: string, dateText: string): number {
const dateValue = Number(dateText.replaceAll("-", ""));
return props.statMap[eventId]?.find(item => item.dateValue === dateValue)?.dailyCount || 0;
}
function getEventColor(event: EventItem): string | undefined {
return event.color || undefined;
}
</script>
<style scoped lang="less">
.chart-section {
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: 1.25rem;
h2 {
color: #0f172a;
margin: 0 0 .875rem 0;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
:global(html.theme-dark) {
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
@@ -0,0 +1,88 @@
<template>
<section class="chart-section">
<h2>事件结构</h2>
<div ref="chartElement" class="chart" />
</section>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import type { EventItem } from "@/types/EventItem";
import type { StoreEventRecordDailyStatView } from "@/types/Store";
import { buildStoreBaseChartOption, useStoreChart } from "@/pages/store/component/useStoreChart";
const props = defineProps<{
dateTextList: string[];
eventList: EventItem[];
statMap: Record<string, StoreEventRecordDailyStatView[]>;
}>();
const chartOption = computed<EChartsOption>(() => ({
...buildStoreBaseChartOption(props.dateTextList),
legend: {
show: false
},
xAxis: {
type: "category",
data: props.eventList.map(item => item.name || "未命名事件"),
axisTick: {
show: false
},
axisLabel: {
color: "#52607a"
}
},
series: [{
name: "登记次数",
type: "bar",
data: props.eventList.map(item => ({
value: countRecordByEvent(item.id || ""),
itemStyle: getEventColor(item) ? {
color: getEventColor(item)
} : undefined
}))
}]
}));
const { chartElement } = useStoreChart(chartOption);
function countRecordByEvent(eventId: string): number {
return (props.statMap[eventId] || []).reduce((sum, item) => sum + (item.dailyCount || 0), 0);
}
function getEventColor(event: EventItem): string | undefined {
return event.color || undefined;
}
</script>
<style scoped lang="less">
.chart-section {
padding: 1rem;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: 1.25rem;
h2 {
color: #0f172a;
margin: 0 0 .875rem 0;
font-size: 1rem;
font-weight: 700;
}
.chart {
width: 100%;
height: 16rem;
}
}
:global(html.theme-dark) {
.chart-section {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
h2 {
color: #e2e8f0;
}
}
}
</style>
+164
View File
@@ -0,0 +1,164 @@
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 type { ComputedRef, Ref } from "vue";
use([
BarChart,
LineChart,
GridComponent,
LegendComponent,
TooltipComponent,
CanvasRenderer
]);
export function buildStoreBaseChartOption(dateTextList: string[]): 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: dateTextList.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)"
}
}
}
};
}
export function useStoreChart(option: ComputedRef<EChartsOption> | Ref<EChartsOption>) {
const chartElement = ref<HTMLElement>();
let chart: ECharts | undefined;
watch(option, async () => {
await nextTick();
renderChart();
}, {
deep: true
});
onMounted(async () => {
await nextTick();
renderChart();
window.addEventListener("resize", resizeChart);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", resizeChart);
chart?.dispose();
chart = undefined;
});
function renderChart(): void {
if (!chartElement.value) {
return;
}
chart = chart || init(chartElement.value);
chart.setOption(option.value, true);
}
function resizeChart(): void {
chart?.resize();
}
return {
chartElement
};
}
export function useStoreChartWindow(dateTextList: ComputedRef<string[]>) {
const sliderValue = ref<number[]>([0, 0]);
const viewportWidth = ref(window.innerWidth);
let isSliderInitialized = false;
const visibleDayCount = computed(() => Math.max(6, Math.floor(viewportWidth.value / 64)));
const maxSliderValue = computed(() => Math.max(0, dateTextList.value.length - 1));
const visibleDateTextList = computed(() => dateTextList.value.slice(sliderValue.value[0], sliderValue.value[1] + 1));
const showSlider = computed(() => visibleDayCount.value < dateTextList.value.length);
const rangeText = computed(() => {
const list = visibleDateTextList.value;
const beginText = list[0]?.slice(5) || "";
const endText = list[list.length - 1]?.slice(5) || "";
return beginText && endText ? `${beginText} 至 ${endText}` : "";
});
watch(maxSliderValue, value => {
if (!isSliderInitialized) {
sliderValue.value = getLatestSliderRange();
isSliderInitialized = true;
return;
}
const [start, end] = sliderValue.value;
if (value < end) {
sliderValue.value = [Math.max(0, value - Math.max(0, end - start)), value];
}
}, {
immediate: true
});
onMounted(() => {
window.addEventListener("resize", updateViewportWidth);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", updateViewportWidth);
});
function handleSliderChange(value: number | number[]): void {
if (!Array.isArray(value)) {
return;
}
const [start = 0, end = start] = value;
sliderValue.value = [start, Math.max(start, end)];
}
function updateViewportWidth(): void {
viewportWidth.value = window.innerWidth;
}
function getLatestSliderRange(): number[] {
const end = maxSliderValue.value;
const start = Math.max(0, end - visibleDayCount.value + 1);
return [start, end];
}
return {
rangeText,
showSlider,
sliderValue,
maxSliderValue,
visibleDateTextList,
handleSliderChange
};
}
+8
View File
@@ -53,3 +53,11 @@ export type CustomerGenderStatView = {
genderCode?: CustomerGender | "UNKNOWN"; genderCode?: CustomerGender | "UNKNOWN";
count?: number; count?: number;
}; };
export type CustomerChartReq = {
storeId?: string;
customerId: string;
beginAt: number;
endAt: number;
eventIdList?: string[];
};
+22
View File
@@ -27,3 +27,25 @@ export type StoreBusinessDayPage = {
endDateValue?: number; endDateValue?: number;
} & BasePage; } & BasePage;
export type StoreChartReq = {
storeId?: string;
beginAt: number;
endAt: number;
eventIdList?: string[];
};
export type StoreEventRecordDailyStatView = {
eventId?: string;
dateValue?: number;
dailyCount?: number;
};
export type StoreEventRecordCalendarView = {
id?: string;
customerId?: string;
customerCode?: string;
customerName?: string;
eventId?: string;
registeredAt?: number;
};